forked from jacobparis-insiders/remix-custom-routes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcore.js
370 lines (332 loc) · 10.1 KB
/
core.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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
const path = require("path")
const { PrefixLookupTrie } = require("./PrefixLookupTrie")
const { isSegmentSeparator } = require("./isSegmentSeparator")
const { normalizeSlashes } = require("./normalizeSlashes")
module.exports = {
getRouteIds,
getRouteManifest,
getRouteIdConflictErrorMessage,
getRoutePathConflictErrorMessage,
}
const paramPrefixChar = /** @type {const} */ "$"
const escapeStart = /** @type {const} */ "["
const escapeEnd = /** @type {const} */ "]"
const optionalStart = /** @type {const} */ "("
const optionalEnd = /** @type {const} */ ")"
/**
* @typedef {Object} Route
* @property {string} file - The file path of the route component.
* @property {string} id - The unique identifier of the route.
* @property {boolean} index - Whether the route is the index route.
* @property {string} path - The URL path of the route.
* @property {string} parentId - The unique identifier of the parent route.
*/
/**
* @typedef {Object.<string, Route>} RouteManifest
*/
/**
*
* @param {string[]} routes
* @param {object} options
* @param {string} [options.prefix] - The prefix to remove from the route id
* @param {string} [options.suffix] - The suffix to remove from the route id
* @param {string[]} [options.indexNames] - The names to use for index routes
*/
function getRouteIds(routes, options = {}) {
const prefix = options.prefix ?? ""
const suffix = options.suffix ?? ""
const indexNames = options.indexNames ?? []
const routeIdConflicts = new Map()
// id -> file
/** @type {Map<string, string>} */
const routeIds = new Map()
for (const file of routes) {
const normalizedFile = normalizeSlashes(file)
const routeExt = path.extname(normalizedFile)
let pathWithoutExt = normalizedFile.slice(
0,
0 - routeExt.length - suffix.length,
)
if (indexNames.includes(path.basename(pathWithoutExt))) {
const segments = pathWithoutExt
.split("/")
.filter((segment) => !segment.endsWith("+"))
if (segments.length > 2) {
// if length = 1 they're in the app directory
// if length = 2 this is the site index
// so if length > 2, they're in a subdirectory we can surface
segments.pop()
pathWithoutExt = segments.join("/")
}
}
const ancestorSegments = pathWithoutExt
.split("/")
.filter((segment) => segment.endsWith("+"))
.map((segment) => segment.slice(0, -1))
// If there's off by one errors, it's the .
const basename = path.basename(pathWithoutExt)
const routeId = [...ancestorSegments, basename.slice(prefix.length)].join(
".",
)
const conflict = routeIds.get(routeId)
if (conflict) {
let currentConflicts = routeIdConflicts.get(routeId)
if (!currentConflicts) {
currentConflicts = [conflict]
}
currentConflicts.push(normalizedFile)
routeIdConflicts.set(routeId, currentConflicts)
continue
}
routeIds.set(routeId, normalizedFile)
}
if (routeIdConflicts.size > 0) {
for (const [id, files] of routeIdConflicts.entries()) {
console.error(getRouteIdConflictErrorMessage(id, files))
}
}
return Array.from(routeIds).sort(([a], [b]) => b.length - a.length)
}
/**
* @param {[string, string][]} sortedRouteIds
*/
function getRouteManifest(sortedRouteIds) {
/** @type {RouteManifest} */
const routeManifest = {}
const prefixLookup = new PrefixLookupTrie()
for (const [id, file] of sortedRouteIds) {
routeManifest[id] = {
file,
id,
index: id.endsWith("_index"),
path: getRouteSegments(id),
}
const childRouteIds = prefixLookup.findAndRemove(id, (value) => {
return [".", "/"].includes(value.slice(id.length).charAt(0))
})
prefixLookup.add(id)
if (childRouteIds.length > 0) {
for (const childRouteId of childRouteIds) {
routeManifest[childRouteId].parentId = id
}
}
}
const urlConflicts = new Map()
const uniqueRoutes = new Map()
for (const [id] of sortedRouteIds) {
const route = routeManifest[id]
const originalPathname = route.path || ""
let pathname = route.path
const parentConfig = route.parentId ? routeManifest[route.parentId] : null
if (parentConfig?.path && pathname) {
pathname = pathname
.slice(parentConfig.path.length)
.replace(/^\//, "")
.replace(/\/$/, "")
}
const conflictRouteId = originalPathname + (route.index ? "?index" : "")
const conflict = uniqueRoutes.get(conflictRouteId)
if (!route.parentId) route.parentId = "root"
route.path = pathname || undefined
uniqueRoutes.set(conflictRouteId, route)
if (conflict && (originalPathname || route.index)) {
let currentConflicts = urlConflicts.get(originalPathname)
if (!currentConflicts) currentConflicts = [conflict]
currentConflicts.push(route)
urlConflicts.set(originalPathname, currentConflicts)
continue
}
}
// report conflicts
if (urlConflicts.size > 0) {
for (const [path, routes] of urlConflicts.entries()) {
// delete all but the first route from the manifest
for (let i = 1; i < routes.length; i++) {
delete routeManifest[routes[i].id]
}
const files = routes.map((r) => r.file)
console.error(getRoutePathConflictErrorMessage(path, files))
}
}
return routeManifest
}
/**
* @param {string} routeId
*/
function getRouteSegments(routeId) {
/** @type string[] */
const routeSegments = []
/** @type string[] */
const rawRouteSegments = []
/** @type "NORMAL" | "ESCAPE" | "OPTIONAL" | "OPTIONAL_ESCAPE" */
let state = "NORMAL"
let index = 0
let routeSegment = ""
let rawRouteSegment = ""
while (index < routeId.length) {
const char = routeId[index]
index++ //advance to next char
switch (state) {
case "NORMAL": {
if (isSegmentSeparator(char)) {
pushRouteSegment(routeSegment, rawRouteSegment)
routeSegment = ""
rawRouteSegment = ""
state = "NORMAL"
break
}
if (char === escapeStart) {
state = "ESCAPE"
rawRouteSegment += char
break
}
if (char === optionalStart) {
state = "OPTIONAL"
rawRouteSegment += char
break
}
if (!routeSegment && char == paramPrefixChar) {
if (index === routeId.length) {
routeSegment += "*"
rawRouteSegment += char
} else {
routeSegment += ":"
rawRouteSegment += char
}
break
}
routeSegment += char
rawRouteSegment += char
break
}
case "ESCAPE": {
if (char === escapeEnd) {
state = "NORMAL"
rawRouteSegment += char
break
}
routeSegment += char
rawRouteSegment += char
break
}
case "OPTIONAL": {
if (char === optionalEnd) {
routeSegment += "?"
rawRouteSegment += char
state = "NORMAL"
break
}
if (char === escapeStart) {
state = "OPTIONAL_ESCAPE"
rawRouteSegment += char
break
}
if (!routeSegment && char === paramPrefixChar) {
if (index === routeId.length) {
routeSegment += "*"
rawRouteSegment += char
} else {
routeSegment += ":"
rawRouteSegment += char
}
break
}
routeSegment += char
rawRouteSegment += char
break
}
case "OPTIONAL_ESCAPE": {
if (char === escapeEnd) {
state = "OPTIONAL"
rawRouteSegment += char
break
}
routeSegment += char
rawRouteSegment += char
break
}
}
}
// process remaining segment
pushRouteSegment(routeSegment, rawRouteSegment)
if (routeId.endsWith("_index")) {
routeSegments.pop()
}
/** @type string[] */
const result = []
for (let index = 0; index < routeSegments.length; index++) {
const segment = routeSegments[index]
const rawSegment = rawRouteSegments[index]
// skip pathless layout segments
if (
segment.startsWith("_") &&
rawSegment.replace(optionalStart, "").startsWith("_") // "_index?" should match "(_[i]ndex)"
) {
continue
}
// remove trailing slash
if (segment.endsWith("_") && rawSegment.endsWith("_")) {
result.push(segment.slice(0, -1))
} else {
result.push(segment)
}
}
return result.length ? result.join("/") : undefined
/**
*
* @param {string} segment
* @param {string} rawSegment
* @returns {void}
*/
function pushRouteSegment(segment, rawSegment) {
if (!segment) return
if (rawSegment.includes("*")) {
return notSupportedInRR(rawSegment, "*")
}
if (rawSegment.includes(":")) {
return notSupportedInRR(rawSegment, ":")
}
if (rawSegment.includes("/")) {
return notSupportedInRR(segment, "/")
}
routeSegments.push(segment)
rawRouteSegments.push(rawSegment)
function notSupportedInRR(segment, char) {
throw new Error(
`Route segment "${segment}" for "${routeId}" cannot contain "${char}".\n` +
`If this is something you need, upvote this proposal for React Router https://github.com/remix-run/react-router/discussions/9822.`,
)
}
}
}
/**
* @param {string} pathname
* @param {string[]} routes
*/
function getRoutePathConflictErrorMessage(pathname, routes) {
const [taken, ...others] = routes
if (!pathname.startsWith("/")) {
pathname = "/" + pathname
}
return (
`⚠️ Route Path Collision: "${pathname}"\n\n` +
`The following routes all define the same URL, only the first one will be used\n\n` +
`🟢 ${taken}\n` +
others.map((route) => `⭕️️ ${route}`).join("\n") +
"\n"
)
}
/**
* @param {string} routeId
* @param {string[]} files
*/
function getRouteIdConflictErrorMessage(routeId, files) {
const [taken, ...others] = files
return (
`⚠️ Route ID Collision: "${routeId}"\n\n` +
`The following routes all define the same Route ID, only the first one will be used\n\n` +
`🟢 ${taken}\n` +
others.map((route) => `⭕️️ ${route}`).join("\n") +
"\n"
)
}