/
route.js
279 lines (258 loc) · 7.87 KB
/
route.js
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
import path from 'path'
import { get } from 'lodash'
import consola from 'consola'
import { normalizeURL, withTrailingSlash, withoutTrailingSlash } from 'ufo'
import { r } from './resolve'
const routeChildren = function (route) {
const hasChildWithEmptyPath = route.children.some(child => child.path === '')
if (hasChildWithEmptyPath) {
return route.children
}
return [
// Add default child to render parent page
{
...route,
children: undefined
},
...route.children
]
}
export const flatRoutes = function flatRoutes (router, fileName = '', routes = []) {
router.forEach((r) => {
if ([':', '*'].some(c => r.path.includes(c))) {
return
}
const route = `${fileName}${r.path}/`.replace(/\/+/g, '/')
if (r.children) {
return flatRoutes(routeChildren(r), route, routes)
}
// if child path is already absolute, do not make any concatenations
if (r.path && r.path.startsWith('/')) {
routes.push(r.path)
} else if (route !== '/' && route[route.length - 1] === '/') {
routes.push(route.slice(0, -1))
} else {
routes.push(route)
}
})
return routes
}
function cleanChildrenRoutes (routes, isChild = false, routeNameSplitter = '-', trailingSlash, parentRouteName) {
const regExpIndex = new RegExp(`${routeNameSplitter}index$`)
const regExpParentRouteName = new RegExp(`^${parentRouteName}${routeNameSplitter}`)
const routesIndex = []
routes.forEach((route) => {
if (regExpIndex.test(route.name) || route.name === 'index') {
const res = route.name.replace(regExpParentRouteName, '').split(routeNameSplitter)
routesIndex.push(res)
}
})
routes.forEach((route) => {
route.path = isChild ? route.path.replace('/', '') : route.path
if (route.path.includes('?')) {
if (route.name.endsWith(`${routeNameSplitter}index`)) {
route.path = route.path.replace(/\?\/?$/, trailingSlash ? '/' : '')
}
const names = route.name.replace(regExpParentRouteName, '').split(routeNameSplitter)
const paths = route.path.split('/')
if (!isChild) {
paths.shift()
} // clean first / for parents
routesIndex.forEach((r) => {
const i = r.indexOf('index')
if (i < paths.length) {
for (let a = 0; a <= i; a++) {
if (a === i) {
paths[a] = paths[a].replace('?', '')
}
if (a < i && names[a] !== r[a]) {
break
}
}
}
})
route.path = (isChild ? '' : '/') + paths.join('/')
}
route.name = route.name.replace(regExpIndex, '')
if (route.children) {
const defaultChildRoute = route.children.find(child => child.path === '/' || child.path === '')
const routeName = route.name
if (defaultChildRoute) {
route.children.forEach((child) => {
if (child.path !== defaultChildRoute.path) {
const parts = child.path.split('/')
parts[1] = parts[1].endsWith('?') ? parts[1].substr(0, parts[1].length - 1) : parts[1]
child.path = parts.join('/')
}
})
delete route.name
}
route.children = cleanChildrenRoutes(route.children, true, routeNameSplitter, trailingSlash, routeName)
}
})
return routes
}
const DYNAMIC_ROUTE_REGEX = /^\/([:*])/
export const sortRoutes = function sortRoutes (routes) {
routes.sort((a, b) => {
if (!a.path.length) {
return -1
}
if (!b.path.length) {
return 1
}
// Order: /static, /index, /:dynamic
// Match exact route before index: /login before /index/_slug
if (a.path === '/') {
return DYNAMIC_ROUTE_REGEX.test(b.path) ? -1 : 1
}
if (b.path === '/') {
return DYNAMIC_ROUTE_REGEX.test(a.path) ? 1 : -1
}
let i
let res = 0
let y = 0
let z = 0
const _a = a.path.split('/')
const _b = b.path.split('/')
for (i = 0; i < _a.length; i++) {
if (res !== 0) {
break
}
y = _a[i] === '*' ? 2 : _a[i].includes(':') ? 1 : 0
z = _b[i] === '*' ? 2 : _b[i].includes(':') ? 1 : 0
res = y - z
// If a.length >= b.length
if (i === _b.length - 1 && res === 0) {
// unless * found sort by level, then alphabetically
res = _a[i] === '*'
? -1
: (
_a.length === _b.length ? a.path.localeCompare(b.path) : (_a.length - _b.length)
)
}
}
if (res === 0) {
// unless * found sort by level, then alphabetically
res = _a[i - 1] === '*' && _b[i]
? 1
: (
_a.length === _b.length ? a.path.localeCompare(b.path) : (_a.length - _b.length)
)
}
return res
})
routes.forEach((route) => {
if (route.children) {
sortRoutes(route.children)
}
})
return routes
}
export const createRoutes = function createRoutes ({
files,
srcDir,
pagesDir = '',
routeNameSplitter = '-',
supportedExtensions = ['vue', 'js'],
trailingSlash
}) {
const routes = []
files.forEach((file) => {
const keys = file
.replace(new RegExp(`^${pagesDir}`), '')
.replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '')
.replace(/\/{2,}/g, '/')
.split('/')
.slice(1)
const route = { name: '', path: '', component: r(srcDir, file) }
let parent = routes
keys.forEach((key, i) => {
// remove underscore only, if its the prefix
const sanitizedKey = key.startsWith('_') ? key.substr(1) : key
route.name = route.name
? route.name + routeNameSplitter + sanitizedKey
: sanitizedKey
route.name += key === '_' ? 'all' : ''
route.chunkName = file.replace(new RegExp(`\\.(${supportedExtensions.join('|')})$`), '')
const child = parent.find(parentRoute => parentRoute.name === route.name)
if (child) {
child.children = child.children || []
parent = child.children
route.path = ''
} else if (key === 'index' && i + 1 === keys.length) {
route.path += i > 0 ? '' : '/'
} else {
route.path += '/' + normalizeURL(getRoutePathExtension(key))
if (key.startsWith('_') && key.length > 1) {
route.path += '?'
}
}
})
if (trailingSlash !== undefined) {
route.pathToRegexpOptions = { ...route.pathToRegexpOptions, strict: true }
if (trailingSlash && !route.path.endsWith('*')) {
route.path = withTrailingSlash(route.path)
} else {
route.path = withoutTrailingSlash(route.path)
}
}
parent.push(route)
})
sortRoutes(routes)
return cleanChildrenRoutes(routes, false, routeNameSplitter, trailingSlash)
}
// Guard dir1 from dir2 which can be indiscriminately removed
export const guardDir = function guardDir (options, key1, key2) {
const dir1 = get(options, key1, false)
const dir2 = get(options, key2, false)
if (
dir1 &&
dir2 &&
(
dir1 === dir2 ||
(
dir1.startsWith(dir2) &&
!path.basename(dir1).startsWith(path.basename(dir2))
)
)
) {
const errorMessage = `options.${key2} cannot be a parent of or same as ${key1}`
consola.fatal(errorMessage)
throw new Error(errorMessage)
}
}
const getRoutePathExtension = (key) => {
if (key === '_') {
return '*'
}
if (key.startsWith('_')) {
return `:${key.substr(1)}`
}
return key
}
export const promisifyRoute = function promisifyRoute (fn, ...args) {
// If routes is an array
if (Array.isArray(fn)) {
return Promise.resolve(fn)
}
// If routes is a function expecting a callback
if (fn.length === arguments.length) {
return new Promise((resolve, reject) => {
fn((err, routeParams) => {
if (err) {
reject(err)
}
resolve(routeParams)
}, ...args)
})
}
let promise = fn(...args)
if (
!promise ||
(!(promise instanceof Promise) && typeof promise.then !== 'function')
) {
promise = Promise.resolve(promise)
}
return promise
}