/
context.ts
245 lines (213 loc) · 7.2 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
import { ResolvedOptions } from '../options'
import { createPrefixTree, TreeNode } from './tree'
import { promises as fs } from 'fs'
import { logTree, throttle } from './utils'
import { generateRouteNamedMap } from '../codegen/generateRouteMap'
import { MODULE_ROUTES_PATH, MODULE_VUE_ROUTER } from './moduleConstants'
import { generateRouteRecord } from '../codegen/generateRouteRecords'
import fg from 'fast-glob'
import { resolve } from 'pathe'
import { ServerContext } from '../options'
import { getRouteBlock } from './customBlock'
import { RoutesFolderWatcher, HandlerContext } from './RoutesFolderWatcher'
import { generateDTS as _generateDTS } from '../codegen/generateDTS'
import { generateVueRouterProxy as _generateVueRouterProxy } from '../codegen/vueRouterModule'
import { hasNamedExports } from '../data-fetching/parse'
import { definePageTransform, extractDefinePageNameAndPath } from './definePage'
export function createRoutesContext(options: ResolvedOptions) {
const { dts: preferDTS, root, routesFolder } = options
const dts =
preferDTS === false
? false
: preferDTS === true
? resolve(root, 'typed-router.d.ts')
: resolve(root, preferDTS)
const routeTree = createPrefixTree(options)
const routeMap = new Map<string, TreeNode>()
function log(...args: any[]) {
if (options.logs) {
console.log(...args)
}
}
// populated by the initial scan pages
const watchers: RoutesFolderWatcher[] = []
async function scanPages() {
if (options.extensions.length < 1) {
throw new Error(
'"extensions" cannot be empty. Please specify at least one extension.'
)
}
// initial scan was already done
if (watchers.length > 0) {
return
}
const pattern =
`**/*` +
(options.extensions.length === 1
? options.extensions[0]
: `.{${options.extensions
.map((extension) => extension.replace('.', ''))
.join(',')}}`)
await Promise.all(
routesFolder.map((folder) => {
const watcher = new RoutesFolderWatcher(folder, options)
setupWatcher(watcher)
watchers.push(watcher)
return fg(pattern, {
cwd: folder.src,
// TODO: do they return the symbolic link path or the original file?
// followSymbolicLinks: false,
ignore: options.exclude,
})
.then((files) => files.map((file) => resolve(folder.src, file)))
.then((files) =>
Promise.all(
files.map((file) =>
addPage({
routePath: watcher.asRoutePath(file),
filePath: file,
})
)
)
)
})
)
await _writeConfigFiles()
}
async function writeRouteInfoToNode(node: TreeNode, path: string) {
const content = await fs.readFile(path, 'utf8')
// TODO: cache the result of parsing the SFC so the transform can reuse the parsing
node.hasDefinePage = content.includes('definePage')
const [definedPageNameAndPath, routeBlock] = await Promise.all([
extractDefinePageNameAndPath(content, path),
getRouteBlock(path, options),
])
// TODO: should warn if hasDefinePage and customRouteBlock
// if (routeBlock) log(routeBlock)
node.setCustomRouteBlock(path, { ...routeBlock, ...definedPageNameAndPath })
node.value.includeLoaderGuard =
options.dataFetching && (await hasNamedExports(path))
}
async function addPage({ filePath: path, routePath }: HandlerContext) {
log(`added "${routePath}" for "${path}"`)
// TODO: handle top level named view HMR
const node = routeTree.insert(
routePath,
// './' + path
resolve(root, path)
)
await writeRouteInfoToNode(node, path)
routeMap.set(path, node)
}
async function updatePage({ filePath: path, routePath }: HandlerContext) {
log(`updated "${routePath}" for "${path}"`)
const node = routeMap.get(path)
if (!node) {
console.warn(`Cannot update "${path}": Not found.`)
return
}
writeRouteInfoToNode(node, path)
}
function removePage({ filePath: path, routePath }: HandlerContext) {
log(`remove "${routePath}" for "${path}"`)
routeTree.remove(routePath)
routeMap.delete(path)
}
function setupWatcher(watcher: RoutesFolderWatcher) {
log(`🤖 Scanning files in ${watcher.src}`)
watcher
.on('change', async (ctx) => {
await updatePage(ctx)
writeConfigFiles()
})
.on('add', async (ctx) => {
await addPage(ctx)
writeConfigFiles()
})
.on('unlink', async (ctx) => {
await removePage(ctx)
writeConfigFiles()
})
}
function generateRoutes() {
// keys are import names while values are paths import __ from __
// TODO: reverse the order and make a list of named imports and another for defaults?
const importList = new Map<string, string>()
const routesExport = `export const routes = ${generateRouteRecord(
routeTree,
options,
importList
)}`
let imports = ''
// FIXME: after demo
if (true || options.dataFetching) {
imports += `import { _HasDataLoaderMeta, _mergeRouteRecord } from 'unplugin-vue-router/runtime'\n`
}
for (const [name, path] of importList) {
imports += `import ${name} from '${path}'\n`
}
// add an empty line for readability
if (imports) {
imports += '\n'
}
return `${imports}\
${routesExport}
`
}
function generateDTS(): string {
return _generateDTS({
vueRouterModule: MODULE_VUE_ROUTER,
routesModule: MODULE_ROUTES_PATH,
routeNamedMap: generateRouteNamedMap(routeTree)
.split('\n')
.filter((line) => line) // remove empty lines
.map((line) => ' ' + line) // Indent by two spaces
.join('\n'),
})
}
// NOTE: this code needs to be generated because otherwise it doesn't go through transforms and `vue-router/auto/routes`
// cannot be resolved.
function generateVueRouterProxy() {
return _generateVueRouterProxy(MODULE_ROUTES_PATH, options)
}
let lastDTS: string | undefined
async function _writeConfigFiles() {
log('💾 writing...')
logTree(routeTree, log)
if (dts) {
const content = generateDTS()
if (lastDTS !== content) {
await fs.writeFile(dts, content, 'utf-8')
lastDTS = content
server?.invalidate(MODULE_ROUTES_PATH)
server?.invalidate(MODULE_VUE_ROUTER)
server?.reload()
}
}
}
// debounce of 100ms + throttle of 500ms
// => Initially wait 100ms (renames are actually remove and add but we rather write once) (debounce)
// subsequent calls after the first execution will wait 500ms-100ms to execute (throttling)
const writeConfigFiles = throttle(_writeConfigFiles, 500, 100)
function stopWatcher() {
watchers.forEach((watcher) => watcher.close())
}
let server: ServerContext | undefined
function setServerContext(_server: ServerContext) {
server = _server
}
return {
scanPages,
writeConfigFiles,
setServerContext,
stopWatcher,
generateRoutes,
generateVueRouterProxy,
definePageTransform(code: string, id: string) {
return definePageTransform({
code,
id,
})
},
}
}