-
-
Notifications
You must be signed in to change notification settings - Fork 58
/
context.ts
211 lines (184 loc) · 6.26 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
import { normalizeRoutesFolderOption, ResolvedOptions } from '../options'
import { createPrefixTree, TreeLeaf } 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'
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, TreeLeaf>()
function log(...args: any[]) {
if (options.logs) {
console.log(...args)
}
}
// it's important to resolve the path before the watcher is created so it give full paths in the handler
const resolvedRoutesFolders = normalizeRoutesFolderOption(routesFolder).map(
(routeOption) => ({
...routeOption,
src: resolve(root, routeOption.src),
})
)
// 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(
resolvedRoutesFolders.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,
// TODO: is this flat necessary?
})
.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 addPage({ filePath: path, routePath }: HandlerContext) {
const routeBlock = await getRouteBlock(path, options)
log(`added "${routePath}" for "${path}"`)
if (routeBlock) log(routeBlock)
// TODO: handle top level named view HMR
const node = routeTree.insert(
routePath,
// './' + path
resolve(root, path)
)
node.setCustomRouteBlock(path, routeBlock)
node.value.includeLoaderGuard = await hasNamedExports(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
}
node.setCustomRouteBlock(path, await getRouteBlock(path, options))
node.value.includeLoaderGuard = await hasNamedExports(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() {
return `import { _LoaderSymbol } from 'unplugin-vue-router/runtime'
export const routes = ${generateRouteRecord(routeTree)}
`
}
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/routes`
// cannot be resolved.
function generateVueRouterProxy() {
return _generateVueRouterProxy(MODULE_ROUTES_PATH)
}
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,
}
}