@se-studio/project-build 1.1.20 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2538 @@
1
+ /**
2
+ * Marketing page allowlist and thin route generator.
3
+ *
4
+ * A URL is a Contentful slug unless it is the CMS catch-all, an article type,
5
+ * a person type under the people base, or a fixed misc route.
6
+ * `src/lib/marketing-routes.json` names the article bases and the person types.
7
+ * Extra `page.ts` / `page.tsx` files fail. Generated pages, flags, and the
8
+ * markdown rewrite module must match this file.
9
+ *
10
+ * @see docs/CUSTOMER_APP_SKELETON.md
11
+ */
12
+
13
+ import { spawnSync } from 'node:child_process';
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+
17
+ export const GENERATED_MARK =
18
+ '/** @generated by scripts/generate-marketing-routes.mjs — do not edit */';
19
+
20
+ const SEGMENT = /^[a-z0-9-]+$/;
21
+
22
+ /** Typed people live here, not under the people base, so the dynamic names do not collide. */
23
+ const PERSON_TYPE_ROOT = 'peopleType';
24
+
25
+ /** Boolean switches written to `src/generated/marketing-flags.ts`. */
26
+ export const MARKETING_FLAG_NAMES = [
27
+ 'enableArticleTypeIndex',
28
+ 'enableArticleTypeTagIndex',
29
+ 'enableTag',
30
+ 'enableTagsIndex',
31
+ 'enablePerson',
32
+ 'enablePeopleIndex',
33
+ 'enablePrimaryTagPartOfSlug',
34
+ ];
35
+
36
+ const FLAGS_REL = 'src/generated/marketing-flags.ts';
37
+ const SLUGS_REL = 'src/generated/marketing-slugs.ts';
38
+ const MARKDOWN_NEGOTIATION_REL = 'src/generated/markdown-negotiation.ts';
39
+
40
+ /**
41
+ * CMS section config. `peopleSlug` may be null. Distinct from hand-written
42
+ * `articleBases` / `personBases`.
43
+ *
44
+ * @param {unknown} config
45
+ */
46
+ export function isSectionConfig(config) {
47
+ return (
48
+ !!config &&
49
+ typeof config === 'object' &&
50
+ (Object.prototype.hasOwnProperty.call(config, 'peopleSlug') ||
51
+ Array.isArray(config.personTypes))
52
+ );
53
+ }
54
+
55
+ /**
56
+ * @param {Record<string, unknown>} config
57
+ */
58
+ export function sectionFlags(config) {
59
+ const people = typeof config.peopleSlug === 'string' && config.peopleSlug.length > 0;
60
+ const personTypes = Array.isArray(config.personTypes) && config.personTypes.length > 0;
61
+ const tags = typeof config.tagsSlug === 'string' && config.tagsSlug.length > 0;
62
+ const tagTypes = Array.isArray(config.tagTypes) && config.tagTypes.length > 0;
63
+ const articles = typeof config.articlesSlug === 'string';
64
+ const articleTypes = Array.isArray(config.articleTypes) && config.articleTypes.length > 0;
65
+ const tagInPath = config.tagInPath === true;
66
+ return {
67
+ enableArticleTypeIndex: articles || articleTypes,
68
+ enableArticleTypeTagIndex: tagInPath && (articles || articleTypes),
69
+ enableTag: tags || tagTypes,
70
+ enableTagsIndex: tags,
71
+ enablePerson: people || personTypes,
72
+ enablePeopleIndex: people,
73
+ enablePrimaryTagPartOfSlug: tagInPath,
74
+ };
75
+ }
76
+
77
+ /**
78
+ * @param {unknown} config
79
+ * @returns {Set<string>} route rests under `(cms-routes)/`, `''` is the home page
80
+ */
81
+ export function allowedRests(config) {
82
+ if (!config || typeof config !== 'object') {
83
+ throw new Error('marketing-routes.json must be an object');
84
+ }
85
+ /** @type {Set<string>} */
86
+ const allowed = new Set();
87
+ if (config.catchAll !== false) {
88
+ allowed.add('');
89
+ allowed.add('[level1]');
90
+ allowed.add('[level1]/[...slugs]');
91
+ }
92
+ if (config.pageTest === true) {
93
+ allowed.add('page-test/[...slugs]');
94
+ }
95
+ if (isSectionConfig(config)) {
96
+ addSectionRests(allowed, config);
97
+ return allowed;
98
+ }
99
+ if (config.tags === true) {
100
+ allowed.add('tags');
101
+ allowed.add('tags/[tag]');
102
+ }
103
+ const articles = Array.isArray(config.articleBases) ? config.articleBases : [];
104
+ for (const base of articles) {
105
+ const segment = requireSegment(base?.path, 'articleBases.path');
106
+ if (base.shape === 'dynamic') {
107
+ allowed.add(segment);
108
+ allowed.add(`${segment}/[articleType]`);
109
+ allowed.add(`${segment}/[articleType]/[...slugs]`);
110
+ if (base.tagInPath === true) {
111
+ allowed.add(`${segment}/[articleType]/[tag]`);
112
+ allowed.add(`${segment}/[articleType]/[tag]/[...slugs]`);
113
+ }
114
+ } else if (base.shape === 'fixed') {
115
+ allowed.add(segment);
116
+ allowed.add(`${segment}/[...slugs]`);
117
+ if (base.tagInPath === true) {
118
+ allowed.add(`${segment}/[tag]`);
119
+ allowed.add(`${segment}/[tag]/[...slugs]`);
120
+ }
121
+ } else {
122
+ throw new Error(`articleBases.shape for "${segment}" must be "fixed" or "dynamic"`);
123
+ }
124
+ }
125
+ const people = Array.isArray(config.personBases) ? config.personBases : [];
126
+ for (const base of people) {
127
+ const segment = requireSegment(base?.path, 'personBases.path');
128
+ if (base.index !== false) {
129
+ allowed.add(segment);
130
+ }
131
+ allowed.add(`${segment}/[person]`);
132
+ for (const type of personTypeNames(base)) {
133
+ allowed.add(`${segment}/${type}`);
134
+ allowed.add(`${segment}/${type}/[person]`);
135
+ }
136
+ }
137
+ if (people.length > 0) {
138
+ allowed.add(typedPersonRest());
139
+ }
140
+ return allowed;
141
+ }
142
+
143
+ /**
144
+ * @param {string} appRoot
145
+ */
146
+ export function readMarketingRoutes(appRoot) {
147
+ const configPath = path.join(appRoot, 'src/lib/marketing-routes.json');
148
+ if (!fs.existsSync(configPath)) {
149
+ return null;
150
+ }
151
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
152
+ }
153
+
154
+ /**
155
+ * @param {string} appRoot
156
+ * @returns {{ pages: string[], outside: string[] }}
157
+ */
158
+ export function listMarketingPages(appRoot) {
159
+ /** @type {string[]} */
160
+ const pages = [];
161
+ /** @type {string[]} */
162
+ const outside = [];
163
+ const appDir = path.join(appRoot, 'src/app');
164
+ if (!fs.existsSync(appDir)) {
165
+ return { pages, outside };
166
+ }
167
+ walk(appDir, (file) => {
168
+ const base = path.basename(file);
169
+ if (base !== 'page.ts' && base !== 'page.tsx') {
170
+ return;
171
+ }
172
+ const rel = path.relative(appRoot, file).split(path.sep).join('/');
173
+ if (rel.includes('/(cms-dev)/') || rel.startsWith('src/app/(cms-dev)/')) {
174
+ return;
175
+ }
176
+ if (isPreviewPage(rel)) {
177
+ return;
178
+ }
179
+ const rest = routeRestFromRel(rel);
180
+ if (rest === null) {
181
+ outside.push(rel);
182
+ return;
183
+ }
184
+ pages.push(rest);
185
+ });
186
+ return { pages, outside };
187
+ }
188
+
189
+ /**
190
+ * URL rest under `(cms-routes)`. Route groups are not segments, including a
191
+ * group nested inside `(cms-routes)` such as `(with-chrome)`.
192
+ *
193
+ * @param {string} rel posix path from the app root
194
+ * @returns {string|null} `''` is the home page; null when this is not a cms page
195
+ */
196
+ export function routeRestFromRel(rel) {
197
+ const marker = '(cms-routes)/';
198
+ const idx = rel.indexOf(marker);
199
+ if (idx === -1) {
200
+ return null;
201
+ }
202
+ let rest = rel.slice(idx + marker.length).replace(/\/page\.tsx?$/, '');
203
+ if (rest === 'page.ts' || rest === 'page.tsx') {
204
+ rest = '';
205
+ }
206
+ return rest
207
+ .split('/')
208
+ .filter((segment) => segment.length > 0 && !isRouteGroup(segment))
209
+ .join('/');
210
+ }
211
+
212
+ /**
213
+ * @param {string} appRoot
214
+ */
215
+ export function checkMarketingRoutes(appRoot) {
216
+ let config;
217
+ try {
218
+ config = readMarketingRoutes(appRoot);
219
+ } catch (error) {
220
+ const message = error instanceof Error ? error.message : String(error);
221
+ return { ok: false, severity: 'error', detail: `marketing-routes.json: ${message}` };
222
+ }
223
+ if (!config) {
224
+ return {
225
+ ok: true,
226
+ severity: 'warn',
227
+ detail: 'no src/lib/marketing-routes.json — extra page check skipped',
228
+ };
229
+ }
230
+ let allowed;
231
+ try {
232
+ allowed = allowedRests(config);
233
+ } catch (error) {
234
+ const message = error instanceof Error ? error.message : String(error);
235
+ return { ok: false, severity: 'error', detail: message };
236
+ }
237
+ const found = listMarketingPages(appRoot);
238
+ const extras = found.pages.filter((rest) => !allowed.has(rest));
239
+ const drift = generatedDrift(appRoot, config);
240
+ /** @type {string[]} */
241
+ const problems = [
242
+ ...found.outside,
243
+ ...extras.map((rest) => `(cms-routes)/${rest ? `${rest}/` : ''}page`),
244
+ ...drift,
245
+ ...supportDrift(appRoot, config),
246
+ ...policyProblems(appRoot, allowed),
247
+ ...proxyMarkdownProblems(appRoot),
248
+ ];
249
+ if (problems.length > 0) {
250
+ return {
251
+ ok: false,
252
+ severity: 'error',
253
+ detail: `page files outside marketing-routes.json: ${problems.join('; ')}`,
254
+ };
255
+ }
256
+ return {
257
+ ok: true,
258
+ detail: `${found.pages.length} cms page files match marketing-routes.json`,
259
+ };
260
+ }
261
+
262
+ /**
263
+ * Thin CMS pages described by marketing-routes.json. Person types are named
264
+ * segments under the people base. `[level1]` stays a generic page.
265
+ *
266
+ * A `tagInPath` base also gets its `[tag]` index and detail files.
267
+ *
268
+ * @param {unknown} config
269
+ * @returns {Map<string, string>} rest → file contents
270
+ */
271
+ export function renderGeneratedRoutes(config) {
272
+ if (!config || typeof config !== 'object') {
273
+ throw new Error('marketing-routes.json must be an object');
274
+ }
275
+ /** @type {Map<string, string>} */
276
+ const files = new Map();
277
+ if (config.catchAll !== false) {
278
+ files.set('', homePage());
279
+ files.set('[level1]', levelPage());
280
+ files.set('[level1]/[...slugs]', levelSlugsPage());
281
+ }
282
+ if (isSectionConfig(config)) {
283
+ renderSectionRoutes(config, files);
284
+ return files;
285
+ }
286
+ if (config.tags === true) {
287
+ files.set('tags', tagsIndexPage());
288
+ files.set('tags/[tag]', tagPage());
289
+ }
290
+ const articles = Array.isArray(config.articleBases) ? config.articleBases : [];
291
+ for (const base of articles) {
292
+ const segment = requireSegment(base?.path, 'articleBases.path');
293
+ if (base.shape === 'fixed') {
294
+ files.set(segment, fixedArticleIndex(segment));
295
+ files.set(`${segment}/[...slugs]`, fixedArticleDetail(segment));
296
+ if (base.tagInPath === true) {
297
+ files.set(`${segment}/[tag]`, fixedArticleTag(segment));
298
+ files.set(`${segment}/[tag]/[...slugs]`, fixedArticleTagDetail(segment));
299
+ }
300
+ } else if (base.shape === 'dynamic') {
301
+ files.set(segment, dynamicArticleIndex(segment));
302
+ files.set(`${segment}/[articleType]`, dynamicArticleType(segment));
303
+ files.set(`${segment}/[articleType]/[...slugs]`, dynamicArticleDetail(segment));
304
+ if (base.tagInPath === true) {
305
+ files.set(`${segment}/[articleType]/[tag]`, dynamicArticleTag(segment));
306
+ files.set(
307
+ `${segment}/[articleType]/[tag]/[...slugs]`,
308
+ dynamicArticleTagDetail(segment),
309
+ );
310
+ }
311
+ } else {
312
+ throw new Error(`articleBases.shape for "${segment}" must be "fixed" or "dynamic"`);
313
+ }
314
+ }
315
+ const people = Array.isArray(config.personBases) ? config.personBases : [];
316
+ for (const base of people) {
317
+ const segment = requireSegment(base?.path, 'personBases.path');
318
+ if (base.index !== false) {
319
+ files.set(segment, peopleIndexPage(segment));
320
+ }
321
+ files.set(`${segment}/[person]`, untypedPersonPage(segment));
322
+ for (const type of personTypeNames(base)) {
323
+ files.set(`${segment}/${type}`, personTypeIndexPage(segment, type));
324
+ files.set(`${segment}/${type}/[person]`, personTypePersonPage(segment, type));
325
+ }
326
+ }
327
+ if (people.length > 0) {
328
+ files.set(typedPersonRest(), typedPersonPage());
329
+ }
330
+ return files;
331
+ }
332
+
333
+ /**
334
+ * `[tag]` segments are generated when `tagInPath` is set. Kept so callers
335
+ * that print skip notes stay quiet.
336
+ *
337
+ * @param {unknown} _config
338
+ * @returns {string[]}
339
+ */
340
+ export function tagRouteSkips(_config) {
341
+ return [];
342
+ }
343
+
344
+ /**
345
+ * @param {unknown} config
346
+ */
347
+ export function renderMarketingFlags(config) {
348
+ const derived = isSectionConfig(config) ? sectionFlags(config) : null;
349
+ const lines = MARKETING_FLAG_NAMES.map((name) => {
350
+ const value = derived ? derived[name] : config?.[name];
351
+ if (value === undefined) {
352
+ return `export const ${name} = false;`;
353
+ }
354
+ if (typeof value !== 'boolean') {
355
+ throw new Error(`${name} must be a boolean`);
356
+ }
357
+ return `export const ${name} = ${value};`;
358
+ });
359
+ return `${header()}\n${lines.join('\n')}\n`;
360
+ }
361
+
362
+ /**
363
+ * @param {unknown[]} values
364
+ */
365
+ function slugList(values) {
366
+ return values.length === 0
367
+ ? '[] as const'
368
+ : `[${values.map((value) => `'${value}'`).join(', ')}] as const`;
369
+ }
370
+
371
+ /**
372
+ * @param {Record<string, unknown>} config
373
+ * @returns {{ slug: string, indexPath: string, articlePath: string }[]}
374
+ */
375
+ function articleRouteRecords(config) {
376
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
377
+ const types = Array.isArray(config.articleTypes) ? config.articleTypes : [];
378
+ const tagInPath = config.tagInPath === true;
379
+ return types.map((type) => {
380
+ const route = articleTypeRoute(type, config);
381
+ if (tagInPath) {
382
+ const path = categoryPath(config)
383
+ ? `/${route.slug}/`
384
+ : `/${underPrefix(articles, route.slug)}/`;
385
+ return { slug: route.slug, indexPath: path, articlePath: path };
386
+ }
387
+ const indexPath = `/${underPrefix(articles, route.indexSlug)}/`;
388
+ const articlePath = `/${underPrefix(articles, route.slug)}/`;
389
+ return { slug: route.slug, indexPath, articlePath };
390
+ });
391
+ }
392
+
393
+ /**
394
+ * @param {Record<string, unknown>} config
395
+ */
396
+ export function renderMarketingSlugs(config) {
397
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
398
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
399
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
400
+ const personTypes = Array.isArray(config.personTypes) ? config.personTypes : [];
401
+ const tagTypes = Array.isArray(config.tagTypes) ? config.tagTypes : [];
402
+ const articleTypes = Array.isArray(config.articleTypes) ? config.articleTypes : [];
403
+ const articleSlugs = articleTypes.map((type) => articleTypeRoute(type, config).slug);
404
+ const routes = articleRouteRecords(config);
405
+ const routeLiteral =
406
+ routes.length === 0
407
+ ? '[] as const'
408
+ : `[\n${routes
409
+ .map(
410
+ (route) =>
411
+ ` { slug: '${route.slug}', indexPath: '${route.indexPath}', articlePath: '${route.articlePath}' },`,
412
+ )
413
+ .join('\n')}\n] as const`;
414
+ const base = (slug) => (slug ? `'/${slug}'` : "''");
415
+ return `${header()}
416
+ export const PEOPLE_SLUG = '${people}';
417
+ export const PEOPLE_BASE = ${base(people)};
418
+ export const TAGS_SLUG = '${tags}';
419
+ export const TAGS_BASE = ${base(tags)};
420
+ export const ARTICLES_SLUG = '${articles}';
421
+ export const ARTICLES_BASE = ${base(articles)};
422
+ export const PERSON_TYPE_SLUGS = ${slugList(personTypes)};
423
+ export const TAG_TYPE_SLUGS = ${slugList(tagTypes)};
424
+ export const ARTICLE_TYPE_SLUGS = ${slugList(articleSlugs)};
425
+ export const ARTICLE_TYPE_ROUTES = ${routeLiteral};
426
+ `;
427
+ }
428
+
429
+ export function renderMarkdownNegotiation() {
430
+ return `${header()}
431
+ /**
432
+ * The only content rewrite. \`src/proxy.ts\` imports \`resolveMarkdownNegotiationPath\`
433
+ * from this module. Do not add a second Accept: text/markdown rewrite.
434
+ * Trailing-slash 308 and the Contentful preview \`redirect()\` are framework
435
+ * behaviour. CMS content redirects stay the map in \`redirects.ts\`.
436
+ */
437
+ export { resolveMarkdownNegotiationPath } from '@se-studio/core-ui';
438
+ `;
439
+ }
440
+
441
+ /**
442
+ * @param {string} appRoot
443
+ * @param {{ write?: boolean, force?: boolean }} [options]
444
+ */
445
+ export function syncGeneratedRoutes(appRoot, options = {}) {
446
+ const config = readMarketingRoutes(appRoot);
447
+ if (!config) {
448
+ throw new Error(`No src/lib/marketing-routes.json under ${appRoot}`);
449
+ }
450
+ const files = renderGeneratedRoutes(config);
451
+ /** @type {string[]} */
452
+ const wrote = [];
453
+ /** @type {string[]} */
454
+ const skipped = [];
455
+ for (const [rest, contents] of files) {
456
+ for (const rel of destinationsForRest(appRoot, rest)) {
457
+ const abs = path.join(appRoot, rel);
458
+ if (fs.existsSync(abs) && !options.force) {
459
+ skipped.push(rel);
460
+ continue;
461
+ }
462
+ if (options.write) {
463
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
464
+ fs.writeFileSync(abs, contents);
465
+ wrote.push(rel);
466
+ }
467
+ }
468
+ }
469
+ /** @type {[string, string][]} */
470
+ const support = [
471
+ [FLAGS_REL, renderMarketingFlags(config)],
472
+ [MARKDOWN_NEGOTIATION_REL, renderMarkdownNegotiation()],
473
+ ];
474
+ if (isSectionConfig(config)) {
475
+ support.push([SLUGS_REL, renderMarketingSlugs(config)]);
476
+ }
477
+ for (const [rel, contents] of support) {
478
+ const abs = path.join(appRoot, rel);
479
+ if (fs.existsSync(abs) && !options.force) {
480
+ skipped.push(rel);
481
+ continue;
482
+ }
483
+ if (options.write) {
484
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
485
+ fs.writeFileSync(abs, contents);
486
+ wrote.push(rel);
487
+ }
488
+ }
489
+ /** @type {string[]} */
490
+ const removed = [];
491
+ if (options.write) {
492
+ removed.push(...removeStaleHandRoutes(appRoot));
493
+ }
494
+ if (options.write && isSectionConfig(config)) {
495
+ const live = new Set(files.keys());
496
+ for (const file of listCmsPageFiles(appRoot)) {
497
+ if (live.has(file.rest)) {
498
+ continue;
499
+ }
500
+ const abs = path.join(appRoot, file.rel);
501
+ const current = fs.readFileSync(abs, 'utf8');
502
+ if (!current.startsWith(GENERATED_MARK)) {
503
+ continue;
504
+ }
505
+ fs.unlinkSync(abs);
506
+ removed.push(file.rel);
507
+ removeEmptyParents(path.dirname(abs), path.join(appRoot, 'src/app'));
508
+ }
509
+ }
510
+ if (options.write) {
511
+ syncRouteBuildPolicy(appRoot, config);
512
+ formatGeneratedPages(appRoot);
513
+ }
514
+ return { wrote, skipped, removed, count: files.size, tagSkips: tagRouteSkips(config) };
515
+ }
516
+
517
+ /**
518
+ * @param {string} dir
519
+ * @param {string} stopAt
520
+ */
521
+ function removeEmptyParents(dir, stopAt) {
522
+ let current = dir;
523
+ while (current.startsWith(stopAt) && current !== stopAt) {
524
+ if (fs.readdirSync(current).length > 0) {
525
+ return;
526
+ }
527
+ fs.rmdirSync(current);
528
+ current = path.dirname(current);
529
+ }
530
+ }
531
+
532
+ /**
533
+ * @param {string} appRoot
534
+ * @param {unknown} config
535
+ * @returns {string[]}
536
+ */
537
+ function generatedDrift(appRoot, config) {
538
+ /** @type {string[]} */
539
+ const drift = [];
540
+ let files;
541
+ try {
542
+ files = renderGeneratedRoutes(config);
543
+ } catch {
544
+ return drift;
545
+ }
546
+ const requireComplete = fs.existsSync(path.join(appRoot, FLAGS_REL));
547
+ for (const [rest, expected] of files) {
548
+ const rels = existingPageRels(appRoot, rest);
549
+ if (rels.length === 0 && requireComplete) {
550
+ drift.push(`missing generated (cms-routes)/${rest ? `${rest}/` : ''}page.ts`);
551
+ continue;
552
+ }
553
+ for (const rel of rels) {
554
+ const current = fs.readFileSync(path.join(appRoot, rel), 'utf8');
555
+ if (!current.startsWith(GENERATED_MARK)) {
556
+ continue;
557
+ }
558
+ if (current !== formatGeneratedSource(appRoot, rel, expected)) {
559
+ drift.push(`${rel} was edited after generation`);
560
+ }
561
+ }
562
+ }
563
+ return drift;
564
+ }
565
+
566
+ /**
567
+ * @param {string} appRoot
568
+ * @param {unknown} config
569
+ * @returns {string[]}
570
+ */
571
+ function supportDrift(appRoot, config) {
572
+ /** @type {string[]} */
573
+ const drift = [];
574
+ const flagsAbs = path.join(appRoot, FLAGS_REL);
575
+ const expectsFlags = MARKETING_FLAG_NAMES.some(
576
+ (name) => config && typeof config === 'object' && name in config,
577
+ );
578
+ if (isSectionConfig(config)) {
579
+ const slugsAbs = path.join(appRoot, SLUGS_REL);
580
+ const expectedSlugs = renderMarketingSlugs(config);
581
+ if (!fs.existsSync(slugsAbs)) {
582
+ drift.push(`${SLUGS_REL} is missing`);
583
+ } else if (fs.readFileSync(slugsAbs, 'utf8') !== expectedSlugs) {
584
+ drift.push(`${SLUGS_REL} was edited after generation`);
585
+ }
586
+ }
587
+ if (expectsFlags || fs.existsSync(flagsAbs)) {
588
+ const expected = renderMarketingFlags(config);
589
+ if (!fs.existsSync(flagsAbs)) {
590
+ drift.push(`${FLAGS_REL} is missing`);
591
+ } else if (fs.readFileSync(flagsAbs, 'utf8') !== expected) {
592
+ drift.push(`${FLAGS_REL} was edited after generation`);
593
+ }
594
+ }
595
+ const markdownAbs = path.join(appRoot, MARKDOWN_NEGOTIATION_REL);
596
+ if (fs.existsSync(flagsAbs) || fs.existsSync(markdownAbs)) {
597
+ const expected = renderMarkdownNegotiation();
598
+ if (!fs.existsSync(markdownAbs)) {
599
+ drift.push(`${MARKDOWN_NEGOTIATION_REL} is missing`);
600
+ } else if (fs.readFileSync(markdownAbs, 'utf8') !== expected) {
601
+ drift.push(`${MARKDOWN_NEGOTIATION_REL} was edited after generation`);
602
+ }
603
+ }
604
+ return drift;
605
+ }
606
+
607
+ /**
608
+ * Legacy hand routes the CMS generator replaces. A folder is removed only
609
+ * when its page was not written by this generator.
610
+ *
611
+ * @param {string} appRoot
612
+ * @returns {string[]}
613
+ */
614
+ function removeStaleHandRoutes(appRoot) {
615
+ const cms = path.join(appRoot, 'src/app/(cms-routes)');
616
+ /** @type {string[]} */
617
+ const removed = [];
618
+ for (const rel of [
619
+ 'resources/[articleType]',
620
+ 'categories/[slug]',
621
+ 'articles',
622
+ 'people',
623
+ 'tags',
624
+ ]) {
625
+ const dir = path.join(cms, rel);
626
+ if (!fs.existsSync(dir)) {
627
+ continue;
628
+ }
629
+ const page = ['page.ts', 'page.tsx']
630
+ .map((name) => path.join(dir, name))
631
+ .find((file) => fs.existsSync(file));
632
+ const text = page ? fs.readFileSync(page, 'utf8') : '';
633
+ if (text.startsWith(GENERATED_MARK)) {
634
+ continue;
635
+ }
636
+ fs.rmSync(dir, { recursive: true, force: true });
637
+ removed.push(rel);
638
+ }
639
+ const tsx = path.join(cms, 'page.tsx');
640
+ const ts = path.join(cms, 'page.ts');
641
+ const handHome =
642
+ fs.existsSync(tsx) &&
643
+ fs.existsSync(ts) &&
644
+ !fs.readFileSync(tsx, 'utf8').startsWith(GENERATED_MARK);
645
+ if (handHome) {
646
+ fs.unlinkSync(tsx);
647
+ removed.push('page.tsx');
648
+ }
649
+ return removed;
650
+ }
651
+
652
+ /**
653
+ * Bracket routes validate-build-routes requires, in the order sites already
654
+ * commit. Indexes stay off the list. Dotted text routes are appended because
655
+ * the policy check ignores them and the sites keep them here.
656
+ *
657
+ * @param {unknown} config
658
+ * @returns {string[]}
659
+ */
660
+ export function mustBeSsgOrStaticRoutes(config) {
661
+ const allowed = allowedRests(config);
662
+ /** @type {string[]} */
663
+ const routes = [];
664
+ /**
665
+ * @param {string} rest
666
+ */
667
+ const push = (rest) => {
668
+ if (!rest.includes('[') || !allowed.has(rest)) {
669
+ return;
670
+ }
671
+ const route = `/${rest}`;
672
+ if (!routes.includes(route)) {
673
+ routes.push(route);
674
+ }
675
+ };
676
+ push('[level1]');
677
+ push('[level1]/[...slugs]');
678
+ if (config && typeof config === 'object') {
679
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
680
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
681
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
682
+ if (categoryPath(config)) {
683
+ for (const type of config.articleTypes ?? []) {
684
+ const route = articleTypeRoute(type, config);
685
+ push(`${route.slug}/[tag]`);
686
+ push(`${route.slug}/[tag]/[...slugs]`);
687
+ }
688
+ } else if (config.tagInPath === true && articles) {
689
+ push(`${articles}/[articleType]`);
690
+ push(`${articles}/[articleType]/[...slugs]`);
691
+ push(`${articles}/[articleType]/[tag]`);
692
+ push(`${articles}/[articleType]/[tag]/[...slugs]`);
693
+ } else if (Array.isArray(config.articleTypes)) {
694
+ for (const type of config.articleTypes) {
695
+ const route = articleTypeRoute(type, config);
696
+ push(`${underPrefix(articles, route.slug)}/[article]`);
697
+ }
698
+ }
699
+ if (people) {
700
+ push(`${people}/[person]`);
701
+ }
702
+ for (const type of config.personTypes ?? []) {
703
+ push(`${underPrefix(people, String(type))}/[person]`);
704
+ }
705
+ if (tags) {
706
+ push(`${tags}/[tag]`);
707
+ }
708
+ for (const type of config.tagTypes ?? []) {
709
+ push(`${underPrefix(tags, String(type))}/[tag]`);
710
+ }
711
+ push('page-test/[...slugs]');
712
+ if (Array.isArray(config.articleBases)) {
713
+ for (const base of config.articleBases) {
714
+ const segment = typeof base?.path === 'string' ? base.path : '';
715
+ push(`${segment}/[articleType]`);
716
+ push(`${segment}/[articleType]/[...slugs]`);
717
+ push(`${segment}/[articleType]/[tag]`);
718
+ push(`${segment}/[articleType]/[tag]/[...slugs]`);
719
+ push(`${segment}/[...slugs]`);
720
+ push(`${segment}/[tag]`);
721
+ push(`${segment}/[tag]/[...slugs]`);
722
+ }
723
+ }
724
+ if (Array.isArray(config.personBases)) {
725
+ for (const base of config.personBases) {
726
+ const segment = typeof base?.path === 'string' ? base.path : '';
727
+ push(`${segment}/[person]`);
728
+ }
729
+ }
730
+ if (config.tags === true) {
731
+ push('tags/[tag]');
732
+ }
733
+ }
734
+ for (const rest of allowed) {
735
+ push(rest);
736
+ }
737
+ routes.push('/llms.txt', '/markdown-index.txt', '/site-info.md');
738
+ return routes;
739
+ }
740
+
741
+ /**
742
+ * @param {string} appRoot
743
+ * @param {unknown} config
744
+ */
745
+ function syncRouteBuildPolicy(appRoot, config) {
746
+ const policyPath = path.join(appRoot, 'route-build-policy.json');
747
+ if (!fs.existsSync(policyPath)) {
748
+ return;
749
+ }
750
+ const policy = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
751
+ policy.mustBeSsgOrStatic = mustBeSsgOrStaticRoutes(config);
752
+ fs.writeFileSync(policyPath, `${JSON.stringify(policy, null, 2)}\n`);
753
+ console.log(`Updated ${path.relative(appRoot, policyPath)}`);
754
+ }
755
+
756
+ /**
757
+ * App Biome, so a narrower line width does not get undone by the next generate.
758
+ * Looks next to the app, then up to the workspace root.
759
+ *
760
+ * @param {string} appRoot
761
+ * @returns {string | null}
762
+ */
763
+ function biomeBinary(appRoot) {
764
+ let dir = appRoot;
765
+ for (let i = 0; i < 4; i += 1) {
766
+ const candidate = path.join(dir, 'node_modules', '.bin', 'biome');
767
+ if (fs.existsSync(candidate)) {
768
+ return candidate;
769
+ }
770
+ const parent = path.dirname(dir);
771
+ if (parent === dir) {
772
+ break;
773
+ }
774
+ dir = parent;
775
+ }
776
+ return null;
777
+ }
778
+
779
+ /**
780
+ * @param {string} appRoot
781
+ * @param {string} rel
782
+ * @param {string} source
783
+ */
784
+ function formatGeneratedSource(appRoot, rel, source) {
785
+ const biome = biomeBinary(appRoot);
786
+ if (!biome) {
787
+ return source;
788
+ }
789
+ const result = spawnSync(biome, ['check', '--write', '--stdin-file-path', rel], {
790
+ cwd: appRoot,
791
+ input: source,
792
+ encoding: 'utf8',
793
+ });
794
+ if (result.status !== 0 || typeof result.stdout !== 'string' || result.stdout.length === 0) {
795
+ return source;
796
+ }
797
+ return result.stdout;
798
+ }
799
+
800
+ /**
801
+ * @param {string} appRoot
802
+ */
803
+ function formatGeneratedPages(appRoot) {
804
+ const biome = biomeBinary(appRoot);
805
+ if (!biome) {
806
+ return;
807
+ }
808
+ /** @type {string[]} */
809
+ const files = [];
810
+ for (const file of listCmsPageFiles(appRoot)) {
811
+ const abs = path.join(appRoot, file.rel);
812
+ if (fs.readFileSync(abs, 'utf8').startsWith(GENERATED_MARK)) {
813
+ files.push(abs);
814
+ }
815
+ }
816
+ if (files.length === 0) {
817
+ return;
818
+ }
819
+ const result = spawnSync(biome, ['check', '--write', ...files], {
820
+ cwd: appRoot,
821
+ stdio: 'inherit',
822
+ });
823
+ if (result.status !== 0) {
824
+ throw new Error('biome check --write failed on generated routes');
825
+ }
826
+ }
827
+
828
+ /**
829
+ * Bracket CMS routes in route-build-policy.json must be the generated tree.
830
+ *
831
+ * @param {string} appRoot
832
+ * @param {Set<string>} allowed
833
+ * @returns {string[]}
834
+ */
835
+ function policyProblems(appRoot, allowed) {
836
+ const policyPath = path.join(appRoot, 'route-build-policy.json');
837
+ if (!fs.existsSync(policyPath)) {
838
+ return [];
839
+ }
840
+ let policy;
841
+ try {
842
+ policy = JSON.parse(fs.readFileSync(policyPath, 'utf8'));
843
+ } catch (error) {
844
+ const message = error instanceof Error ? error.message : String(error);
845
+ return [`route-build-policy.json: ${message}`];
846
+ }
847
+ const must = new Set(Array.isArray(policy.mustBeSsgOrStatic) ? policy.mustBeSsgOrStatic : []);
848
+ /** @type {string[]} */
849
+ const problems = [];
850
+ for (const rest of allowed) {
851
+ if (!rest.includes('[')) {
852
+ continue;
853
+ }
854
+ const route = `/${rest}`;
855
+ if (!must.has(route)) {
856
+ problems.push(`route-build-policy.json missing ${route}`);
857
+ }
858
+ }
859
+ for (const route of must) {
860
+ if (typeof route !== 'string' || !route.startsWith('/') || route.includes('.')) {
861
+ continue;
862
+ }
863
+ const rest = route.slice(1);
864
+ if (!allowed.has(rest)) {
865
+ problems.push(`route-build-policy.json lists ${route} outside marketing-routes.json`);
866
+ }
867
+ }
868
+ return problems;
869
+ }
870
+
871
+ /**
872
+ * @param {string} appRoot
873
+ * @returns {string[]}
874
+ */
875
+ function proxyMarkdownProblems(appRoot) {
876
+ const proxyPath = path.join(appRoot, 'src/proxy.ts');
877
+ if (!fs.existsSync(proxyPath)) {
878
+ return [];
879
+ }
880
+ const text = fs.readFileSync(proxyPath, 'utf8');
881
+ /** @type {string[]} */
882
+ const problems = [];
883
+ if (!text.includes("from '@/generated/markdown-negotiation'")) {
884
+ problems.push(
885
+ 'src/proxy.ts must import the markdown rewrite from @/generated/markdown-negotiation',
886
+ );
887
+ }
888
+ const coreImport = text.match(/import\s*\{[^}]*\}\s*from\s*'@se-studio\/core-ui'/);
889
+ if (coreImport?.[0]?.includes('resolveMarkdownNegotiationPath')) {
890
+ problems.push(
891
+ 'src/proxy.ts imports resolveMarkdownNegotiationPath from @se-studio/core-ui; use the generated module',
892
+ );
893
+ }
894
+ return problems;
895
+ }
896
+
897
+ /**
898
+ * @param {Set<string>} allowed
899
+ * @param {Record<string, unknown>} config
900
+ */
901
+ /**
902
+ * Category in the path, with no articles prefix. The article type slug is the
903
+ * public path (`resources/news`). Flat mode (Eagle) stays one segment.
904
+ *
905
+ * @param {Record<string, unknown>} config
906
+ */
907
+ function categoryPath(config) {
908
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
909
+ return config.tagInPath === true && articles.length === 0;
910
+ }
911
+
912
+ /**
913
+ * @param {unknown} type
914
+ * @param {Record<string, unknown>} [config]
915
+ * @returns {{ slug: string, indexSlug: string }}
916
+ */
917
+ function articleTypeRoute(type, config = {}) {
918
+ const category = categoryPath(config);
919
+ if (typeof type === 'string') {
920
+ const slug = category
921
+ ? requireRoutePath(type, 'articleTypes')
922
+ : requireSegment(type, 'articleTypes');
923
+ return { slug, indexSlug: slug };
924
+ }
925
+ const slug = category
926
+ ? requireRoutePath(type?.slug, 'articleTypes.slug')
927
+ : requireSegment(type?.slug, 'articleTypes.slug');
928
+ const rawIndex =
929
+ typeof type?.indexSlug === 'string' && type.indexSlug.length > 0 ? type.indexSlug : slug;
930
+ if (category && rawIndex !== slug) {
931
+ throw new Error(
932
+ `${slug} indexSlug must equal the article type slug when the category is in the path`,
933
+ );
934
+ }
935
+ return {
936
+ slug,
937
+ indexSlug: category ? slug : requireSegment(rawIndex, 'articleTypes.indexSlug'),
938
+ };
939
+ }
940
+
941
+ /**
942
+ * @param {string} prefix
943
+ * @param {string} segment
944
+ */
945
+ function underPrefix(prefix, segment) {
946
+ return prefix ? `${prefix}/${segment}` : segment;
947
+ }
948
+
949
+ function addSectionRests(allowed, config) {
950
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
951
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
952
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
953
+ if (people) {
954
+ allowed.add(people);
955
+ allowed.add(`${people}/[person]`);
956
+ }
957
+ for (const type of config.personTypes ?? []) {
958
+ const segment = requireSegment(type, 'personTypes');
959
+ const rest = underPrefix(people, segment);
960
+ allowed.add(rest);
961
+ allowed.add(`${rest}/[person]`);
962
+ }
963
+ if (tags) {
964
+ allowed.add(tags);
965
+ allowed.add(`${tags}/[tag]`);
966
+ }
967
+ for (const type of config.tagTypes ?? []) {
968
+ const segment = requireSegment(type, 'tagTypes');
969
+ const rest = underPrefix(tags, segment);
970
+ allowed.add(rest);
971
+ allowed.add(`${rest}/[tag]`);
972
+ }
973
+ if (categoryPath(config)) {
974
+ for (const type of config.articleTypes ?? []) {
975
+ const route = articleTypeRoute(type, config);
976
+ allowed.add(route.slug);
977
+ allowed.add(`${route.slug}/[tag]`);
978
+ allowed.add(`${route.slug}/[tag]/[...slugs]`);
979
+ }
980
+ return;
981
+ }
982
+ if (config.tagInPath === true) {
983
+ if (!articles) {
984
+ throw new Error('tagInPath needs an articles custom type prefix');
985
+ }
986
+ allowed.add(articles);
987
+ allowed.add(`${articles}/[articleType]`);
988
+ allowed.add(`${articles}/[articleType]/[...slugs]`);
989
+ allowed.add(`${articles}/[articleType]/[tag]`);
990
+ allowed.add(`${articles}/[articleType]/[tag]/[...slugs]`);
991
+ return;
992
+ }
993
+ if (articles) {
994
+ allowed.add(articles);
995
+ }
996
+ for (const type of config.articleTypes ?? []) {
997
+ const route = articleTypeRoute(type, config);
998
+ const indexRest = underPrefix(articles, route.indexSlug);
999
+ const articleRest = underPrefix(articles, route.slug);
1000
+ allowed.add(indexRest);
1001
+ allowed.add(`${articleRest}/[article]`);
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * @param {Record<string, unknown>} config
1007
+ * @param {Map<string, string>} files
1008
+ */
1009
+ function renderSectionRoutes(config, files) {
1010
+ const people = typeof config.peopleSlug === 'string' ? config.peopleSlug : '';
1011
+ const tags = typeof config.tagsSlug === 'string' ? config.tagsSlug : '';
1012
+ const articles = typeof config.articlesSlug === 'string' ? config.articlesSlug : '';
1013
+ if (people) {
1014
+ const segment = requireSegment(people, 'peopleSlug');
1015
+ files.set(segment, peopleIndexPage(segment));
1016
+ files.set(`${segment}/[person]`, untypedPersonPage(segment));
1017
+ }
1018
+ for (const type of config.personTypes ?? []) {
1019
+ const segment = requireSegment(type, 'personTypes');
1020
+ const rest = underPrefix(people, segment);
1021
+ files.set(rest, topPersonTypeIndex(rest, segment));
1022
+ files.set(`${rest}/[person]`, topPersonTypePerson(rest, segment));
1023
+ }
1024
+ if (tags) {
1025
+ const segment = requireSegment(tags, 'tagsSlug');
1026
+ files.set(segment, sectionTagsIndex(segment));
1027
+ files.set(`${segment}/[tag]`, sectionTagPage(segment));
1028
+ }
1029
+ for (const type of config.tagTypes ?? []) {
1030
+ const segment = requireSegment(type, 'tagTypes');
1031
+ const rest = underPrefix(tags, segment);
1032
+ files.set(rest, tagTypeIndexPage(rest, segment));
1033
+ files.set(`${rest}/[tag]`, tagTypeTagPage(rest));
1034
+ }
1035
+ if (categoryPath(config)) {
1036
+ for (const type of config.articleTypes ?? []) {
1037
+ const route = articleTypeRoute(type, config);
1038
+ files.set(route.slug, concreteArticleTypeIndex(route.slug, route.slug));
1039
+ files.set(`${route.slug}/[tag]`, fixedArticleTag(route.slug));
1040
+ files.set(`${route.slug}/[tag]/[...slugs]`, fixedArticleTagDetail(route.slug));
1041
+ }
1042
+ return;
1043
+ }
1044
+ if (config.tagInPath === true) {
1045
+ if (!articles) {
1046
+ throw new Error('tagInPath needs an articles custom type prefix');
1047
+ }
1048
+ const segment = requireSegment(articles, 'articlesSlug');
1049
+ files.set(segment, dynamicArticleIndex(segment));
1050
+ files.set(`${segment}/[articleType]`, dynamicArticleType(segment));
1051
+ files.set(`${segment}/[articleType]/[...slugs]`, dynamicArticleDetail(segment));
1052
+ files.set(`${segment}/[articleType]/[tag]`, dynamicArticleTag(segment));
1053
+ files.set(`${segment}/[articleType]/[tag]/[...slugs]`, dynamicArticleTagDetail(segment));
1054
+ return;
1055
+ }
1056
+ if (articles) {
1057
+ const segment = requireSegment(articles, 'articlesSlug');
1058
+ files.set(segment, dynamicArticleIndex(segment));
1059
+ }
1060
+ for (const type of config.articleTypes ?? []) {
1061
+ const route = articleTypeRoute(type, config);
1062
+ const indexRest = underPrefix(articles, route.indexSlug);
1063
+ const articleRest = underPrefix(articles, route.slug);
1064
+ files.set(indexRest, concreteArticleTypeIndex(indexRest, route.slug));
1065
+ files.set(`${articleRest}/[article]`, concreteArticlePage(articleRest, route.slug));
1066
+ }
1067
+ }
1068
+
1069
+ /**
1070
+ * Person type index. `rest` may include a person custom-type prefix.
1071
+ *
1072
+ * @param {string} rest
1073
+ * @param {string} type
1074
+ */
1075
+ function topPersonTypeIndex(rest, type) {
1076
+ const props = `PageProps<'/${rest}'>`;
1077
+ const routePath = `/${rest}/`;
1078
+ const metadata = openFn('export async function generateMetadata', [
1079
+ `_props: ${props}`,
1080
+ 'parent: ResolvingMetadata',
1081
+ ]);
1082
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1083
+ return `${header()}import type { ResolvingMetadata } from 'next';
1084
+ import { notFound } from 'next/navigation';
1085
+ import { enablePerson } from '@/generated/marketing-flags';
1086
+ import {
1087
+ generatePersonTypeIndexMetadata,
1088
+ generatePersonTypeIndexPage,
1089
+ } from '@/lib/route-handlers';
1090
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1091
+
1092
+ const PERSON_TYPE = '${type}';
1093
+ const PATH = '${routePath}';
1094
+
1095
+ export function generateStaticParams() {
1096
+ return [];
1097
+ }
1098
+
1099
+ ${metadata}
1100
+ if (!enablePerson) {
1101
+ return {};
1102
+ }
1103
+ return await generatePersonTypeIndexMetadata(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1104
+ }
1105
+
1106
+ ${page}
1107
+ if (!enablePerson) {
1108
+ notFound();
1109
+ }
1110
+ return await generatePersonTypeIndexPage(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1111
+ }
1112
+ `;
1113
+ }
1114
+
1115
+ /**
1116
+ * @param {string} rest
1117
+ * @param {string} _type
1118
+ */
1119
+ function topPersonTypePerson(rest, _type) {
1120
+ const props = `PageProps<'/${rest}/[person]'>`;
1121
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1122
+ const metadata = openFn('export async function generateMetadata', [
1123
+ `props: ${props}`,
1124
+ 'parent: ResolvingMetadata',
1125
+ ]);
1126
+ const page = openFn('export default async function ', [`props: ${props}`]);
1127
+ return `${header()}import type { ResolvingMetadata } from 'next';
1128
+ import { notFound } from 'next/navigation';
1129
+ import { enablePerson } from '@/generated/marketing-flags';
1130
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
1131
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1132
+
1133
+ export function generateStaticParams() {
1134
+ return [];
1135
+ }
1136
+
1137
+ ${extract}
1138
+ const params = await props.params;
1139
+ const { person } = params;
1140
+ return { person, path: \`/${rest}/\${person}/\` };
1141
+ }
1142
+
1143
+ ${metadata}
1144
+ if (!enablePerson) {
1145
+ return {};
1146
+ }
1147
+ const { person, path } = await extractDetails(props);
1148
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
1149
+ }
1150
+
1151
+ ${page}
1152
+ if (!enablePerson) {
1153
+ notFound();
1154
+ }
1155
+ const { person, path } = await extractDetails(props);
1156
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
1157
+ }
1158
+ `;
1159
+ }
1160
+
1161
+ /**
1162
+ * @param {string} rest
1163
+ * @param {string} type
1164
+ */
1165
+ function tagTypeIndexPage(rest, type) {
1166
+ const props = `PageProps<'/${rest}'>`;
1167
+ const routePath = `/${rest}/`;
1168
+ const metadata = openFn('export async function generateMetadata', [
1169
+ `_props: ${props}`,
1170
+ 'parent: ResolvingMetadata',
1171
+ ]);
1172
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1173
+ return `${header()}import type { ResolvingMetadata } from 'next';
1174
+ import { generateTagTypeMetadata, generateTagTypePage } from '@/lib/route-handlers';
1175
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1176
+
1177
+ const TAG_TYPE = '${type}';
1178
+ const PATH = '${routePath}';
1179
+
1180
+ export function generateStaticParams() {
1181
+ return [];
1182
+ }
1183
+
1184
+ ${metadata}
1185
+ return await generateTagTypeMetadata(TAG_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1186
+ }
1187
+
1188
+ ${page}
1189
+ return await generateTagTypePage(TAG_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1190
+ }
1191
+ `;
1192
+ }
1193
+
1194
+ /**
1195
+ * Tag page under a tag type. The path is the route, not the tag calculator.
1196
+ *
1197
+ * @param {string} rest
1198
+ */
1199
+ function tagTypeTagPage(rest) {
1200
+ const props = `PageProps<'/${rest}/[tag]'>`;
1201
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1202
+ const metadata = openFn('export async function generateMetadata', [
1203
+ `props: ${props}`,
1204
+ 'parent: ResolvingMetadata',
1205
+ ]);
1206
+ const page = openFn('export default async function ', [`props: ${props}`]);
1207
+ return `${header()}import type { ResolvingMetadata } from 'next';
1208
+ import { generateTagMetadata, generateTagPage } from '@/lib/route-handlers';
1209
+ import { TAG_LISTING_ROUTE_CONFIG } from '@/lib/routeConfig';
1210
+
1211
+ export function generateStaticParams() {
1212
+ return [];
1213
+ }
1214
+
1215
+ ${extract}
1216
+ const params = await props.params;
1217
+ const { tag } = params;
1218
+ return { tagSlug: tag, path: \`/${rest}/\${tag}/\` };
1219
+ }
1220
+
1221
+ ${metadata}
1222
+ const { tagSlug, path } = await extractDetails(props);
1223
+ return await generateTagMetadata(tagSlug, path, TAG_LISTING_ROUTE_CONFIG, parent);
1224
+ }
1225
+
1226
+ ${page}
1227
+ const { tagSlug, path } = await extractDetails(props);
1228
+ return await generateTagPage(tagSlug, path, TAG_LISTING_ROUTE_CONFIG);
1229
+ }
1230
+ `;
1231
+ }
1232
+
1233
+ /**
1234
+ * Article type index. The handler is called with the type slug, not the index slug.
1235
+ *
1236
+ * @param {string} rest
1237
+ * @param {string} typeSlug
1238
+ */
1239
+ function concreteArticleTypeIndex(rest, typeSlug) {
1240
+ const props = `PageProps<'/${rest}'>`;
1241
+ const routePath = `/${rest}/`;
1242
+ const metadata = openFn('export async function generateMetadata', [
1243
+ `_props: ${props}`,
1244
+ 'parent: ResolvingMetadata',
1245
+ ]);
1246
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1247
+ return `${header()}import type { ResolvingMetadata } from 'next';
1248
+ import { generateArticleTypeMetadata, generateArticleTypePage } from '@/lib/route-handlers';
1249
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1250
+
1251
+ const ARTICLE_TYPE = '${typeSlug}';
1252
+ const PATH = '${routePath}';
1253
+
1254
+ export function generateStaticParams() {
1255
+ return [];
1256
+ }
1257
+
1258
+ ${metadata}
1259
+ return await generateArticleTypeMetadata(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1260
+ }
1261
+
1262
+ ${page}
1263
+ return await generateArticleTypePage(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1264
+ }
1265
+ `;
1266
+ }
1267
+
1268
+ /**
1269
+ * @param {string} rest directory of the article, without `[article]`
1270
+ * @param {string} typeSlug
1271
+ */
1272
+ function concreteArticlePage(rest, typeSlug) {
1273
+ const props = `PageProps<'/${rest}/[article]'>`;
1274
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1275
+ const metadata = openFn('export async function generateMetadata', [
1276
+ `props: ${props}`,
1277
+ 'parent: ResolvingMetadata',
1278
+ ]);
1279
+ const page = openFn('export default async function ', [`props: ${props}`]);
1280
+ return `${header()}import type { ResolvingMetadata } from 'next';
1281
+ import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
1282
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
1283
+
1284
+ const ARTICLE_TYPE = '${typeSlug}';
1285
+
1286
+ export function generateStaticParams() {
1287
+ return [];
1288
+ }
1289
+
1290
+ ${extract}
1291
+ const params = await props.params;
1292
+ const { article } = params;
1293
+ return { articleSlug: article, path: \`/${rest}/\${article}/\` };
1294
+ }
1295
+
1296
+ ${metadata}
1297
+ const { articleSlug, path } = await extractDetails(props);
1298
+ return await generateArticleMetadata(
1299
+ ARTICLE_TYPE,
1300
+ articleSlug,
1301
+ path,
1302
+ ARTICLE_DETAIL_ROUTE_CONFIG,
1303
+ parent,
1304
+ );
1305
+ }
1306
+
1307
+ ${page}
1308
+ const { articleSlug, path } = await extractDetails(props);
1309
+ return await generateArticlePage(ARTICLE_TYPE, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
1310
+ }
1311
+ `;
1312
+ }
1313
+
1314
+ /**
1315
+ * @param {string} segment
1316
+ */
1317
+ function sectionTagsIndex(segment) {
1318
+ const props = `PageProps<'/${segment}'>`;
1319
+ const metadata = openFn('export function generateMetadata', [
1320
+ `_props: ${props}`,
1321
+ 'parent: ResolvingMetadata',
1322
+ ]);
1323
+ const page = openFn('export default function ', [`_props: ${props}`]);
1324
+ return `${header()}import type { ResolvingMetadata } from 'next';
1325
+ import { TAGS_BASE } from '@/lib/constants';
1326
+ import { generateTagsIndexMetadata, generateTagsIndexPage } from '@/lib/route-handlers';
1327
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1328
+
1329
+ export function generateStaticParams() {
1330
+ return [];
1331
+ }
1332
+
1333
+ ${metadata}
1334
+ return generateTagsIndexMetadata(TAGS_BASE, DEFAULT_ROUTE_CONFIG, parent);
1335
+ }
1336
+
1337
+ ${page}
1338
+ return generateTagsIndexPage(TAGS_BASE, DEFAULT_ROUTE_CONFIG);
1339
+ }
1340
+ `;
1341
+ }
1342
+
1343
+ /**
1344
+ * @param {string} segment
1345
+ */
1346
+ function sectionTagPage(segment) {
1347
+ const props = `PageProps<'/${segment}/[tag]'>`;
1348
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1349
+ const metadata = openFn('export async function generateMetadata', [
1350
+ `props: ${props}`,
1351
+ 'parent: ResolvingMetadata',
1352
+ ]);
1353
+ const page = openFn('export default async function ', [`props: ${props}`]);
1354
+ return `${header()}import type { ResolvingMetadata } from 'next';
1355
+ import { converterContext } from '@/lib/converter-context';
1356
+ import { generateTagMetadata, generateTagPage } from '@/lib/route-handlers';
1357
+ import { TAG_LISTING_ROUTE_CONFIG } from '@/lib/routeConfig';
1358
+
1359
+ export function generateStaticParams() {
1360
+ return [];
1361
+ }
1362
+
1363
+ ${extract}
1364
+ const params = await props.params;
1365
+ const { tag } = params;
1366
+ return { tagSlug: tag, path: converterContext.urlCalculators.tag(tag) };
1367
+ }
1368
+
1369
+ ${metadata}
1370
+ const { tagSlug, path } = await extractDetails(props);
1371
+ return await generateTagMetadata(tagSlug, path, TAG_LISTING_ROUTE_CONFIG, parent);
1372
+ }
1373
+
1374
+ ${page}
1375
+ const { tagSlug, path } = await extractDetails(props);
1376
+ return await generateTagPage(tagSlug, path, TAG_LISTING_ROUTE_CONFIG);
1377
+ }
1378
+ `;
1379
+ }
1380
+
1381
+ /**
1382
+ * Named person types on a people base. An empty list writes no named folders.
1383
+ * Every people base also writes `[person]`. Typed people are one `peopleType/` tree.
1384
+ *
1385
+ * @param {unknown} base
1386
+ * @returns {string[]}
1387
+ */
1388
+ function personTypeNames(base) {
1389
+ if (!Array.isArray(base?.types)) {
1390
+ return [];
1391
+ }
1392
+ /** @type {Set<string>} */
1393
+ const seen = new Set();
1394
+ return base.types.map((type) => {
1395
+ const segment = requireSegment(type, 'personBases.types');
1396
+ if (seen.has(segment)) {
1397
+ throw new Error(`personBases.types lists "${segment}" twice`);
1398
+ }
1399
+ seen.add(segment);
1400
+ return segment;
1401
+ });
1402
+ }
1403
+
1404
+ /**
1405
+ * @param {string} segment
1406
+ */
1407
+ function isRouteGroup(segment) {
1408
+ return /^\([^)/]+\)$/.test(segment);
1409
+ }
1410
+
1411
+ /**
1412
+ * Prefix through `(cms-routes)/` and any route groups nested directly inside it.
1413
+ *
1414
+ * @param {string} rel
1415
+ * @returns {string|null}
1416
+ */
1417
+ function cmsPagePrefix(rel) {
1418
+ const marker = '(cms-routes)/';
1419
+ const idx = rel.indexOf(marker);
1420
+ if (idx === -1) {
1421
+ return null;
1422
+ }
1423
+ const groups = [];
1424
+ for (const segment of rel.slice(idx + marker.length).split('/')) {
1425
+ if (!isRouteGroup(segment)) {
1426
+ break;
1427
+ }
1428
+ groups.push(segment);
1429
+ }
1430
+ const nested = groups.length > 0 ? `${groups.join('/')}/` : '';
1431
+ return `${rel.slice(0, idx + marker.length)}${nested}`;
1432
+ }
1433
+
1434
+ /**
1435
+ * @param {string} appRoot
1436
+ * @returns {{ rel: string, rest: string }[]}
1437
+ */
1438
+ function listCmsPageFiles(appRoot) {
1439
+ /** @type {{ rel: string, rest: string }[]} */
1440
+ const files = [];
1441
+ const appDir = path.join(appRoot, 'src/app');
1442
+ if (!fs.existsSync(appDir)) {
1443
+ return files;
1444
+ }
1445
+ walk(appDir, (file) => {
1446
+ const base = path.basename(file);
1447
+ if (base !== 'page.ts' && base !== 'page.tsx') {
1448
+ return;
1449
+ }
1450
+ const rel = path.relative(appRoot, file).split(path.sep).join('/');
1451
+ if (rel.includes('/(cms-dev)/') || rel.startsWith('src/app/(cms-dev)/')) {
1452
+ return;
1453
+ }
1454
+ if (isPreviewPage(rel)) {
1455
+ return;
1456
+ }
1457
+ const rest = routeRestFromRel(rel);
1458
+ if (rest === null) {
1459
+ return;
1460
+ }
1461
+ files.push({ rel, rest });
1462
+ });
1463
+ return files;
1464
+ }
1465
+
1466
+ /**
1467
+ * @param {string} appRoot
1468
+ * @param {string} rest
1469
+ * @returns {string[]}
1470
+ */
1471
+ function existingPageRels(appRoot, rest) {
1472
+ return listCmsPageFiles(appRoot)
1473
+ .filter((file) => file.rest === rest)
1474
+ .map((file) => file.rel);
1475
+ }
1476
+
1477
+ /**
1478
+ * Trees that already serve CMS pages. A bare `src/app/(cms-routes)/` is not
1479
+ * added when the site uses `(default)` or an inner group: that file is a
1480
+ * second copy of the same URL.
1481
+ *
1482
+ * @param {string[]} prefixes
1483
+ */
1484
+ function preferExistingTrees(prefixes) {
1485
+ let next = prefixes;
1486
+ if (next.some((prefix) => prefix.includes('/(default)/'))) {
1487
+ next = next.filter(
1488
+ (prefix) => prefix.includes('/(default)/') || !prefix.startsWith('src/app/(cms-routes)/'),
1489
+ );
1490
+ }
1491
+ if (next.some((prefix) => prefix.startsWith('src/app/(cms-routes)/('))) {
1492
+ next = next.filter((prefix) => prefix !== 'src/app/(cms-routes)/');
1493
+ }
1494
+ return next;
1495
+ }
1496
+
1497
+ /**
1498
+ * @param {string} appRoot
1499
+ * @returns {string[]}
1500
+ */
1501
+ function writePrefixes(appRoot) {
1502
+ const fromPages = [
1503
+ ...new Set(listCmsPageFiles(appRoot).map((file) => cmsPagePrefix(file.rel)).filter(Boolean)),
1504
+ ];
1505
+ if (fromPages.length > 0) {
1506
+ return preferExistingTrees(fromPages);
1507
+ }
1508
+ const fromDirs = findCmsRouteDirs(appRoot).map((dir) => prefixFromCmsDir(appRoot, dir));
1509
+ if (fromDirs.length > 0) {
1510
+ return preferExistingTrees(fromDirs);
1511
+ }
1512
+ return ['src/app/(cms-routes)/'];
1513
+ }
1514
+
1515
+ /**
1516
+ * @param {string} appRoot
1517
+ * @returns {string[]} absolute directories
1518
+ */
1519
+ function findCmsRouteDirs(appRoot) {
1520
+ /** @type {string[]} */
1521
+ const found = [];
1522
+ const appDir = path.join(appRoot, 'src/app');
1523
+ if (!fs.existsSync(appDir)) {
1524
+ return found;
1525
+ }
1526
+ const visit = (dir) => {
1527
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1528
+ if (!entry.isDirectory()) {
1529
+ continue;
1530
+ }
1531
+ const full = path.join(dir, entry.name);
1532
+ if (entry.name === '(cms-routes)') {
1533
+ found.push(full);
1534
+ continue;
1535
+ }
1536
+ visit(full);
1537
+ }
1538
+ };
1539
+ visit(appDir);
1540
+ return found;
1541
+ }
1542
+
1543
+ /**
1544
+ * @param {string} appRoot
1545
+ * @param {string} absDir
1546
+ */
1547
+ function prefixFromCmsDir(appRoot, absDir) {
1548
+ let rel = `${path.relative(appRoot, absDir).split(path.sep).join('/')}/`;
1549
+ const groups = fs
1550
+ .readdirSync(absDir, { withFileTypes: true })
1551
+ .filter((entry) => entry.isDirectory() && isRouteGroup(entry.name))
1552
+ .map((entry) => entry.name);
1553
+ if (groups.length === 1) {
1554
+ rel += `${groups[0]}/`;
1555
+ }
1556
+ return rel;
1557
+ }
1558
+
1559
+ /**
1560
+ * @param {string} prefix
1561
+ * @param {string} rest
1562
+ */
1563
+ function pageRel(prefix, rest) {
1564
+ return rest ? `${prefix}${rest}/page.ts` : `${prefix}page.ts`;
1565
+ }
1566
+
1567
+ /**
1568
+ * Path before `(cms-routes)/`, with route groups removed. `(default)`, a bare
1569
+ * `(cms-routes)`, and `(with-chrome)` share one slot. A locale prefix does not.
1570
+ *
1571
+ * @param {string} rel
1572
+ */
1573
+ function urlSlot(rel) {
1574
+ const marker = '(cms-routes)/';
1575
+ const idx = rel.indexOf(marker);
1576
+ const before = idx === -1 ? rel : rel.slice(0, idx);
1577
+ return `${before
1578
+ .split('/')
1579
+ .filter((segment) => segment.length > 0 && !isRouteGroup(segment))
1580
+ .join('/')}/`;
1581
+ }
1582
+
1583
+ /**
1584
+ * One destination per serving tree. An existing page covers its own URL slot
1585
+ * only, so a default-locale file does not skip `es-US`. A new sibling stays
1586
+ * next to an article file that already lives in that slot.
1587
+ *
1588
+ * @param {string} appRoot
1589
+ * @param {string} rest
1590
+ * @returns {string[]}
1591
+ */
1592
+ function destinationsForRest(appRoot, rest) {
1593
+ const existing = existingPageRels(appRoot, rest);
1594
+ /** @type {string[]} */
1595
+ const dest = [];
1596
+ const seen = new Set();
1597
+ for (const prefix of writePrefixes(appRoot)) {
1598
+ const slot = urlSlot(prefix);
1599
+ const onSlot = existing.filter((rel) => urlSlot(rel) === slot);
1600
+ const chosen =
1601
+ onSlot.length > 0
1602
+ ? onSlot
1603
+ : [pageRel(siblingPrefix(appRoot, rest, slot) ?? prefix, rest)];
1604
+ for (const rel of chosen) {
1605
+ if (seen.has(rel)) {
1606
+ continue;
1607
+ }
1608
+ seen.add(rel);
1609
+ dest.push(rel);
1610
+ }
1611
+ }
1612
+ return dest;
1613
+ }
1614
+
1615
+ /**
1616
+ * @param {string} appRoot
1617
+ * @param {string} rest
1618
+ * @param {string} slot
1619
+ * @returns {string|null}
1620
+ */
1621
+ function siblingPrefix(appRoot, rest, slot) {
1622
+ const base = rest.split('/')[0];
1623
+ if (!base) {
1624
+ return null;
1625
+ }
1626
+ const sibling = listCmsPageFiles(appRoot).find(
1627
+ (file) =>
1628
+ urlSlot(file.rel) === slot && (file.rest === base || file.rest.startsWith(`${base}/`)),
1629
+ );
1630
+ return sibling ? cmsPagePrefix(sibling.rel) : null;
1631
+ }
1632
+
1633
+ /**
1634
+ * @param {unknown} value
1635
+ * @param {string} label
1636
+ */
1637
+ function requireSegment(value, label) {
1638
+ if (typeof value !== 'string' || !SEGMENT.test(value)) {
1639
+ throw new Error(`${label} must be a single lowercase segment`);
1640
+ }
1641
+ return value;
1642
+ }
1643
+
1644
+ /**
1645
+ * @param {unknown} value
1646
+ * @param {string} label
1647
+ */
1648
+ function requireRoutePath(value, label) {
1649
+ if (typeof value !== 'string' || value.length === 0) {
1650
+ throw new Error(`${label} must be a path of lowercase segments`);
1651
+ }
1652
+ const parts = value.split('/');
1653
+ if (parts.some((part) => !SEGMENT.test(part))) {
1654
+ throw new Error(`${label} must be a path of lowercase segments`);
1655
+ }
1656
+ return value;
1657
+ }
1658
+
1659
+ /**
1660
+ * @param {string} dir
1661
+ * @param {(file: string) => void} visit
1662
+ */
1663
+ function walk(dir, visit) {
1664
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
1665
+ const full = path.join(dir, entry.name);
1666
+ if (entry.isDirectory()) {
1667
+ walk(full, visit);
1668
+ } else {
1669
+ visit(full);
1670
+ }
1671
+ }
1672
+ }
1673
+
1674
+ function header() {
1675
+ return `${GENERATED_MARK}\n`;
1676
+ }
1677
+
1678
+ function homePage() {
1679
+ return `${header()}import type { ResolvingMetadata } from 'next';
1680
+ import { generatePage, generatePageMetadata } from '@/lib/route-handlers';
1681
+ import { getPageRouteConfig } from '@/lib/routeConfig';
1682
+
1683
+ export function generateMetadata(_props: PageProps<'/'>, parent: ResolvingMetadata) {
1684
+ return generatePageMetadata('index', '/', getPageRouteConfig('index'), parent);
1685
+ }
1686
+
1687
+ export default function (_props: PageProps<'/'>) {
1688
+ return generatePage('index', '/', getPageRouteConfig('index'));
1689
+ }
1690
+ `;
1691
+ }
1692
+
1693
+ function levelPage() {
1694
+ const props = "PageProps<'/[level1]'>";
1695
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1696
+ const metadata = openFn('export async function generateMetadata', [
1697
+ `props: ${props}`,
1698
+ 'parent: ResolvingMetadata',
1699
+ ]);
1700
+ const page = openFn('export default async function ', [`props: ${props}`]);
1701
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
1702
+ import type { ResolvingMetadata } from 'next';
1703
+ import { notFound } from 'next/navigation';
1704
+ import { generatePage, generatePageMetadata } from '@/lib/route-handlers';
1705
+ import { getPageRouteConfig } from '@/lib/routeConfig';
1706
+
1707
+ export function generateStaticParams() {
1708
+ return [];
1709
+ }
1710
+
1711
+ ${extract}
1712
+ const params = await props.params;
1713
+ const slug = joinCmsPathSegments(params.level1);
1714
+ if (!slug) {
1715
+ notFound();
1716
+ }
1717
+ return { slug, path: \`/\${slug}/\` };
1718
+ }
1719
+
1720
+ ${metadata}
1721
+ const { slug, path } = await extractDetails(props);
1722
+ return generatePageMetadata(slug, path, getPageRouteConfig(slug), parent);
1723
+ }
1724
+
1725
+ ${page}
1726
+ const { slug, path } = await extractDetails(props);
1727
+ return generatePage(slug, path, getPageRouteConfig(slug));
1728
+ }
1729
+ `;
1730
+ }
1731
+
1732
+ function levelSlugsPage() {
1733
+ const props = "PageProps<'/[level1]/[...slugs]'>";
1734
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1735
+ const metadata = openFn('export async function generateMetadata', [
1736
+ `props: ${props}`,
1737
+ 'parent: ResolvingMetadata',
1738
+ ]);
1739
+ const page = openFn('export default async function ', [`props: ${props}`]);
1740
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
1741
+ import type { ResolvingMetadata } from 'next';
1742
+ import { notFound } from 'next/navigation';
1743
+ import { generatePage, generatePageMetadata } from '@/lib/route-handlers';
1744
+ import { getPageRouteConfig } from '@/lib/routeConfig';
1745
+
1746
+ export function generateStaticParams() {
1747
+ return [];
1748
+ }
1749
+
1750
+ ${extract}
1751
+ const params = await props.params;
1752
+ const slug = joinCmsPathSegments(params.level1, params.slugs);
1753
+ if (!slug) {
1754
+ notFound();
1755
+ }
1756
+ return { slug, path: \`/\${slug}/\` };
1757
+ }
1758
+
1759
+ ${metadata}
1760
+ const { slug, path } = await extractDetails(props);
1761
+ return generatePageMetadata(slug, path, getPageRouteConfig(slug), parent);
1762
+ }
1763
+
1764
+ ${page}
1765
+ const { slug, path } = await extractDetails(props);
1766
+ return generatePage(slug, path, getPageRouteConfig(slug));
1767
+ }
1768
+ `;
1769
+ }
1770
+
1771
+ function tagsIndexPage() {
1772
+ const props = "PageProps<'/tags'>";
1773
+ const metadata = openFn('export function generateMetadata', [
1774
+ `_props: ${props}`,
1775
+ 'parent: ResolvingMetadata',
1776
+ ]);
1777
+ const page = openFn('export default function ', [`_props: ${props}`]);
1778
+ return `${header()}import type { ResolvingMetadata } from 'next';
1779
+ import { TAGS_BASE } from '@/lib/constants';
1780
+ import { generateTagsIndexMetadata, generateTagsIndexPage } from '@/lib/route-handlers';
1781
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1782
+
1783
+ export function generateStaticParams() {
1784
+ return [];
1785
+ }
1786
+
1787
+ ${metadata}
1788
+ return generateTagsIndexMetadata(TAGS_BASE, DEFAULT_ROUTE_CONFIG, parent);
1789
+ }
1790
+
1791
+ ${page}
1792
+ return generateTagsIndexPage(TAGS_BASE, DEFAULT_ROUTE_CONFIG);
1793
+ }
1794
+ `;
1795
+ }
1796
+
1797
+ function tagPage() {
1798
+ const props = "PageProps<'/tags/[tag]'>";
1799
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1800
+ const metadata = openFn('export async function generateMetadata', [
1801
+ `props: ${props}`,
1802
+ 'parent: ResolvingMetadata',
1803
+ ]);
1804
+ const page = openFn('export default async function ', [`props: ${props}`]);
1805
+ return `${header()}import type { ResolvingMetadata } from 'next';
1806
+ import { converterContext } from '@/lib/converter-context';
1807
+ import { generateTagMetadata, generateTagPage } from '@/lib/route-handlers';
1808
+ import { TAG_LISTING_ROUTE_CONFIG } from '@/lib/routeConfig';
1809
+
1810
+ export function generateStaticParams() {
1811
+ return [];
1812
+ }
1813
+
1814
+ ${extract}
1815
+ const params = await props.params;
1816
+ const { tag } = params;
1817
+ return { tagSlug: tag, path: converterContext.urlCalculators.tag(tag) };
1818
+ }
1819
+
1820
+ ${metadata}
1821
+ const { tagSlug, path } = await extractDetails(props);
1822
+ return await generateTagMetadata(tagSlug, path, TAG_LISTING_ROUTE_CONFIG, parent);
1823
+ }
1824
+
1825
+ ${page}
1826
+ const { tagSlug, path } = await extractDetails(props);
1827
+ return await generateTagPage(tagSlug, path, TAG_LISTING_ROUTE_CONFIG);
1828
+ }
1829
+ `;
1830
+ }
1831
+
1832
+ /**
1833
+ * @param {string} segment
1834
+ */
1835
+ function peopleIndexPage(segment) {
1836
+ const props = `PageProps<'/${segment}'>`;
1837
+ const metadata = openFn('export function generateMetadata', [
1838
+ `_props: ${props}`,
1839
+ 'parent: ResolvingMetadata',
1840
+ ]);
1841
+ const page = openFn('export default function ', [`_props: ${props}`]);
1842
+ const baseImport =
1843
+ segment === 'people'
1844
+ ? `import { PEOPLE_BASE } from '@/lib/constants';\n`
1845
+ : '';
1846
+ const baseExpr = segment === 'people' ? 'PEOPLE_BASE' : `'/${segment}'`;
1847
+ return `${header()}import type { ResolvingMetadata } from 'next';
1848
+ ${baseImport}import { generateTeamIndexMetadata, generateTeamIndexPage } from '@/lib/route-handlers';
1849
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1850
+
1851
+ export function generateStaticParams() {
1852
+ return [];
1853
+ }
1854
+
1855
+ ${metadata}
1856
+ return generateTeamIndexMetadata(${baseExpr}, DEFAULT_ROUTE_CONFIG, parent);
1857
+ }
1858
+
1859
+ ${page}
1860
+ return generateTeamIndexPage(${baseExpr}, DEFAULT_ROUTE_CONFIG);
1861
+ }
1862
+ `;
1863
+ }
1864
+
1865
+ /**
1866
+ * @param {string} base
1867
+ * @param {string} type
1868
+ */
1869
+ function personTypeIndexPage(base, type) {
1870
+ const props = `PageProps<'/${base}/${type}'>`;
1871
+ const routePath = `/${base}/${type}/`;
1872
+ const metadata = openFn('export async function generateMetadata', [
1873
+ `_props: ${props}`,
1874
+ 'parent: ResolvingMetadata',
1875
+ ]);
1876
+ const page = openFn('export default async function ', [`_props: ${props}`]);
1877
+ return `${header()}import type { ResolvingMetadata } from 'next';
1878
+ import { notFound } from 'next/navigation';
1879
+ import { enablePerson } from '@/generated/marketing-flags';
1880
+ import {
1881
+ generatePersonTypeIndexMetadata,
1882
+ generatePersonTypeIndexPage,
1883
+ } from '@/lib/route-handlers';
1884
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1885
+
1886
+ const PERSON_TYPE = '${type}';
1887
+ const PATH = '${routePath}';
1888
+
1889
+ export function generateStaticParams() {
1890
+ return [];
1891
+ }
1892
+
1893
+ ${metadata}
1894
+ if (!enablePerson) {
1895
+ return {};
1896
+ }
1897
+ return await generatePersonTypeIndexMetadata(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
1898
+ }
1899
+
1900
+ ${page}
1901
+ if (!enablePerson) {
1902
+ notFound();
1903
+ }
1904
+ return await generatePersonTypeIndexPage(PERSON_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
1905
+ }
1906
+ `;
1907
+ }
1908
+
1909
+ /**
1910
+ * @param {string} base
1911
+ * @param {string} type
1912
+ */
1913
+ function personTypePersonPage(base, type) {
1914
+ const props = `PageProps<'/${base}/${type}/[person]'>`;
1915
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1916
+ const metadata = openFn('export async function generateMetadata', [
1917
+ `props: ${props}`,
1918
+ 'parent: ResolvingMetadata',
1919
+ ]);
1920
+ const page = openFn('export default async function ', [`props: ${props}`]);
1921
+ return `${header()}import type { ResolvingMetadata } from 'next';
1922
+ import { notFound } from 'next/navigation';
1923
+ import { enablePerson } from '@/generated/marketing-flags';
1924
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
1925
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1926
+
1927
+ export function generateStaticParams() {
1928
+ return [];
1929
+ }
1930
+
1931
+ ${extract}
1932
+ const params = await props.params;
1933
+ const { person } = params;
1934
+ return { person, path: \`/${base}/${type}/\${person}/\` };
1935
+ }
1936
+
1937
+ ${metadata}
1938
+ if (!enablePerson) {
1939
+ return {};
1940
+ }
1941
+ const { person, path } = await extractDetails(props);
1942
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
1943
+ }
1944
+
1945
+ ${page}
1946
+ if (!enablePerson) {
1947
+ notFound();
1948
+ }
1949
+ const { person, path } = await extractDetails(props);
1950
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
1951
+ }
1952
+ `;
1953
+ }
1954
+
1955
+ /**
1956
+ * Person with no person type. Does not redirect to the typed URL.
1957
+ *
1958
+ * @param {string} segment
1959
+ */
1960
+ function untypedPersonPage(segment) {
1961
+ const props = `PageProps<'/${segment}/[person]'>`;
1962
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
1963
+ const metadata = openFn('export async function generateMetadata', [
1964
+ `props: ${props}`,
1965
+ 'parent: ResolvingMetadata',
1966
+ ]);
1967
+ const page = openFn('export default async function ', [`props: ${props}`]);
1968
+ return `${header()}import type { ResolvingMetadata } from 'next';
1969
+ import { notFound } from 'next/navigation';
1970
+ import { enablePerson } from '@/generated/marketing-flags';
1971
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
1972
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
1973
+
1974
+ export function generateStaticParams() {
1975
+ return [];
1976
+ }
1977
+
1978
+ ${extract}
1979
+ const params = await props.params;
1980
+ const { person } = params;
1981
+ return { person, path: \`/${segment}/\${person}/\` };
1982
+ }
1983
+
1984
+ ${metadata}
1985
+ if (!enablePerson) {
1986
+ return {};
1987
+ }
1988
+ const { person, path } = await extractDetails(props);
1989
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
1990
+ }
1991
+
1992
+ ${page}
1993
+ if (!enablePerson) {
1994
+ notFound();
1995
+ }
1996
+ const { person, path } = await extractDetails(props);
1997
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
1998
+ }
1999
+ `;
2000
+ }
2001
+
2002
+ /** @returns {string} */
2003
+ function typedPersonRest() {
2004
+ return `${PERSON_TYPE_ROOT}/[peopleType]/[person]`;
2005
+ }
2006
+
2007
+ /**
2008
+ * Person under a person type, at /peopleType/{peopleType}/{person}/.
2009
+ * Does not redirect to /people/{person}/.
2010
+ */
2011
+ function typedPersonPage() {
2012
+ const props = `PageProps<'/${PERSON_TYPE_ROOT}/[peopleType]/[person]'>`;
2013
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2014
+ const metadata = openFn('export async function generateMetadata', [
2015
+ `props: ${props}`,
2016
+ 'parent: ResolvingMetadata',
2017
+ ]);
2018
+ const page = openFn('export default async function ', [`props: ${props}`]);
2019
+ return `${header()}import type { ResolvingMetadata } from 'next';
2020
+ import { notFound } from 'next/navigation';
2021
+ import { enablePerson } from '@/generated/marketing-flags';
2022
+ import { generatePersonMetadata, generatePersonPage } from '@/lib/route-handlers';
2023
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2024
+
2025
+ export function generateStaticParams() {
2026
+ return [];
2027
+ }
2028
+
2029
+ ${extract}
2030
+ const params = await props.params;
2031
+ const { person, peopleType } = params;
2032
+ return { person, path: \`/${PERSON_TYPE_ROOT}/\${peopleType}/\${person}/\` };
2033
+ }
2034
+
2035
+ ${metadata}
2036
+ if (!enablePerson) {
2037
+ return {};
2038
+ }
2039
+ const { person, path } = await extractDetails(props);
2040
+ return await generatePersonMetadata(person, path, DEFAULT_ROUTE_CONFIG, parent);
2041
+ }
2042
+
2043
+ ${page}
2044
+ if (!enablePerson) {
2045
+ notFound();
2046
+ }
2047
+ const { person, path } = await extractDetails(props);
2048
+ return await generatePersonPage(person, path, DEFAULT_ROUTE_CONFIG);
2049
+ }
2050
+ `;
2051
+ }
2052
+
2053
+ /**
2054
+ * Preview lives at the app root or under Brightlife's `(default)` group.
2055
+ *
2056
+ * @param {string} rel
2057
+ */
2058
+ function isPreviewPage(rel) {
2059
+ return (
2060
+ rel === 'src/app/preview/page.ts' ||
2061
+ rel === 'src/app/preview/page.tsx' ||
2062
+ rel === 'src/app/(default)/preview/page.ts' ||
2063
+ rel === 'src/app/(default)/preview/page.tsx'
2064
+ );
2065
+ }
2066
+
2067
+ /** example-empty Biome line width. Longer signatures are wrapped the same way. */
2068
+ const LINE_WIDTH = 100;
2069
+
2070
+ /**
2071
+ * Dynamic `articles` keeps `urlCalculators`, matching the hand-written pages.
2072
+ * Any other base uses the path of the file that was written. `article()`
2073
+ * inserts the primary tag (`other`) and prefixes `ARTICLES_BASE`.
2074
+ *
2075
+ * @param {string} segment
2076
+ */
2077
+ function usesArticleCalculator(segment) {
2078
+ return segment === 'articles';
2079
+ }
2080
+
2081
+ /**
2082
+ * @param {string} prefix text before `(`, including a trailing space for `function `
2083
+ * @param {string[]} params
2084
+ */
2085
+ function openFn(prefix, params) {
2086
+ const oneLine = `${prefix}(${params.join(', ')}) {`;
2087
+ if (oneLine.length <= LINE_WIDTH) {
2088
+ return oneLine;
2089
+ }
2090
+ const inner = params.map((param) => ` ${param},`).join('\n');
2091
+ return `${prefix}(\n${inner}\n) {`;
2092
+ }
2093
+
2094
+ /**
2095
+ * @param {string} segment
2096
+ */
2097
+ function fixedArticleIndex(segment) {
2098
+ const props = `PageProps<'/${segment}'>`;
2099
+ const metadata = openFn('export async function generateMetadata', [
2100
+ `_props: ${props}`,
2101
+ 'parent: ResolvingMetadata',
2102
+ ]);
2103
+ const page = openFn('export default async function ', [`_props: ${props}`]);
2104
+ return `${header()}import type { ResolvingMetadata } from 'next';
2105
+ import { generateArticleTypeMetadata, generateArticleTypePage } from '@/lib/route-handlers';
2106
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2107
+
2108
+ const ARTICLE_TYPE = '${segment}';
2109
+ const PATH = '/${segment}/';
2110
+
2111
+ export function generateStaticParams() {
2112
+ return [];
2113
+ }
2114
+
2115
+ ${metadata}
2116
+ return await generateArticleTypeMetadata(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG, parent);
2117
+ }
2118
+
2119
+ ${page}
2120
+ return await generateArticleTypePage(ARTICLE_TYPE, PATH, DEFAULT_ROUTE_CONFIG);
2121
+ }
2122
+ `;
2123
+ }
2124
+
2125
+ /**
2126
+ * @param {string} segment
2127
+ */
2128
+ function fixedArticleDetail(segment) {
2129
+ const props = `PageProps<'/${segment}/[...slugs]'>`;
2130
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2131
+ const metadata = openFn('export async function generateMetadata', [
2132
+ `props: ${props}`,
2133
+ 'parent: ResolvingMetadata',
2134
+ ]);
2135
+ const page = openFn('export default async function ', [`props: ${props}`]);
2136
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2137
+ import type { ResolvingMetadata } from 'next';
2138
+ import { notFound } from 'next/navigation';
2139
+ import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2140
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2141
+
2142
+ const ARTICLE_TYPE = '${segment}';
2143
+
2144
+ export function generateStaticParams() {
2145
+ return [];
2146
+ }
2147
+
2148
+ ${extract}
2149
+ const params = await props.params;
2150
+ const articleSlug = joinCmsPathSegments(params.slugs);
2151
+ if (!articleSlug) {
2152
+ notFound();
2153
+ }
2154
+ return {
2155
+ articleSlug,
2156
+ path: \`/${segment}/\${articleSlug}/\`,
2157
+ };
2158
+ }
2159
+
2160
+ ${metadata}
2161
+ const { articleSlug, path } = await extractDetails(props);
2162
+ return await generateArticleMetadata(
2163
+ ARTICLE_TYPE,
2164
+ articleSlug,
2165
+ path,
2166
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2167
+ parent,
2168
+ );
2169
+ }
2170
+
2171
+ ${page}
2172
+ const { articleSlug, path } = await extractDetails(props);
2173
+ return await generateArticlePage(ARTICLE_TYPE, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2174
+ }
2175
+ `;
2176
+ }
2177
+
2178
+ /**
2179
+ * @param {string} segment
2180
+ */
2181
+ function dynamicArticleIndex(segment) {
2182
+ const props = `PageProps<'/${segment}'>`;
2183
+ const articles = usesArticleCalculator(segment);
2184
+ const importBase = articles
2185
+ ? `import { enableArticleTypeIndex } from '@/generated/marketing-flags';
2186
+ import { ARTICLES_BASE } from '@/lib/constants';`
2187
+ : `import { enableArticleTypeIndex } from '@/generated/marketing-flags';`;
2188
+ const baseDecl = articles ? '' : `const BASE = '/${segment}';\n\n`;
2189
+ const baseIdent = articles ? 'ARTICLES_BASE' : 'BASE';
2190
+ const metadata = openFn('export function generateMetadata', [
2191
+ `_props: ${props}`,
2192
+ 'parent: ResolvingMetadata',
2193
+ ]);
2194
+ const page = openFn('export default function ', [`_props: ${props}`]);
2195
+ return `${header()}import type { ResolvingMetadata } from 'next';
2196
+ import { notFound } from 'next/navigation';
2197
+ ${importBase}
2198
+ import {
2199
+ generateArticleTypesIndexMetadata,
2200
+ generateArticleTypesIndexPage,
2201
+ } from '@/lib/route-handlers';
2202
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2203
+
2204
+ ${baseDecl}export function generateStaticParams() {
2205
+ return [];
2206
+ }
2207
+
2208
+ ${metadata}
2209
+ if (!enableArticleTypeIndex) {
2210
+ notFound();
2211
+ }
2212
+ return generateArticleTypesIndexMetadata(${baseIdent}, DEFAULT_ROUTE_CONFIG, parent);
2213
+ }
2214
+
2215
+ ${page}
2216
+ if (!enableArticleTypeIndex) {
2217
+ notFound();
2218
+ }
2219
+ return generateArticleTypesIndexPage(${baseIdent}, DEFAULT_ROUTE_CONFIG);
2220
+ }
2221
+ `;
2222
+ }
2223
+
2224
+ /**
2225
+ * @param {string} segment
2226
+ */
2227
+ function dynamicArticleType(segment) {
2228
+ const props = `PageProps<'/${segment}/[articleType]'>`;
2229
+ const calculator = usesArticleCalculator(segment);
2230
+ const converterImport = calculator
2231
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2232
+ : '';
2233
+ const pathExpr = calculator
2234
+ ? 'converterContext.urlCalculators.articleType(articleType)'
2235
+ : `\`/${segment}/\${articleType}/\``;
2236
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2237
+ const metadata = openFn('export async function generateMetadata', [
2238
+ `props: ${props}`,
2239
+ 'parent: ResolvingMetadata',
2240
+ ]);
2241
+ const page = openFn('export default async function ', [`props: ${props}`]);
2242
+ return `${header()}import type { ResolvingMetadata } from 'next';
2243
+ ${converterImport}import { generateArticleTypeMetadata, generateArticleTypePage } from '@/lib/route-handlers';
2244
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2245
+
2246
+ export function generateStaticParams() {
2247
+ return [];
2248
+ }
2249
+
2250
+ ${extract}
2251
+ const params = await props.params;
2252
+ const { articleType } = params;
2253
+ return { slug: articleType, path: ${pathExpr} };
2254
+ }
2255
+
2256
+ ${metadata}
2257
+ const { slug, path } = await extractDetails(props);
2258
+ return await generateArticleTypeMetadata(slug, path, DEFAULT_ROUTE_CONFIG, parent);
2259
+ }
2260
+
2261
+ ${page}
2262
+ const { slug, path } = await extractDetails(props);
2263
+ return await generateArticleTypePage(slug, path, DEFAULT_ROUTE_CONFIG);
2264
+ }
2265
+ `;
2266
+ }
2267
+
2268
+ /**
2269
+ * @param {string} segment
2270
+ */
2271
+ function dynamicArticleDetail(segment) {
2272
+ const props = `PageProps<'/${segment}/[articleType]/[...slugs]'>`;
2273
+ const calculator = usesArticleCalculator(segment);
2274
+ const converterImport = calculator
2275
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2276
+ : '';
2277
+ const pathExpr = calculator
2278
+ ? 'converterContext.urlCalculators.article(articleType, articleSlug)'
2279
+ : `\`/${segment}/\${articleType}/\${articleSlug}/\``;
2280
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2281
+ const metadata = openFn('export async function generateMetadata', [
2282
+ `props: ${props}`,
2283
+ 'parent: ResolvingMetadata',
2284
+ ]);
2285
+ const page = openFn('export default async function ', [`props: ${props}`]);
2286
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2287
+ import type { ResolvingMetadata } from 'next';
2288
+ import { notFound } from 'next/navigation';
2289
+ ${converterImport}import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2290
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2291
+
2292
+ export function generateStaticParams() {
2293
+ return [];
2294
+ }
2295
+
2296
+ ${extract}
2297
+ const params = await props.params;
2298
+ const articleType = joinCmsPathSegments(params.articleType);
2299
+ const articleSlug = joinCmsPathSegments(params.slugs);
2300
+ if (!(articleType && articleSlug)) {
2301
+ notFound();
2302
+ }
2303
+ return {
2304
+ articleType,
2305
+ articleSlug,
2306
+ path: ${pathExpr},
2307
+ };
2308
+ }
2309
+
2310
+ ${metadata}
2311
+ const { articleType, articleSlug, path } = await extractDetails(props);
2312
+ return await generateArticleMetadata(
2313
+ articleType,
2314
+ articleSlug,
2315
+ path,
2316
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2317
+ parent,
2318
+ );
2319
+ }
2320
+
2321
+ ${page}
2322
+ const { articleType, articleSlug, path } = await extractDetails(props);
2323
+ return await generateArticlePage(articleType, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2324
+ }
2325
+ `;
2326
+ }
2327
+
2328
+ /**
2329
+ * @param {string} segment
2330
+ */
2331
+ function fixedArticleTag(segment) {
2332
+ const props = `PageProps<'/${segment}/[tag]'>`;
2333
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2334
+ const metadata = openFn('export async function generateMetadata', [
2335
+ `props: ${props}`,
2336
+ 'parent: ResolvingMetadata',
2337
+ ]);
2338
+ const page = openFn('export default async function ', [`props: ${props}`]);
2339
+ return `${header()}import type { ResolvingMetadata } from 'next';
2340
+ import {
2341
+ generateArticleTypeTagMetadata,
2342
+ generateArticleTypeTagPage,
2343
+ } from '@/lib/route-handlers';
2344
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2345
+
2346
+ const ARTICLE_TYPE = '${segment}';
2347
+
2348
+ export function generateStaticParams() {
2349
+ return [];
2350
+ }
2351
+
2352
+ ${extract}
2353
+ const params = await props.params;
2354
+ const { tag } = params;
2355
+ return { tag, path: \`/${segment}/\${tag}/\` };
2356
+ }
2357
+
2358
+ ${metadata}
2359
+ const { tag, path } = await extractDetails(props);
2360
+ return await generateArticleTypeTagMetadata(ARTICLE_TYPE, tag, path, DEFAULT_ROUTE_CONFIG, parent);
2361
+ }
2362
+
2363
+ ${page}
2364
+ const { tag, path } = await extractDetails(props);
2365
+ return await generateArticleTypeTagPage(ARTICLE_TYPE, tag, path, DEFAULT_ROUTE_CONFIG);
2366
+ }
2367
+ `;
2368
+ }
2369
+
2370
+ /**
2371
+ * @param {string} segment
2372
+ */
2373
+ function fixedArticleTagDetail(segment) {
2374
+ const props = `PageProps<'/${segment}/[tag]/[...slugs]'>`;
2375
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2376
+ const metadata = openFn('export async function generateMetadata', [
2377
+ `props: ${props}`,
2378
+ 'parent: ResolvingMetadata',
2379
+ ]);
2380
+ const page = openFn('export default async function ', [`props: ${props}`]);
2381
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2382
+ import type { ResolvingMetadata } from 'next';
2383
+ import { notFound } from 'next/navigation';
2384
+ import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2385
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2386
+
2387
+ const ARTICLE_TYPE = '${segment}';
2388
+
2389
+ export function generateStaticParams() {
2390
+ return [];
2391
+ }
2392
+
2393
+ ${extract}
2394
+ const params = await props.params;
2395
+ const tag = joinCmsPathSegments(params.tag);
2396
+ const articleSlug = joinCmsPathSegments(params.slugs);
2397
+ if (!(tag && articleSlug)) {
2398
+ notFound();
2399
+ }
2400
+ return {
2401
+ tag,
2402
+ articleSlug,
2403
+ path: \`/${segment}/\${tag}/\${articleSlug}/\`,
2404
+ };
2405
+ }
2406
+
2407
+ ${metadata}
2408
+ const { articleSlug, path } = await extractDetails(props);
2409
+ return await generateArticleMetadata(
2410
+ ARTICLE_TYPE,
2411
+ articleSlug,
2412
+ path,
2413
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2414
+ parent,
2415
+ );
2416
+ }
2417
+
2418
+ ${page}
2419
+ const { articleSlug, path } = await extractDetails(props);
2420
+ return await generateArticlePage(ARTICLE_TYPE, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2421
+ }
2422
+ `;
2423
+ }
2424
+
2425
+ /**
2426
+ * @param {string} segment
2427
+ */
2428
+ function dynamicArticleTag(segment) {
2429
+ const props = `PageProps<'/${segment}/[articleType]/[tag]'>`;
2430
+ const calculator = usesArticleCalculator(segment);
2431
+ const converterImport = calculator
2432
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2433
+ : '';
2434
+ const pathExpr = calculator
2435
+ ? 'converterContext.urlCalculators.articleTypeTag(articleType, tag)'
2436
+ : `\`/${segment}/\${articleType}/\${tag}/\``;
2437
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2438
+ const metadata = openFn('export async function generateMetadata', [
2439
+ `props: ${props}`,
2440
+ 'parent: ResolvingMetadata',
2441
+ ]);
2442
+ const page = openFn('export default async function ', [`props: ${props}`]);
2443
+ return `${header()}import type { ResolvingMetadata } from 'next';
2444
+ ${converterImport}import {
2445
+ generateArticleTypeTagMetadata,
2446
+ generateArticleTypeTagPage,
2447
+ } from '@/lib/route-handlers';
2448
+ import { DEFAULT_ROUTE_CONFIG } from '@/lib/routeConfig';
2449
+
2450
+ export function generateStaticParams() {
2451
+ return [];
2452
+ }
2453
+
2454
+ ${extract}
2455
+ const params = await props.params;
2456
+ const { articleType, tag } = params;
2457
+ return { articleType, tag, path: ${pathExpr} };
2458
+ }
2459
+
2460
+ ${metadata}
2461
+ const { articleType, tag, path } = await extractDetails(props);
2462
+ return await generateArticleTypeTagMetadata(
2463
+ articleType,
2464
+ tag,
2465
+ path,
2466
+ DEFAULT_ROUTE_CONFIG,
2467
+ parent,
2468
+ );
2469
+ }
2470
+
2471
+ ${page}
2472
+ const { articleType, tag, path } = await extractDetails(props);
2473
+ return await generateArticleTypeTagPage(articleType, tag, path, DEFAULT_ROUTE_CONFIG);
2474
+ }
2475
+ `;
2476
+ }
2477
+
2478
+ /**
2479
+ * @param {string} segment
2480
+ */
2481
+ function dynamicArticleTagDetail(segment) {
2482
+ const props = `PageProps<'/${segment}/[articleType]/[tag]/[...slugs]'>`;
2483
+ const calculator = usesArticleCalculator(segment);
2484
+ const converterImport = calculator
2485
+ ? `import { converterContext } from '@/lib/converter-context';\n`
2486
+ : '';
2487
+ const pathExpr = calculator
2488
+ ? 'converterContext.urlCalculators.article(articleType, articleSlug, tag)'
2489
+ : `\`/${segment}/\${articleType}/\${tag}/\${articleSlug}/\``;
2490
+ const extract = openFn('async function extractDetails', [`props: ${props}`]);
2491
+ const metadata = openFn('export async function generateMetadata', [
2492
+ `props: ${props}`,
2493
+ 'parent: ResolvingMetadata',
2494
+ ]);
2495
+ const page = openFn('export default async function ', [`props: ${props}`]);
2496
+ return `${header()}import { joinCmsPathSegments } from '@se-studio/core-ui';
2497
+ import type { ResolvingMetadata } from 'next';
2498
+ import { notFound } from 'next/navigation';
2499
+ ${converterImport}import { generateArticleMetadata, generateArticlePage } from '@/lib/route-handlers';
2500
+ import { ARTICLE_DETAIL_ROUTE_CONFIG } from '@/lib/routeConfig';
2501
+
2502
+ export function generateStaticParams() {
2503
+ return [];
2504
+ }
2505
+
2506
+ ${extract}
2507
+ const params = await props.params;
2508
+ const articleType = joinCmsPathSegments(params.articleType);
2509
+ const tag = joinCmsPathSegments(params.tag);
2510
+ const articleSlug = joinCmsPathSegments(params.slugs);
2511
+ if (!(articleType && tag && articleSlug)) {
2512
+ notFound();
2513
+ }
2514
+ return {
2515
+ articleType,
2516
+ tag,
2517
+ articleSlug,
2518
+ path: ${pathExpr},
2519
+ };
2520
+ }
2521
+
2522
+ ${metadata}
2523
+ const { articleType, articleSlug, path } = await extractDetails(props);
2524
+ return await generateArticleMetadata(
2525
+ articleType,
2526
+ articleSlug,
2527
+ path,
2528
+ ARTICLE_DETAIL_ROUTE_CONFIG,
2529
+ parent,
2530
+ );
2531
+ }
2532
+
2533
+ ${page}
2534
+ const { articleType, articleSlug, path } = await extractDetails(props);
2535
+ return await generateArticlePage(articleType, articleSlug, path, ARTICLE_DETAIL_ROUTE_CONFIG);
2536
+ }
2537
+ `;
2538
+ }