-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathcontext.ts
305 lines (255 loc) · 7.93 KB
/
context.ts
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import { relative } from 'path'
import type fs from 'fs'
import Debug from 'debug'
import type { UpdatePayload, ViteDevServer } from 'vite'
import { slash, throttle, toArray } from '@antfu/utils'
import type { ComponentInfo, Options, ResolvedOptions, Transformer } from '../types'
import { DIRECTIVE_IMPORT_PREFIX } from './constants'
import { getNameFromFilePath, matchGlobs, normalizeComponetInfo, parseId, pascalCase, resolveAlias } from './utils'
import { resolveOptions } from './options'
import { searchComponents } from './fs/glob'
import { writeDeclaration } from './declaration'
import transformer from './transformer'
const debug = {
components: Debug('unplugin-vue-components:context:components'),
search: Debug('unplugin-vue-components:context:search'),
hmr: Debug('unplugin-vue-components:context:hmr'),
decleration: Debug('unplugin-vue-components:decleration'),
env: Debug('unplugin-vue-components:env'),
}
export class Context {
options: ResolvedOptions
transformer: Transformer = undefined!
private _componentPaths = new Set<string>()
private _componentNameMap: Record<string, ComponentInfo> = {}
private _componentUsageMap: Record<string, Set<string>> = {}
private _componentCustomMap: Record<string, ComponentInfo> = {}
private _directiveCustomMap: Record<string, ComponentInfo> = {}
private _server: ViteDevServer | undefined
root = process.cwd()
sourcemap: string | boolean = true
alias: Record<string, string> = {}
constructor(
private rawOptions: Options,
) {
this.options = resolveOptions(rawOptions, this.root)
this.generateDeclaration
= throttle(500, false, this._generateDeclaration.bind(this)) as
// `throttle` will omit return value.
((removeUnused?: boolean) => void)
this.setTransformer(this.options.transformer)
}
setRoot(root: string) {
if (this.root === root)
return
debug.env('root', root)
this.root = root
this.options = resolveOptions(this.rawOptions, this.root)
}
setTransformer(name: Options['transformer']) {
debug.env('transformer', name)
this.transformer = transformer(this, name || 'vue3')
}
transform(code: string, id: string) {
const { path, query } = parseId(id)
return this.transformer(code, id, path, query)
}
setupViteServer(server: ViteDevServer) {
if (this._server === server)
return
this._server = server
this.setupWatcher(server.watcher)
}
setupWatcher(watcher: fs.FSWatcher) {
const { globs } = this.options
watcher
.on('unlink', (path) => {
if (!matchGlobs(path, globs))
return
path = slash(path)
this.removeComponents(path)
this.onUpdate(path)
})
watcher
.on('add', (path) => {
if (!matchGlobs(path, globs))
return
path = slash(path)
this.addComponents(path)
this.onUpdate(path)
})
}
/**
* start watcher for webpack
*/
setupWatcherWebpack(watcher: fs.FSWatcher, emitUpdate: (path: string, type: 'unlink' | 'add') => void) {
const { globs } = this.options
watcher
.on('unlink', (path) => {
if (!matchGlobs(path, globs))
return
path = slash(path)
this.removeComponents(path)
emitUpdate(path, 'unlink')
})
watcher
.on('add', (path) => {
if (!matchGlobs(path, globs))
return
path = slash(path)
this.addComponents(path)
emitUpdate(path, 'add')
})
}
/**
* Record the usage of components
* @param path
* @param paths paths of used components
*/
updateUsageMap(path: string, paths: string[]) {
if (!this._componentUsageMap[path])
this._componentUsageMap[path] = new Set()
paths.forEach((p) => {
this._componentUsageMap[path].add(p)
})
}
addComponents(paths: string | string[]) {
debug.components('add', paths)
const size = this._componentPaths.size
toArray(paths).forEach(p => this._componentPaths.add(p))
if (this._componentPaths.size !== size) {
this.updateComponentNameMap()
return true
}
return false
}
addCustomComponents(info: ComponentInfo) {
if (info.as)
this._componentCustomMap[info.as] = info
}
addCustomDirectives(info: ComponentInfo) {
if (info.as)
this._directiveCustomMap[info.as] = info
}
removeComponents(paths: string | string[]) {
debug.components('remove', paths)
const size = this._componentPaths.size
toArray(paths).forEach(p => this._componentPaths.delete(p))
if (this._componentPaths.size !== size) {
this.updateComponentNameMap()
return true
}
return false
}
onUpdate(path: string) {
this.generateDeclaration()
if (!this._server)
return
const payload: UpdatePayload = {
type: 'update',
updates: [],
}
const timestamp = +new Date()
const name = pascalCase(getNameFromFilePath(path, this.options))
Object.entries(this._componentUsageMap)
.forEach(([key, values]) => {
if (values.has(name)) {
const r = `/${slash(relative(this.root, key))}`
payload.updates.push({
acceptedPath: r,
path: r,
timestamp,
type: 'js-update',
})
}
})
if (payload.updates.length)
this._server.ws.send(payload)
}
private updateComponentNameMap() {
this._componentNameMap = {}
Array
.from(this._componentPaths)
.forEach((path) => {
const name = pascalCase(getNameFromFilePath(path, this.options))
if (this._componentNameMap[name] && !this.options.allowOverrides) {
console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`)
return
}
this._componentNameMap[name] = {
as: name,
from: path,
}
})
}
async findComponent(name: string, type: 'component' | 'directive', excludePaths: string[] = []): Promise<ComponentInfo | undefined> {
// resolve from fs
let info = this._componentNameMap[name]
if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
return info
// custom resolvers
for (const resolver of this.options.resolvers) {
if (resolver.type !== type)
continue
const result = await resolver.resolve(type === 'directive' ? name.slice(DIRECTIVE_IMPORT_PREFIX.length) : name)
if (!result)
continue
if (typeof result === 'string') {
info = {
as: name,
from: result,
}
}
else {
info = {
as: name,
...normalizeComponetInfo(result),
}
}
if (type === 'component')
this.addCustomComponents(info)
else if (type === 'directive')
this.addCustomDirectives(info)
return info
}
return undefined
}
normalizePath(path: string) {
// @ts-expect-error backward compatibility
return resolveAlias(path, this.viteConfig?.resolve?.alias || this.viteConfig?.alias || [])
}
relative(path: string) {
if (path.startsWith('/') && !path.startsWith(this.root))
return slash(path.slice(1))
return slash(relative(this.root, path))
}
_searched = false
/**
* This search for components in with the given options.
* Will be called multiple times to ensure file loaded,
* should normally run only once.
*/
searchGlob() {
if (this._searched)
return
searchComponents(this)
debug.search(this._componentNameMap)
this._searched = true
}
_generateDeclaration(removeUnused = !this._server) {
if (!this.options.dts)
return
debug.decleration('generating')
return writeDeclaration(this, this.options.dts, removeUnused)
}
generateDeclaration
get componentNameMap() {
return this._componentNameMap
}
get componentCustomMap() {
return this._componentCustomMap
}
get directiveCustomMap() {
return this._directiveCustomMap
}
}