-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathoptions.ts
More file actions
173 lines (161 loc) · 4.85 KB
/
options.ts
File metadata and controls
173 lines (161 loc) · 4.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import type { CorsOptions } from 'cors'
import type { Alias, AliasOptions, ResolvedConfig } from 'vite'
import type {
MockServerPluginOptions,
RecordOptions,
ResolvedRecordOptions,
ServerBuildOption,
} from '../types'
import type { Logger } from './logger'
import path from 'node:path'
import process from 'node:process'
import { isArray, isBoolean, toArray, uniq } from '@pengzhanbo/utils'
import ansis from 'ansis'
import { viteDefine } from './define'
import { createLogger } from './logger'
export type ResolvedMockServerPluginOptions = Required<
Omit<MockServerPluginOptions, 'build' | 'cors' | 'wsPrefix' | 'prefix' | 'record'>
> & {
context: string
logger: Logger
alias: Alias[]
define: Record<string, any>
proxies: string[]
wsProxies: string[]
build: false | ServerBuildOption
cors: false | CorsOptions
record: ResolvedRecordOptions
}
export function resolvePluginOptions({
prefix = [],
wsPrefix = [],
cwd: rawCwd,
dir = 'mock',
include = ['**/*.mock.{js,ts,cjs,mjs,json,json5}'],
exclude = [],
reload = false,
log = 'info',
cors = true,
formidableOptions = {},
build = false,
cookiesOptions = {},
bodyParserOptions = {},
priority = {},
record = false,
replay,
}: MockServerPluginOptions, config: ResolvedConfig): ResolvedMockServerPluginOptions {
const cwd = rawCwd || process.cwd()
const logger = createLogger('vite:mock', isBoolean(log) ? (log ? 'info' : 'error') : log)
const { httpProxies } = ensureProxies(config.server.proxy || {})
const proxies = uniq([...toArray(prefix), ...httpProxies])
const wsProxies = toArray(wsPrefix)
if (!proxies.length && !wsProxies.length)
logger.warn(`No proxy was configured, mock server will not work. See ${ansis.cyan('https://vite-plugin-mock-dev-server.netlify.app/guide/usage')}`)
// enable cors by default
const enabled = cors === false ? false : config.server.cors !== false
let corsOptions: CorsOptions = {}
if (enabled && config.server.cors !== false) {
corsOptions = {
...corsOptions,
...((typeof config.server.cors === 'boolean'
? {}
: config.server.cors) as CorsOptions),
}
}
if (enabled && cors !== false) {
corsOptions = {
...corsOptions,
...(typeof cors === 'boolean' ? {} : cors),
}
}
const alias: Alias[] = []
const aliasConfig = (config.resolve.alias || []) as AliasOptions
if (isArray<Alias>(aliasConfig)) {
alias.push(...aliasConfig)
}
else {
Object.entries(aliasConfig).forEach(([find, replacement]) => {
alias.push({ find, replacement })
})
}
const resolvedRecord = resolveRecordOptions(cwd, dir, record)
return {
enabled: true,
cwd,
dir,
include,
exclude,
context: config.root,
reload,
cors: enabled ? corsOptions : false,
cookiesOptions,
log,
formidableOptions: { multiples: true, ...formidableOptions },
bodyParserOptions,
priority,
build: build
? {
serverPort: 8080,
dist: 'mockServer',
log: 'error',
includeRecord: replay ?? resolvedRecord.enabled ?? false,
...typeof build === 'object' ? build : {},
}
: false,
proxies,
wsProxies,
logger,
alias,
define: viteDefine(config),
record: resolvedRecord,
replay: replay ?? resolvedRecord.enabled ?? false,
}
}
export function ensureProxies(
serverProxy: ResolvedConfig['server']['proxy'] = {},
): { httpProxies: string[], wsProxies: string[] } {
const httpProxies: string[] = []
const wsProxies: string[] = []
Object.keys(serverProxy).forEach((key) => {
const value = serverProxy[key]
if (
typeof value === 'string'
|| (!value.ws
&& !value.target?.toString().startsWith('ws:')
&& !value.target?.toString().startsWith('wss:'))
) {
httpProxies.push(key)
}
else {
wsProxies.push(key)
}
})
return { httpProxies, wsProxies }
}
/**
* Resolve record options
*
* 解析录制配置
*
* @param cwd - Current working directory / 当前工作目录
* @param dir - Mock context directory / 模拟上下文目录
* @param record - Record options / 录制配置
* @returns Resolved record options / 解析后的录制配置
*/
export function resolveRecordOptions(cwd: string, dir: string, record?: boolean | RecordOptions): ResolvedRecordOptions {
// Parse record configuration
const recordOptions = typeof record === 'boolean'
? { enabled: record }
: record
const expires = recordOptions?.expires ?? 0
return {
enabled: recordOptions?.enabled ?? false,
cwd,
dir: path.join(dir, recordOptions?.dir || '.recordings'),
overwrite: recordOptions?.overwrite ?? true,
status: toArray(recordOptions?.status).map(Number),
expires: expires === 0 ? Number.MAX_SAFE_INTEGER : expires * 1000,
gitignore: recordOptions?.gitignore ?? true,
filter: recordOptions?.filter || (() => true),
}
}