@unbase-app/pages 0.3.0 → 0.4.1
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.
- package/README.md +40 -4
- package/astro.d.mts +14 -1
- package/astro.mjs +93 -5
- package/binding.mjs +1687 -0
- package/core.mjs +1278 -50
- package/node.mjs +24 -2
- package/package.json +5 -3
- package/vite.d.mts +20 -1
- package/vite.mjs +234 -13
package/core.mjs
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
//
|
|
14
14
|
// parsePageFile unbase.pages.json, validated
|
|
15
15
|
// deployContext production | preview | development, never from NODE_ENV
|
|
16
|
-
// discover the pages the code makes (Astro, Next.js, React Router)
|
|
16
|
+
// discover the pages the code makes (Astro, Next.js, React Router, HTML files)
|
|
17
17
|
// draftCheck whether one page can be kept out of a production build
|
|
18
18
|
// linksTo the files that name a page's address
|
|
19
19
|
// leakPrints text that only a draft page has, to search the output for
|
|
@@ -54,13 +54,19 @@ export function normalisePath(p) {
|
|
|
54
54
|
// ── The page file ──────────────────────────────────────────────────────────
|
|
55
55
|
|
|
56
56
|
/**
|
|
57
|
-
* unbase.pages.json: `{ "pages": { "/address": { "draft": true
|
|
57
|
+
* unbase.pages.json: `{ "pages": { "/address": { "draft": true, "name": "Pricing" } },
|
|
58
|
+
* "folders": { "/legal": { "name": "Legal" } }, "redirects": { "/old": "/new" } }`. Absent is valid
|
|
59
|
+
* (no flags, no redirects). A page's or folder's `name` is what Unbase calls it (never rendered; a
|
|
60
|
+
* folder is an address with pages under it and none of its own, docs/plan-folders-and-redirects.md);
|
|
61
|
+
* `redirects` send an old address on, applied at build by the framework's package
|
|
62
|
+
* (docs/plan-page-actions.md). A redirect's address may end in `/[...path]`: everything under it,
|
|
63
|
+
* carried over.
|
|
58
64
|
* @param {string | null | undefined} text
|
|
59
|
-
* @returns {{ ok: true, exists: boolean, pages: Record<string, { draft?: boolean }> } | { ok: false, exists: true, error: string, pages: {} }}
|
|
65
|
+
* @returns {{ ok: true, exists: boolean, error?: undefined, pages: Record<string, { draft?: boolean, name?: string }>, folders: Record<string, { name: string }>, redirects: Record<string, string> } | { ok: false, exists: true, error: string, pages: {}, folders: {}, redirects: {} }}
|
|
60
66
|
*/
|
|
61
67
|
export function parsePageFile(text) {
|
|
62
|
-
if (text == null) return { ok: true, exists: false, pages: {} };
|
|
63
|
-
const fail = (error) => ({ ok: /** @type {const} */ (false), exists: true, error, pages: {} });
|
|
68
|
+
if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
|
|
69
|
+
const fail = (error) => ({ ok: /** @type {const} */ (false), exists: /** @type {const} */ (true), error, pages: {}, folders: {}, redirects: {} });
|
|
64
70
|
let data;
|
|
65
71
|
try {
|
|
66
72
|
data = JSON.parse(text);
|
|
@@ -70,17 +76,40 @@ export function parsePageFile(text) {
|
|
|
70
76
|
if (!isObject(data)) return fail("the file is not an object");
|
|
71
77
|
const pages = data.pages ?? {};
|
|
72
78
|
if (!isObject(pages)) return fail("`pages` is not an object");
|
|
73
|
-
/** @type {Record<string, { draft?: boolean }>} */
|
|
79
|
+
/** @type {Record<string, { draft?: boolean, name?: string }>} */
|
|
74
80
|
const out = {};
|
|
75
81
|
for (const [address, entry] of Object.entries(pages)) {
|
|
76
82
|
if (!address.startsWith("/")) return fail(`${address}: an address starts with /`);
|
|
77
83
|
if (!isObject(entry)) return fail(`${address}: not an object`);
|
|
78
84
|
if (entry.draft !== undefined && typeof entry.draft !== "boolean") return fail(`${address}: draft is true or false`);
|
|
79
|
-
|
|
85
|
+
if (entry.name !== undefined && typeof entry.name !== "string") return fail(`${address}: name is text`);
|
|
86
|
+
out[normalisePath(address)] = { ...(entry.draft === undefined ? {} : { draft: entry.draft }), ...(entry.name ? { name: entry.name } : {}) };
|
|
80
87
|
}
|
|
81
|
-
|
|
88
|
+
const folderData = data.folders ?? {};
|
|
89
|
+
if (!isObject(folderData)) return fail("`folders` is not an object");
|
|
90
|
+
/** @type {Record<string, { name: string }>} */
|
|
91
|
+
const folders = {};
|
|
92
|
+
for (const [address, entry] of Object.entries(folderData)) {
|
|
93
|
+
if (!address.startsWith("/")) return fail(`folders: ${address}: an address starts with /`);
|
|
94
|
+
if (!isObject(entry) || (entry.name !== undefined && typeof entry.name !== "string")) return fail(`folders: ${address}: name is text`);
|
|
95
|
+
if (entry.name) folders[normalisePath(address)] = { name: entry.name };
|
|
96
|
+
}
|
|
97
|
+
const redirects = data.redirects ?? {};
|
|
98
|
+
if (!isObject(redirects)) return fail("`redirects` is not an object");
|
|
99
|
+
/** @type {Record<string, string>} */
|
|
100
|
+
const sends = {};
|
|
101
|
+
for (const [from, to] of Object.entries(redirects)) {
|
|
102
|
+
if (!from.startsWith("/")) return fail(`redirects: ${from}: an address starts with /`);
|
|
103
|
+
if (typeof to !== "string" || !to.startsWith("/")) return fail(`redirects: ${from}: goes to an address that starts with /`);
|
|
104
|
+
if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
|
|
105
|
+
sends[normalisePath(from)] = normalisePath(to);
|
|
106
|
+
}
|
|
107
|
+
return { ok: true, exists: true, pages: out, folders, redirects: sends };
|
|
82
108
|
}
|
|
83
109
|
|
|
110
|
+
/** A redirect's address that carries what is under it: `/old/[...path]`. */
|
|
111
|
+
const REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
|
|
112
|
+
|
|
84
113
|
/** The addresses flagged as draft, sorted. */
|
|
85
114
|
export const draftPaths = (file) =>
|
|
86
115
|
Object.keys(file.pages)
|
|
@@ -134,14 +163,24 @@ function stringEnd(src, i) {
|
|
|
134
163
|
export function stripComments(src) {
|
|
135
164
|
let out = "";
|
|
136
165
|
let i = 0;
|
|
166
|
+
// Text up to the next comment or string goes across whole: a large file is not built a character at a time.
|
|
167
|
+
const special = /\/[/*]|["'`]/g;
|
|
137
168
|
while (i < src.length) {
|
|
169
|
+
special.lastIndex = i;
|
|
170
|
+
const next = special.exec(src);
|
|
171
|
+
const to = next ? next.index : src.length;
|
|
172
|
+
if (to > i) {
|
|
173
|
+
out += src.slice(i, to);
|
|
174
|
+
i = to;
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
138
177
|
const c = src[i];
|
|
139
178
|
const d = src[i + 1];
|
|
140
179
|
if (c === "/" && d === "/") {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
180
|
+
const end = src.indexOf("\n", i);
|
|
181
|
+
const stop = end < 0 ? src.length : end;
|
|
182
|
+
out += " ".repeat(stop - i);
|
|
183
|
+
i = stop;
|
|
145
184
|
continue;
|
|
146
185
|
}
|
|
147
186
|
if (c === "/" && d === "*") {
|
|
@@ -245,6 +284,24 @@ function astroPages(paths) {
|
|
|
245
284
|
return out;
|
|
246
285
|
}
|
|
247
286
|
|
|
287
|
+
/**
|
|
288
|
+
* A site of HTML files (detection `html`: no build): a page per .html file, at the address Vercel
|
|
289
|
+
* serves it from (and the runner's static server, unbase-operator src/static-server.ts): `index.html`
|
|
290
|
+
* of a folder at the folder, any other file by its name. 404.html is the not-found page, no page.
|
|
291
|
+
*/
|
|
292
|
+
function htmlPages(paths) {
|
|
293
|
+
/** @type {Page[]} */
|
|
294
|
+
const out = [];
|
|
295
|
+
for (const p of paths) {
|
|
296
|
+
if (!p.endsWith(".html") || p === "404.html") continue;
|
|
297
|
+
const segments = p.split("/");
|
|
298
|
+
if (segments.some((s) => s.startsWith("."))) continue;
|
|
299
|
+
if (segments.at(-1) === "index.html") segments.pop();
|
|
300
|
+
out.push({ path: address(segments), kind: "file", file: p });
|
|
301
|
+
}
|
|
302
|
+
return out;
|
|
303
|
+
}
|
|
304
|
+
|
|
248
305
|
/** Next.js: app/**\/page.* and pages/**, as unbase-projects' pages.ts read them. */
|
|
249
306
|
function nextPages(paths) {
|
|
250
307
|
/** @type {Page[]} */
|
|
@@ -422,7 +479,15 @@ export function removeRoutes({ file, code, paths, text, drop }) {
|
|
|
422
479
|
export function discover({ framework, paths, text }) {
|
|
423
480
|
const kept = paths.filter((p) => !SKIP.test(p));
|
|
424
481
|
const found =
|
|
425
|
-
framework === "astro"
|
|
482
|
+
framework === "astro"
|
|
483
|
+
? { pages: astroPages(kept), notFound: null }
|
|
484
|
+
: framework === "next"
|
|
485
|
+
? { pages: nextPages(kept), notFound: null }
|
|
486
|
+
: framework === "vite-react"
|
|
487
|
+
? reactRouterPages(kept, text)
|
|
488
|
+
: framework === "html"
|
|
489
|
+
? { pages: htmlPages(kept), notFound: null }
|
|
490
|
+
: { pages: [], notFound: null };
|
|
426
491
|
const seen = new Set();
|
|
427
492
|
const pages = found.pages
|
|
428
493
|
.filter((p) => (seen.has(p.path) ? false : (seen.add(p.path), true)))
|
|
@@ -435,8 +500,26 @@ export function discover({ framework, paths, text }) {
|
|
|
435
500
|
const CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
|
|
436
501
|
/** Where content collections are defined: naming one there is not using it. */
|
|
437
502
|
const CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
|
|
438
|
-
/**
|
|
439
|
-
|
|
503
|
+
/**
|
|
504
|
+
* Written by comment-modus: content file → its collection, where that is not its folder. 1.11 and
|
|
505
|
+
* newer write collections.json; LEGACY-NL: older ones only collecties.json. Both are read, merged as
|
|
506
|
+
* comment-modus merges them (the English one wins), and both are written.
|
|
507
|
+
*/
|
|
508
|
+
const COLLECTIONS = "src/content/.schemas/collections.json";
|
|
509
|
+
const LEGACY_COLLECTIONS = "src/content/.schemas/collecties.json";
|
|
510
|
+
|
|
511
|
+
/** The list from either file; null when neither is there or readable. */
|
|
512
|
+
function readCollections(text) {
|
|
513
|
+
/** @type {Record<string, unknown> | null} */
|
|
514
|
+
let out = null;
|
|
515
|
+
for (const p of [LEGACY_COLLECTIONS, COLLECTIONS]) {
|
|
516
|
+
try {
|
|
517
|
+
const d = JSON.parse(text(p) ?? "null");
|
|
518
|
+
if (isObject(d)) out = { ...(out ?? {}), ...d };
|
|
519
|
+
} catch {}
|
|
520
|
+
}
|
|
521
|
+
return out;
|
|
522
|
+
}
|
|
440
523
|
|
|
441
524
|
/** The names a content file goes by: its entry id (file name) and its collection. */
|
|
442
525
|
function contentNames(paths, text) {
|
|
@@ -446,9 +529,10 @@ function contentNames(paths, text) {
|
|
|
446
529
|
if (!files.has(name)) files.set(name, new Set());
|
|
447
530
|
files.get(name).add(f);
|
|
448
531
|
};
|
|
532
|
+
/** @type {Record<string, unknown>} */
|
|
449
533
|
let collections = {};
|
|
450
534
|
try {
|
|
451
|
-
collections =
|
|
535
|
+
collections = readCollections(text) ?? {};
|
|
452
536
|
} catch {}
|
|
453
537
|
for (const f of paths) {
|
|
454
538
|
if (!CONTENT_JSON.test(f)) continue;
|
|
@@ -485,22 +569,91 @@ function ownCode(page, importers, imports) {
|
|
|
485
569
|
|
|
486
570
|
/** Astro's own reading functions: collection first, then (getEntry) the entry. */
|
|
487
571
|
const ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
|
|
572
|
+
/** Whether a text names one of them. */
|
|
573
|
+
const ASTRO_NAMED = /getCollection|getEntry|getEntries/;
|
|
488
574
|
|
|
489
575
|
/**
|
|
490
576
|
* How the site reads content, as the editability manifest's `reads` say it (plan-editable F0):
|
|
491
577
|
* Astro's functions; the site's own functions that pass their first argument on as the collection
|
|
492
578
|
* (`getPagina(naam)`: `byName`); and those that read fixed content (`getEvenementen()` a whole
|
|
493
|
-
* collection, `getActieAgendaTeksten()` one entry: `fixed`). `
|
|
494
|
-
*
|
|
579
|
+
* collection, `getActieAgendaTeksten()` one entry: `fixed`). `files` is every code file with its
|
|
580
|
+
* text; `code` holds, without comments, the ones that can read content (`reading`).
|
|
581
|
+
*
|
|
582
|
+
* Only files that name a reading function are read for helpers: Astro's own, then the helpers
|
|
583
|
+
* found, again until no file is added. A file that names none of them defines no helper that reads
|
|
584
|
+
* and calls none, so the answer is the one all files give (a large repo's backend, tests and docs:
|
|
585
|
+
* 1.9 s of an Edge Function's 2 s on Unbase's own, docs/plan-page-analysis.md).
|
|
495
586
|
*/
|
|
496
587
|
function contentReads(paths, text) {
|
|
497
|
-
/** @type {
|
|
498
|
-
const
|
|
588
|
+
/** @type {[string, string][]} */
|
|
589
|
+
const files = [];
|
|
499
590
|
for (const p of paths) {
|
|
500
591
|
if (!CODE.test(p) || SKIP.test(p)) continue;
|
|
501
592
|
const src = text(p);
|
|
502
|
-
if (src)
|
|
593
|
+
if (src) files.push([p, src]);
|
|
594
|
+
}
|
|
595
|
+
const picked = new Set();
|
|
596
|
+
// Each round asks the files not yet read only about the names it found: they named none before.
|
|
597
|
+
// A file is parsed once, whichever round reads it.
|
|
598
|
+
const asked = new Set(ASTRO_READS);
|
|
599
|
+
const parsed = new Map();
|
|
600
|
+
let names = ASTRO_READS;
|
|
601
|
+
let reads = null;
|
|
602
|
+
for (;;) {
|
|
603
|
+
let grew = false;
|
|
604
|
+
if (names.length) {
|
|
605
|
+
const naming = new RegExp(names.map(escape).join("|"));
|
|
606
|
+
for (const [p, src] of files) {
|
|
607
|
+
if (picked.has(p) || !naming.test(src)) continue;
|
|
608
|
+
picked.add(p);
|
|
609
|
+
grew = true;
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
if (reads && !grew) return { ...reads, files };
|
|
613
|
+
reads = readsOver(files.filter(([p]) => picked.has(p)), parsed);
|
|
614
|
+
names = [...reads.byName, ...reads.fixed.keys()].filter((n) => !asked.has(n));
|
|
615
|
+
names.forEach((n) => asked.add(n));
|
|
616
|
+
if (!names.length) return { ...reads, files };
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const DIRECT = new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
621
|
+
const FUNCTION = /(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*\(([^)]*)\)|export\s+const\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?(?:<[^>]*>)?\s*\(([^)]*)\)\s*(?::[^=]*)?=>/g;
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* One file's code without comments and its functions: each one's name, body and where it is, and
|
|
625
|
+
* what its own body reads (`byName`: it passes its first argument on as the collection, with the
|
|
626
|
+
* entry it always reads; `direct`: Astro's functions called with a literal). Only from the file.
|
|
627
|
+
*/
|
|
628
|
+
function parseCode(p, src) {
|
|
629
|
+
const code = stripComments(src);
|
|
630
|
+
const fns = [];
|
|
631
|
+
if (!/\.(ts|mts|js|mjs)$/.test(p)) return { code, fns };
|
|
632
|
+
// Functions whether exported or not: a site's helpers may go through a module's own `enkel(collectie)`.
|
|
633
|
+
for (const m of code.matchAll(FUNCTION)) {
|
|
634
|
+
const name = m[1] ?? m[3];
|
|
635
|
+
const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
|
|
636
|
+
// The body: a block, or for an arrow the expression up to the end of its statement.
|
|
637
|
+
let at = m.index + m[0].length;
|
|
638
|
+
while (/\s/.test(code[at] ?? "")) at++;
|
|
639
|
+
const block = code.indexOf("{", at);
|
|
640
|
+
const braces = code[at] === "{" ? at : m[1] && block > 0 ? block : -1;
|
|
641
|
+
const body = braces >= 0 ? (braced(code, braces) ?? "") : code.slice(at, code.slice(at).search(/;|\n\s*\n|$/) + at);
|
|
642
|
+
const start = braces >= 0 ? braces + 1 : at;
|
|
643
|
+
// Every reading below names one of Astro's functions: a body that names none is not searched.
|
|
644
|
+
const naming = ASTRO_NAMED.test(body);
|
|
645
|
+
const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape(first)}\\b`).test(body));
|
|
646
|
+
const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : undefined;
|
|
647
|
+
const direct = naming ? Array.from(body.matchAll(DIRECT), (d) => [d[1], d[2]]) : [];
|
|
648
|
+
fns.push({ name, start, end: start + body.length, body, byName, entry, direct });
|
|
503
649
|
}
|
|
650
|
+
return { code, fns };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** contentReads over `files` (in path order): what their functions read, and their code without comments. */
|
|
654
|
+
function readsOver(files, parsed = new Map()) {
|
|
655
|
+
/** @type {Map<string, string>} */
|
|
656
|
+
const code = new Map();
|
|
504
657
|
const astro = ASTRO_READS.join("|");
|
|
505
658
|
const byName = new Set(ASTRO_READS);
|
|
506
659
|
/** The entry a reading function always reads: `getEntry(collectie, "pagina")` → "pagina". */
|
|
@@ -511,47 +664,38 @@ function contentReads(paths, text) {
|
|
|
511
664
|
const bodies = new Map();
|
|
512
665
|
/** Where each file's helpers have their bodies, [start, end): what a body reads, its callers read. */
|
|
513
666
|
const spans = new Map();
|
|
514
|
-
const DIRECT = new RegExp(`\\b(?:${astro})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
515
667
|
const addFixed = (name, whole, entry) => {
|
|
516
668
|
if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
|
|
517
669
|
if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
|
|
518
670
|
else fixed.get(name).whole.add(whole);
|
|
519
671
|
};
|
|
520
|
-
for (const [p, src] of
|
|
521
|
-
if (
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
|
|
526
|
-
// The body: a block, or for an arrow the expression up to the end of its statement.
|
|
527
|
-
let at = m.index + m[0].length;
|
|
528
|
-
while (/\s/.test(src[at] ?? "")) at++;
|
|
529
|
-
const block = src.indexOf("{", at);
|
|
530
|
-
const braces = src[at] === "{" ? at : m[1] && block > 0 ? block : -1;
|
|
531
|
-
const body = braces >= 0 ? (braced(src, braces) ?? "") : src.slice(at, src.slice(at).search(/;|\n\s*\n|$/) + at);
|
|
532
|
-
const start = braces >= 0 ? braces + 1 : at;
|
|
672
|
+
for (const [p, src] of files) {
|
|
673
|
+
if (!parsed.has(p)) parsed.set(p, parseCode(p, src));
|
|
674
|
+
const file = parsed.get(p);
|
|
675
|
+
code.set(p, file.code);
|
|
676
|
+
for (const fn of file.fns) {
|
|
533
677
|
if (!spans.has(p)) spans.set(p, []);
|
|
534
|
-
spans.get(p).push([start,
|
|
535
|
-
if (
|
|
536
|
-
byName.add(name);
|
|
537
|
-
|
|
538
|
-
if (entry) entryOf.set(name, entry);
|
|
678
|
+
spans.get(p).push([fn.start, fn.end]);
|
|
679
|
+
if (fn.byName) {
|
|
680
|
+
byName.add(fn.name);
|
|
681
|
+
if (fn.entry) entryOf.set(fn.name, fn.entry);
|
|
539
682
|
}
|
|
540
|
-
bodies.set(name, body);
|
|
541
|
-
for (const
|
|
683
|
+
bodies.set(fn.name, fn.body);
|
|
684
|
+
for (const [whole, entry] of fn.direct) addFixed(fn.name, whole, entry);
|
|
542
685
|
}
|
|
543
686
|
}
|
|
544
687
|
// A helper that calls one of the site's reading functions with a literal reads that content
|
|
545
688
|
// (`getVerlangensOverzicht = () => enkel("verlangensOverzicht", …)`): its entry, else the collection.
|
|
546
689
|
for (const [name, body] of bodies) {
|
|
547
690
|
for (const fn of byName) {
|
|
548
|
-
if (fn === name || ASTRO_READS.includes(fn)) continue;
|
|
691
|
+
if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
|
|
549
692
|
for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
|
|
550
693
|
}
|
|
551
694
|
}
|
|
552
695
|
// A helper that calls a helper reads what that one reads (`getActieAgenda()` → `getActieAgendaTeksten()`).
|
|
553
696
|
// Each body's calls are read once and looked up, not searched for helper by helper.
|
|
554
|
-
|
|
697
|
+
// Nothing read yet: no call can pass anything on.
|
|
698
|
+
const calls = fixed.size ? new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))])) : new Map();
|
|
555
699
|
for (let grew = true; grew; ) {
|
|
556
700
|
grew = false;
|
|
557
701
|
for (const [name, called] of calls) {
|
|
@@ -567,8 +711,10 @@ function contentReads(paths, text) {
|
|
|
567
711
|
}
|
|
568
712
|
}
|
|
569
713
|
}
|
|
714
|
+
// The helpers that read, as whole identifiers (as IDENTIFIER would find them), longest first.
|
|
715
|
+
const helpers = fixed.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
|
|
570
716
|
const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
571
|
-
return { code, byName, byNameCall, entryOf, fixed, astro, spans };
|
|
717
|
+
return { code, byName, byNameCall, entryOf, fixed, astro, spans, helpers };
|
|
572
718
|
}
|
|
573
719
|
|
|
574
720
|
/** A call: `name(`, not `obj.name(`. */
|
|
@@ -621,8 +767,9 @@ function readsIn(src, reads, path = null) {
|
|
|
621
767
|
}
|
|
622
768
|
// The file's names counted once, and the helpers among them looked up: one pass per file, however
|
|
623
769
|
// many helpers the site has (1,000 pages each with its own took 1.6 s searched one by one).
|
|
770
|
+
// Only the helpers' own names are counted: an identifier that is none of them adds nothing.
|
|
624
771
|
const mentions = new Map();
|
|
625
|
-
for (const [name] of code.matchAll(
|
|
772
|
+
if (reads.helpers) for (const [name] of code.matchAll(reads.helpers)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
|
|
626
773
|
const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
|
|
627
774
|
for (const [name, n] of mentions) {
|
|
628
775
|
const read = reads.fixed.get(name);
|
|
@@ -637,20 +784,30 @@ function readsIn(src, reads, path = null) {
|
|
|
637
784
|
* What the whole site reads, which no page changes: once per set of files, not once per page (20
|
|
638
785
|
* pages each reading a real site's 300 files ran out of an Edge Function's CPU, 26-10). Kept by the import
|
|
639
786
|
* graph, which a registry or a build makes once from the same files.
|
|
640
|
-
* @
|
|
787
|
+
* @typedef {{ collections: Record<string, unknown>, names: Map<string, Set<string>>, readsByFile: Map<string, ReturnType<typeof readsIn>>,
|
|
788
|
+
* counts: { names: Map<string, number>, entries: Map<string, number>, whole: Map<string, number> },
|
|
789
|
+
* byEntry: Map<string, string[]>, byCollection: Map<string, string[]>, namesOf: Map<string, string[]>, routeOf: Map<string, string[]>,
|
|
790
|
+
* isRoute: (f: string) => boolean, jsonOf: Map<string, string[]>, imports: Map<string, string[]>, byName: any }} SiteReads
|
|
791
|
+
* @type {WeakMap<Map<string, Set<string>>, SiteReads>}
|
|
641
792
|
*/
|
|
642
793
|
const siteReadsOf = new WeakMap();
|
|
643
794
|
|
|
644
795
|
function siteReads(paths, text, importers) {
|
|
645
796
|
const kept = siteReadsOf.get(importers);
|
|
646
797
|
if (kept) return kept;
|
|
798
|
+
/** @type {Record<string, unknown>} */
|
|
647
799
|
let collections = {};
|
|
648
800
|
try {
|
|
649
|
-
collections =
|
|
801
|
+
collections = readCollections(text) ?? {};
|
|
650
802
|
} catch {}
|
|
651
803
|
const reads = contentReads(paths, text);
|
|
652
804
|
const readsByFile = new Map();
|
|
653
|
-
|
|
805
|
+
// A file that names no reading function reads nothing (contentReads): its answer without a look.
|
|
806
|
+
for (const [p] of reads.files) {
|
|
807
|
+
if (CONTENT_CONFIG.test(p)) continue;
|
|
808
|
+
const code = reads.code.get(p);
|
|
809
|
+
readsByFile.set(p, code === undefined ? { names: new Set(), entries: new Set(), whole: new Set(), helped: new Set() } : readsIn(code, reads, p));
|
|
810
|
+
}
|
|
654
811
|
// How many files read each name, entry and collection: "read elsewhere" is the site's count
|
|
655
812
|
// less the page's own files', not a union of every other file made again for each page.
|
|
656
813
|
const counts = { names: new Map(), entries: new Map(), whole: new Map() };
|
|
@@ -691,7 +848,7 @@ function siteReads(paths, text, importers) {
|
|
|
691
848
|
if (target.endsWith(".json")) push(jsonOf, f, target);
|
|
692
849
|
}
|
|
693
850
|
}
|
|
694
|
-
const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports };
|
|
851
|
+
const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads.byName };
|
|
695
852
|
siteReadsOf.set(importers, site);
|
|
696
853
|
return site;
|
|
697
854
|
}
|
|
@@ -1072,3 +1229,1074 @@ export function withoutInContentMap(json, files) {
|
|
|
1072
1229
|
}
|
|
1073
1230
|
return JSON.stringify(map);
|
|
1074
1231
|
}
|
|
1232
|
+
|
|
1233
|
+
// ── Page actions: rename, duplicate, delete (docs/plan-page-actions.md) ────
|
|
1234
|
+
//
|
|
1235
|
+
// One rule for what each action changes, from the code at one commit: the same files always give
|
|
1236
|
+
// the same writes, so Unbase's editor (unbase-projects page_action), the CLI (`unbase page …`) and
|
|
1237
|
+
// a developer's own agent make byte-identical changes. What it cannot do by rule, it refuses with a
|
|
1238
|
+
// reason; the editor says why, and offers the Operator where it can (`content_bound`).
|
|
1239
|
+
|
|
1240
|
+
/** Frameworks the actions know how a page is made in. */
|
|
1241
|
+
export const PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
|
|
1242
|
+
|
|
1243
|
+
/** Since which version each package applies the page file's redirects at build. */
|
|
1244
|
+
export const REDIRECTS_SINCE = { "@unbase-app/pages": "0.4.0", "@unbase-app/astro": "0.3.0", "@unbase-app/vite": "0.3.0", "@unbase-app/next": "0.3.0" };
|
|
1245
|
+
|
|
1246
|
+
/** The lowest version a dependency's range allows ("^0.4.0" → [0, 4, 0]); null when it does not say (a file, a tag, "*"). */
|
|
1247
|
+
export function lowestVersion(spec) {
|
|
1248
|
+
if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
|
|
1249
|
+
const m = spec.trim().replace(/^[\^~>=v\s]+/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
|
1250
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
const atLeast = (have, want) => {
|
|
1254
|
+
for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] > want[i];
|
|
1255
|
+
return true;
|
|
1256
|
+
};
|
|
1257
|
+
|
|
1258
|
+
/**
|
|
1259
|
+
* Whether the site's build applies the page file's redirects: the kit is installed (kitInstalled)
|
|
1260
|
+
* by a package whose range in package.json starts at or after the version that applies them. A
|
|
1261
|
+
* range that does not say (a file, a tag) counts as not: a moved live page must never lose its
|
|
1262
|
+
* old address silently.
|
|
1263
|
+
*/
|
|
1264
|
+
export function kitRedirects({ framework, text }) {
|
|
1265
|
+
if (!kitInstalled({ framework, text })) return false;
|
|
1266
|
+
let pkg = null;
|
|
1267
|
+
try {
|
|
1268
|
+
pkg = JSON.parse(text("package.json") ?? "null");
|
|
1269
|
+
} catch {}
|
|
1270
|
+
const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
|
|
1271
|
+
return (KITS[String(framework)] ?? []).some((name) => {
|
|
1272
|
+
const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
|
|
1273
|
+
const since = REDIRECTS_SINCE[name];
|
|
1274
|
+
const have = lowestVersion(spec);
|
|
1275
|
+
return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
/** "Pricing plans" → "pricing-plans"; "Één agenda" → "een-agenda". */
|
|
1280
|
+
export function slugOf(name) {
|
|
1281
|
+
return String(name)
|
|
1282
|
+
.normalize("NFKD")
|
|
1283
|
+
.replace(/[̀-ͯ]/g, "")
|
|
1284
|
+
.toLowerCase()
|
|
1285
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
1286
|
+
.replace(/^-+|-+$/g, "")
|
|
1287
|
+
.slice(0, 80);
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
|
|
1291
|
+
|
|
1292
|
+
/** Whether `p` is an address a page can be given: plain segments, no template, not too long. */
|
|
1293
|
+
export function validAddress(p) {
|
|
1294
|
+
const at = normalisePath(p);
|
|
1295
|
+
if (at.length > 200) return false;
|
|
1296
|
+
if (at === "/") return true;
|
|
1297
|
+
return at
|
|
1298
|
+
.slice(1)
|
|
1299
|
+
.split("/")
|
|
1300
|
+
.every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
|
|
1301
|
+
}
|
|
1302
|
+
|
|
1303
|
+
const under = (path, at) => (at === "/" ? path !== "/" : path.startsWith(`${at}/`));
|
|
1304
|
+
const within = (path, at) => path === at || under(path, at);
|
|
1305
|
+
/** `path` with its `from` part replaced by `to`: "/a/b" from "/a" to "/c" → "/c/b". */
|
|
1306
|
+
const moveAddress = (path, from, to) => (path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`));
|
|
1307
|
+
const parentOf = (p) => (p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/"))));
|
|
1308
|
+
const lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
|
|
1309
|
+
|
|
1310
|
+
/** The redirects the site sets itself where Unbase can read them: an Astro config's `redirects` literal, vercel.json, a literal in next.config. Sources only. */
|
|
1311
|
+
export function siteRedirects({ framework, text }) {
|
|
1312
|
+
const out = new Set();
|
|
1313
|
+
try {
|
|
1314
|
+
const v = JSON.parse(text("vercel.json") ?? "null");
|
|
1315
|
+
for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
|
|
1316
|
+
} catch {}
|
|
1317
|
+
for (const c of CONFIGS[String(framework)] ?? []) {
|
|
1318
|
+
const src = stripComments(text(c) ?? "");
|
|
1319
|
+
if (framework === "astro") {
|
|
1320
|
+
const at = src.search(/\bredirects\s*:\s*\{/);
|
|
1321
|
+
if (at < 0) continue;
|
|
1322
|
+
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
1323
|
+
for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
|
|
1324
|
+
} else if (framework === "next") {
|
|
1325
|
+
for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
return out;
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/** Whether a redirect source (a page file's or the site's) takes `path`. */
|
|
1332
|
+
function sends(source, path) {
|
|
1333
|
+
if (REST.test(source)) {
|
|
1334
|
+
const base = normalisePath(source.replace(REST, ""));
|
|
1335
|
+
return within(path, base);
|
|
1336
|
+
}
|
|
1337
|
+
return source === path || matchesPattern(source, path);
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
function matchesPattern(source, path) {
|
|
1341
|
+
if (!/\[|:/.test(source)) return false;
|
|
1342
|
+
const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => (i % 2 ? (part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+") : escape(part))).join("")}$`);
|
|
1343
|
+
return re.test(path);
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
// ── Writing the page file ──
|
|
1347
|
+
|
|
1348
|
+
/**
|
|
1349
|
+
* The page file after `change`, as text (two spaces, a newline at the end, keys in the order they
|
|
1350
|
+
* were). Null when there is nothing to write: no file before and nothing in it after.
|
|
1351
|
+
*/
|
|
1352
|
+
function changedPageFile(before, change) {
|
|
1353
|
+
/** @type {Record<string, any>} */
|
|
1354
|
+
let data = {};
|
|
1355
|
+
try {
|
|
1356
|
+
data = before == null ? {} : (JSON.parse(before) ?? {});
|
|
1357
|
+
} catch {
|
|
1358
|
+
data = {};
|
|
1359
|
+
}
|
|
1360
|
+
if (!isObject(data)) data = {};
|
|
1361
|
+
if (!isObject(data.pages)) data.pages = {};
|
|
1362
|
+
const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
|
|
1363
|
+
const folders = isObject(data.folders) ? { ...data.folders } : {};
|
|
1364
|
+
change(data.pages, redirects, folders);
|
|
1365
|
+
for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
|
|
1366
|
+
for (const [k, v] of Object.entries(folders)) if (!isObject(v) || !v.name) delete folders[k];
|
|
1367
|
+
if (Object.keys(folders).length) data.folders = folders;
|
|
1368
|
+
else delete data.folders;
|
|
1369
|
+
if (Object.keys(redirects).length) data.redirects = redirects;
|
|
1370
|
+
else delete data.redirects;
|
|
1371
|
+
const empty = !Object.keys(data.pages).length && !data.redirects && !data.folders && Object.keys(data).length === 1;
|
|
1372
|
+
if (before == null && empty) return null;
|
|
1373
|
+
const after = `${JSON.stringify(data, null, 2)}\n`;
|
|
1374
|
+
return after === before ? null : after;
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
/** The redirects with every one that leads into `from` (or under it) led to `to` instead, and none left that takes `to` itself. */
|
|
1378
|
+
function repoint(redirects, from, to) {
|
|
1379
|
+
for (const [source, dest] of Object.entries(redirects)) {
|
|
1380
|
+
const rest = REST.test(dest);
|
|
1381
|
+
const base = rest ? normalisePath(dest.replace(REST, "")) : dest;
|
|
1382
|
+
if (within(base, from)) redirects[source] = rest ? `${moveAddress(base, from, to)}${dest.slice(dest.lastIndexOf("/"))}` : moveAddress(base, from, to);
|
|
1383
|
+
}
|
|
1384
|
+
for (const [source, dest] of Object.entries(redirects)) {
|
|
1385
|
+
const base = REST.test(source) ? normalisePath(source.replace(REST, "")) : source;
|
|
1386
|
+
if (to && within(to, base) && sends(source, to)) delete redirects[source];
|
|
1387
|
+
else if (source === dest) delete redirects[source];
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
|
|
1391
|
+
// ── Moving code ──
|
|
1392
|
+
|
|
1393
|
+
/** Import specifiers, with where each sits: `from "x"`, `import "x"`, `import("x")`, `require("x")`. */
|
|
1394
|
+
const SPECIFIER = /((?:\bfrom|\bimport|\brequire)\s*\(?\s*)(["'])([^"'\n]+)\2/g;
|
|
1395
|
+
/** An Astro Markdown page's layout. */
|
|
1396
|
+
const MD_LAYOUT = /^(layout:\s*)(["']?)([^"'\n]+?)\2\s*$/m;
|
|
1397
|
+
|
|
1398
|
+
const relativeSpec = (fromFile, target) => {
|
|
1399
|
+
const from = dirname(fromFile).split("/").filter(Boolean);
|
|
1400
|
+
const to = target.split("/");
|
|
1401
|
+
let i = 0;
|
|
1402
|
+
while (i < from.length && i < to.length - 1 && from[i] === to[i]) i++;
|
|
1403
|
+
const up = from.length - i;
|
|
1404
|
+
const rest = to.slice(i).join("/");
|
|
1405
|
+
return up ? `${"../".repeat(up)}${rest}` : `./${rest}`;
|
|
1406
|
+
};
|
|
1407
|
+
|
|
1408
|
+
/**
|
|
1409
|
+
* The specifier `fromFile` now needs for `target`, in the style the old one had: an alias stays
|
|
1410
|
+
* an alias, a specifier with an extension keeps it, one to a folder's index names the folder.
|
|
1411
|
+
*/
|
|
1412
|
+
function specFor(fromFile, target, old, oldTarget) {
|
|
1413
|
+
const index = /\/index\.[a-z]+$/.test(oldTarget) && !/\/index(\.[a-z]+)?$/.test(old);
|
|
1414
|
+
const ext = /\.[a-z]+$/.test(old.split("/").pop() ?? "") && old.endsWith(oldTarget.slice(oldTarget.lastIndexOf(".")));
|
|
1415
|
+
let t = target;
|
|
1416
|
+
if (index) t = dirname(target);
|
|
1417
|
+
else if (!ext) t = target.replace(/\.[a-z]+$/, "");
|
|
1418
|
+
if (old.startsWith("@/") && t.startsWith("src/")) return `@/${t.slice(4)}`;
|
|
1419
|
+
return relativeSpec(fromFile, t);
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
/**
|
|
1423
|
+
* `src` of a file now at `now` (before at `was`) with each specifier pointed where its target is
|
|
1424
|
+
* after `moves` (old path → new path). Unchanged when nothing it imports moved and it did not.
|
|
1425
|
+
*/
|
|
1426
|
+
function respecified(src, was, now, moves, have) {
|
|
1427
|
+
const fix = (spec) => {
|
|
1428
|
+
const target = resolveImport(was, spec, have);
|
|
1429
|
+
if (!target) return spec;
|
|
1430
|
+
const next = moves.get(target) ?? target;
|
|
1431
|
+
if (next === target && was === now) return spec;
|
|
1432
|
+
if (!spec.startsWith(".") && next === target) return spec;
|
|
1433
|
+
return specFor(now, next, spec, target);
|
|
1434
|
+
};
|
|
1435
|
+
let out = src.replace(SPECIFIER, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
|
|
1436
|
+
if (/\.mdx?$/.test(now)) out = out.replace(MD_LAYOUT, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
|
|
1437
|
+
return out;
|
|
1438
|
+
}
|
|
1439
|
+
|
|
1440
|
+
// ── Links ──
|
|
1441
|
+
|
|
1442
|
+
/** Quoted addresses in code and content, and Markdown links: what a rename rewrites. */
|
|
1443
|
+
const QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
|
|
1444
|
+
const MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
|
|
1445
|
+
|
|
1446
|
+
/** `src` with every address in `from` (or under it) moved to `to`; anchors, queries and a trailing slash kept. */
|
|
1447
|
+
function relinked(src, from, to, markdown) {
|
|
1448
|
+
const swap = (address) => {
|
|
1449
|
+
const bare = address.replace(/[#?][\s\S]*$/, "");
|
|
1450
|
+
const tail = address.slice(bare.length);
|
|
1451
|
+
const slash = bare.length > 1 && bare.endsWith("/") ? "/" : "";
|
|
1452
|
+
const clean = slash ? bare.slice(0, -1) : bare;
|
|
1453
|
+
if (clean === from) return `${to}${to === "/" ? "" : slash}${tail}`;
|
|
1454
|
+
if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
|
|
1455
|
+
return address;
|
|
1456
|
+
};
|
|
1457
|
+
let out = src.replace(QUOTED, (m, q, address) => `${q}${swap(address)}`);
|
|
1458
|
+
if (markdown) out = out.replace(MD_LINK, (m, a, address, b) => `${a}${swap(address)}${b}`);
|
|
1459
|
+
return out;
|
|
1460
|
+
}
|
|
1461
|
+
|
|
1462
|
+
/** `src` with the inside of its string literals blanked, offsets kept: names in code, not in text. */
|
|
1463
|
+
function blankStrings(src) {
|
|
1464
|
+
let out = "";
|
|
1465
|
+
let i = 0;
|
|
1466
|
+
while (i < src.length) {
|
|
1467
|
+
const c = src[i];
|
|
1468
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
1469
|
+
const j = stringEnd(src, i);
|
|
1470
|
+
out += c + blank(src.slice(i + 1, j - 1)) + (j - 1 > i ? src[j - 1] : "");
|
|
1471
|
+
i = j;
|
|
1472
|
+
continue;
|
|
1473
|
+
}
|
|
1474
|
+
out += c;
|
|
1475
|
+
i++;
|
|
1476
|
+
}
|
|
1477
|
+
return out;
|
|
1478
|
+
}
|
|
1479
|
+
|
|
1480
|
+
// ── Per framework: where a page's files are ──
|
|
1481
|
+
|
|
1482
|
+
/** The folder the pages router or Astro keeps routes in, from the page's file. */
|
|
1483
|
+
const routesBase = (file) => (file.startsWith("src/pages/") ? "src/pages" : file.startsWith("pages/") ? "pages" : file.startsWith("src/app/") ? "src/app" : file.startsWith("app/") ? "app" : null);
|
|
1484
|
+
|
|
1485
|
+
/**
|
|
1486
|
+
* Where a page at `to` would have its file, in the form the page at `page` has (a file, a folder's
|
|
1487
|
+
* index, a Next.js app router folder), and the folder whose files go along with it.
|
|
1488
|
+
*/
|
|
1489
|
+
function destination(page, to, discovered) {
|
|
1490
|
+
const base = routesBase(page.file);
|
|
1491
|
+
if (!base) return null;
|
|
1492
|
+
const ext = page.file.slice(page.file.lastIndexOf("."));
|
|
1493
|
+
if (base.endsWith("app")) {
|
|
1494
|
+
// app/(group)/x/page.tsx: the folder is the page. Its new folder sits where its new parent's does.
|
|
1495
|
+
const dir = dirname(page.file);
|
|
1496
|
+
const parent = parentOf(to);
|
|
1497
|
+
const sameParent = parent === parentOf(page.path);
|
|
1498
|
+
const parentPage = parent === null ? null : discovered.pages.find((p) => p.path === parent && p.file && routesBase(p.file) === base);
|
|
1499
|
+
const parentDir = sameParent ? dirname(dir) : parentPage ? dirname(parentPage.file) : `${base}${parent === "/" ? "" : parent}`;
|
|
1500
|
+
const newDir = to === "/" ? base : `${parentDir}/${lastOf(to)}`;
|
|
1501
|
+
return { file: `${newDir}/${page.file.slice(dir.length + 1)}`, dir, newDir, folder: true };
|
|
1502
|
+
}
|
|
1503
|
+
const index = /(^|\/)index\.[a-z]+$/.test(page.file);
|
|
1504
|
+
const oldDir = `${base}${page.path === "/" ? "" : page.path}`;
|
|
1505
|
+
const newDir = `${base}${to === "/" ? "" : to}`;
|
|
1506
|
+
return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
/** Next.js app router files beside a page that are its own, not a route of their own: everything in its folder but the folders of other routes. */
|
|
1510
|
+
function appSegmentOwn(dir, paths) {
|
|
1511
|
+
return paths.filter((p) => {
|
|
1512
|
+
if (dirname(p) === dir) return true;
|
|
1513
|
+
if (!p.startsWith(`${dir}/`)) return false;
|
|
1514
|
+
const first = p.slice(dir.length + 1).split("/")[0];
|
|
1515
|
+
return first.startsWith("_");
|
|
1516
|
+
});
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1519
|
+
/** A component name for a new route's file: "/pricing-copy" → "PricingCopy". */
|
|
1520
|
+
const componentName = (address) =>
|
|
1521
|
+
(lastOf(address) || "Home")
|
|
1522
|
+
.split(/[^A-Za-z0-9]+/)
|
|
1523
|
+
.filter(Boolean)
|
|
1524
|
+
.map((w) => w[0].toUpperCase() + w.slice(1))
|
|
1525
|
+
.join("")
|
|
1526
|
+
.replace(/^(\d)/, "Page$1") || "Page";
|
|
1527
|
+
|
|
1528
|
+
/** The route element's `path` attribute's value and where it sits in `src`, or null. */
|
|
1529
|
+
function routePathAttr(src, router) {
|
|
1530
|
+
const tag = src.slice(router.start, router.end);
|
|
1531
|
+
const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
|
|
1532
|
+
if (!m) return null;
|
|
1533
|
+
const value = m.slice(2).find((v) => v !== undefined) ?? "";
|
|
1534
|
+
const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
|
|
1535
|
+
return { value, start: valueAt, end: valueAt + value.length };
|
|
1536
|
+
}
|
|
1537
|
+
|
|
1538
|
+
// ── The plan ──
|
|
1539
|
+
|
|
1540
|
+
/**
|
|
1541
|
+
* @typedef {{ path: string, content?: string, from?: string, deleted?: true }} PageWrite
|
|
1542
|
+
* `content`: the file's new text; `from`: the file whose bytes it gets (a move or copy keeps
|
|
1543
|
+
* them as they are, whatever kind of file); `deleted`: it goes.
|
|
1544
|
+
* @typedef {{ ok: true, action: string, path: string, to: string | null, files: PageWrite[], redirects: Record<string, string | null>, links: string[], unlinked: string[], moves: { from: string, to: string }[], renamed: { from: string, to: string }[], message: string, folder?: boolean }} PagePlan
|
|
1545
|
+
* @typedef {{ ok: true } | { ok: false, reason: string, detail?: string }} Capability
|
|
1546
|
+
* @typedef {{ ok: false, reason: string, detail?: string }} PageRefusal
|
|
1547
|
+
*/
|
|
1548
|
+
|
|
1549
|
+
/**
|
|
1550
|
+
* What one action does to a site's code, or why it cannot: `rename` (to a new address, with a new
|
|
1551
|
+
* name), `duplicate` (a copy at `to`, by default the first free `<address>-copy`) or `delete`
|
|
1552
|
+
* (visitors to the old address sent to `redirect`, by default the page above it; null: Not
|
|
1553
|
+
* Found). `live` says whether the page is on Live now: only then does a rename or delete leave a
|
|
1554
|
+
* redirect, and only then does it need the kit to apply one. `drafts`: a copy starts as a draft.
|
|
1555
|
+
*
|
|
1556
|
+
* `paths` are every file of the app (a move takes files whose text was not read along);
|
|
1557
|
+
* `text` gives the code and content files' text.
|
|
1558
|
+
* @param {{ action: "rename" | "duplicate" | "delete", path: string, to?: string, name?: string | null, redirect?: string | null, live?: boolean, drafts?: boolean }} request
|
|
1559
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>> }} input
|
|
1560
|
+
* @returns {PagePlan | PageRefusal}
|
|
1561
|
+
*/
|
|
1562
|
+
export function planPage(request, input) {
|
|
1563
|
+
const { framework, text } = input;
|
|
1564
|
+
const paths = input.paths.filter((p) => !SKIP.test(p));
|
|
1565
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1566
|
+
const action = request.action;
|
|
1567
|
+
if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
|
|
1568
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
|
|
1569
|
+
const at = normalisePath(request.path);
|
|
1570
|
+
const discovered = input.found ?? discover({ framework, paths, text });
|
|
1571
|
+
const page = discovered.pages.find((p) => p.path === at);
|
|
1572
|
+
// A folder: an address with pages under it and none of its own (docs/plan-folders-and-redirects.md).
|
|
1573
|
+
if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
|
|
1574
|
+
if (!page) {
|
|
1575
|
+
const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
|
|
1576
|
+
return template ? no("template", template.path) : no("missing");
|
|
1577
|
+
}
|
|
1578
|
+
if (page.kind === "template") return no("template", page.path);
|
|
1579
|
+
if (!page.file || page.reason === "unparsed") return no("unparsed");
|
|
1580
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1581
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
1582
|
+
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
1583
|
+
const have = new Set(paths);
|
|
1584
|
+
const importers = input.importers ?? importGraph(paths, text);
|
|
1585
|
+
const live = request.live === true;
|
|
1586
|
+
const redirects = live ? kitRedirects({ framework, text }) : false;
|
|
1587
|
+
const ownRedirects = siteRedirects({ framework, text });
|
|
1588
|
+
const taken = (p) => discovered.pages.some((q) => q.path === p) || [...ownRedirects].some((s) => sends(s, p));
|
|
1589
|
+
/** @type {Map<string, PageWrite>} */
|
|
1590
|
+
const writes = new Map();
|
|
1591
|
+
const write = (w) => writes.set(w.path, w);
|
|
1592
|
+
const current = (p) => (writes.has(p) ? (writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null)) : text(p));
|
|
1593
|
+
const links = new Set();
|
|
1594
|
+
const unlinked = new Set();
|
|
1595
|
+
const moves = [];
|
|
1596
|
+
/** Files that moved, old path → new path: drafts waiting on them follow. */
|
|
1597
|
+
const renamed = [];
|
|
1598
|
+
let to = null;
|
|
1599
|
+
/** @type {Record<string, string | null>} */
|
|
1600
|
+
const redirectChanges = {};
|
|
1601
|
+
const collections = (() => {
|
|
1602
|
+
try {
|
|
1603
|
+
return readCollections(text);
|
|
1604
|
+
} catch {
|
|
1605
|
+
return null;
|
|
1606
|
+
}
|
|
1607
|
+
})();
|
|
1608
|
+
const collectionsAfter = isObject(collections) ? { ...collections } : null;
|
|
1609
|
+
|
|
1610
|
+
if (action === "rename") {
|
|
1611
|
+
if (at === "/") return no("home");
|
|
1612
|
+
const target = request.to == null ? at : normalisePath(request.to);
|
|
1613
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1614
|
+
if (target !== at && within(target, at)) return no("address", target);
|
|
1615
|
+
if (target !== at && taken(target)) return no("taken", target);
|
|
1616
|
+
if (target !== at && live && !redirects) return no("no_redirects");
|
|
1617
|
+
to = target;
|
|
1618
|
+
/** @type {Map<string, string>} old path → new path, of the files that move */
|
|
1619
|
+
const moved = new Map();
|
|
1620
|
+
if (target !== at) {
|
|
1621
|
+
if (framework === "vite-react") {
|
|
1622
|
+
// The route's own path, when it is relative to a parent route: its last part only.
|
|
1623
|
+
const src = text(page.router.file) ?? "";
|
|
1624
|
+
const attr = routePathAttr(src, page.router);
|
|
1625
|
+
if (!attr) return no("unparsed", "index route");
|
|
1626
|
+
if (!attr.value.startsWith("/")) {
|
|
1627
|
+
const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
|
|
1628
|
+
if (parent !== "/" && !under(target, parent)) return no("unparsed", "a route inside another route keeps its parent");
|
|
1629
|
+
const rel = parent === "/" ? target.slice(1) : target.slice(parent.length + 1);
|
|
1630
|
+
write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
|
|
1631
|
+
}
|
|
1632
|
+
} else {
|
|
1633
|
+
const dest = destination(page, target, discovered);
|
|
1634
|
+
if (!dest) return no("unparsed");
|
|
1635
|
+
// Its file, and everything in its folder: the pages under it, and what they keep there.
|
|
1636
|
+
for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
|
|
1637
|
+
moved.set(page.file, dest.file);
|
|
1638
|
+
for (const [from, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
|
|
1639
|
+
for (const [from, next] of moved) {
|
|
1640
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
1641
|
+
const content = src == null ? null : respecified(src, from, next, moved, have);
|
|
1642
|
+
write(content == null || content === src ? { path: next, from } : { path: next, content });
|
|
1643
|
+
write({ path: from, deleted: true });
|
|
1644
|
+
}
|
|
1645
|
+
// Files that import a moved one.
|
|
1646
|
+
for (const p of paths) {
|
|
1647
|
+
if (moved.has(p) || !CODE.test(p)) continue;
|
|
1648
|
+
const src = text(p);
|
|
1649
|
+
if (!src) continue;
|
|
1650
|
+
const out = respecified(src, p, p, moved, have);
|
|
1651
|
+
if (out !== src) write({ path: p, content: out });
|
|
1652
|
+
}
|
|
1653
|
+
}
|
|
1654
|
+
// Every link to it, or under it, in code and content (route files' own `pad` too).
|
|
1655
|
+
for (const p of paths) {
|
|
1656
|
+
// Not the content config: it defines schemas, and an address there is an example in a message.
|
|
1657
|
+
if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
1658
|
+
const where = moved.get(p) ?? p;
|
|
1659
|
+
const src = current(where);
|
|
1660
|
+
if (!src) continue;
|
|
1661
|
+
const out = relinked(src, at, target, /\.mdx?$/.test(p));
|
|
1662
|
+
if (out === src) continue;
|
|
1663
|
+
write({ path: where, content: out });
|
|
1664
|
+
if (!moved.has(p)) links.add(where);
|
|
1665
|
+
}
|
|
1666
|
+
moves.push({ from: at, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at, target) })));
|
|
1667
|
+
for (const [from, next] of moved) renamed.push({ from, to: next });
|
|
1668
|
+
}
|
|
1669
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1670
|
+
if (target !== at) {
|
|
1671
|
+
for (const key of Object.keys(pages)) {
|
|
1672
|
+
if (!within(key, at)) continue;
|
|
1673
|
+
pages[moveAddress(key, at, target)] = { ...pages[key], ...(pages[moveAddress(key, at, target)] ?? {}) };
|
|
1674
|
+
delete pages[key];
|
|
1675
|
+
}
|
|
1676
|
+
const before = { ...sendsOn };
|
|
1677
|
+
if (live) {
|
|
1678
|
+
sendsOn[at] = target;
|
|
1679
|
+
if (below.length) sendsOn[`${at}/[...path]`] = `${target}/[...path]`;
|
|
1680
|
+
}
|
|
1681
|
+
repoint(sendsOn, at, target);
|
|
1682
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1683
|
+
}
|
|
1684
|
+
if (request.name !== undefined) {
|
|
1685
|
+
const entry = pages[target] ?? {};
|
|
1686
|
+
if (request.name) entry.name = String(request.name).trim().slice(0, 120);
|
|
1687
|
+
else delete entry.name;
|
|
1688
|
+
pages[target] = entry;
|
|
1689
|
+
}
|
|
1690
|
+
});
|
|
1691
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1692
|
+
if (!writes.size) return no("same");
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
if (action === "duplicate") {
|
|
1696
|
+
if (framework === "vite-react" && page.reason === "nested") return no("nested");
|
|
1697
|
+
let target;
|
|
1698
|
+
if (request.to != null) {
|
|
1699
|
+
target = normalisePath(request.to);
|
|
1700
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1701
|
+
if (taken(target)) return no("taken", target);
|
|
1702
|
+
} else {
|
|
1703
|
+
const base = at === "/" ? "/home-copy" : `${at}-copy`;
|
|
1704
|
+
target = base;
|
|
1705
|
+
for (let n = 2; taken(target) && n < 100; n++) target = `${base}-${n}`;
|
|
1706
|
+
}
|
|
1707
|
+
to = target;
|
|
1708
|
+
const content = ownedContent(page, { paths, text, importers });
|
|
1709
|
+
if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
|
|
1710
|
+
const own = new Set(content.files);
|
|
1711
|
+
const reads = siteReads(paths, text, importers);
|
|
1712
|
+
const ownCodeFiles = ownCode(page, importers, reads.imports);
|
|
1713
|
+
// How the page reads each content file it owns, and whether its copy can read a copy instead.
|
|
1714
|
+
const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set(), whole: new Set(), helped: new Set() };
|
|
1715
|
+
const imported = new Set(reads.jsonOf.get(page.file) ?? []);
|
|
1716
|
+
/** @type {Map<string, string>} content file → its copy */
|
|
1717
|
+
const copies = new Map();
|
|
1718
|
+
/** @type {{ kind: "name" | "entry", name: string, collection?: string, next: string }[]} */
|
|
1719
|
+
const rebinds = [];
|
|
1720
|
+
const newId = slugOf(lastOf(target)) || "copy";
|
|
1721
|
+
const freeFile = (dir, base, ext) => {
|
|
1722
|
+
let f = `${dir}/${base}${ext}`;
|
|
1723
|
+
for (let n = 2; (have.has(f) || [...writes.keys()].includes(f) || [...copies.values()].includes(f)) && n < 100; n++) f = `${dir}/${base}-${n}${ext}`;
|
|
1724
|
+
return f;
|
|
1725
|
+
};
|
|
1726
|
+
for (const f of own) {
|
|
1727
|
+
if (reads.isRoute(f)) continue;
|
|
1728
|
+
if (imported.has(f)) {
|
|
1729
|
+
copies.set(f, freeFile(dirname(f), `${f.slice(f.lastIndexOf("/") + 1, -5)}-${newId}`, ".json"));
|
|
1730
|
+
continue;
|
|
1731
|
+
}
|
|
1732
|
+
const collection = collectionOfFile(f, reads.collections);
|
|
1733
|
+
const id = f.slice(f.lastIndexOf("/") + 1, -5);
|
|
1734
|
+
// A collection several files make (a folder): a copy beside it is one more entry.
|
|
1735
|
+
const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
|
|
1736
|
+
const entry = `${collection}/${id}`;
|
|
1737
|
+
if (pageReads.entries.has(entry) && folder) {
|
|
1738
|
+
const next = freeFile(dirname(f), newId, ".json");
|
|
1739
|
+
copies.set(f, next);
|
|
1740
|
+
rebinds.push({ kind: "entry", name: id, collection, next: next.slice(next.lastIndexOf("/") + 1, -5) });
|
|
1741
|
+
} else if (pageReads.names.has(id) && id !== collection && folder) {
|
|
1742
|
+
const next = freeFile(dirname(f), newId, ".json");
|
|
1743
|
+
copies.set(f, next);
|
|
1744
|
+
rebinds.push({ kind: "name", name: id, next: next.slice(next.lastIndexOf("/") + 1, -5) });
|
|
1745
|
+
} else {
|
|
1746
|
+
return no("content_bound", f);
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
if (content.unknown) return no("content_bound", "content it reads that Unbase cannot place");
|
|
1750
|
+
// Its own modules stay shared; a module of its own that reads its content would read the original's.
|
|
1751
|
+
for (const m of ownCodeFiles) {
|
|
1752
|
+
if (m === page.file) continue;
|
|
1753
|
+
const r = reads.readsByFile.get(m);
|
|
1754
|
+
if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && [...own].some((f) => !reads.isRoute(f))) return no("content_bound", m);
|
|
1755
|
+
}
|
|
1756
|
+
const rebind = (src) => {
|
|
1757
|
+
let out = src;
|
|
1758
|
+
for (const r of rebinds) {
|
|
1759
|
+
if (r.kind === "entry") out = out.replace(new RegExp(`(\\bgetEntry\\(\\s*["']${escape(r.collection)}["']\\s*,\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
|
|
1760
|
+
else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
|
|
1761
|
+
}
|
|
1762
|
+
for (const [f, next] of copies) {
|
|
1763
|
+
if (!imported.has(f)) continue;
|
|
1764
|
+
out = out.replace(SPECIFIER, (m, lead, q, spec) => (resolveImport(page.file, spec, have) === f ? `${lead}${q}${spec.slice(0, spec.lastIndexOf("/") + 1)}${next.slice(next.lastIndexOf("/") + 1)}${q}` : m));
|
|
1765
|
+
}
|
|
1766
|
+
return out;
|
|
1767
|
+
};
|
|
1768
|
+
if (framework === "vite-react") {
|
|
1769
|
+
const router = page.router.file;
|
|
1770
|
+
const src = current(router) ?? "";
|
|
1771
|
+
const attr = routePathAttr(src, page.router);
|
|
1772
|
+
if (!attr) return no("unparsed", "index route");
|
|
1773
|
+
let name = componentName(target);
|
|
1774
|
+
for (let n = 2; new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(src) && n < 100; n++) name = `${componentName(target)}${n}`;
|
|
1775
|
+
const ext = page.file.slice(page.file.lastIndexOf("."));
|
|
1776
|
+
const file = freeFile(dirname(page.file), name, ext);
|
|
1777
|
+
const original = text(page.file) ?? "";
|
|
1778
|
+
write({ path: file, content: rebind(respecified(original, page.file, file, new Map([[page.file, file]]), have)) });
|
|
1779
|
+
// Its import, beside the original's, in the same form.
|
|
1780
|
+
const comp = page.router.component;
|
|
1781
|
+
const statement =
|
|
1782
|
+
page.router.importKind === "lazy"
|
|
1783
|
+
? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m"))
|
|
1784
|
+
: src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
|
|
1785
|
+
if (!statement) return no("unparsed", "its import");
|
|
1786
|
+
const added = statement[0].replace(new RegExp(`(?<![\\w$])${escape(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(router, file, spec, page.file)}${q}`);
|
|
1787
|
+
const value = attr.value.startsWith("/") ? target : (() => {
|
|
1788
|
+
const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
|
|
1789
|
+
return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
|
|
1790
|
+
})();
|
|
1791
|
+
if (value === null) return no("unparsed", "a route inside another route keeps its parent");
|
|
1792
|
+
const newTag = (src.slice(page.router.start, attr.start) + value + src.slice(attr.end, page.router.end)).replace(new RegExp(`(<|\\{\\s*)${escape(comp)}(?![\\w$])`, "g"), `$1${name}`);
|
|
1793
|
+
const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
|
|
1794
|
+
const at1 = page.router.end;
|
|
1795
|
+
let out = `${src.slice(0, at1)}\n${indent}${newTag}${src.slice(at1)}`;
|
|
1796
|
+
const lineEnd = statement.index + statement[0].length;
|
|
1797
|
+
out = `${out.slice(0, lineEnd)}\n${added}${out.slice(lineEnd)}`;
|
|
1798
|
+
write({ path: router, content: out });
|
|
1799
|
+
} else {
|
|
1800
|
+
const dest = destination(page, target, discovered);
|
|
1801
|
+
if (!dest) return no("unparsed");
|
|
1802
|
+
// A Next.js app router page brings what its folder keeps for it; Home's folder is the whole app's.
|
|
1803
|
+
const along = framework === "next" && routesBase(page.file).endsWith("app") && at !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
|
|
1804
|
+
const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
|
|
1805
|
+
for (const next of moved.values()) if (have.has(next)) return no("taken", next);
|
|
1806
|
+
for (const [from, next] of moved) {
|
|
1807
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
1808
|
+
if (src == null) {
|
|
1809
|
+
write({ path: next, from });
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
let out = respecified(src, from, next, moved, have);
|
|
1813
|
+
if (from === page.file) out = rebind(out);
|
|
1814
|
+
write(out === src ? { path: next, from } : { path: next, content: out });
|
|
1815
|
+
}
|
|
1816
|
+
}
|
|
1817
|
+
for (const [f, next] of copies) {
|
|
1818
|
+
write({ path: next, from: f });
|
|
1819
|
+
if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
|
|
1820
|
+
}
|
|
1821
|
+
// Its route file (its address and SEO), copied with the new address.
|
|
1822
|
+
for (const f of own) {
|
|
1823
|
+
if (!reads.isRoute(f)) continue;
|
|
1824
|
+
const src = text(f) ?? "";
|
|
1825
|
+
const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
|
|
1826
|
+
write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at)}(")`), `$1${target}$2`) });
|
|
1827
|
+
if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
|
|
1828
|
+
}
|
|
1829
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
|
|
1830
|
+
const entry = { ...(request.drafts ? { draft: true } : {}), ...(request.name ? { name: String(request.name).trim().slice(0, 120) } : {}) };
|
|
1831
|
+
if (Object.keys(entry).length) pages[target] = entry;
|
|
1832
|
+
});
|
|
1833
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1834
|
+
}
|
|
1835
|
+
|
|
1836
|
+
if (action === "delete") {
|
|
1837
|
+
if (at === "/") return no("home");
|
|
1838
|
+
if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
|
|
1839
|
+
let target = null;
|
|
1840
|
+
if (live && request.redirect !== null) {
|
|
1841
|
+
if (request.redirect !== undefined) {
|
|
1842
|
+
target = normalisePath(request.redirect);
|
|
1843
|
+
if (within(target, at) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
|
|
1844
|
+
} else {
|
|
1845
|
+
for (let p = parentOf(at); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
|
|
1846
|
+
target = target ?? "/";
|
|
1847
|
+
}
|
|
1848
|
+
if (!redirects) return no("no_redirects");
|
|
1849
|
+
}
|
|
1850
|
+
to = target;
|
|
1851
|
+
if (framework === "vite-react") {
|
|
1852
|
+
const router = page.router.file;
|
|
1853
|
+
const src = current(router) ?? "";
|
|
1854
|
+
// Its route element, and its line when nothing else is on it.
|
|
1855
|
+
let { start, end } = page.router;
|
|
1856
|
+
const lineStart = src.lastIndexOf("\n", start - 1) + 1;
|
|
1857
|
+
const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
|
|
1858
|
+
if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
|
|
1859
|
+
start = lineStart;
|
|
1860
|
+
end = Math.min(src.length, lineEnd + 1);
|
|
1861
|
+
}
|
|
1862
|
+
let out = src.slice(0, start) + src.slice(end);
|
|
1863
|
+
const comp = page.router.component;
|
|
1864
|
+
// Its import goes when nothing else in the file names it.
|
|
1865
|
+
const rest = blankStrings(stripComments(out));
|
|
1866
|
+
const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
|
|
1867
|
+
if (uses <= 1) {
|
|
1868
|
+
const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
|
|
1869
|
+
out = out.replace(re, "");
|
|
1870
|
+
if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
|
|
1871
|
+
}
|
|
1872
|
+
write({ path: router, content: out });
|
|
1873
|
+
} else {
|
|
1874
|
+
const dir = dirname(page.file);
|
|
1875
|
+
const files = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
|
|
1876
|
+
for (const f of files) write({ path: f, deleted: true });
|
|
1877
|
+
}
|
|
1878
|
+
const content = ownedContent(page, { paths, text, importers });
|
|
1879
|
+
for (const f of content.files) {
|
|
1880
|
+
write({ path: f, deleted: true });
|
|
1881
|
+
if (collectionsAfter) delete collectionsAfter[f];
|
|
1882
|
+
}
|
|
1883
|
+
for (const f of linksTo(at, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
|
|
1884
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1885
|
+
delete pages[at];
|
|
1886
|
+
const before = { ...sendsOn };
|
|
1887
|
+
if (target) sendsOn[at] = target;
|
|
1888
|
+
if (target) repoint(sendsOn, at, target);
|
|
1889
|
+
else for (const [s, d] of Object.entries(sendsOn)) if (d === at) delete sendsOn[s];
|
|
1890
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1891
|
+
});
|
|
1892
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1893
|
+
}
|
|
1894
|
+
|
|
1895
|
+
if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
|
|
1896
|
+
const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
1897
|
+
const content = `${JSON.stringify(sorted, null, 2)}\n`;
|
|
1898
|
+
write({ path: COLLECTIONS, content });
|
|
1899
|
+
write({ path: LEGACY_COLLECTIONS, content });
|
|
1900
|
+
}
|
|
1901
|
+
const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
1902
|
+
const message =
|
|
1903
|
+
action === "rename" ? (to === at ? `Unbase: rename ${at}` : `Unbase: move ${at} to ${to}`) : action === "duplicate" ? `Unbase: duplicate ${at} as ${to}` : `Unbase: delete ${at}${to ? ` (visitors go to ${to})` : ""}`;
|
|
1904
|
+
return { ok: true, action, path: at, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
|
|
1905
|
+
}
|
|
1906
|
+
|
|
1907
|
+
// ── Folders ──
|
|
1908
|
+
|
|
1909
|
+
/**
|
|
1910
|
+
* The folders of a tree of pages: every address above a page that is no page itself ("/juridisch"
|
|
1911
|
+
* above "/juridisch/[slug]"), sorted. Home is never one.
|
|
1912
|
+
* @param {{ path: string }[]} pages
|
|
1913
|
+
*/
|
|
1914
|
+
export function folderPaths(pages) {
|
|
1915
|
+
const own = new Set(pages.map((p) => p.path));
|
|
1916
|
+
const out = new Set();
|
|
1917
|
+
for (const p of pages) for (let up = parentOf(p.path); up && up !== "/"; up = parentOf(up)) if (!own.has(up)) out.add(up);
|
|
1918
|
+
return [...out].sort();
|
|
1919
|
+
}
|
|
1920
|
+
|
|
1921
|
+
/** A Next.js app router folder that is not a segment of the address: a route group `(x)` or a slot `@x`. */
|
|
1922
|
+
const unsegmented = (dir) => /^\(.*\)$|^@/.test(dir.slice(dir.lastIndexOf("/") + 1));
|
|
1923
|
+
|
|
1924
|
+
/**
|
|
1925
|
+
* Where a folder's files are, in the routers that are files: one folder per routes base (Astro's
|
|
1926
|
+
* src/pages, the pages router's pages, the app router's app, a route group there too). Null when a
|
|
1927
|
+
* page under it is not in a file router's folder of that name (React Router, or an odd layout).
|
|
1928
|
+
*/
|
|
1929
|
+
function folderDirs(at, below) {
|
|
1930
|
+
const dirs = new Set();
|
|
1931
|
+
for (const p of below) {
|
|
1932
|
+
if (!p.file) return null;
|
|
1933
|
+
const base = routesBase(p.file);
|
|
1934
|
+
if (!base) return null;
|
|
1935
|
+
if (!base.endsWith("app")) {
|
|
1936
|
+
const dir = `${base}${at}`;
|
|
1937
|
+
if (!p.file.startsWith(`${dir}/`)) return null;
|
|
1938
|
+
dirs.add(dir);
|
|
1939
|
+
continue;
|
|
1940
|
+
}
|
|
1941
|
+
// app/(group)/juridisch/x/page.tsx: up from the page's folder, one real segment per part of the address under the folder.
|
|
1942
|
+
let d = dirname(p.file);
|
|
1943
|
+
let n = p.path.slice(at.length + 1).split("/").length;
|
|
1944
|
+
while (n > 0 && d.length > base.length) {
|
|
1945
|
+
if (!unsegmented(d)) n--;
|
|
1946
|
+
d = dirname(d);
|
|
1947
|
+
}
|
|
1948
|
+
while (unsegmented(d) && d.length > base.length) d = dirname(d);
|
|
1949
|
+
if (lastOf(d) !== lastOf(at)) return null;
|
|
1950
|
+
dirs.add(d);
|
|
1951
|
+
}
|
|
1952
|
+
return dirs.size ? [...dirs].sort() : null;
|
|
1953
|
+
}
|
|
1954
|
+
|
|
1955
|
+
/**
|
|
1956
|
+
* Renaming a folder: its name in the page file, its address (only its last part: a folder keeps its
|
|
1957
|
+
* place), and every page under it with it, in one plan. In the file routers its folder moves as a
|
|
1958
|
+
* whole, a template and the files its pages keep there too; in React Router each route under it.
|
|
1959
|
+
* Links to anything under it follow; a live folder leaves one redirect for everything under it,
|
|
1960
|
+
* `/old/[...path]` → `/new/[...path]`. `request.live`: any page under it is on Live now.
|
|
1961
|
+
* @returns {PagePlan | PageRefusal}
|
|
1962
|
+
*/
|
|
1963
|
+
function planFolder(request, { framework, paths, text, discovered, importers: given }) {
|
|
1964
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1965
|
+
const at = normalisePath(request.path);
|
|
1966
|
+
if (at === "/") return no("home");
|
|
1967
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1968
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
1969
|
+
const target = request.to == null ? at : normalisePath(request.to);
|
|
1970
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1971
|
+
if (target !== at && (within(target, at) || parentOf(target) !== parentOf(at))) return no("address", target);
|
|
1972
|
+
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
1973
|
+
const ownRedirects = siteRedirects({ framework, text });
|
|
1974
|
+
if (target !== at && (discovered.pages.some((p) => within(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
|
|
1975
|
+
const live = request.live === true;
|
|
1976
|
+
if (target !== at && live && !kitRedirects({ framework, text })) return no("no_redirects");
|
|
1977
|
+
const have = new Set(paths);
|
|
1978
|
+
/** @type {Map<string, PageWrite>} */
|
|
1979
|
+
const writes = new Map();
|
|
1980
|
+
const write = (w) => writes.set(w.path, w);
|
|
1981
|
+
const current = (p) => (writes.has(p) ? (writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null)) : text(p));
|
|
1982
|
+
const links = new Set();
|
|
1983
|
+
/** @type {Map<string, string>} old path → new path, of the files that move */
|
|
1984
|
+
const moved = new Map();
|
|
1985
|
+
/** @type {Record<string, string | null>} */
|
|
1986
|
+
const redirectChanges = {};
|
|
1987
|
+
if (target !== at) {
|
|
1988
|
+
if (framework === "vite-react") {
|
|
1989
|
+
// Each route under it, its path's value rewritten; edits per router file from its end, so offsets hold.
|
|
1990
|
+
/** @type {Map<string, { start: number, end: number, value: string }[]>} */
|
|
1991
|
+
const edits = new Map();
|
|
1992
|
+
for (const p of below) {
|
|
1993
|
+
if (!p.router) return no("unparsed", p.path);
|
|
1994
|
+
const src = text(p.router.file) ?? "";
|
|
1995
|
+
const attr = routePathAttr(src, p.router);
|
|
1996
|
+
if (!attr) return no("unparsed", "index route");
|
|
1997
|
+
const next = moveAddress(p.path, at, target);
|
|
1998
|
+
let value;
|
|
1999
|
+
if (attr.value.startsWith("/")) value = `${next}${attr.value.endsWith("/") && next !== "/" ? "/" : ""}`;
|
|
2000
|
+
else {
|
|
2001
|
+
const parent = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr.value).length));
|
|
2002
|
+
// Inside a route that is under the folder itself: that one moves, this one keeps its value.
|
|
2003
|
+
if (under(parent, at)) continue;
|
|
2004
|
+
value = parent === "/" ? next.slice(1) : next.slice(parent.length + 1);
|
|
2005
|
+
}
|
|
2006
|
+
edits.set(p.router.file, [...(edits.get(p.router.file) ?? []), { start: attr.start, end: attr.end, value }]);
|
|
2007
|
+
}
|
|
2008
|
+
for (const [file, list] of edits) {
|
|
2009
|
+
let out = text(file) ?? "";
|
|
2010
|
+
for (const e of [...list].sort((a, b) => b.start - a.start)) out = out.slice(0, e.start) + e.value + out.slice(e.end);
|
|
2011
|
+
write({ path: file, content: out });
|
|
2012
|
+
}
|
|
2013
|
+
} else {
|
|
2014
|
+
const dirs = folderDirs(at, below);
|
|
2015
|
+
if (!dirs) return no("unparsed", at);
|
|
2016
|
+
for (const dir of dirs) {
|
|
2017
|
+
const newDir = `${dirname(dir)}/${lastOf(target)}`;
|
|
2018
|
+
for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
|
|
2019
|
+
}
|
|
2020
|
+
for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
|
|
2021
|
+
for (const [from, next] of moved) {
|
|
2022
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
2023
|
+
const content = src == null ? null : respecified(src, from, next, moved, have);
|
|
2024
|
+
write(content == null || content === src ? { path: next, from } : { path: next, content });
|
|
2025
|
+
write({ path: from, deleted: true });
|
|
2026
|
+
}
|
|
2027
|
+
const importers = given ?? null;
|
|
2028
|
+
for (const p of paths) {
|
|
2029
|
+
if (moved.has(p) || !CODE.test(p)) continue;
|
|
2030
|
+
if (importers && ![...moved.keys()].some((m) => importers.get(m)?.has(p))) continue;
|
|
2031
|
+
const src = text(p);
|
|
2032
|
+
if (!src) continue;
|
|
2033
|
+
const out = respecified(src, p, p, moved, have);
|
|
2034
|
+
if (out !== src) write({ path: p, content: out });
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
// Every link to anything under it, in code and content.
|
|
2038
|
+
for (const p of paths) {
|
|
2039
|
+
if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
2040
|
+
const where = moved.get(p) ?? p;
|
|
2041
|
+
const src = current(where);
|
|
2042
|
+
if (!src) continue;
|
|
2043
|
+
const out = relinked(src, at, target, /\.mdx?$/.test(p));
|
|
2044
|
+
if (out === src) continue;
|
|
2045
|
+
write({ path: where, content: out });
|
|
2046
|
+
if (!moved.has(p)) links.add(where);
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn, folders) => {
|
|
2050
|
+
if (target !== at) {
|
|
2051
|
+
for (const key of Object.keys(pages)) {
|
|
2052
|
+
if (!within(key, at)) continue;
|
|
2053
|
+
pages[moveAddress(key, at, target)] = { ...pages[key], ...(pages[moveAddress(key, at, target)] ?? {}) };
|
|
2054
|
+
delete pages[key];
|
|
2055
|
+
}
|
|
2056
|
+
for (const key of Object.keys(folders)) {
|
|
2057
|
+
if (!within(key, at)) continue;
|
|
2058
|
+
folders[moveAddress(key, at, target)] = folders[key];
|
|
2059
|
+
delete folders[key];
|
|
2060
|
+
}
|
|
2061
|
+
const before = { ...sendsOn };
|
|
2062
|
+
if (live) sendsOn[`${at}/[...path]`] = `${target}/[...path]`;
|
|
2063
|
+
repoint(sendsOn, at, target);
|
|
2064
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
2065
|
+
}
|
|
2066
|
+
if (request.name !== undefined) {
|
|
2067
|
+
const name = request.name ? String(request.name).trim().slice(0, 120) : "";
|
|
2068
|
+
if (name) folders[target] = { name };
|
|
2069
|
+
else delete folders[target];
|
|
2070
|
+
}
|
|
2071
|
+
});
|
|
2072
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
2073
|
+
if (!writes.size) return no("same");
|
|
2074
|
+
const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
2075
|
+
const moves = target === at ? [] : [{ from: at, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at, target) }))];
|
|
2076
|
+
const renamed = [...moved].map(([from, to]) => ({ from, to }));
|
|
2077
|
+
const message = target === at ? `Unbase: rename ${at}` : `Unbase: move ${at} to ${target}`;
|
|
2078
|
+
return { ok: true, action: "rename", path: at, to: target, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [], moves, renamed, message, folder: true };
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
/**
|
|
2082
|
+
* What can be done to each page of the code here, and why not (the menu's grey lines): per
|
|
2083
|
+
* address, `rename`, `duplicate` and `delete`, each `{ ok: true }` or `{ ok: false, reason }`.
|
|
2084
|
+
* `live`: the addresses on Live now (a live page needs the kit's redirects to move); `redirects`:
|
|
2085
|
+
* whether this code's build applies them. Cheaper than a plan: no writes are worked out.
|
|
2086
|
+
*/
|
|
2087
|
+
export function pageActions({ framework, paths, text, live = new Set(), found, importers }) {
|
|
2088
|
+
const kept = paths.filter((p) => !SKIP.test(p));
|
|
2089
|
+
const discovered = found ?? discover({ framework, paths: kept, text });
|
|
2090
|
+
const graph = importers ?? importGraph(kept, text);
|
|
2091
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
2092
|
+
const redirects = kitRedirects({ framework, text });
|
|
2093
|
+
const reads = siteReads(kept, text, graph);
|
|
2094
|
+
/** @type {Record<string, { rename: Capability, duplicate: Capability, delete: Capability, under: number }>} */
|
|
2095
|
+
const out = {};
|
|
2096
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
2097
|
+
const yes = { ok: /** @type {const} */ (true) };
|
|
2098
|
+
for (const page of discovered.pages) {
|
|
2099
|
+
if (page.path.includes(" ")) continue;
|
|
2100
|
+
const below = discovered.pages.filter((p) => under(p.path, page.path));
|
|
2101
|
+
const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
|
|
2102
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
|
|
2103
|
+
out[page.path] = all(no("framework"));
|
|
2104
|
+
continue;
|
|
2105
|
+
}
|
|
2106
|
+
if (!pageFile.ok) {
|
|
2107
|
+
out[page.path] = all(no("invalid"));
|
|
2108
|
+
continue;
|
|
2109
|
+
}
|
|
2110
|
+
if (page.kind === "template") {
|
|
2111
|
+
out[page.path] = all(no("template"));
|
|
2112
|
+
continue;
|
|
2113
|
+
}
|
|
2114
|
+
if (!page.file || page.reason === "unparsed") {
|
|
2115
|
+
out[page.path] = all(no("unparsed"));
|
|
2116
|
+
continue;
|
|
2117
|
+
}
|
|
2118
|
+
const onLive = live.has(page.path);
|
|
2119
|
+
let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
|
|
2120
|
+
if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
|
|
2121
|
+
const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
|
|
2122
|
+
let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
|
|
2123
|
+
if (duplicate.ok) {
|
|
2124
|
+
const content = ownedContent(page, { paths: kept, text, importers: graph });
|
|
2125
|
+
const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set() };
|
|
2126
|
+
const imported = new Set(reads.jsonOf.get(page.file) ?? []);
|
|
2127
|
+
if (content.unregistered.length) duplicate = no("content_unregistered", content.unregistered.join(", "));
|
|
2128
|
+
else if (content.unknown) duplicate = no("content_bound");
|
|
2129
|
+
else
|
|
2130
|
+
for (const f of content.files) {
|
|
2131
|
+
if (reads.isRoute(f) || imported.has(f)) continue;
|
|
2132
|
+
const collection = collectionOfFile(f, reads.collections);
|
|
2133
|
+
const id = f.slice(f.lastIndexOf("/") + 1, -5);
|
|
2134
|
+
const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
|
|
2135
|
+
const bound = !folder || !(pageReads.entries.has(`${collection}/${id}`) || (pageReads.names.has(id) && id !== collection));
|
|
2136
|
+
if (bound) {
|
|
2137
|
+
duplicate = no("content_bound", f);
|
|
2138
|
+
break;
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
if (duplicate.ok) {
|
|
2142
|
+
const mine = ownCode(page, graph, reads.imports);
|
|
2143
|
+
for (const m of mine) {
|
|
2144
|
+
if (m === page.file) continue;
|
|
2145
|
+
const r = reads.readsByFile.get(m);
|
|
2146
|
+
if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && content.files.some((f) => !reads.isRoute(f))) {
|
|
2147
|
+
duplicate = no("content_bound", m);
|
|
2148
|
+
break;
|
|
2149
|
+
}
|
|
2150
|
+
}
|
|
2151
|
+
}
|
|
2152
|
+
}
|
|
2153
|
+
out[page.path] = { rename, duplicate, delete: remove, under: below.length };
|
|
2154
|
+
}
|
|
2155
|
+
/** @type {Record<string, { rename: Capability, under: number }>} */
|
|
2156
|
+
const folders = {};
|
|
2157
|
+
for (const at of folderPaths(discovered.pages)) {
|
|
2158
|
+
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
2159
|
+
let rename = !PAGE_ACTION_FRAMEWORKS.includes(String(framework)) ? no("framework") : !pageFile.ok ? no("invalid") : yes;
|
|
2160
|
+
// A template's addresses are on Live without being listed: a folder with one counts as live.
|
|
2161
|
+
if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && !redirects) rename = no("no_redirects");
|
|
2162
|
+
if (rename.ok && framework === "vite-react" && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
|
|
2163
|
+
if (rename.ok && framework !== "vite-react" && !folderDirs(at, below)) rename = no("unparsed", at);
|
|
2164
|
+
folders[at] = { rename, under: below.length };
|
|
2165
|
+
}
|
|
2166
|
+
return { redirects, actions: out, folders };
|
|
2167
|
+
}
|
|
2168
|
+
|
|
2169
|
+
/**
|
|
2170
|
+
* The page file's redirects for a framework's build, without those whose address is a page now (a
|
|
2171
|
+
* page made where one used to send visitors on: the page wins). `skipped` names them.
|
|
2172
|
+
* Astro gets `[...path]` as it is here; a static Astro site needs it as one redirect per page
|
|
2173
|
+
* under the new address, which the Astro integration makes (astro.mjs). Next.js `:path*`; React
|
|
2174
|
+
* Router a route per address, `prefix` when everything under it goes along.
|
|
2175
|
+
*/
|
|
2176
|
+
export function redirectsFor(framework, pageFile, pagePaths = []) {
|
|
2177
|
+
const pages = new Set(pagePaths.map(normalisePath));
|
|
2178
|
+
const list = [];
|
|
2179
|
+
const skipped = [];
|
|
2180
|
+
for (const [source, destination] of Object.entries(pageFile.redirects ?? {})) {
|
|
2181
|
+
const prefix = REST.test(source);
|
|
2182
|
+
const base = prefix ? normalisePath(source.replace(REST, "")) : source;
|
|
2183
|
+
if (!prefix && pages.has(source)) {
|
|
2184
|
+
skipped.push(source);
|
|
2185
|
+
continue;
|
|
2186
|
+
}
|
|
2187
|
+
const destBase = prefix ? normalisePath(destination.replace(REST, "")) : destination;
|
|
2188
|
+
if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination, permanent: true });
|
|
2189
|
+
else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
|
|
2190
|
+
else list.push({ source, destination });
|
|
2191
|
+
}
|
|
2192
|
+
return { list, skipped };
|
|
2193
|
+
}
|
|
2194
|
+
|
|
2195
|
+
// ── Redirects by hand (docs/plan-folders-and-redirects.md, Part 2) ──
|
|
2196
|
+
|
|
2197
|
+
/**
|
|
2198
|
+
* The redirects the site sets itself, where Unbase can read them, with where each goes and where it
|
|
2199
|
+
* is set: vercel.json's `redirects`, an Astro config's `redirects` literal (a string or `{
|
|
2200
|
+
* destination }`), a Next.js config's literal `{ source, destination }` objects. In the order found.
|
|
2201
|
+
* @returns {{ from: string, to: string, file: string }[]}
|
|
2202
|
+
*/
|
|
2203
|
+
export function siteRedirectList({ framework, text }) {
|
|
2204
|
+
const out = [];
|
|
2205
|
+
try {
|
|
2206
|
+
const v = JSON.parse(text("vercel.json") ?? "null");
|
|
2207
|
+
for (const r of Array.isArray(v?.redirects) ? v.redirects : []) {
|
|
2208
|
+
if (typeof r?.source === "string" && typeof r?.destination === "string") out.push({ from: r.source, to: r.destination, file: "vercel.json" });
|
|
2209
|
+
}
|
|
2210
|
+
} catch {}
|
|
2211
|
+
for (const c of CONFIGS[String(framework)] ?? []) {
|
|
2212
|
+
const src = stripComments(text(c) ?? "");
|
|
2213
|
+
if (framework === "astro") {
|
|
2214
|
+
const at = src.search(/\bredirects\s*:\s*\{/);
|
|
2215
|
+
if (at < 0) continue;
|
|
2216
|
+
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
2217
|
+
const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
|
|
2218
|
+
for (const m of body.matchAll(entry)) out.push({ from: m[1], to: m[2] ?? m[3], file: c });
|
|
2219
|
+
} else if (framework === "next") {
|
|
2220
|
+
for (const m of src.matchAll(/\{[^{}]*\}/g)) {
|
|
2221
|
+
const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
|
|
2222
|
+
const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
|
|
2223
|
+
if (from && to) out.push({ from, to, file: c });
|
|
2224
|
+
}
|
|
2225
|
+
}
|
|
2226
|
+
}
|
|
2227
|
+
return out;
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
/** "/old/…", "/old/*" or "/old/[...path]" → the address and whether everything under it goes along. */
|
|
2231
|
+
function redirectEnd(p) {
|
|
2232
|
+
const s = String(p ?? "").trim();
|
|
2233
|
+
const prefix = /\/(…|\.\.\.|\*)$/.test(s) || REST.test(s);
|
|
2234
|
+
const base = normalisePath(prefix ? s.replace(REST, "").replace(/\/(…|\.\.\.|\*)$/, "") : s);
|
|
2235
|
+
return { base, prefix, key: prefix ? `${base === "/" ? "" : base}/[...path]` : base };
|
|
2236
|
+
}
|
|
2237
|
+
|
|
2238
|
+
/**
|
|
2239
|
+
* A redirect added, changed or removed by hand, in the page file: the plan of that one write, or why
|
|
2240
|
+
* not. `from` may end in `/…` (or `/*`, `/[...path]`): everything under it, to the same place under
|
|
2241
|
+
* `to`. `was`: the redirect's address before a change. Refused: an address that is a page now
|
|
2242
|
+
* (`page`: the page wins), one already sent on (`exists`), none to change (`missing`), one sent to
|
|
2243
|
+
* itself or into itself (`self`), a loop (`loop`), an address the site's own redirects take
|
|
2244
|
+
* (`redirect_conflict`), and adding without the package that applies them (`no_redirects`). A `to`
|
|
2245
|
+
* that is sent on itself is followed to where it ends, so no chain of hops is made; redirects that
|
|
2246
|
+
* led to `from` lead to `to` too.
|
|
2247
|
+
* @param {{ action: "add" | "change" | "remove", from: string, to?: string, was?: string }} request
|
|
2248
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[] } }} input
|
|
2249
|
+
*/
|
|
2250
|
+
export function planRedirect(request, { framework, paths, text, found }) {
|
|
2251
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
2252
|
+
const action = request.action;
|
|
2253
|
+
if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
|
|
2254
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
|
|
2255
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
2256
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
2257
|
+
const from = redirectEnd(request.from);
|
|
2258
|
+
const was = request.was != null ? redirectEnd(request.was) : from;
|
|
2259
|
+
if (action !== "add" && !(was.key in pageFile.redirects)) return no("missing", was.key);
|
|
2260
|
+
/** @type {Record<string, string | null>} */
|
|
2261
|
+
const changes = {};
|
|
2262
|
+
let to = null;
|
|
2263
|
+
if (action !== "remove") {
|
|
2264
|
+
if (!kitRedirects({ framework, text })) return no("no_redirects");
|
|
2265
|
+
if (from.base === "/" || !validAddress(from.base)) return no("address", request.from);
|
|
2266
|
+
const end = redirectEnd(request.to);
|
|
2267
|
+
if (!validAddress(end.base)) return no("address", request.to);
|
|
2268
|
+
const discovered = found ?? discover({ framework, paths: paths.filter((p) => !SKIP.test(p)), text });
|
|
2269
|
+
const isPage = (p) => discovered.pages.some((q) => (q.kind === "template" ? templateMatches(q.path, p) : q.path === p));
|
|
2270
|
+
if (from.prefix ? discovered.pages.some((q) => within(q.path, from.base)) : isPage(from.base)) return no("page", from.base);
|
|
2271
|
+
if (from.key !== was.key && from.key in pageFile.redirects) return no("exists", from.key);
|
|
2272
|
+
if (action === "add" && from.key in pageFile.redirects) return no("exists", from.key);
|
|
2273
|
+
const own = [...siteRedirects({ framework, text })].find((s) => sends(s, from.base));
|
|
2274
|
+
if (own) return no("redirect_conflict", own);
|
|
2275
|
+
// Where `to` ends when it is sent on itself: never a chain of hops.
|
|
2276
|
+
let dest = end.base;
|
|
2277
|
+
const others = { ...pageFile.redirects };
|
|
2278
|
+
delete others[was.key];
|
|
2279
|
+
for (let hops = 0; hops < 20; hops++) {
|
|
2280
|
+
const next = Object.entries(others).find(([s]) => !REST.test(s) && s === dest);
|
|
2281
|
+
if (!next) break;
|
|
2282
|
+
dest = next[1];
|
|
2283
|
+
}
|
|
2284
|
+
if (from.prefix ? within(dest, from.base) : dest === from.base) return no(dest === from.base ? "self" : "loop", dest);
|
|
2285
|
+
if (Object.entries(others).some(([s, d]) => d === from.base && s === dest)) return no("loop", dest);
|
|
2286
|
+
to = from.prefix ? `${dest === "/" ? "" : dest}/[...path]` : dest;
|
|
2287
|
+
}
|
|
2288
|
+
const content = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
2289
|
+
const before = { ...sendsOn };
|
|
2290
|
+
delete sendsOn[was.key];
|
|
2291
|
+
if (to !== null) {
|
|
2292
|
+
sendsOn[from.key] = to;
|
|
2293
|
+
// What led to this address leads on to where it now goes, not through it.
|
|
2294
|
+
if (!from.prefix) for (const [s, d] of Object.entries(sendsOn)) if (d === from.base && s !== from.key) sendsOn[s] = to;
|
|
2295
|
+
}
|
|
2296
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) changes[k] = sendsOn[k] ?? null;
|
|
2297
|
+
});
|
|
2298
|
+
if (content === null) return no("same");
|
|
2299
|
+
const shown = (k) => k.replace(REST, "/…");
|
|
2300
|
+
const message = action === "remove" ? `Unbase: remove redirect ${shown(was.key)}` : `Unbase: redirect ${shown(from.key)} to ${shown(to)}`;
|
|
2301
|
+
return { ok: /** @type {const} */ (true), action, from: from.key, to, was: was.key, files: [{ path: PAGE_FILE, content }], redirects: changes, message };
|
|
2302
|
+
}
|