-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
create.ts
903 lines (798 loc) · 27.4 KB
/
create.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
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
import type {
AstroConfig,
AstroSettings,
ManifestData,
RouteData,
RoutePart,
RoutePriorityOverride,
} from '../../../@types/astro.js';
import type { Logger } from '../../logger/core.js';
import { createRequire } from 'module';
import nodeFs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { bold } from 'kleur/colors';
import { toRoutingStrategy } from '../../../i18n/utils.js';
import { getPrerenderDefault } from '../../../prerender/utils.js';
import { SUPPORTED_MARKDOWN_FILE_EXTENSIONS } from '../../constants.js';
import { MissingIndexForInternationalization } from '../../errors/errors-data.js';
import { AstroError } from '../../errors/index.js';
import { removeLeadingForwardSlash, slash } from '../../path.js';
import { resolvePages } from '../../util.js';
import { getRouteGenerator } from './generator.js';
const require = createRequire(import.meta.url);
interface Item {
basename: string;
ext: string;
parts: RoutePart[];
file: string;
isDir: boolean;
isIndex: boolean;
isPage: boolean;
routeSuffix: string;
}
function countOccurrences(needle: string, haystack: string) {
let count = 0;
for (const hay of haystack) {
if (hay === needle) count += 1;
}
return count;
}
// Disable eslint as we're not sure how to improve this regex yet
// eslint-disable-next-line regexp/no-super-linear-backtracking
const ROUTE_DYNAMIC_SPLIT = /\[(.+?\(.+?\)|.+?)\]/;
const ROUTE_SPREAD = /^\.{3}.+$/;
function getParts(part: string, file: string) {
const result: RoutePart[] = [];
part.split(ROUTE_DYNAMIC_SPLIT).map((str, i) => {
if (!str) return;
const dynamic = i % 2 === 1;
const [, content] = dynamic ? /([^(]+)$/.exec(str) || [null, null] : [null, str];
if (!content || (dynamic && !/^(?:\.\.\.)?[\w$]+$/.test(content))) {
throw new Error(`Invalid route ${file} — parameter name must match /^[a-zA-Z0-9_$]+$/`);
}
result.push({
content,
dynamic,
spread: dynamic && ROUTE_SPREAD.test(content),
});
});
return result;
}
function getPattern(
segments: RoutePart[][],
config: AstroConfig,
addTrailingSlash: AstroConfig['trailingSlash']
) {
const base = config.base;
const pathname = segments
.map((segment) => {
if (segment.length === 1 && segment[0].spread) {
return '(?:\\/(.*?))?';
} else {
return (
'\\/' +
segment
.map((part) => {
if (part.spread) {
return '(.*?)';
} else if (part.dynamic) {
return '([^/]+?)';
} else {
return part.content
.normalize()
.replace(/\?/g, '%3F')
.replace(/#/g, '%23')
.replace(/%5B/g, '[')
.replace(/%5D/g, ']')
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
})
.join('')
);
}
})
.join('');
const trailing =
addTrailingSlash && segments.length ? getTrailingSlashPattern(addTrailingSlash) : '$';
let initial = '\\/';
if (addTrailingSlash === 'never' && base !== '/') {
initial = '';
}
return new RegExp(`^${pathname || initial}${trailing}`);
}
function getTrailingSlashPattern(addTrailingSlash: AstroConfig['trailingSlash']): string {
if (addTrailingSlash === 'always') {
return '\\/$';
}
if (addTrailingSlash === 'never') {
return '$';
}
return '\\/?$';
}
function validateSegment(segment: string, file = '') {
if (!file) file = segment;
if (/\]\[/.test(segment)) {
throw new Error(`Invalid route ${file} \u2014 parameters must be separated`);
}
if (countOccurrences('[', segment) !== countOccurrences(']', segment)) {
throw new Error(`Invalid route ${file} \u2014 brackets are unbalanced`);
}
if (
(/.+\[\.\.\.[^\]]+\]/.test(segment) || /\[\.\.\.[^\]]+\].+/.test(segment)) &&
file.endsWith('.astro')
) {
throw new Error(`Invalid route ${file} \u2014 rest parameter must be a standalone segment`);
}
}
/**
* Checks whether two route segments are semantically equivalent.
*
* Two segments are equivalent if they would match the same paths. This happens when:
* - They have the same length.
* - Each part in the same position is either:
* - Both static and with the same content (e.g. `/foo` and `/foo`).
* - Both dynamic, regardless of the content (e.g. `/[bar]` and `/[baz]`).
* - Both rest parameters, regardless of the content (e.g. `/[...bar]` and `/[...baz]`).
*/
function isSemanticallyEqualSegment(segmentA: RoutePart[], segmentB: RoutePart[]) {
if (segmentA.length !== segmentB.length) {
return false;
}
for (const [index, partA] of segmentA.entries()) {
// Safe to use the index of one segment for the other because the segments have the same length
const partB = segmentB[index];
if (partA.dynamic !== partB.dynamic || partA.spread !== partB.spread) {
return false;
}
// Only compare the content on non-dynamic segments
// `/[bar]` and `/[baz]` are effectively the same route,
// only bound to a different path parameter.
if (!partA.dynamic && partA.content !== partB.content) {
return false;
}
}
return true;
}
/**
* Comparator for sorting routes in resolution order.
*
* The routes are sorted in by the following rules in order, following the first rule that
* applies:
* - More specific routes are sorted before less specific routes. Here, "specific" means
* the number of segments in the route, so a parent route is always sorted after its children.
* For example, `/foo/bar` is sorted before `/foo`.
* Index routes, originating from a file named `index.astro`, are considered to have one more
* segment than the URL they represent.
* - Static routes are sorted before dynamic routes.
* For example, `/foo/bar` is sorted before `/foo/[bar]`.
* - Dynamic routes with single parameters are sorted before dynamic routes with rest parameters.
* For example, `/foo/[bar]` is sorted before `/foo/[...bar]`.
* - Prerendered routes are sorted before non-prerendered routes.
* - Endpoints are sorted before pages.
* For example, a file `/foo.ts` is sorted before `/bar.astro`.
* - If both routes are equal regarding all previosu conditions, they are sorted alphabetically.
* For example, `/bar` is sorted before `/foo`.
* The definition of "alphabetically" is dependent on the default locale of the running system.
*/
function routeComparator(a: RouteData, b: RouteData) {
const commonLength = Math.min(a.segments.length, b.segments.length);
for (let index = 0; index < commonLength; index++) {
const aSegment = a.segments[index];
const bSegment = b.segments[index];
const aIsStatic = aSegment.every((part) => !part.dynamic && !part.spread);
const bIsStatic = bSegment.every((part) => !part.dynamic && !part.spread);
if (aIsStatic && bIsStatic) {
// Both segments are static, they are sorted alphabetically if they are different
const aContent = aSegment.map((part) => part.content).join('');
const bContent = bSegment.map((part) => part.content).join('');
if (aContent !== bContent) {
return aContent.localeCompare(bContent);
}
}
// Sort static routes before dynamic routes
if (aIsStatic !== bIsStatic) {
return aIsStatic ? -1 : 1;
}
const aAllDynamic = aSegment.every((part) => part.dynamic);
const bAllDynamic = bSegment.every((part) => part.dynamic);
// Some route might have partial dynamic segments, e.g. game-[title].astro
// These routes should have higher priority against route that have **only** dynamic segments, e.g. [title].astro
if (aAllDynamic !== bAllDynamic) {
return aAllDynamic ? 1 : -1;
}
const aHasSpread = aSegment.some((part) => part.spread);
const bHasSpread = bSegment.some((part) => part.spread);
// Sort dynamic routes with rest parameters after dynamic routes with single parameters
// (also after static, but that is already covered by the previous condition)
if (aHasSpread !== bHasSpread) {
return aHasSpread ? 1 : -1;
}
}
const aLength = a.segments.length;
const bLength = b.segments.length;
if (aLength !== bLength) {
const aEndsInRest = a.segments.at(-1)?.some((part) => part.spread);
const bEndsInRest = b.segments.at(-1)?.some((part) => part.spread);
if (aEndsInRest !== bEndsInRest && Math.abs(aLength - bLength) === 1) {
// If only one of the routes ends in a rest parameter
// and the difference in length is exactly 1
// and the shorter route is the one that ends in a rest parameter
// the shorter route is considered more specific.
// I.e. `/foo` is considered more specific than `/foo/[...bar]`
if (aLength > bLength && aEndsInRest) {
// b: /foo
// a: /foo/[...bar]
return 1;
}
if (bLength > aLength && bEndsInRest) {
// a: /foo
// b: /foo/[...bar]
return -1;
}
}
// Sort routes by length
return aLength > bLength ? -1 : 1;
}
// Sort endpoints before pages
if ((a.type === 'endpoint') !== (b.type === 'endpoint')) {
return a.type === 'endpoint' ? -1 : 1;
}
// Both routes have segments with the same properties
return a.route.localeCompare(b.route);
}
export interface CreateRouteManifestParams {
/** Astro Settings object */
settings: AstroSettings;
/** Current working directory */
cwd?: string;
/** fs module, for testing */
fsMod?: typeof nodeFs;
}
function createFileBasedRoutes(
{ settings, cwd, fsMod }: CreateRouteManifestParams,
logger: Logger
): RouteData[] {
const components: string[] = [];
const routes: RouteData[] = [];
const validPageExtensions = new Set<string>([
'.astro',
...SUPPORTED_MARKDOWN_FILE_EXTENSIONS,
...settings.pageExtensions,
]);
const validEndpointExtensions = new Set<string>(['.js', '.ts']);
const localFs = fsMod ?? nodeFs;
const prerender = getPrerenderDefault(settings.config);
function walk(
fs: typeof nodeFs,
dir: string,
parentSegments: RoutePart[][],
parentParams: string[]
) {
let items: Item[] = [];
const files = fs.readdirSync(dir);
for (const basename of files) {
const resolved = path.join(dir, basename);
const file = slash(path.relative(cwd || fileURLToPath(settings.config.root), resolved));
const isDir = fs.statSync(resolved).isDirectory();
const ext = path.extname(basename);
const name = ext ? basename.slice(0, -ext.length) : basename;
if (name[0] === '_') {
continue;
}
if (basename[0] === '.' && basename !== '.well-known') {
continue;
}
// filter out "foo.astro_tmp" files, etc
if (!isDir && !validPageExtensions.has(ext) && !validEndpointExtensions.has(ext)) {
logger.warn(
null,
`Unsupported file type ${bold(
resolved
)} found. Prefix filename with an underscore (\`_\`) to ignore.`
);
continue;
}
const segment = isDir ? basename : name;
validateSegment(segment, file);
const parts = getParts(segment, file);
const isIndex = isDir ? false : basename.startsWith('index.');
const routeSuffix = basename.slice(basename.indexOf('.'), -ext.length);
const isPage = validPageExtensions.has(ext);
items.push({
basename,
ext,
parts,
file: file.replace(/\\/g, '/'),
isDir,
isIndex,
isPage,
routeSuffix,
});
}
for (const item of items) {
const segments = parentSegments.slice();
if (item.isIndex) {
if (item.routeSuffix) {
if (segments.length > 0) {
const lastSegment = segments[segments.length - 1].slice();
const lastPart = lastSegment[lastSegment.length - 1];
if (lastPart.dynamic) {
lastSegment.push({
dynamic: false,
spread: false,
content: item.routeSuffix,
});
} else {
lastSegment[lastSegment.length - 1] = {
dynamic: false,
spread: false,
content: `${lastPart.content}${item.routeSuffix}`,
};
}
segments[segments.length - 1] = lastSegment;
} else {
segments.push(item.parts);
}
}
} else {
segments.push(item.parts);
}
const params = parentParams.slice();
params.push(...item.parts.filter((p) => p.dynamic).map((p) => p.content));
if (item.isDir) {
walk(fsMod ?? fs, path.join(dir, item.basename), segments, params);
} else {
components.push(item.file);
const component = item.file;
const { trailingSlash } = settings.config;
const pattern = getPattern(segments, settings.config, trailingSlash);
const generate = getRouteGenerator(segments, trailingSlash);
const pathname = segments.every((segment) => segment.length === 1 && !segment[0].dynamic)
? `/${segments.map((segment) => segment[0].content).join('/')}`
: null;
const route = joinSegments(segments);
routes.push({
route,
isIndex: item.isIndex,
type: item.isPage ? 'page' : 'endpoint',
pattern,
segments,
params,
component,
generate,
pathname: pathname || undefined,
prerender,
fallbackRoutes: [],
});
}
}
}
const { config } = settings;
const pages = resolvePages(config);
if (localFs.existsSync(pages)) {
walk(localFs, fileURLToPath(pages), [], []);
} else if (settings.injectedRoutes.length === 0) {
const pagesDirRootRelative = pages.href.slice(settings.config.root.href.length);
logger.warn(null, `Missing pages directory: ${pagesDirRootRelative}`);
}
return routes;
}
type PrioritizedRoutesData = Record<RoutePriorityOverride, RouteData[]>;
function createInjectedRoutes({ settings, cwd }: CreateRouteManifestParams): PrioritizedRoutesData {
const { config } = settings;
const prerender = getPrerenderDefault(config);
const routes: PrioritizedRoutesData = {
normal: [],
legacy: [],
};
const priority = computeRoutePriority(config);
for (const injectedRoute of settings.injectedRoutes) {
const { pattern: name, entrypoint, prerender: prerenderInjected } = injectedRoute;
let resolved: string;
try {
resolved = require.resolve(entrypoint, { paths: [cwd || fileURLToPath(config.root)] });
} catch (e) {
resolved = fileURLToPath(new URL(entrypoint, config.root));
}
const component = slash(path.relative(cwd || fileURLToPath(config.root), resolved));
const segments = removeLeadingForwardSlash(name)
.split(path.posix.sep)
.filter(Boolean)
.map((s: string) => {
validateSegment(s);
return getParts(s, component);
});
const type = resolved.endsWith('.astro') ? 'page' : 'endpoint';
const isPage = type === 'page';
const trailingSlash = isPage ? config.trailingSlash : 'never';
const pattern = getPattern(segments, settings.config, trailingSlash);
const generate = getRouteGenerator(segments, trailingSlash);
const pathname = segments.every((segment) => segment.length === 1 && !segment[0].dynamic)
? `/${segments.map((segment) => segment[0].content).join('/')}`
: null;
const params = segments
.flat()
.filter((p) => p.dynamic)
.map((p) => p.content);
const route = joinSegments(segments);
routes[priority].push({
type,
// For backwards compatibility, an injected route is never considered an index route.
isIndex: false,
route,
pattern,
segments,
params,
component,
generate,
pathname: pathname || void 0,
prerender: prerenderInjected ?? prerender,
fallbackRoutes: [],
});
}
return routes;
}
/**
* Create route data for all configured redirects.
*/
function createRedirectRoutes(
{ settings }: CreateRouteManifestParams,
routeMap: Map<string, RouteData>,
logger: Logger
): PrioritizedRoutesData {
const { config } = settings;
const trailingSlash = config.trailingSlash;
const routes: PrioritizedRoutesData = {
normal: [],
legacy: [],
};
const priority = computeRoutePriority(settings.config);
for (const [from, to] of Object.entries(settings.config.redirects)) {
const segments = removeLeadingForwardSlash(from)
.split(path.posix.sep)
.filter(Boolean)
.map((s: string) => {
validateSegment(s);
return getParts(s, from);
});
const pattern = getPattern(segments, settings.config, trailingSlash);
const generate = getRouteGenerator(segments, trailingSlash);
const pathname = segments.every((segment) => segment.length === 1 && !segment[0].dynamic)
? `/${segments.map((segment) => segment[0].content).join('/')}`
: null;
const params = segments
.flat()
.filter((p) => p.dynamic)
.map((p) => p.content);
const route = joinSegments(segments);
let destination: string;
if (typeof to === 'string') {
destination = to;
} else {
destination = to.destination;
}
if (/^https?:\/\//.test(destination)) {
logger.warn(
'redirects',
`Redirecting to an external URL is not officially supported: ${from} -> ${destination}`
);
}
routes[priority].push({
type: 'redirect',
// For backwards compatibility, a redirect is never considered an index route.
isIndex: false,
route,
pattern,
segments,
params,
component: from,
generate,
pathname: pathname || void 0,
prerender: false,
redirect: to,
redirectRoute: routeMap.get(destination),
fallbackRoutes: [],
});
}
return routes;
}
/**
* Checks whether a route segment is static.
*/
function isStaticSegment(segment: RoutePart[]) {
return segment.every((part) => !part.dynamic && !part.spread);
}
/**
* Check whether two are sure to collide in clearly unintended ways report appropriately.
*
* Fallback routes are never considered to collide with any other route.
* Routes that may collide depending on the parameters returned by their `getStaticPaths`
* are not reported as collisions at this stage.
*
* Two routes are guarantted to collide in the following scenarios:
* - Both are the exact same static route.
* For example, `/foo` from an injected route and `/foo` from a file in the project.
* - Both are non-prerendered dynamic routes with equal static parts in matching positions
* and dynamic parts of same type in the same positions.
* For example, `/foo/[bar]` and `/foo/[baz]` or `/foo/[...bar]` and `/foo/[...baz]`
* but not `/foo/[bar]` and `/foo/[...baz]`.
*/
function detectRouteCollision(a: RouteData, b: RouteData, config: AstroConfig, logger: Logger) {
if (a.type === 'fallback' || b.type === 'fallback') {
// If either route is a fallback route, they don't collide.
// Fallbacks are always added below other routes exactly to avoid collisions.
return;
}
if (
a.route === b.route &&
a.segments.every(isStaticSegment) &&
b.segments.every(isStaticSegment)
) {
// If both routes are the same and completely static they are guaranteed to collide
// such that one of them will never be matched.
logger.warn(
'router',
`The route "${a.route}" is defined in both "${a.component}" and "${b.component}". A static route cannot be defined more than once.`
);
logger.warn(
'router',
'A collision will result in an hard error in following versions of Astro.'
);
return;
}
if (a.prerender || b.prerender) {
// If either route is prerendered, it is impossible to know if they collide
// at this stage because it depends on the parameters returned by `getStaticPaths`.
return;
}
if (a.segments.length !== b.segments.length) {
// If the routes have different number of segments, they cannot perfectly overlap
// each other, so a collision is either not guaranteed or may be intentional.
return;
}
// Routes have the same number of segments, can use either.
const segmentCount = a.segments.length;
for (let index = 0; index < segmentCount; index++) {
const segmentA = a.segments[index];
const segmentB = b.segments[index];
if (!isSemanticallyEqualSegment(segmentA, segmentB)) {
// If any segment is not semantically equal between the routes
// it is not certain that the routes collide.
return;
}
}
// Both routes are guaranteed to collide such that one will never be matched.
logger.warn(
'router',
`The route "${a.route}" is defined in both "${a.component}" and "${b.component}" using SSR mode. A dynamic SSR route cannot be defined more than once.`
);
logger.warn('router', 'A collision will result in an hard error in following versions of Astro.');
}
/** Create manifest of all static routes */
export function createRouteManifest(
params: CreateRouteManifestParams,
logger: Logger
): ManifestData {
const { settings } = params;
const { config } = settings;
// Create a map of all routes so redirects can refer to any route
const routeMap = new Map();
const fileBasedRoutes = createFileBasedRoutes(params, logger);
for (const route of fileBasedRoutes) {
routeMap.set(route.route, route);
}
const injectedRoutes = createInjectedRoutes(params);
for (const [, routes] of Object.entries(injectedRoutes)) {
for (const route of routes) {
routeMap.set(route.route, route);
}
}
const redirectRoutes = createRedirectRoutes(params, routeMap, logger);
const routes: RouteData[] = [
...injectedRoutes['legacy'].sort(routeComparator),
...[...fileBasedRoutes, ...injectedRoutes['normal'], ...redirectRoutes['normal']].sort(
routeComparator
),
...redirectRoutes['legacy'].sort(routeComparator),
];
// Report route collisions
if (config.experimental.globalRoutePriority) {
for (const [index, higherRoute] of routes.entries()) {
for (const lowerRoute of routes.slice(index + 1)) {
detectRouteCollision(higherRoute, lowerRoute, config, logger);
}
}
}
const i18n = settings.config.i18n;
if (i18n) {
const strategy = toRoutingStrategy(i18n);
// First we check if the user doesn't have an index page.
if (strategy === 'pathname-prefix-always') {
let index = routes.find((route) => route.route === '/');
if (!index) {
let relativePath = path.relative(
fileURLToPath(settings.config.root),
fileURLToPath(new URL('pages', settings.config.srcDir))
);
throw new AstroError({
...MissingIndexForInternationalization,
message: MissingIndexForInternationalization.message(i18n.defaultLocale),
hint: MissingIndexForInternationalization.hint(relativePath),
});
}
}
// In this block of code we group routes based on their locale
// A map like: locale => RouteData[]
const routesByLocale = new Map<string, RouteData[]>();
// This type is here only as a helper. We copy the routes and make them unique, so we don't "process" the same route twice.
// The assumption is that a route in the file system belongs to only one locale.
const setRoutes = new Set(routes.filter((route) => route.type === 'page'));
// First loop
// We loop over the locales minus the default locale and add only the routes that contain `/<locale>`.
const filteredLocales = i18n.locales
.filter((loc) => {
if (typeof loc === 'string') {
return loc !== i18n.defaultLocale;
}
return loc.path !== i18n.defaultLocale;
})
.map((locale) => {
if (typeof locale === 'string') {
return locale;
}
return locale.path;
});
for (const locale of filteredLocales) {
for (const route of setRoutes) {
if (!route.route.includes(`/${locale}`)) {
continue;
}
const currentRoutes = routesByLocale.get(locale);
if (currentRoutes) {
currentRoutes.push(route);
routesByLocale.set(locale, currentRoutes);
} else {
routesByLocale.set(locale, [route]);
}
setRoutes.delete(route);
}
}
// we loop over the remaining routes and add them to the default locale
for (const route of setRoutes) {
const currentRoutes = routesByLocale.get(i18n.defaultLocale);
if (currentRoutes) {
currentRoutes.push(route);
routesByLocale.set(i18n.defaultLocale, currentRoutes);
} else {
routesByLocale.set(i18n.defaultLocale, [route]);
}
setRoutes.delete(route);
}
// Work done, now we start creating "fallback" routes based on the configuration
if (strategy === 'pathname-prefix-always') {
// we attempt to retrieve the index page of the default locale
const defaultLocaleRoutes = routesByLocale.get(i18n.defaultLocale);
if (defaultLocaleRoutes) {
// The index for the default locale will be either already at the root path
// or at the root of the locale.
const indexDefaultRoute =
defaultLocaleRoutes.find(({ route }) => route === '/') ??
defaultLocaleRoutes.find(({ route }) => route === `/${i18n.defaultLocale}`);
if (indexDefaultRoute) {
// we found the index of the default locale, now we create a root index that will redirect to the index of the default locale
const pathname = '/';
const route = '/';
const segments = removeLeadingForwardSlash(route)
.split(path.posix.sep)
.filter(Boolean)
.map((s: string) => {
validateSegment(s);
return getParts(s, route);
});
routes.push({
...indexDefaultRoute,
pathname,
route,
segments,
pattern: getPattern(segments, config, config.trailingSlash),
type: 'fallback',
});
}
}
}
if (i18n.fallback) {
let fallback = Object.entries(i18n.fallback);
if (fallback.length > 0) {
for (const [fallbackFromLocale, fallbackToLocale] of fallback) {
let fallbackToRoutes;
if (fallbackToLocale === i18n.defaultLocale) {
fallbackToRoutes = routesByLocale.get(i18n.defaultLocale);
} else {
fallbackToRoutes = routesByLocale.get(fallbackToLocale);
}
const fallbackFromRoutes = routesByLocale.get(fallbackFromLocale);
// Technically, we should always have a fallback to. Added this to make TS happy.
if (!fallbackToRoutes) {
continue;
}
for (const fallbackToRoute of fallbackToRoutes) {
const hasRoute =
fallbackFromRoutes &&
// we check if the fallback from locale (the origin) has already this route
fallbackFromRoutes.some((route) => {
if (fallbackToLocale === i18n.defaultLocale) {
return (
route.route.replace(`/${fallbackFromLocale}`, '') === fallbackToRoute.route
);
} else {
return (
route.route.replace(`/${fallbackToLocale}`, `/${fallbackFromLocale}`) ===
fallbackToRoute.route
);
}
});
if (!hasRoute) {
let pathname: string | undefined;
let route: string;
if (
fallbackToLocale === i18n.defaultLocale &&
strategy === 'pathname-prefix-other-locales'
) {
if (fallbackToRoute.pathname) {
pathname = `/${fallbackFromLocale}${fallbackToRoute.pathname}`;
}
route = `/${fallbackFromLocale}${fallbackToRoute.route}`;
} else {
pathname = fallbackToRoute.pathname
?.replace(`/${fallbackToLocale}/`, `/${fallbackFromLocale}/`)
.replace(`/${fallbackToLocale}`, `/${fallbackFromLocale}`);
route = fallbackToRoute.route
.replace(`/${fallbackToLocale}`, `/${fallbackFromLocale}`)
.replace(`/${fallbackToLocale}/`, `/${fallbackFromLocale}/`);
}
const segments = removeLeadingForwardSlash(route)
.split(path.posix.sep)
.filter(Boolean)
.map((s: string) => {
validateSegment(s);
return getParts(s, route);
});
const generate = getRouteGenerator(segments, config.trailingSlash);
const index = routes.findIndex((r) => r === fallbackToRoute);
if (index >= 0) {
const fallbackRoute: RouteData = {
...fallbackToRoute,
pathname,
route,
segments,
generate,
pattern: getPattern(segments, config, config.trailingSlash),
type: 'fallback',
fallbackRoutes: [],
};
const routeData = routes[index];
routeData.fallbackRoutes.push(fallbackRoute);
}
}
}
}
}
}
}
return {
routes,
};
}
function computeRoutePriority(config: AstroConfig): RoutePriorityOverride {
if (config.experimental.globalRoutePriority) {
return 'normal';
}
return 'legacy';
}
function joinSegments(segments: RoutePart[][]): string {
const arr = segments.map((segment) => {
return segment.map((rp) => (rp.dynamic ? `[${rp.content}]` : rp.content)).join('');
});
return `/${arr.join('/')}`.toLowerCase();
}