@unbase-app/pages 0.0.0-stage → 0.4.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.
- package/LICENSE +21 -0
- package/README.md +138 -2
- package/astro.d.mts +29 -0
- package/astro.mjs +202 -0
- package/core.mjs +1859 -0
- package/node.mjs +205 -0
- package/package.json +43 -4
- package/vite.d.mts +27 -0
- package/vite.mjs +287 -0
package/core.mjs
ADDED
|
@@ -0,0 +1,1859 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// @unbase-app/pages — core (docs/plan-pages.md)
|
|
3
|
+
//
|
|
4
|
+
// The one implementation of what a site's pages are and whether a draft can
|
|
5
|
+
// be kept off Live, shared by the build plugins (astro.mjs, vite.mjs, and
|
|
6
|
+
// @unbase-app/next's withUnbase) and by Unbase's backend. Exact copies in
|
|
7
|
+
// supabase/functions/_shared/pages-core.mjs, kit/vite/pages/core.mjs and
|
|
8
|
+
// kit/next/core.mjs; tests fail when they differ.
|
|
9
|
+
//
|
|
10
|
+
// Pure: no file system, no network, no clock. Everything reads the app's files
|
|
11
|
+
// through `text(path)` (paths relative to the app's root) and a list of
|
|
12
|
+
// `paths`, so the same commit always gives the same answer.
|
|
13
|
+
//
|
|
14
|
+
// parsePageFile unbase.pages.json, validated
|
|
15
|
+
// deployContext production | preview | development, never from NODE_ENV
|
|
16
|
+
// discover the pages the code makes (Astro, Next.js, React Router)
|
|
17
|
+
// draftCheck whether one page can be kept out of a production build
|
|
18
|
+
// linksTo the files that name a page's address
|
|
19
|
+
// leakPrints text that only a draft page has, to search the output for
|
|
20
|
+
// ============================================================================
|
|
21
|
+
|
|
22
|
+
export const PAGE_FILE = "unbase.pages.json";
|
|
23
|
+
export const KIT = "@unbase-app/pages";
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The packages that bring the kit into a framework's build: the kit itself, the framework's own
|
|
27
|
+
* package that carries it (@unbase-app/astro; @unbase-app/vite, whose `unbase()` is the kit's Vite
|
|
28
|
+
* plugin and comment mode's loader in one; @unbase-app/next, whose `withUnbase` runs this core in a
|
|
29
|
+
* Next.js build), and the kit's name before K5 (03-11), which sites installed then still have until
|
|
30
|
+
* they move across.
|
|
31
|
+
*/
|
|
32
|
+
export const KITS = {
|
|
33
|
+
astro: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
|
|
34
|
+
"vite-react": [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
|
|
35
|
+
next: ["@unbase-app/next"],
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** Frameworks the kit keeps drafts out of: those with a package that brings it (KITS). */
|
|
39
|
+
export const DRAFTABLE = Object.keys(KITS);
|
|
40
|
+
|
|
41
|
+
const EXTS = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".mts", ".astro", ".vue", ".svelte", ".json"];
|
|
42
|
+
const CODE = /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html)$/;
|
|
43
|
+
const SKIP = /(^|\/)(node_modules|dist|build|\.git|\.astro|\.next|\.vercel|\.output)(\/|$)/;
|
|
44
|
+
|
|
45
|
+
const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
46
|
+
const escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
47
|
+
|
|
48
|
+
/** "about/" → "/about"; "" → "/". */
|
|
49
|
+
export function normalisePath(p) {
|
|
50
|
+
const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
|
|
51
|
+
return s || "/";
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// ── The page file ──────────────────────────────────────────────────────────
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* unbase.pages.json: `{ "pages": { "/address": { "draft": true, "name": "Pricing" } },
|
|
58
|
+
* "redirects": { "/old": "/new" } }`. Absent is valid (no flags, no redirects). A page's `name` is
|
|
59
|
+
* what Unbase calls it (never rendered); `redirects` send an old address on, applied at build by
|
|
60
|
+
* the framework's package (docs/plan-page-actions.md). A redirect's address may end in
|
|
61
|
+
* `/[...path]`: everything under it, carried over.
|
|
62
|
+
* @param {string | null | undefined} text
|
|
63
|
+
* @returns {{ ok: true, exists: boolean, pages: Record<string, { draft?: boolean, name?: string }>, redirects: Record<string, string> } | { ok: false, exists: true, error: string, pages: {}, redirects: {} }}
|
|
64
|
+
*/
|
|
65
|
+
export function parsePageFile(text) {
|
|
66
|
+
if (text == null) return { ok: true, exists: false, pages: {}, redirects: {} };
|
|
67
|
+
const fail = (error) => ({ ok: /** @type {const} */ (false), exists: true, error, pages: {}, redirects: {} });
|
|
68
|
+
let data;
|
|
69
|
+
try {
|
|
70
|
+
data = JSON.parse(text);
|
|
71
|
+
} catch {
|
|
72
|
+
return fail("not valid JSON");
|
|
73
|
+
}
|
|
74
|
+
if (!isObject(data)) return fail("the file is not an object");
|
|
75
|
+
const pages = data.pages ?? {};
|
|
76
|
+
if (!isObject(pages)) return fail("`pages` is not an object");
|
|
77
|
+
/** @type {Record<string, { draft?: boolean, name?: string }>} */
|
|
78
|
+
const out = {};
|
|
79
|
+
for (const [address, entry] of Object.entries(pages)) {
|
|
80
|
+
if (!address.startsWith("/")) return fail(`${address}: an address starts with /`);
|
|
81
|
+
if (!isObject(entry)) return fail(`${address}: not an object`);
|
|
82
|
+
if (entry.draft !== undefined && typeof entry.draft !== "boolean") return fail(`${address}: draft is true or false`);
|
|
83
|
+
if (entry.name !== undefined && typeof entry.name !== "string") return fail(`${address}: name is text`);
|
|
84
|
+
out[normalisePath(address)] = { ...(entry.draft === undefined ? {} : { draft: entry.draft }), ...(entry.name ? { name: entry.name } : {}) };
|
|
85
|
+
}
|
|
86
|
+
const redirects = data.redirects ?? {};
|
|
87
|
+
if (!isObject(redirects)) return fail("`redirects` is not an object");
|
|
88
|
+
/** @type {Record<string, string>} */
|
|
89
|
+
const sends = {};
|
|
90
|
+
for (const [from, to] of Object.entries(redirects)) {
|
|
91
|
+
if (!from.startsWith("/")) return fail(`redirects: ${from}: an address starts with /`);
|
|
92
|
+
if (typeof to !== "string" || !to.startsWith("/")) return fail(`redirects: ${from}: goes to an address that starts with /`);
|
|
93
|
+
if (REST.test(from) !== REST.test(to)) return fail(`redirects: ${from}: both ends end in /[...path], or neither`);
|
|
94
|
+
sends[normalisePath(from)] = normalisePath(to);
|
|
95
|
+
}
|
|
96
|
+
return { ok: true, exists: true, pages: out, redirects: sends };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A redirect's address that carries what is under it: `/old/[...path]`. */
|
|
100
|
+
const REST = /\/\[\.\.\.[A-Za-z_]\w*\]$/;
|
|
101
|
+
|
|
102
|
+
/** The addresses flagged as draft, sorted. */
|
|
103
|
+
export const draftPaths = (file) =>
|
|
104
|
+
Object.keys(file.pages)
|
|
105
|
+
.filter((p) => file.pages[p].draft === true)
|
|
106
|
+
.sort();
|
|
107
|
+
|
|
108
|
+
// ── The deployment context ─────────────────────────────────────────────────
|
|
109
|
+
|
|
110
|
+
const CONTEXTS = new Set(["production", "preview", "development"]);
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Which build this is. Explicit first, then a dev server, then the host; anything else is
|
|
114
|
+
* production, so a draft only shows where a host says it is a preview. NODE_ENV is never read:
|
|
115
|
+
* previews are production-optimised builds too.
|
|
116
|
+
* @param {{ env?: Record<string, string | undefined>, command?: "build" | "dev" }} [input]
|
|
117
|
+
* @returns {{ context: "production" | "preview" | "development", source: string }}
|
|
118
|
+
*/
|
|
119
|
+
export function deployContext({ env = {}, command = "build" } = {}) {
|
|
120
|
+
const own = env.UNBASE_DEPLOY_CONTEXT;
|
|
121
|
+
if (own) return CONTEXTS.has(own) ? { context: /** @type {any} */ (own), source: "UNBASE_DEPLOY_CONTEXT" } : { context: "production", source: `UNBASE_DEPLOY_CONTEXT=${own} (unknown)` };
|
|
122
|
+
if (command === "dev") return { context: "development", source: "dev server" };
|
|
123
|
+
const vercel = env.VERCEL_ENV;
|
|
124
|
+
if (vercel) return { context: vercel === "preview" ? "preview" : vercel === "development" ? "development" : "production", source: `VERCEL_ENV=${vercel}` };
|
|
125
|
+
if (env.NETLIFY === "true" && env.CONTEXT) {
|
|
126
|
+
const c = env.CONTEXT;
|
|
127
|
+
return { context: c === "deploy-preview" || c === "branch-deploy" ? "preview" : c === "dev" ? "development" : "production", source: `CONTEXT=${c}` };
|
|
128
|
+
}
|
|
129
|
+
return { context: "production", source: "no deployment context (counts as production)" };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// ── Reading code ───────────────────────────────────────────────────────────
|
|
133
|
+
|
|
134
|
+
/** Where a quoted string that starts at `i` ends (after its closing quote). One line for ' and ". */
|
|
135
|
+
function stringEnd(src, i) {
|
|
136
|
+
const q = src[i];
|
|
137
|
+
let j = i + 1;
|
|
138
|
+
while (j < src.length) {
|
|
139
|
+
const c = src[j];
|
|
140
|
+
if (c === "\\") {
|
|
141
|
+
j += 2;
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
if (c === q) return j + 1;
|
|
145
|
+
if (c === "\n" && q !== "`") return i + 1; // not a string after all (an apostrophe in text)
|
|
146
|
+
j++;
|
|
147
|
+
}
|
|
148
|
+
return src.length;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The source with its comments blanked out, so offsets stay the same. */
|
|
152
|
+
export function stripComments(src) {
|
|
153
|
+
let out = "";
|
|
154
|
+
let i = 0;
|
|
155
|
+
while (i < src.length) {
|
|
156
|
+
const c = src[i];
|
|
157
|
+
const d = src[i + 1];
|
|
158
|
+
if (c === "/" && d === "/") {
|
|
159
|
+
while (i < src.length && src[i] !== "\n") {
|
|
160
|
+
out += " ";
|
|
161
|
+
i++;
|
|
162
|
+
}
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
if (c === "/" && d === "*") {
|
|
166
|
+
const end = src.indexOf("*/", i + 2);
|
|
167
|
+
const stop = end < 0 ? src.length : end + 2;
|
|
168
|
+
out += src.slice(i, stop).replace(/[^\n]/g, " ");
|
|
169
|
+
i = stop;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
173
|
+
const j = stringEnd(src, i);
|
|
174
|
+
out += src.slice(i, j);
|
|
175
|
+
i = j;
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
out += c;
|
|
179
|
+
i++;
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const dirname = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
|
|
185
|
+
|
|
186
|
+
function joinRelative(dir, spec) {
|
|
187
|
+
const parts = dir ? dir.split("/") : [];
|
|
188
|
+
for (const s of spec.split("/")) {
|
|
189
|
+
if (s === "." || s === "") continue;
|
|
190
|
+
if (s === "..") parts.pop();
|
|
191
|
+
else parts.push(s);
|
|
192
|
+
}
|
|
193
|
+
return parts.join("/");
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* A module specifier from `from` to a file of the app: relative, or `@/` for src/ (Lovable's and
|
|
198
|
+
* shadcn's alias). Null for a package or a file that is not there.
|
|
199
|
+
*/
|
|
200
|
+
export function resolveImport(from, spec, have) {
|
|
201
|
+
let base;
|
|
202
|
+
if (spec.startsWith("@/")) base = `src/${spec.slice(2)}`;
|
|
203
|
+
else if (spec.startsWith("./") || spec.startsWith("../")) base = joinRelative(dirname(from), spec);
|
|
204
|
+
else return null;
|
|
205
|
+
base = base.replace(/\?.*$/, "");
|
|
206
|
+
for (const c of [base, ...EXTS.map((e) => base + e), ...EXTS.map((e) => `${base}/index${e}`)]) if (have.has(c)) return c;
|
|
207
|
+
return null;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const IMPORTS = [
|
|
211
|
+
/(?:import|export)\s+(?:type\s+)?[\w$*{}\s,]*?\s*from\s*["']([^"']+)["']/g,
|
|
212
|
+
/import\s*["']([^"']+)["']/g,
|
|
213
|
+
/import\(\s*["']([^"']+)["']\s*\)/g,
|
|
214
|
+
/require\(\s*["']([^"']+)["']\s*\)/g,
|
|
215
|
+
];
|
|
216
|
+
|
|
217
|
+
/** Every file of the app another file imports, with who imports it. */
|
|
218
|
+
export function importGraph(paths, text) {
|
|
219
|
+
const have = new Set(paths);
|
|
220
|
+
/** @type {Map<string, Set<string>>} */
|
|
221
|
+
const importers = new Map();
|
|
222
|
+
for (const p of paths) {
|
|
223
|
+
if (!CODE.test(p) || SKIP.test(p)) continue;
|
|
224
|
+
const src = text(p);
|
|
225
|
+
if (!src) continue;
|
|
226
|
+
for (const re of IMPORTS) {
|
|
227
|
+
re.lastIndex = 0;
|
|
228
|
+
for (const m of src.matchAll(re)) {
|
|
229
|
+
const target = resolveImport(p, m[1], have);
|
|
230
|
+
if (!target || target === p) continue;
|
|
231
|
+
if (!importers.has(target)) importers.set(target, new Set());
|
|
232
|
+
importers.get(target).add(p);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
return importers;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// ── Discovery ──────────────────────────────────────────────────────────────
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* @typedef {{ file: string, start: number, end: number, component: string, importKind: "default" | "lazy" }} RouteSite
|
|
243
|
+
* @typedef {{ path: string, kind: "file" | "route" | "template", file: string | null, reason?: "nested" | "unparsed", router?: RouteSite }} Page
|
|
244
|
+
*/
|
|
245
|
+
|
|
246
|
+
const address = (segments) => normalisePath(segments.join("/"));
|
|
247
|
+
const unlisted = (s) => s.startsWith("_") || s.startsWith("@") || s.startsWith("(.");
|
|
248
|
+
const routeGroup = (s) => /^\([^.)][^)]*\)$/.test(s);
|
|
249
|
+
|
|
250
|
+
/** Astro: src/pages/**; a page per file, `[x]` a template, `_x` private, an endpoint (.ts) none. */
|
|
251
|
+
function astroPages(paths) {
|
|
252
|
+
/** @type {Page[]} */
|
|
253
|
+
const out = [];
|
|
254
|
+
const ext = /\.(astro|md|mdx|html)$/;
|
|
255
|
+
for (const p of paths) {
|
|
256
|
+
if (!p.startsWith("src/pages/") || !ext.test(p)) continue;
|
|
257
|
+
const segments = p.slice("src/pages/".length).replace(ext, "").split("/");
|
|
258
|
+
if (segments.some((s) => s.startsWith("_"))) continue;
|
|
259
|
+
if (segments.at(-1) === "index") segments.pop();
|
|
260
|
+
if (segments.length === 1 && /^(404|500)$/.test(segments[0])) continue;
|
|
261
|
+
out.push({ path: address(segments), kind: segments.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
|
|
262
|
+
}
|
|
263
|
+
return out;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Next.js: app/**\/page.* and pages/**, as unbase-projects' pages.ts read them. */
|
|
267
|
+
function nextPages(paths) {
|
|
268
|
+
/** @type {Page[]} */
|
|
269
|
+
const out = [];
|
|
270
|
+
const ext = /\.(tsx|ts|jsx|js|mdx|md)$/;
|
|
271
|
+
for (const base of ["app/", "src/app/"]) {
|
|
272
|
+
for (const p of paths) {
|
|
273
|
+
if (!p.startsWith(base)) continue;
|
|
274
|
+
const segments = p.slice(base.length).split("/");
|
|
275
|
+
const file = segments.pop();
|
|
276
|
+
if (!/^page\./.test(file) || !ext.test(file) || segments.some(unlisted)) continue;
|
|
277
|
+
const kept = segments.filter((s) => !routeGroup(s));
|
|
278
|
+
out.push({ path: address(kept), kind: kept.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
for (const base of ["pages/", "src/pages/"]) {
|
|
282
|
+
for (const p of paths) {
|
|
283
|
+
if (!p.startsWith(base) || !ext.test(p)) continue;
|
|
284
|
+
const segments = p.slice(base.length).replace(ext, "").split("/");
|
|
285
|
+
if (segments[0] === "api" || segments.some(unlisted)) continue;
|
|
286
|
+
if (segments.at(-1) === "index") segments.pop();
|
|
287
|
+
if (segments.length === 1 && /^(404|500)$/.test(segments[0])) continue;
|
|
288
|
+
out.push({ path: address(segments), kind: segments.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return out;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Where a JSX tag that starts after `from` ends, braces and strings skipped. */
|
|
295
|
+
function tagEnd(src, from) {
|
|
296
|
+
let depth = 0;
|
|
297
|
+
let i = from;
|
|
298
|
+
while (i < src.length) {
|
|
299
|
+
const c = src[i];
|
|
300
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
301
|
+
i = stringEnd(src, i);
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (c === "{") depth++;
|
|
305
|
+
else if (c === "}") depth--;
|
|
306
|
+
else if (depth === 0 && c === "/" && src[i + 1] === ">") return { end: i + 2, selfClosing: true };
|
|
307
|
+
else if (depth === 0 && c === ">") return { end: i + 1, selfClosing: false };
|
|
308
|
+
i++;
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The text inside the braces that open at `i`. */
|
|
314
|
+
function braced(src, i) {
|
|
315
|
+
let depth = 0;
|
|
316
|
+
for (let j = i; j < src.length; j++) {
|
|
317
|
+
const c = src[j];
|
|
318
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
319
|
+
j = stringEnd(src, j) - 1;
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
if (c === "{") depth++;
|
|
323
|
+
else if (c === "}" && --depth === 0) return src.slice(i + 1, j);
|
|
324
|
+
}
|
|
325
|
+
return null;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** A `path` attribute: its literal value, null when absent, false when not a literal. */
|
|
329
|
+
function pathAttr(attrs) {
|
|
330
|
+
const m = attrs.match(/(?:^|\s)path\s*=\s*/);
|
|
331
|
+
if (!m) return null;
|
|
332
|
+
const rest = attrs.slice(m.index + m[0].length);
|
|
333
|
+
const lit = rest.match(/^"([^"]*)"|^'([^']*)'|^\{\s*"([^"]*)"\s*\}|^\{\s*'([^']*)'\s*\}|^\{\s*`([^`$]*)`\s*\}/);
|
|
334
|
+
if (!lit) return false;
|
|
335
|
+
return lit.slice(1).find((v) => v !== undefined) ?? "";
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/** The one component an element renders (`element={<About />}`, `Component={About}`), or null. */
|
|
339
|
+
function componentAttr(attrs) {
|
|
340
|
+
const comp = attrs.match(/(?:^|\s)Component\s*=\s*\{\s*([A-Z][\w$]*)\s*\}/);
|
|
341
|
+
if (comp) return comp[1];
|
|
342
|
+
const m = attrs.match(/(?:^|\s)element\s*=\s*\{/);
|
|
343
|
+
if (!m) return null;
|
|
344
|
+
const inner = braced(attrs, m.index + m[0].length - 1);
|
|
345
|
+
if (inner === null) return null;
|
|
346
|
+
const el = inner.trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/);
|
|
347
|
+
return el ? el[1] : null;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** The components a router file imports, by name: a default import or React.lazy. */
|
|
351
|
+
function importedComponents(src) {
|
|
352
|
+
/** @type {Map<string, { spec: string, kind: "default" | "lazy" }>} */
|
|
353
|
+
const out = new Map();
|
|
354
|
+
for (const m of src.matchAll(/import\s+([A-Za-z_$][\w$]*)\s*(?:,\s*\{[^}]*\})?\s*from\s*["']([^"']+)["']/g)) out.set(m[1], { spec: m[2], kind: "default" });
|
|
355
|
+
for (const m of src.matchAll(/(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:React\.)?lazy\(\s*(?:async\s*)?\(\)\s*=>\s*import\(\s*["']([^"']+)["']\s*\)\s*\)/g))
|
|
356
|
+
out.set(m[1], { spec: m[2], kind: "lazy" });
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* React Router: the JSX `<Route>` elements of every file that imports react-router(-dom), with
|
|
362
|
+
* their nesting (an index route takes its parent's path, a layout route without a path adds
|
|
363
|
+
* nothing), each traced to the file its component comes from. `*` is the catch-all (Not Found).
|
|
364
|
+
* @returns {{ pages: Page[], notFound: string | null }}
|
|
365
|
+
*/
|
|
366
|
+
function reactRouterPages(paths, text, only = paths) {
|
|
367
|
+
const have = new Set(paths);
|
|
368
|
+
/** @type {Page[]} */
|
|
369
|
+
const pages = [];
|
|
370
|
+
let notFound = null;
|
|
371
|
+
for (const file of only) {
|
|
372
|
+
if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP.test(file)) continue;
|
|
373
|
+
const raw = text(file);
|
|
374
|
+
if (!raw || !raw.includes("<Route") || !/from\s*["']react-router(-dom)?["']/.test(raw)) continue;
|
|
375
|
+
const src = stripComments(raw);
|
|
376
|
+
const imports = importedComponents(src);
|
|
377
|
+
/** @type {{ at: number, close?: true }[]} */
|
|
378
|
+
const events = [];
|
|
379
|
+
for (const m of src.matchAll(/<Route(?=[\s/>])/g)) events.push({ at: m.index });
|
|
380
|
+
for (const m of src.matchAll(/<\/Route\s*>/g)) events.push({ at: m.index, close: true });
|
|
381
|
+
events.sort((a, b) => a.at - b.at);
|
|
382
|
+
/** @type {string[]} */
|
|
383
|
+
const stack = [];
|
|
384
|
+
for (const e of events) {
|
|
385
|
+
if (e.close) {
|
|
386
|
+
stack.pop();
|
|
387
|
+
continue;
|
|
388
|
+
}
|
|
389
|
+
const tag = tagEnd(src, e.at + "<Route".length);
|
|
390
|
+
if (!tag) break;
|
|
391
|
+
const attrs = src.slice(e.at + "<Route".length, tag.end - (tag.selfClosing ? 2 : 1));
|
|
392
|
+
const parent = stack.at(-1) ?? "";
|
|
393
|
+
const index = /(?:^|\s)index(?=\s|$|=\{\s*true\s*\})/.test(attrs);
|
|
394
|
+
const p = pathAttr(attrs);
|
|
395
|
+
const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
|
|
396
|
+
if (!tag.selfClosing) stack.push(typeof full === "string" ? full : parent);
|
|
397
|
+
if (full === null) continue; // a layout route: no address of its own
|
|
398
|
+
const component = componentAttr(attrs);
|
|
399
|
+
const imported = component ? imports.get(component) : undefined;
|
|
400
|
+
const target = imported ? resolveImport(file, imported.spec, have) : null;
|
|
401
|
+
if (full === false) {
|
|
402
|
+
pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (full === "/*" || full.endsWith("/*") || full === "*") {
|
|
406
|
+
if (full === "/*" && target) notFound = target;
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
/** @type {Page} */
|
|
410
|
+
const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
|
|
411
|
+
if (target && imported && component) page.router = { file, start: e.at, end: tag.end, component, importKind: imported.kind };
|
|
412
|
+
if (!tag.selfClosing) page.reason = "nested";
|
|
413
|
+
else if (!target) page.reason = "unparsed";
|
|
414
|
+
pages.push(page);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return { pages, notFound };
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* A router file's `code` without the `<Route … />` of each address in `drop` that it holds, as
|
|
422
|
+
* discovery found them (the same parser, so what was checked is what goes). `removed` names them;
|
|
423
|
+
* the plugin refuses the build when a draft's route was removed nowhere.
|
|
424
|
+
* @param {{ file: string, code: string, paths: string[], text: (path: string) => string | null, drop: string[] }} input
|
|
425
|
+
*/
|
|
426
|
+
export function removeRoutes({ file, code, paths, text, drop }) {
|
|
427
|
+
const { pages } = reactRouterPages(paths, (p) => (p === file ? code : text(p)), [file]);
|
|
428
|
+
const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
|
|
429
|
+
spans.sort((a, b) => b.start - a.start);
|
|
430
|
+
let out = code;
|
|
431
|
+
for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
|
|
432
|
+
return { code: out, removed: spans.map((s) => s.path) };
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* The pages the code makes, sorted by address. Unknown frameworks make none here.
|
|
437
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null }} input
|
|
438
|
+
* @returns {{ pages: Page[], notFound: string | null }}
|
|
439
|
+
*/
|
|
440
|
+
export function discover({ framework, paths, text }) {
|
|
441
|
+
const kept = paths.filter((p) => !SKIP.test(p));
|
|
442
|
+
const found =
|
|
443
|
+
framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : { pages: [], notFound: null };
|
|
444
|
+
const seen = new Set();
|
|
445
|
+
const pages = found.pages
|
|
446
|
+
.filter((p) => (seen.has(p.path) ? false : (seen.add(p.path), true)))
|
|
447
|
+
.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
448
|
+
return { pages, notFound: found.notFound };
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// ── Content a page owns ────────────────────────────────────────────────────
|
|
452
|
+
|
|
453
|
+
const CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
|
|
454
|
+
/** Where content collections are defined: naming one there is not using it. */
|
|
455
|
+
const CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
|
|
456
|
+
/** Written by comment-modus: content file → its collection, where that is not its folder. */
|
|
457
|
+
const COLLECTIONS = "src/content/.schemas/collecties.json";
|
|
458
|
+
|
|
459
|
+
/** The names a content file goes by: its entry id (file name) and its collection. */
|
|
460
|
+
function contentNames(paths, text) {
|
|
461
|
+
/** @type {Map<string, Set<string>>} */
|
|
462
|
+
const files = new Map();
|
|
463
|
+
const add = (name, f) => {
|
|
464
|
+
if (!files.has(name)) files.set(name, new Set());
|
|
465
|
+
files.get(name).add(f);
|
|
466
|
+
};
|
|
467
|
+
let collections = {};
|
|
468
|
+
try {
|
|
469
|
+
collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
|
|
470
|
+
} catch {}
|
|
471
|
+
for (const f of paths) {
|
|
472
|
+
if (!CONTENT_JSON.test(f)) continue;
|
|
473
|
+
add(f.slice(f.lastIndexOf("/") + 1, -".json".length), f);
|
|
474
|
+
const named = collections[f];
|
|
475
|
+
add(typeof named === "string" ? named : f.slice("src/content/".length).split("/")[0].replace(/\.json$/, ""), f);
|
|
476
|
+
}
|
|
477
|
+
return files;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** A content file's collection: as collecties.json says, else its first folder under src/content. */
|
|
481
|
+
function collectionOfFile(f, collections) {
|
|
482
|
+
const named = collections[f];
|
|
483
|
+
return typeof named === "string" ? named : f.slice("src/content/".length).split("/")[0].replace(/\.json$/, "");
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* The files only `page` uses: its own file, and every file it imports (however deep) that nothing
|
|
488
|
+
* outside that set imports. What these read is the page's; what any other file reads is not.
|
|
489
|
+
*/
|
|
490
|
+
function ownCode(page, importers, imports) {
|
|
491
|
+
const own = new Set([page.file]);
|
|
492
|
+
// Forward from what is its own: a file joins once its last importer has (or is the router).
|
|
493
|
+
const queue = [page.file];
|
|
494
|
+
while (queue.length) {
|
|
495
|
+
for (const target of imports.get(queue.pop()) ?? []) {
|
|
496
|
+
if (own.has(target) || ![...importers.get(target)].every((f) => own.has(f) || f === page.router?.file)) continue;
|
|
497
|
+
own.add(target);
|
|
498
|
+
queue.push(target);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return own;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Astro's own reading functions: collection first, then (getEntry) the entry. */
|
|
505
|
+
const ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* How the site reads content, as the editability manifest's `reads` say it (plan-editable F0):
|
|
509
|
+
* Astro's functions; the site's own functions that pass their first argument on as the collection
|
|
510
|
+
* (`getPagina(naam)`: `byName`); and those that read fixed content (`getEvenementen()` a whole
|
|
511
|
+
* collection, `getActieAgendaTeksten()` one entry: `fixed`). `code` is every code file without
|
|
512
|
+
* its comments.
|
|
513
|
+
*/
|
|
514
|
+
function contentReads(paths, text) {
|
|
515
|
+
/** @type {Map<string, string>} */
|
|
516
|
+
const code = new Map();
|
|
517
|
+
for (const p of paths) {
|
|
518
|
+
if (!CODE.test(p) || SKIP.test(p)) continue;
|
|
519
|
+
const src = text(p);
|
|
520
|
+
if (src) code.set(p, stripComments(src));
|
|
521
|
+
}
|
|
522
|
+
const astro = ASTRO_READS.join("|");
|
|
523
|
+
const byName = new Set(ASTRO_READS);
|
|
524
|
+
/** The entry a reading function always reads: `getEntry(collectie, "pagina")` → "pagina". */
|
|
525
|
+
const entryOf = new Map();
|
|
526
|
+
/** @type {Map<string, { whole: Set<string>, entries: Set<string> }>} */
|
|
527
|
+
const fixed = new Map();
|
|
528
|
+
/** @type {Map<string, string>} */
|
|
529
|
+
const bodies = new Map();
|
|
530
|
+
/** Where each file's helpers have their bodies, [start, end): what a body reads, its callers read. */
|
|
531
|
+
const spans = new Map();
|
|
532
|
+
const DIRECT = new RegExp(`\\b(?:${astro})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
533
|
+
const addFixed = (name, whole, entry) => {
|
|
534
|
+
if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
|
|
535
|
+
if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
|
|
536
|
+
else fixed.get(name).whole.add(whole);
|
|
537
|
+
};
|
|
538
|
+
for (const [p, src] of code) {
|
|
539
|
+
if (!/\.(ts|mts|js|mjs)$/.test(p)) continue;
|
|
540
|
+
// Functions whether exported or not: a site's helpers may go through a module's own `enkel(collectie)`.
|
|
541
|
+
for (const m of src.matchAll(/(?: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)) {
|
|
542
|
+
const name = m[1] ?? m[3];
|
|
543
|
+
const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
|
|
544
|
+
// The body: a block, or for an arrow the expression up to the end of its statement.
|
|
545
|
+
let at = m.index + m[0].length;
|
|
546
|
+
while (/\s/.test(src[at] ?? "")) at++;
|
|
547
|
+
const block = src.indexOf("{", at);
|
|
548
|
+
const braces = src[at] === "{" ? at : m[1] && block > 0 ? block : -1;
|
|
549
|
+
const body = braces >= 0 ? (braced(src, braces) ?? "") : src.slice(at, src.slice(at).search(/;|\n\s*\n|$/) + at);
|
|
550
|
+
const start = braces >= 0 ? braces + 1 : at;
|
|
551
|
+
if (!spans.has(p)) spans.set(p, []);
|
|
552
|
+
spans.get(p).push([start, start + body.length]);
|
|
553
|
+
if (first && new RegExp(`\\b(?:${astro})\\(\\s*${escape(first)}\\b`).test(body)) {
|
|
554
|
+
byName.add(name);
|
|
555
|
+
const entry = new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1];
|
|
556
|
+
if (entry) entryOf.set(name, entry);
|
|
557
|
+
}
|
|
558
|
+
bodies.set(name, body);
|
|
559
|
+
for (const d of body.matchAll(DIRECT)) addFixed(name, d[1], d[2]);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
// A helper that calls one of the site's reading functions with a literal reads that content
|
|
563
|
+
// (`getVerlangensOverzicht = () => enkel("verlangensOverzicht", …)`): its entry, else the collection.
|
|
564
|
+
for (const [name, body] of bodies) {
|
|
565
|
+
for (const fn of byName) {
|
|
566
|
+
if (fn === name || ASTRO_READS.includes(fn)) continue;
|
|
567
|
+
for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
// A helper that calls a helper reads what that one reads (`getActieAgenda()` → `getActieAgendaTeksten()`).
|
|
571
|
+
// Each body's calls are read once and looked up, not searched for helper by helper.
|
|
572
|
+
const calls = new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))]));
|
|
573
|
+
for (let grew = true; grew; ) {
|
|
574
|
+
grew = false;
|
|
575
|
+
for (const [name, called] of calls) {
|
|
576
|
+
for (const other of called) {
|
|
577
|
+
const read = fixed.get(other);
|
|
578
|
+
if (other === name || !read) continue;
|
|
579
|
+
if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
|
|
580
|
+
const mine = fixed.get(name);
|
|
581
|
+
const before = mine.whole.size + mine.entries.size;
|
|
582
|
+
read.whole.forEach((c) => mine.whole.add(c));
|
|
583
|
+
read.entries.forEach((e) => mine.entries.add(e));
|
|
584
|
+
if (mine.whole.size + mine.entries.size > before) grew = true;
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
|
|
589
|
+
return { code, byName, byNameCall, entryOf, fixed, astro, spans };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** A call: `name(`, not `obj.name(`. */
|
|
593
|
+
const CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
|
|
594
|
+
/** Every identifier, as `(?<![\w$.])name(?![\w$])` would find it. */
|
|
595
|
+
const IDENTIFIER = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
|
|
596
|
+
/** A definition of a function or constant, by name. */
|
|
597
|
+
const DEFINITION = /function\s+([A-Za-z_$][\w$]*)|const\s+([A-Za-z_$][\w$]*)\s*=/g;
|
|
598
|
+
|
|
599
|
+
/** `src` with `ranges` ([start, end)) blanked, offsets kept: one pass however many there are. */
|
|
600
|
+
function blankRanges(src, ranges) {
|
|
601
|
+
if (!ranges.length) return src;
|
|
602
|
+
let out = "";
|
|
603
|
+
let at = 0;
|
|
604
|
+
for (const [start, end] of [...ranges].sort((a, b) => a[0] - b[0])) {
|
|
605
|
+
if (end <= at) continue;
|
|
606
|
+
const from = Math.max(start, at);
|
|
607
|
+
out += src.slice(at, from) + blank(src.slice(from, end));
|
|
608
|
+
at = end;
|
|
609
|
+
}
|
|
610
|
+
return out + src.slice(at);
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
/** Import statements: they name a helper, they do not read with it. */
|
|
614
|
+
const IMPORT_STATEMENT = /\bimport\s+(?:type\s+)?[\s\S]*?\bfrom\s*["'][^"'\n]+["']/g;
|
|
615
|
+
|
|
616
|
+
const blank = (s) => s.replace(/[^\n]/g, " ");
|
|
617
|
+
|
|
618
|
+
/**
|
|
619
|
+
* What a file reads by name: collections or entries (`getPagina("overOns")`), entries of one
|
|
620
|
+
* collection (`getEntry("pages", "funding")`: `entries`, as "pages/funding"), and the collections
|
|
621
|
+
* it reads whole (`getCollection("x")`, `getEntry("x", slug)`, `getEvenementen()`). Only calls of
|
|
622
|
+
* reading functions count: `invoer("organisatie")` names a form field. A helper's body is read for
|
|
623
|
+
* its callers, not for the file that defines it; a helper the file passes on as a value (not only
|
|
624
|
+
* calls) counts as read here too, as nobody can follow it further.
|
|
625
|
+
*/
|
|
626
|
+
function readsIn(src, reads, path = null) {
|
|
627
|
+
const code = blankRanges(src, reads.spans?.get(path) ?? []).replace(IMPORT_STATEMENT, blank);
|
|
628
|
+
const names = new Set();
|
|
629
|
+
const entries = new Set();
|
|
630
|
+
const whole = new Set();
|
|
631
|
+
const helped = new Set();
|
|
632
|
+
for (const m of code.matchAll(reads.byNameCall)) {
|
|
633
|
+
const [, fn, first, entry, other] = m;
|
|
634
|
+
if (reads.entryOf?.has(fn)) entries.add(`${first}/${reads.entryOf.get(fn)}`);
|
|
635
|
+
else if (entry) entries.add(`${first}/${entry}`);
|
|
636
|
+
else if (other && ASTRO_READS.includes(fn)) whole.add(first);
|
|
637
|
+
else if (fn === "getCollection") whole.add(first);
|
|
638
|
+
else names.add(first);
|
|
639
|
+
}
|
|
640
|
+
// The file's names counted once, and the helpers among them looked up: one pass per file, however
|
|
641
|
+
// many helpers the site has (1,000 pages each with its own took 1.6 s searched one by one).
|
|
642
|
+
const mentions = new Map();
|
|
643
|
+
for (const [name] of code.matchAll(IDENTIFIER)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
|
|
644
|
+
const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
|
|
645
|
+
for (const [name, n] of mentions) {
|
|
646
|
+
const read = reads.fixed.get(name);
|
|
647
|
+
if (!read || n - (defined.has(name) ? 1 : 0) <= 0) continue;
|
|
648
|
+
read.whole.forEach((c) => whole.add(c));
|
|
649
|
+
read.entries.forEach((e) => helped.add(e));
|
|
650
|
+
}
|
|
651
|
+
return { names, entries, whole, helped };
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* What the whole site reads, which no page changes: once per set of files, not once per page (20
|
|
656
|
+
* pages each reading a real site's 300 files ran out of an Edge Function's CPU, 26-10). Kept by the import
|
|
657
|
+
* graph, which a registry or a build makes once from the same files.
|
|
658
|
+
* @type {WeakMap<Map<string, Set<string>>, { collections: Record<string, unknown>, names: Map<string, Set<string>>, readsByFile: Map<string, ReturnType<typeof readsIn>>, isRoute: (f: string) => boolean }>}
|
|
659
|
+
*/
|
|
660
|
+
const siteReadsOf = new WeakMap();
|
|
661
|
+
|
|
662
|
+
function siteReads(paths, text, importers) {
|
|
663
|
+
const kept = siteReadsOf.get(importers);
|
|
664
|
+
if (kept) return kept;
|
|
665
|
+
let collections = {};
|
|
666
|
+
try {
|
|
667
|
+
collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
|
|
668
|
+
} catch {}
|
|
669
|
+
const reads = contentReads(paths, text);
|
|
670
|
+
const readsByFile = new Map();
|
|
671
|
+
for (const [p, src] of reads.code) if (!CONTENT_CONFIG.test(p)) readsByFile.set(p, readsIn(src, reads, p));
|
|
672
|
+
// How many files read each name, entry and collection: "read elsewhere" is the site's count
|
|
673
|
+
// less the page's own files', not a union of every other file made again for each page.
|
|
674
|
+
const counts = { names: new Map(), entries: new Map(), whole: new Map() };
|
|
675
|
+
const count = (kind, keys) => keys.forEach((k) => counts[kind].set(k, (counts[kind].get(k) ?? 0) + 1));
|
|
676
|
+
for (const r of readsByFile.values()) {
|
|
677
|
+
count("names", r.names);
|
|
678
|
+
count("entries", new Set([...r.entries, ...r.helped]));
|
|
679
|
+
count("whole", r.whole);
|
|
680
|
+
}
|
|
681
|
+
// The content files, each parsed once: by entry, by collection, by name, and the route files
|
|
682
|
+
// (`pad`, per page by contract: only ownedContent's last rule gives one to its page) by address.
|
|
683
|
+
const names = contentNames(paths, text);
|
|
684
|
+
const byEntry = new Map();
|
|
685
|
+
const byCollection = new Map();
|
|
686
|
+
const namesOf = new Map();
|
|
687
|
+
const routeOf = new Map();
|
|
688
|
+
const routes = new Set();
|
|
689
|
+
const push = (map, k, v) => (map.has(k) ? map.get(k).push(v) : map.set(k, [v]));
|
|
690
|
+
for (const f of paths) {
|
|
691
|
+
if (!CONTENT_JSON.test(f)) continue;
|
|
692
|
+
const c = collectionOfFile(f, collections);
|
|
693
|
+
push(byEntry, `${c}/${f.slice(f.lastIndexOf("/") + 1, -5)}`, f);
|
|
694
|
+
push(byCollection, c, f);
|
|
695
|
+
try {
|
|
696
|
+
const d = JSON.parse(text(f) ?? "null");
|
|
697
|
+
if (!isObject(d)) continue;
|
|
698
|
+
if (typeof (d.pad ?? d.path) === "string" && String(d.pad ?? d.path).startsWith("/")) routes.add(f);
|
|
699
|
+
for (const a of new Set([d.pad, d.path])) if (typeof a === "string") push(routeOf, a, f);
|
|
700
|
+
} catch {}
|
|
701
|
+
}
|
|
702
|
+
for (const [n, fs] of names) for (const f of fs) push(namesOf, f, n);
|
|
703
|
+
// Which JSON files each file imports, and what each file imports.
|
|
704
|
+
const jsonOf = new Map();
|
|
705
|
+
const imports = new Map();
|
|
706
|
+
for (const [target, by] of importers) {
|
|
707
|
+
for (const f of by) {
|
|
708
|
+
push(imports, f, target);
|
|
709
|
+
if (target.endsWith(".json")) push(jsonOf, f, target);
|
|
710
|
+
}
|
|
711
|
+
}
|
|
712
|
+
const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports, byName: reads.byName };
|
|
713
|
+
siteReadsOf.set(importers, site);
|
|
714
|
+
return site;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* Whether a page reads content itself: it imports astro:content, or a data module (.ts, .js) that
|
|
719
|
+
* does, however deep. Components are not followed: a layout that reads the page's SEO is the
|
|
720
|
+
* layout's, and the route file covers that.
|
|
721
|
+
*/
|
|
722
|
+
function readsContent(page, { paths, text }) {
|
|
723
|
+
const have = new Set(paths);
|
|
724
|
+
const seen = new Set();
|
|
725
|
+
const visit = (file) => {
|
|
726
|
+
if (seen.has(file)) return false;
|
|
727
|
+
seen.add(file);
|
|
728
|
+
const src = text(file) ?? "";
|
|
729
|
+
if (/from\s*["']astro:content["']/.test(src)) return true;
|
|
730
|
+
for (const m of src.matchAll(IMPORTS[0])) {
|
|
731
|
+
const target = resolveImport(file, m[1], have);
|
|
732
|
+
if (target && /\.(ts|mts|js|mjs)$/.test(target) && visit(target)) return true;
|
|
733
|
+
}
|
|
734
|
+
return false;
|
|
735
|
+
};
|
|
736
|
+
return visit(page.file);
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
/**
|
|
740
|
+
* The content files a page reads that no other code reads: JSON it imports, content it names by
|
|
741
|
+
* entry id or collection (`getEntry("pages", "funding")`, a helper's `getPagina("overOns")`), and
|
|
742
|
+
* the route file whose `pad`/`path` is its address. `shared` lists those another file also uses:
|
|
743
|
+
* drafting the page would leave that content live, so the draft is refused. `unregistered` lists
|
|
744
|
+
* the names the page reads content by that no content file goes by (a collection the site's
|
|
745
|
+
* generated `.schemas/collecties.json` does not list yet): what they read cannot be kept out
|
|
746
|
+
* either. `unknown` when the page reads content and none of it could be named: then nobody can
|
|
747
|
+
* say what to keep out.
|
|
748
|
+
*/
|
|
749
|
+
export function ownedContent(page, { paths, text, importers }) {
|
|
750
|
+
const own = new Set();
|
|
751
|
+
const shared = new Set();
|
|
752
|
+
const unregistered = new Set();
|
|
753
|
+
if (!page.file) return { files: [], shared: [], unregistered: [], unknown: false };
|
|
754
|
+
const site = siteReads(paths, text, importers);
|
|
755
|
+
const { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute } = site;
|
|
756
|
+
for (const target of site.jsonOf.get(page.file) ?? []) {
|
|
757
|
+
const others = [...importers.get(target)].filter((f) => f !== page.file && f !== page.router?.file);
|
|
758
|
+
(others.length ? shared : own).add(target);
|
|
759
|
+
}
|
|
760
|
+
const fileOf = (entry) => {
|
|
761
|
+
const [collection, id] = entry.split("/");
|
|
762
|
+
return byEntry.get(`${collection}/${id}`) ?? [];
|
|
763
|
+
};
|
|
764
|
+
// What the page's own code reads; what every other file reads is the site's count less that.
|
|
765
|
+
const mine = ownCode(page, importers, site.imports);
|
|
766
|
+
const named = new Set();
|
|
767
|
+
const entries = new Set();
|
|
768
|
+
const helped = new Set();
|
|
769
|
+
const wholeMine = new Set();
|
|
770
|
+
const minus = { names: new Map(), entries: new Map(), whole: new Map() };
|
|
771
|
+
const less = (kind, keys) => keys.forEach((k) => minus[kind].set(k, (minus[kind].get(k) ?? 0) + 1));
|
|
772
|
+
for (const p of mine) {
|
|
773
|
+
const r = readsByFile.get(p);
|
|
774
|
+
if (!r) continue;
|
|
775
|
+
r.names.forEach((n) => (names.has(n) ? named.add(n) : unregistered.add(n)));
|
|
776
|
+
r.entries.forEach((e) => entries.add(e));
|
|
777
|
+
r.helped.forEach((e) => helped.add(e));
|
|
778
|
+
r.whole.forEach((c) => wholeMine.add(c));
|
|
779
|
+
less("names", r.names);
|
|
780
|
+
less("entries", new Set([...r.entries, ...r.helped]));
|
|
781
|
+
less("whole", r.whole);
|
|
782
|
+
}
|
|
783
|
+
const has = (kind) => ({ has: (k) => (counts[kind].get(k) ?? 0) - (minus[kind].get(k) ?? 0) > 0 });
|
|
784
|
+
const elsewhere = { names: has("names"), entries: has("entries"), whole: has("whole") };
|
|
785
|
+
const readElsewhere = (f) => elsewhere.whole.has(collectionOfFile(f, collections)) || (namesOf.get(f) ?? []).some((n) => elsewhere.names.has(n));
|
|
786
|
+
// What the page names itself is its subject: read elsewhere too, the draft cannot hide it.
|
|
787
|
+
for (const n of named) for (const f of names.get(n)) if (!isRoute(f)) (elsewhere.names.has(n) || readElsewhere(f) ? shared : own).add(f);
|
|
788
|
+
for (const e of entries) for (const f of fileOf(e)) if (!isRoute(f)) (elsewhere.entries.has(e) || readElsewhere(f) ? shared : own).add(f);
|
|
789
|
+
// What comes through a helper or a whole collection is the page's only when nothing else reads it;
|
|
790
|
+
// otherwise it is the site's (menus, shared texts), live anyway, and no reason to refuse.
|
|
791
|
+
for (const e of helped) for (const f of fileOf(e)) if (!isRoute(f) && !elsewhere.entries.has(e) && !readElsewhere(f)) own.add(f);
|
|
792
|
+
for (const c of wholeMine) if (!elsewhere.whole.has(c)) for (const f of byCollection.get(c) ?? []) if (!isRoute(f) && !readElsewhere(f) && !elsewhere.entries.has(`${c}/${f.slice(f.lastIndexOf("/") + 1, -5)}`)) own.add(f);
|
|
793
|
+
const read = own.size > 0;
|
|
794
|
+
// The route file: per page by contract (read_settings), whatever reads the collection to find it.
|
|
795
|
+
for (const f of routeOf.get(page.path) ?? []) if (!shared.has(f)) own.add(f);
|
|
796
|
+
for (const f of shared) own.delete(f);
|
|
797
|
+
return {
|
|
798
|
+
files: [...own].sort(),
|
|
799
|
+
shared: [...shared].sort(),
|
|
800
|
+
unregistered: [...unregistered].sort(),
|
|
801
|
+
unknown: !read && !shared.size && !unregistered.size && readsContent(page, { paths, text }),
|
|
802
|
+
};
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// ── Can a draft be kept out? ───────────────────────────────────────────────
|
|
806
|
+
|
|
807
|
+
/**
|
|
808
|
+
* Packages that draw a page's text into images (share images, cards). A picture of a draft's title
|
|
809
|
+
* cannot be searched for, so a site that makes them cannot have drafts until the kit knows how
|
|
810
|
+
* they are made (docs/plan-pages.md, what the kit can prove).
|
|
811
|
+
*/
|
|
812
|
+
const MEDIA = ["satori", "@vercel/og", "astro-og-canvas", "og-img", "@resvg/resvg-js", "astro-opengraph-images"];
|
|
813
|
+
|
|
814
|
+
export function mediaGenerators(text) {
|
|
815
|
+
let pkg = null;
|
|
816
|
+
try {
|
|
817
|
+
pkg = JSON.parse(text("package.json") ?? "null");
|
|
818
|
+
} catch {}
|
|
819
|
+
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
820
|
+
return MEDIA.filter((m) => m in deps);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Packages that write a site's page list after the build, from its output (next-sitemap reads
|
|
825
|
+
* Next.js's manifests, where a draft's address still is): the kit cannot clean what they write.
|
|
826
|
+
*/
|
|
827
|
+
const LIST_TOOLS = { next: ["next-sitemap"] };
|
|
828
|
+
|
|
829
|
+
export function listTools(framework, text) {
|
|
830
|
+
const tools = LIST_TOOLS[String(framework)] ?? [];
|
|
831
|
+
if (!tools.length) return [];
|
|
832
|
+
let pkg = null;
|
|
833
|
+
try {
|
|
834
|
+
pkg = JSON.parse(text("package.json") ?? "null");
|
|
835
|
+
} catch {}
|
|
836
|
+
const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
|
|
837
|
+
return tools.filter((t) => t in deps);
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/**
|
|
841
|
+
* @typedef {{ ok: true, path: string, page: Page, content: string[] } | { ok: false, path: string, reason: string, detail?: string }} DraftCheck
|
|
842
|
+
*/
|
|
843
|
+
|
|
844
|
+
/**
|
|
845
|
+
* Whether `path` can be left out of a production build, and what goes with it. The same answer
|
|
846
|
+
* for the build plugin (which then does it) and for Unbase (which then allows it).
|
|
847
|
+
* @param {string} path
|
|
848
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>> }} input
|
|
849
|
+
* @returns {DraftCheck}
|
|
850
|
+
*/
|
|
851
|
+
export function draftCheck(path, { framework, paths, text, found, importers }) {
|
|
852
|
+
const at = normalisePath(path);
|
|
853
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), path: at, reason, ...(detail ? { detail } : {}) });
|
|
854
|
+
if (!DRAFTABLE.includes(String(framework))) return no("framework");
|
|
855
|
+
if (at === "/") return no("home");
|
|
856
|
+
const media = mediaGenerators(text);
|
|
857
|
+
if (media.length) return no("generated_media", media.join(", "));
|
|
858
|
+
const lists = listTools(framework, text);
|
|
859
|
+
if (lists.length) return no("page_list", lists.join(", "));
|
|
860
|
+
const discovered = found ?? discover({ framework, paths, text });
|
|
861
|
+
const page = discovered.pages.find((p) => p.path === at);
|
|
862
|
+
if (!page) {
|
|
863
|
+
const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
|
|
864
|
+
return template ? no("template", template.path) : no("missing");
|
|
865
|
+
}
|
|
866
|
+
if (page.kind === "template") return no("template", page.path);
|
|
867
|
+
if (page.reason) return no(page.reason);
|
|
868
|
+
if (!page.file) return no("unparsed");
|
|
869
|
+
if (framework === "next") {
|
|
870
|
+
const beside = segmentFiles(page.file, paths);
|
|
871
|
+
if (beside.length) return no("segment", beside.join(", "));
|
|
872
|
+
}
|
|
873
|
+
const graph = importers ?? importGraph(paths, text);
|
|
874
|
+
const by = [...(graph.get(page.file) ?? [])].filter((f) => f !== page.router?.file);
|
|
875
|
+
if (by.length) return no("shared", by.sort().join(", "));
|
|
876
|
+
const twice = discovered.pages.find((p) => p !== page && p.file === page.file);
|
|
877
|
+
if (twice) return no("shared", twice.path);
|
|
878
|
+
const content = ownedContent(page, { paths, text, importers: graph });
|
|
879
|
+
if (content.shared.length) return no("shared", content.shared.join(", "));
|
|
880
|
+
// Content read by a name no file goes by: the site's generated list of collections is behind its
|
|
881
|
+
// code (a collection added since it was made). Making it again fixes this; nothing else does.
|
|
882
|
+
if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
|
|
883
|
+
if (content.unknown) return no("content_unknown");
|
|
884
|
+
return { ok: true, path: at, page, content: content.files };
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
/**
|
|
888
|
+
* Next.js's special files beside an app router page (`app/x/page.tsx`): a layout, loading or
|
|
889
|
+
* not-found renders around the page, and an opengraph-image, icon, sitemap or route is a route of
|
|
890
|
+
* its own. What they say is not the page's to keep out, so the page cannot be a draft.
|
|
891
|
+
*/
|
|
892
|
+
const SEGMENT_FILE = /^(layout|template|loading|error|global-error|not-found|forbidden|unauthorized|default|route|sitemap|manifest|robots|(?:opengraph-image|twitter-image|icon|apple-icon)\d*)(\.alt)?\.[a-z]+$/;
|
|
893
|
+
|
|
894
|
+
export function segmentFiles(file, paths) {
|
|
895
|
+
if (!/(^|\/)page\.[a-z]+$/.test(file)) return [];
|
|
896
|
+
const dir = dirname(file);
|
|
897
|
+
return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
/** "/blog/:slug" or "/blog/[slug]" against "/blog/hello". */
|
|
901
|
+
function templateMatches(template, path) {
|
|
902
|
+
const t = template.split("/");
|
|
903
|
+
const p = path.split("/");
|
|
904
|
+
if (t.at(-1)?.startsWith("[...") || t.at(-1) === "*") return p.length >= t.length - 1 && t.slice(0, -1).every((s, i) => s === p[i] || /^(\[|:)/.test(s));
|
|
905
|
+
return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
/**
|
|
909
|
+
* Every draft in the page file, checked. `failed` holds the ones a production build cannot keep
|
|
910
|
+
* out; a build refuses while there is one.
|
|
911
|
+
*/
|
|
912
|
+
export function draftPlan({ framework, paths, text, pageFile }) {
|
|
913
|
+
if (!pageFile.ok) return { checks: [], failed: [{ ok: /** @type {const} */ (false), path: PAGE_FILE, reason: "invalid", detail: pageFile.error }] };
|
|
914
|
+
const found = discover({ framework, paths, text });
|
|
915
|
+
const importers = importGraph(paths, text);
|
|
916
|
+
const checks = draftPaths(pageFile).map((p) => draftCheck(p, { framework, paths, text, found, importers }));
|
|
917
|
+
return { checks, failed: checks.filter((c) => !c.ok), found, importers };
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// ── Links ──────────────────────────────────────────────────────────────────
|
|
921
|
+
|
|
922
|
+
/** What a visitor's page is made from; not READMEs, scripts or config. */
|
|
923
|
+
const APP_SOURCE = /^(src|app|pages|components|lib)\//;
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* The files that name `path` as a link: a quoted address (with or without a trailing slash, an
|
|
927
|
+
* anchor or a query) in code or content, other than the page's own files (`own`: its file and the
|
|
928
|
+
* content it owns) and its route's `path`. Built at runtime (`/${slug}`) is not found.
|
|
929
|
+
*/
|
|
930
|
+
export function linksTo(path, { paths, text, own = [] }) {
|
|
931
|
+
if (path === "/") return [];
|
|
932
|
+
const mine = new Set(own);
|
|
933
|
+
return [...(linkIndex(paths, text).get(path) ?? [])].filter((p) => !mine.has(p)).sort();
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Every quoted address in the app's source, to the files that name it: read once per set of files,
|
|
938
|
+
* not once per page. The same quotes as a search for each address would find: an opening quote, the
|
|
939
|
+
* address, an optional trailing slash, anchor or query, and the same quote (the closing one may open
|
|
940
|
+
* the next); not a route's own `path` or `pad`.
|
|
941
|
+
* @type {WeakMap<(path: string) => string | null, { paths: string[], index: Map<string, Set<string>> }>}
|
|
942
|
+
*/
|
|
943
|
+
const linkIndexOf = new WeakMap();
|
|
944
|
+
const QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
|
|
945
|
+
|
|
946
|
+
function linkIndex(paths, text) {
|
|
947
|
+
const kept = linkIndexOf.get(text);
|
|
948
|
+
if (kept?.paths === paths) return kept.index;
|
|
949
|
+
const index = new Map();
|
|
950
|
+
for (const p of paths) {
|
|
951
|
+
if (SKIP.test(p) || !APP_SOURCE.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
952
|
+
for (const [, , quoted] of (text(p) ?? "").matchAll(QUOTED_ADDRESS)) {
|
|
953
|
+
const bare = quoted.replace(/[#?][\s\S]*$/, "");
|
|
954
|
+
const address = bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare;
|
|
955
|
+
if (!index.has(address)) index.set(address, new Set());
|
|
956
|
+
index.get(address).add(p);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
linkIndexOf.set(text, { paths, index });
|
|
960
|
+
return index;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// ── Kit installed ──────────────────────────────────────────────────────────
|
|
964
|
+
|
|
965
|
+
const CONFIGS = {
|
|
966
|
+
astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
|
|
967
|
+
"vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
|
|
968
|
+
next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
|
|
969
|
+
};
|
|
970
|
+
|
|
971
|
+
/** The files kitInstalled reads: the package and the build's config, relative to the app. */
|
|
972
|
+
export const kitFiles = (framework) => ["package.json", ...(CONFIGS[String(framework)] ?? [])];
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* The kit is a dependency, by one of the names that bring it (KITS), and the build's config uses
|
|
976
|
+
* that one, comments not counted.
|
|
977
|
+
*/
|
|
978
|
+
export function kitInstalled({ framework, text }) {
|
|
979
|
+
let pkg = null;
|
|
980
|
+
try {
|
|
981
|
+
pkg = JSON.parse(text("package.json") ?? "null");
|
|
982
|
+
} catch {}
|
|
983
|
+
if (!pkg) return false;
|
|
984
|
+
const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
|
|
985
|
+
return (KITS[String(framework)] ?? []).some((name) => !!(pkg.dependencies?.[name] || pkg.devDependencies?.[name]) && configs.some((c) => c.includes(name)));
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// ── Leak check ─────────────────────────────────────────────────────────────
|
|
989
|
+
|
|
990
|
+
const normal = (s) => s.replace(/\s+/g, " ");
|
|
991
|
+
|
|
992
|
+
/**
|
|
993
|
+
* Sentences in a text: runs of words and plain punctuation, four words or more, most of them
|
|
994
|
+
* plain words (not a class list such as "flex items-center px-4"). Each as its longest piece of
|
|
995
|
+
* plain ASCII without quotes, which any build writes the same way.
|
|
996
|
+
*/
|
|
997
|
+
export function sentences(src) {
|
|
998
|
+
const out = [];
|
|
999
|
+
for (const m of normal(src).matchAll(/[\p{L}\p{N}][\p{L}\p{N} ,.!?;'’-]*/gu)) {
|
|
1000
|
+
const run = m[0].trim();
|
|
1001
|
+
const words = run.split(" ");
|
|
1002
|
+
if (run.length < 24 || words.length < 4) continue;
|
|
1003
|
+
// A word as people write it: no camelCase, no class name, no dotted name.
|
|
1004
|
+
const plain = words.filter((w) => /^(\p{Lu}?\p{Ll}+|\p{Lu}+)[,.!?;]?$/u.test(w)).length;
|
|
1005
|
+
if (plain / words.length < 0.75) continue;
|
|
1006
|
+
const piece = run
|
|
1007
|
+
.split(/['’]|[^\x20-\x7e]/)
|
|
1008
|
+
.map((s) => s.trim())
|
|
1009
|
+
.sort((a, b) => b.length - a.length)[0];
|
|
1010
|
+
if (piece && piece.length >= 20 && piece.split(" ").length >= 3) out.push(piece);
|
|
1011
|
+
}
|
|
1012
|
+
return out;
|
|
1013
|
+
}
|
|
1014
|
+
|
|
1015
|
+
/** The strings of a JSON file, depth first. */
|
|
1016
|
+
function jsonStrings(text) {
|
|
1017
|
+
const out = [];
|
|
1018
|
+
const walk = (v) => {
|
|
1019
|
+
if (typeof v === "string") out.push(v);
|
|
1020
|
+
else if (Array.isArray(v)) v.forEach(walk);
|
|
1021
|
+
else if (isObject(v)) Object.values(v).forEach(walk);
|
|
1022
|
+
};
|
|
1023
|
+
try {
|
|
1024
|
+
walk(JSON.parse(text));
|
|
1025
|
+
} catch {}
|
|
1026
|
+
return out;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/**
|
|
1030
|
+
* Text only a draft page has: the sentences of its file and of the content it owns that no other
|
|
1031
|
+
* file of the app holds. A production build that still contains one of them has leaked the page.
|
|
1032
|
+
* At most `max`, longest first.
|
|
1033
|
+
*/
|
|
1034
|
+
export function leakPrints(check, { paths, text, max = 24 }) {
|
|
1035
|
+
if (!check.ok) return [];
|
|
1036
|
+
const mine = new Set([check.page.file, ...check.content]);
|
|
1037
|
+
const candidates = new Set();
|
|
1038
|
+
// Comments never reach a visitor; only what the page says.
|
|
1039
|
+
const own = stripComments(text(check.page.file) ?? "").replace(/<!--[\s\S]*?-->/g, " ");
|
|
1040
|
+
for (const s of sentences(own)) candidates.add(s);
|
|
1041
|
+
for (const f of check.content) for (const v of jsonStrings(text(f) ?? "")) for (const s of sentences(v)) candidates.add(s);
|
|
1042
|
+
if (!candidates.size) return [];
|
|
1043
|
+
const others = paths
|
|
1044
|
+
.filter((p) => !mine.has(p) && !SKIP.test(p) && (CODE.test(p) || p.endsWith(".json")))
|
|
1045
|
+
.map((p) => normal(text(p) ?? ""))
|
|
1046
|
+
.join("\n");
|
|
1047
|
+
return [...candidates]
|
|
1048
|
+
.filter((s) => !others.includes(s))
|
|
1049
|
+
.sort((a, b) => b.length - a.length || (a < b ? -1 : 1))
|
|
1050
|
+
.slice(0, max);
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/** The prints a built file still holds. */
|
|
1054
|
+
export const leaksIn = (output, prints) => {
|
|
1055
|
+
const text = normal(output);
|
|
1056
|
+
return prints.filter((p) => text.includes(p));
|
|
1057
|
+
};
|
|
1058
|
+
|
|
1059
|
+
// ── Page lists in the output ───────────────────────────────────────────────
|
|
1060
|
+
|
|
1061
|
+
/** A sitemap without the draft addresses (any origin). */
|
|
1062
|
+
export function withoutInSitemap(xml, drafts) {
|
|
1063
|
+
return xml.replace(/<url>[\s\S]*?<\/url>/g, (block) => {
|
|
1064
|
+
const loc = block.match(/<loc>\s*([^<\s]+)\s*<\/loc>/)?.[1];
|
|
1065
|
+
if (!loc) return block;
|
|
1066
|
+
let path;
|
|
1067
|
+
try {
|
|
1068
|
+
path = normalisePath(new URL(loc, "https://x.invalid").pathname);
|
|
1069
|
+
} catch {
|
|
1070
|
+
return block;
|
|
1071
|
+
}
|
|
1072
|
+
return drafts.includes(path) ? "" : block;
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
/** comment-modus/pages.json without the draft addresses. */
|
|
1077
|
+
export function withoutInPageList(json, drafts) {
|
|
1078
|
+
const list = JSON.parse(json);
|
|
1079
|
+
return Array.isArray(list) ? JSON.stringify(list.filter((p) => !drafts.includes(normalisePath(p?.path ?? "")))) : json;
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
/** comment-modus/content-map.json without the files a draft owns, wherever a file is a key. */
|
|
1083
|
+
export function withoutInContentMap(json, files) {
|
|
1084
|
+
const map = JSON.parse(json);
|
|
1085
|
+
if (!isObject(map)) return json;
|
|
1086
|
+
const gone = new Set(files);
|
|
1087
|
+
for (const [key, value] of Object.entries(map)) {
|
|
1088
|
+
if (isObject(value)) for (const f of Object.keys(value)) if (gone.has(f)) delete value[f];
|
|
1089
|
+
if (Array.isArray(value)) map[key] = value.filter((v) => !(typeof v === "string" && gone.has(v)));
|
|
1090
|
+
}
|
|
1091
|
+
return JSON.stringify(map);
|
|
1092
|
+
}
|
|
1093
|
+
|
|
1094
|
+
// ── Page actions: rename, duplicate, delete (docs/plan-page-actions.md) ────
|
|
1095
|
+
//
|
|
1096
|
+
// One rule for what each action changes, from the code at one commit: the same files always give
|
|
1097
|
+
// the same writes, so Unbase's editor (unbase-projects page_action), the CLI (`unbase page …`) and
|
|
1098
|
+
// a developer's own agent make byte-identical changes. What it cannot do by rule, it refuses with a
|
|
1099
|
+
// reason; the editor says why, and offers the Operator where it can (`content_bound`).
|
|
1100
|
+
|
|
1101
|
+
/** Frameworks the actions know how a page is made in. */
|
|
1102
|
+
export const PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
|
|
1103
|
+
|
|
1104
|
+
/** Since which version each package applies the page file's redirects at build. */
|
|
1105
|
+
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" };
|
|
1106
|
+
|
|
1107
|
+
/** The lowest version a dependency's range allows ("^0.4.0" → [0, 4, 0]); null when it does not say (a file, a tag, "*"). */
|
|
1108
|
+
export function lowestVersion(spec) {
|
|
1109
|
+
if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
|
|
1110
|
+
const m = spec.trim().replace(/^[\^~>=v\s]+/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
|
|
1111
|
+
return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
const atLeast = (have, want) => {
|
|
1115
|
+
for (let i = 0; i < 3; i++) if (have[i] !== want[i]) return have[i] > want[i];
|
|
1116
|
+
return true;
|
|
1117
|
+
};
|
|
1118
|
+
|
|
1119
|
+
/**
|
|
1120
|
+
* Whether the site's build applies the page file's redirects: the kit is installed (kitInstalled)
|
|
1121
|
+
* by a package whose range in package.json starts at or after the version that applies them. A
|
|
1122
|
+
* range that does not say (a file, a tag) counts as not: a moved live page must never lose its
|
|
1123
|
+
* old address silently.
|
|
1124
|
+
*/
|
|
1125
|
+
export function kitRedirects({ framework, text }) {
|
|
1126
|
+
if (!kitInstalled({ framework, text })) return false;
|
|
1127
|
+
let pkg = null;
|
|
1128
|
+
try {
|
|
1129
|
+
pkg = JSON.parse(text("package.json") ?? "null");
|
|
1130
|
+
} catch {}
|
|
1131
|
+
const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
|
|
1132
|
+
return (KITS[String(framework)] ?? []).some((name) => {
|
|
1133
|
+
const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
|
|
1134
|
+
const since = REDIRECTS_SINCE[name];
|
|
1135
|
+
const have = lowestVersion(spec);
|
|
1136
|
+
return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/** "Pricing plans" → "pricing-plans"; "Één agenda" → "een-agenda". */
|
|
1141
|
+
export function slugOf(name) {
|
|
1142
|
+
return String(name)
|
|
1143
|
+
.normalize("NFKD")
|
|
1144
|
+
.replace(/[̀-ͯ]/g, "")
|
|
1145
|
+
.toLowerCase()
|
|
1146
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
1147
|
+
.replace(/^-+|-+$/g, "")
|
|
1148
|
+
.slice(0, 80);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
|
|
1152
|
+
|
|
1153
|
+
/** Whether `p` is an address a page can be given: plain segments, no template, not too long. */
|
|
1154
|
+
export function validAddress(p) {
|
|
1155
|
+
const at = normalisePath(p);
|
|
1156
|
+
if (at.length > 200) return false;
|
|
1157
|
+
if (at === "/") return true;
|
|
1158
|
+
return at
|
|
1159
|
+
.slice(1)
|
|
1160
|
+
.split("/")
|
|
1161
|
+
.every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
const under = (path, at) => (at === "/" ? path !== "/" : path.startsWith(`${at}/`));
|
|
1165
|
+
const within = (path, at) => path === at || under(path, at);
|
|
1166
|
+
/** `path` with its `from` part replaced by `to`: "/a/b" from "/a" to "/c" → "/c/b". */
|
|
1167
|
+
const moveAddress = (path, from, to) => (path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`));
|
|
1168
|
+
const parentOf = (p) => (p === "/" ? null : normalisePath(p.slice(0, p.lastIndexOf("/"))));
|
|
1169
|
+
const lastOf = (p) => p.slice(p.lastIndexOf("/") + 1);
|
|
1170
|
+
|
|
1171
|
+
/** 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. */
|
|
1172
|
+
export function siteRedirects({ framework, text }) {
|
|
1173
|
+
const out = new Set();
|
|
1174
|
+
try {
|
|
1175
|
+
const v = JSON.parse(text("vercel.json") ?? "null");
|
|
1176
|
+
for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
|
|
1177
|
+
} catch {}
|
|
1178
|
+
for (const c of CONFIGS[String(framework)] ?? []) {
|
|
1179
|
+
const src = stripComments(text(c) ?? "");
|
|
1180
|
+
if (framework === "astro") {
|
|
1181
|
+
const at = src.search(/\bredirects\s*:\s*\{/);
|
|
1182
|
+
if (at < 0) continue;
|
|
1183
|
+
const body = braced(src, src.indexOf("{", at)) ?? "";
|
|
1184
|
+
for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
|
|
1185
|
+
} else if (framework === "next") {
|
|
1186
|
+
for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
return out;
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/** Whether a redirect source (a page file's or the site's) takes `path`. */
|
|
1193
|
+
function sends(source, path) {
|
|
1194
|
+
if (REST.test(source)) {
|
|
1195
|
+
const base = normalisePath(source.replace(REST, ""));
|
|
1196
|
+
return within(path, base);
|
|
1197
|
+
}
|
|
1198
|
+
return source === path || matchesPattern(source, path);
|
|
1199
|
+
}
|
|
1200
|
+
|
|
1201
|
+
function matchesPattern(source, path) {
|
|
1202
|
+
if (!/\[|:/.test(source)) return false;
|
|
1203
|
+
const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => (i % 2 ? (part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+") : escape(part))).join("")}$`);
|
|
1204
|
+
return re.test(path);
|
|
1205
|
+
}
|
|
1206
|
+
|
|
1207
|
+
// ── Writing the page file ──
|
|
1208
|
+
|
|
1209
|
+
/**
|
|
1210
|
+
* The page file after `change`, as text (two spaces, a newline at the end, keys in the order they
|
|
1211
|
+
* were). Null when there is nothing to write: no file before and nothing in it after.
|
|
1212
|
+
*/
|
|
1213
|
+
function changedPageFile(before, change) {
|
|
1214
|
+
let data = {};
|
|
1215
|
+
try {
|
|
1216
|
+
data = before == null ? {} : (JSON.parse(before) ?? {});
|
|
1217
|
+
} catch {
|
|
1218
|
+
data = {};
|
|
1219
|
+
}
|
|
1220
|
+
if (!isObject(data)) data = {};
|
|
1221
|
+
if (!isObject(data.pages)) data.pages = {};
|
|
1222
|
+
const redirects = isObject(data.redirects) ? { ...data.redirects } : {};
|
|
1223
|
+
change(data.pages, redirects);
|
|
1224
|
+
for (const [k, v] of Object.entries(data.pages)) if (isObject(v) && !Object.keys(v).length) delete data.pages[k];
|
|
1225
|
+
if (Object.keys(redirects).length) data.redirects = redirects;
|
|
1226
|
+
else delete data.redirects;
|
|
1227
|
+
const empty = !Object.keys(data.pages).length && !data.redirects && Object.keys(data).length === 1;
|
|
1228
|
+
if (before == null && empty) return null;
|
|
1229
|
+
const after = `${JSON.stringify(data, null, 2)}\n`;
|
|
1230
|
+
return after === before ? null : after;
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/** The redirects with every one that leads into `from` (or under it) led to `to` instead, and none left that takes `to` itself. */
|
|
1234
|
+
function repoint(redirects, from, to) {
|
|
1235
|
+
for (const [source, dest] of Object.entries(redirects)) {
|
|
1236
|
+
const rest = REST.test(dest);
|
|
1237
|
+
const base = rest ? normalisePath(dest.replace(REST, "")) : dest;
|
|
1238
|
+
if (within(base, from)) redirects[source] = rest ? `${moveAddress(base, from, to)}${dest.slice(dest.lastIndexOf("/"))}` : moveAddress(base, from, to);
|
|
1239
|
+
}
|
|
1240
|
+
for (const [source, dest] of Object.entries(redirects)) {
|
|
1241
|
+
const base = REST.test(source) ? normalisePath(source.replace(REST, "")) : source;
|
|
1242
|
+
if (to && within(to, base) && sends(source, to)) delete redirects[source];
|
|
1243
|
+
else if (source === dest) delete redirects[source];
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
// ── Moving code ──
|
|
1248
|
+
|
|
1249
|
+
/** Import specifiers, with where each sits: `from "x"`, `import "x"`, `import("x")`, `require("x")`. */
|
|
1250
|
+
const SPECIFIER = /((?:\bfrom|\bimport|\brequire)\s*\(?\s*)(["'])([^"'\n]+)\2/g;
|
|
1251
|
+
/** An Astro Markdown page's layout. */
|
|
1252
|
+
const MD_LAYOUT = /^(layout:\s*)(["']?)([^"'\n]+?)\2\s*$/m;
|
|
1253
|
+
|
|
1254
|
+
const relativeSpec = (fromFile, target) => {
|
|
1255
|
+
const from = dirname(fromFile).split("/").filter(Boolean);
|
|
1256
|
+
const to = target.split("/");
|
|
1257
|
+
let i = 0;
|
|
1258
|
+
while (i < from.length && i < to.length - 1 && from[i] === to[i]) i++;
|
|
1259
|
+
const up = from.length - i;
|
|
1260
|
+
const rest = to.slice(i).join("/");
|
|
1261
|
+
return up ? `${"../".repeat(up)}${rest}` : `./${rest}`;
|
|
1262
|
+
};
|
|
1263
|
+
|
|
1264
|
+
/**
|
|
1265
|
+
* The specifier `fromFile` now needs for `target`, in the style the old one had: an alias stays
|
|
1266
|
+
* an alias, a specifier with an extension keeps it, one to a folder's index names the folder.
|
|
1267
|
+
*/
|
|
1268
|
+
function specFor(fromFile, target, old, oldTarget) {
|
|
1269
|
+
const index = /\/index\.[a-z]+$/.test(oldTarget) && !/\/index(\.[a-z]+)?$/.test(old);
|
|
1270
|
+
const ext = /\.[a-z]+$/.test(old.split("/").pop() ?? "") && old.endsWith(oldTarget.slice(oldTarget.lastIndexOf(".")));
|
|
1271
|
+
let t = target;
|
|
1272
|
+
if (index) t = dirname(target);
|
|
1273
|
+
else if (!ext) t = target.replace(/\.[a-z]+$/, "");
|
|
1274
|
+
if (old.startsWith("@/") && t.startsWith("src/")) return `@/${t.slice(4)}`;
|
|
1275
|
+
return relativeSpec(fromFile, t);
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
/**
|
|
1279
|
+
* `src` of a file now at `now` (before at `was`) with each specifier pointed where its target is
|
|
1280
|
+
* after `moves` (old path → new path). Unchanged when nothing it imports moved and it did not.
|
|
1281
|
+
*/
|
|
1282
|
+
function respecified(src, was, now, moves, have) {
|
|
1283
|
+
const fix = (spec) => {
|
|
1284
|
+
const target = resolveImport(was, spec, have);
|
|
1285
|
+
if (!target) return spec;
|
|
1286
|
+
const next = moves.get(target) ?? target;
|
|
1287
|
+
if (next === target && was === now) return spec;
|
|
1288
|
+
if (!spec.startsWith(".") && next === target) return spec;
|
|
1289
|
+
return specFor(now, next, spec, target);
|
|
1290
|
+
};
|
|
1291
|
+
let out = src.replace(SPECIFIER, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
|
|
1292
|
+
if (/\.mdx?$/.test(now)) out = out.replace(MD_LAYOUT, (m, lead, q, spec) => `${lead}${q}${fix(spec)}${q}`);
|
|
1293
|
+
return out;
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
// ── Links ──
|
|
1297
|
+
|
|
1298
|
+
/** Quoted addresses in code and content, and Markdown links: what a rename rewrites. */
|
|
1299
|
+
const QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
|
|
1300
|
+
const MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
|
|
1301
|
+
|
|
1302
|
+
/** `src` with every address in `from` (or under it) moved to `to`; anchors, queries and a trailing slash kept. */
|
|
1303
|
+
function relinked(src, from, to, markdown) {
|
|
1304
|
+
const swap = (address) => {
|
|
1305
|
+
const bare = address.replace(/[#?][\s\S]*$/, "");
|
|
1306
|
+
const tail = address.slice(bare.length);
|
|
1307
|
+
const slash = bare.length > 1 && bare.endsWith("/") ? "/" : "";
|
|
1308
|
+
const clean = slash ? bare.slice(0, -1) : bare;
|
|
1309
|
+
if (clean === from) return `${to}${to === "/" ? "" : slash}${tail}`;
|
|
1310
|
+
if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
|
|
1311
|
+
return address;
|
|
1312
|
+
};
|
|
1313
|
+
let out = src.replace(QUOTED, (m, q, address) => `${q}${swap(address)}`);
|
|
1314
|
+
if (markdown) out = out.replace(MD_LINK, (m, a, address, b) => `${a}${swap(address)}${b}`);
|
|
1315
|
+
return out;
|
|
1316
|
+
}
|
|
1317
|
+
|
|
1318
|
+
/** `src` with the inside of its string literals blanked, offsets kept: names in code, not in text. */
|
|
1319
|
+
function blankStrings(src) {
|
|
1320
|
+
let out = "";
|
|
1321
|
+
let i = 0;
|
|
1322
|
+
while (i < src.length) {
|
|
1323
|
+
const c = src[i];
|
|
1324
|
+
if (c === '"' || c === "'" || c === "`") {
|
|
1325
|
+
const j = stringEnd(src, i);
|
|
1326
|
+
out += c + blank(src.slice(i + 1, j - 1)) + (j - 1 > i ? src[j - 1] : "");
|
|
1327
|
+
i = j;
|
|
1328
|
+
continue;
|
|
1329
|
+
}
|
|
1330
|
+
out += c;
|
|
1331
|
+
i++;
|
|
1332
|
+
}
|
|
1333
|
+
return out;
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// ── Per framework: where a page's files are ──
|
|
1337
|
+
|
|
1338
|
+
/** The folder the pages router or Astro keeps routes in, from the page's file. */
|
|
1339
|
+
const routesBase = (file) => (file.startsWith("src/pages/") ? "src/pages" : file.startsWith("pages/") ? "pages" : file.startsWith("src/app/") ? "src/app" : file.startsWith("app/") ? "app" : null);
|
|
1340
|
+
|
|
1341
|
+
/**
|
|
1342
|
+
* Where a page at `to` would have its file, in the form the page at `page` has (a file, a folder's
|
|
1343
|
+
* index, a Next.js app router folder), and the folder whose files go along with it.
|
|
1344
|
+
*/
|
|
1345
|
+
function destination(page, to, discovered) {
|
|
1346
|
+
const base = routesBase(page.file);
|
|
1347
|
+
if (!base) return null;
|
|
1348
|
+
const ext = page.file.slice(page.file.lastIndexOf("."));
|
|
1349
|
+
if (base.endsWith("app")) {
|
|
1350
|
+
// app/(group)/x/page.tsx: the folder is the page. Its new folder sits where its new parent's does.
|
|
1351
|
+
const dir = dirname(page.file);
|
|
1352
|
+
const parent = parentOf(to);
|
|
1353
|
+
const sameParent = parent === parentOf(page.path);
|
|
1354
|
+
const parentPage = parent === null ? null : discovered.pages.find((p) => p.path === parent && p.file && routesBase(p.file) === base);
|
|
1355
|
+
const parentDir = sameParent ? dirname(dir) : parentPage ? dirname(parentPage.file) : `${base}${parent === "/" ? "" : parent}`;
|
|
1356
|
+
const newDir = to === "/" ? base : `${parentDir}/${lastOf(to)}`;
|
|
1357
|
+
return { file: `${newDir}/${page.file.slice(dir.length + 1)}`, dir, newDir, folder: true };
|
|
1358
|
+
}
|
|
1359
|
+
const index = /(^|\/)index\.[a-z]+$/.test(page.file);
|
|
1360
|
+
const oldDir = `${base}${page.path === "/" ? "" : page.path}`;
|
|
1361
|
+
const newDir = `${base}${to === "/" ? "" : to}`;
|
|
1362
|
+
return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
|
|
1363
|
+
}
|
|
1364
|
+
|
|
1365
|
+
/** 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. */
|
|
1366
|
+
function appSegmentOwn(dir, paths) {
|
|
1367
|
+
return paths.filter((p) => {
|
|
1368
|
+
if (dirname(p) === dir) return true;
|
|
1369
|
+
if (!p.startsWith(`${dir}/`)) return false;
|
|
1370
|
+
const first = p.slice(dir.length + 1).split("/")[0];
|
|
1371
|
+
return first.startsWith("_");
|
|
1372
|
+
});
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
/** A component name for a new route's file: "/pricing-copy" → "PricingCopy". */
|
|
1376
|
+
const componentName = (address) =>
|
|
1377
|
+
(lastOf(address) || "Home")
|
|
1378
|
+
.split(/[^A-Za-z0-9]+/)
|
|
1379
|
+
.filter(Boolean)
|
|
1380
|
+
.map((w) => w[0].toUpperCase() + w.slice(1))
|
|
1381
|
+
.join("")
|
|
1382
|
+
.replace(/^(\d)/, "Page$1") || "Page";
|
|
1383
|
+
|
|
1384
|
+
/** The route element's `path` attribute's value and where it sits in `src`, or null. */
|
|
1385
|
+
function routePathAttr(src, router) {
|
|
1386
|
+
const tag = src.slice(router.start, router.end);
|
|
1387
|
+
const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
|
|
1388
|
+
if (!m) return null;
|
|
1389
|
+
const value = m.slice(2).find((v) => v !== undefined) ?? "";
|
|
1390
|
+
const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
|
|
1391
|
+
return { value, start: valueAt, end: valueAt + value.length };
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// ── The plan ──
|
|
1395
|
+
|
|
1396
|
+
/**
|
|
1397
|
+
* @typedef {{ path: string, content?: string, from?: string, deleted?: true }} PageWrite
|
|
1398
|
+
* `content`: the file's new text; `from`: the file whose bytes it gets (a move or copy keeps
|
|
1399
|
+
* them as they are, whatever kind of file); `deleted`: it goes.
|
|
1400
|
+
* @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 }} PagePlan
|
|
1401
|
+
* @typedef {{ ok: false, reason: string, detail?: string }} PageRefusal
|
|
1402
|
+
*/
|
|
1403
|
+
|
|
1404
|
+
/**
|
|
1405
|
+
* What one action does to a site's code, or why it cannot: `rename` (to a new address, with a new
|
|
1406
|
+
* name), `duplicate` (a copy at `to`, by default the first free `<address>-copy`) or `delete`
|
|
1407
|
+
* (visitors to the old address sent to `redirect`, by default the page above it; null: Not
|
|
1408
|
+
* Found). `live` says whether the page is on Live now: only then does a rename or delete leave a
|
|
1409
|
+
* redirect, and only then does it need the kit to apply one. `drafts`: a copy starts as a draft.
|
|
1410
|
+
*
|
|
1411
|
+
* `paths` are every file of the app (a move takes files whose text was not read along);
|
|
1412
|
+
* `text` gives the code and content files' text.
|
|
1413
|
+
* @param {{ action: "rename" | "duplicate" | "delete", path: string, to?: string, name?: string | null, redirect?: string | null, live?: boolean, drafts?: boolean }} request
|
|
1414
|
+
* @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>> }} input
|
|
1415
|
+
* @returns {PagePlan | PageRefusal}
|
|
1416
|
+
*/
|
|
1417
|
+
export function planPage(request, input) {
|
|
1418
|
+
const { framework, text } = input;
|
|
1419
|
+
const paths = input.paths.filter((p) => !SKIP.test(p));
|
|
1420
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1421
|
+
const action = request.action;
|
|
1422
|
+
if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
|
|
1423
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
|
|
1424
|
+
const at = normalisePath(request.path);
|
|
1425
|
+
const discovered = input.found ?? discover({ framework, paths, text });
|
|
1426
|
+
const page = discovered.pages.find((p) => p.path === at);
|
|
1427
|
+
if (!page) {
|
|
1428
|
+
const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
|
|
1429
|
+
return template ? no("template", template.path) : no("missing");
|
|
1430
|
+
}
|
|
1431
|
+
if (page.kind === "template") return no("template", page.path);
|
|
1432
|
+
if (!page.file || page.reason === "unparsed") return no("unparsed");
|
|
1433
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1434
|
+
if (!pageFile.ok) return no("invalid", pageFile.error);
|
|
1435
|
+
const below = discovered.pages.filter((p) => under(p.path, at));
|
|
1436
|
+
const have = new Set(paths);
|
|
1437
|
+
const importers = input.importers ?? importGraph(paths, text);
|
|
1438
|
+
const live = request.live === true;
|
|
1439
|
+
const redirects = live ? kitRedirects({ framework, text }) : false;
|
|
1440
|
+
const ownRedirects = siteRedirects({ framework, text });
|
|
1441
|
+
const taken = (p) => discovered.pages.some((q) => q.path === p) || [...ownRedirects].some((s) => sends(s, p));
|
|
1442
|
+
/** @type {Map<string, PageWrite>} */
|
|
1443
|
+
const writes = new Map();
|
|
1444
|
+
const write = (w) => writes.set(w.path, w);
|
|
1445
|
+
const current = (p) => (writes.has(p) ? (writes.get(p).content ?? (writes.get(p).from ? text(writes.get(p).from) : null)) : text(p));
|
|
1446
|
+
const links = new Set();
|
|
1447
|
+
const unlinked = new Set();
|
|
1448
|
+
const moves = [];
|
|
1449
|
+
/** Files that moved, old path → new path: drafts waiting on them follow. */
|
|
1450
|
+
const renamed = [];
|
|
1451
|
+
let to = null;
|
|
1452
|
+
/** @type {Record<string, string | null>} */
|
|
1453
|
+
const redirectChanges = {};
|
|
1454
|
+
const collections = (() => {
|
|
1455
|
+
try {
|
|
1456
|
+
return JSON.parse(text(COLLECTIONS) ?? "null");
|
|
1457
|
+
} catch {
|
|
1458
|
+
return null;
|
|
1459
|
+
}
|
|
1460
|
+
})();
|
|
1461
|
+
const collectionsAfter = isObject(collections) ? { ...collections } : null;
|
|
1462
|
+
|
|
1463
|
+
if (action === "rename") {
|
|
1464
|
+
if (at === "/") return no("home");
|
|
1465
|
+
const target = request.to == null ? at : normalisePath(request.to);
|
|
1466
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1467
|
+
if (target !== at && within(target, at)) return no("address", target);
|
|
1468
|
+
if (target !== at && taken(target)) return no("taken", target);
|
|
1469
|
+
if (target !== at && live && !redirects) return no("no_redirects");
|
|
1470
|
+
to = target;
|
|
1471
|
+
/** @type {Map<string, string>} old path → new path, of the files that move */
|
|
1472
|
+
const moved = new Map();
|
|
1473
|
+
if (target !== at) {
|
|
1474
|
+
if (framework === "vite-react") {
|
|
1475
|
+
// The route's own path, when it is relative to a parent route: its last part only.
|
|
1476
|
+
const src = text(page.router.file) ?? "";
|
|
1477
|
+
const attr = routePathAttr(src, page.router);
|
|
1478
|
+
if (!attr) return no("unparsed", "index route");
|
|
1479
|
+
if (!attr.value.startsWith("/")) {
|
|
1480
|
+
const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
|
|
1481
|
+
if (parent !== "/" && !under(target, parent)) return no("unparsed", "a route inside another route keeps its parent");
|
|
1482
|
+
const rel = parent === "/" ? target.slice(1) : target.slice(parent.length + 1);
|
|
1483
|
+
write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
|
|
1484
|
+
}
|
|
1485
|
+
} else {
|
|
1486
|
+
const dest = destination(page, target, discovered);
|
|
1487
|
+
if (!dest) return no("unparsed");
|
|
1488
|
+
// Its file, and everything in its folder: the pages under it, and what they keep there.
|
|
1489
|
+
for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
|
|
1490
|
+
moved.set(page.file, dest.file);
|
|
1491
|
+
for (const [from, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
|
|
1492
|
+
for (const [from, next] of moved) {
|
|
1493
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
1494
|
+
const content = src == null ? null : respecified(src, from, next, moved, have);
|
|
1495
|
+
write(content == null || content === src ? { path: next, from } : { path: next, content });
|
|
1496
|
+
write({ path: from, deleted: true });
|
|
1497
|
+
}
|
|
1498
|
+
// Files that import a moved one.
|
|
1499
|
+
for (const p of paths) {
|
|
1500
|
+
if (moved.has(p) || !CODE.test(p)) continue;
|
|
1501
|
+
const src = text(p);
|
|
1502
|
+
if (!src) continue;
|
|
1503
|
+
const out = respecified(src, p, p, moved, have);
|
|
1504
|
+
if (out !== src) write({ path: p, content: out });
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
// Every link to it, or under it, in code and content (route files' own `pad` too).
|
|
1508
|
+
for (const p of paths) {
|
|
1509
|
+
// Not the content config: it defines schemas, and an address there is an example in a message.
|
|
1510
|
+
if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
|
|
1511
|
+
const where = moved.get(p) ?? p;
|
|
1512
|
+
const src = current(where);
|
|
1513
|
+
if (!src) continue;
|
|
1514
|
+
const out = relinked(src, at, target, /\.mdx?$/.test(p));
|
|
1515
|
+
if (out === src) continue;
|
|
1516
|
+
write({ path: where, content: out });
|
|
1517
|
+
if (!moved.has(p)) links.add(where);
|
|
1518
|
+
}
|
|
1519
|
+
moves.push({ from: at, to: target }, ...below.map((p) => ({ from: p.path, to: moveAddress(p.path, at, target) })));
|
|
1520
|
+
for (const [from, next] of moved) renamed.push({ from, to: next });
|
|
1521
|
+
}
|
|
1522
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1523
|
+
if (target !== at) {
|
|
1524
|
+
for (const key of Object.keys(pages)) {
|
|
1525
|
+
if (!within(key, at)) continue;
|
|
1526
|
+
pages[moveAddress(key, at, target)] = { ...pages[key], ...(pages[moveAddress(key, at, target)] ?? {}) };
|
|
1527
|
+
delete pages[key];
|
|
1528
|
+
}
|
|
1529
|
+
const before = { ...sendsOn };
|
|
1530
|
+
if (live) {
|
|
1531
|
+
sendsOn[at] = target;
|
|
1532
|
+
if (below.length) sendsOn[`${at}/[...path]`] = `${target}/[...path]`;
|
|
1533
|
+
}
|
|
1534
|
+
repoint(sendsOn, at, target);
|
|
1535
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1536
|
+
}
|
|
1537
|
+
if (request.name !== undefined) {
|
|
1538
|
+
const entry = pages[target] ?? {};
|
|
1539
|
+
if (request.name) entry.name = String(request.name).trim().slice(0, 120);
|
|
1540
|
+
else delete entry.name;
|
|
1541
|
+
pages[target] = entry;
|
|
1542
|
+
}
|
|
1543
|
+
});
|
|
1544
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1545
|
+
if (!writes.size) return no("same");
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
if (action === "duplicate") {
|
|
1549
|
+
if (framework === "vite-react" && page.reason === "nested") return no("nested");
|
|
1550
|
+
let target;
|
|
1551
|
+
if (request.to != null) {
|
|
1552
|
+
target = normalisePath(request.to);
|
|
1553
|
+
if (!validAddress(target) || target === "/") return no("address", target);
|
|
1554
|
+
if (taken(target)) return no("taken", target);
|
|
1555
|
+
} else {
|
|
1556
|
+
const base = at === "/" ? "/home-copy" : `${at}-copy`;
|
|
1557
|
+
target = base;
|
|
1558
|
+
for (let n = 2; taken(target) && n < 100; n++) target = `${base}-${n}`;
|
|
1559
|
+
}
|
|
1560
|
+
to = target;
|
|
1561
|
+
const content = ownedContent(page, { paths, text, importers });
|
|
1562
|
+
if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
|
|
1563
|
+
const own = new Set(content.files);
|
|
1564
|
+
const reads = siteReads(paths, text, importers);
|
|
1565
|
+
const ownCodeFiles = ownCode(page, importers, reads.imports);
|
|
1566
|
+
// How the page reads each content file it owns, and whether its copy can read a copy instead.
|
|
1567
|
+
const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set(), whole: new Set(), helped: new Set() };
|
|
1568
|
+
const imported = new Set(reads.jsonOf.get(page.file) ?? []);
|
|
1569
|
+
/** @type {Map<string, string>} content file → its copy */
|
|
1570
|
+
const copies = new Map();
|
|
1571
|
+
/** @type {{ kind: "name" | "entry", name: string, collection?: string, next: string }[]} */
|
|
1572
|
+
const rebinds = [];
|
|
1573
|
+
const newId = slugOf(lastOf(target)) || "copy";
|
|
1574
|
+
const freeFile = (dir, base, ext) => {
|
|
1575
|
+
let f = `${dir}/${base}${ext}`;
|
|
1576
|
+
for (let n = 2; (have.has(f) || [...writes.keys()].includes(f) || [...copies.values()].includes(f)) && n < 100; n++) f = `${dir}/${base}-${n}${ext}`;
|
|
1577
|
+
return f;
|
|
1578
|
+
};
|
|
1579
|
+
for (const f of own) {
|
|
1580
|
+
if (reads.isRoute(f)) continue;
|
|
1581
|
+
if (imported.has(f)) {
|
|
1582
|
+
copies.set(f, freeFile(dirname(f), `${f.slice(f.lastIndexOf("/") + 1, -5)}-${newId}`, ".json"));
|
|
1583
|
+
continue;
|
|
1584
|
+
}
|
|
1585
|
+
const collection = collectionOfFile(f, reads.collections);
|
|
1586
|
+
const id = f.slice(f.lastIndexOf("/") + 1, -5);
|
|
1587
|
+
// A collection several files make (a folder): a copy beside it is one more entry.
|
|
1588
|
+
const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
|
|
1589
|
+
const entry = `${collection}/${id}`;
|
|
1590
|
+
if (pageReads.entries.has(entry) && folder) {
|
|
1591
|
+
const next = freeFile(dirname(f), newId, ".json");
|
|
1592
|
+
copies.set(f, next);
|
|
1593
|
+
rebinds.push({ kind: "entry", name: id, collection, next: next.slice(next.lastIndexOf("/") + 1, -5) });
|
|
1594
|
+
} else if (pageReads.names.has(id) && id !== collection && folder) {
|
|
1595
|
+
const next = freeFile(dirname(f), newId, ".json");
|
|
1596
|
+
copies.set(f, next);
|
|
1597
|
+
rebinds.push({ kind: "name", name: id, next: next.slice(next.lastIndexOf("/") + 1, -5) });
|
|
1598
|
+
} else {
|
|
1599
|
+
return no("content_bound", f);
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
if (content.unknown) return no("content_bound", "content it reads that Unbase cannot place");
|
|
1603
|
+
// Its own modules stay shared; a module of its own that reads its content would read the original's.
|
|
1604
|
+
for (const m of ownCodeFiles) {
|
|
1605
|
+
if (m === page.file) continue;
|
|
1606
|
+
const r = reads.readsByFile.get(m);
|
|
1607
|
+
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);
|
|
1608
|
+
}
|
|
1609
|
+
const rebind = (src) => {
|
|
1610
|
+
let out = src;
|
|
1611
|
+
for (const r of rebinds) {
|
|
1612
|
+
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`);
|
|
1613
|
+
else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
|
|
1614
|
+
}
|
|
1615
|
+
for (const [f, next] of copies) {
|
|
1616
|
+
if (!imported.has(f)) continue;
|
|
1617
|
+
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));
|
|
1618
|
+
}
|
|
1619
|
+
return out;
|
|
1620
|
+
};
|
|
1621
|
+
if (framework === "vite-react") {
|
|
1622
|
+
const router = page.router.file;
|
|
1623
|
+
const src = current(router) ?? "";
|
|
1624
|
+
const attr = routePathAttr(src, page.router);
|
|
1625
|
+
if (!attr) return no("unparsed", "index route");
|
|
1626
|
+
let name = componentName(target);
|
|
1627
|
+
for (let n = 2; new RegExp(`(?<![\\w$])${name}(?![\\w$])`).test(src) && n < 100; n++) name = `${componentName(target)}${n}`;
|
|
1628
|
+
const ext = page.file.slice(page.file.lastIndexOf("."));
|
|
1629
|
+
const file = freeFile(dirname(page.file), name, ext);
|
|
1630
|
+
const original = text(page.file) ?? "";
|
|
1631
|
+
write({ path: file, content: rebind(respecified(original, page.file, file, new Map([[page.file, file]]), have)) });
|
|
1632
|
+
// Its import, beside the original's, in the same form.
|
|
1633
|
+
const comp = page.router.component;
|
|
1634
|
+
const statement =
|
|
1635
|
+
page.router.importKind === "lazy"
|
|
1636
|
+
? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m"))
|
|
1637
|
+
: src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
|
|
1638
|
+
if (!statement) return no("unparsed", "its import");
|
|
1639
|
+
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}`);
|
|
1640
|
+
const value = attr.value.startsWith("/") ? target : (() => {
|
|
1641
|
+
const parent = normalisePath(at.slice(0, at.length - normalisePath(attr.value).length));
|
|
1642
|
+
return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
|
|
1643
|
+
})();
|
|
1644
|
+
if (value === null) return no("unparsed", "a route inside another route keeps its parent");
|
|
1645
|
+
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}`);
|
|
1646
|
+
const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
|
|
1647
|
+
const at1 = page.router.end;
|
|
1648
|
+
let out = `${src.slice(0, at1)}\n${indent}${newTag}${src.slice(at1)}`;
|
|
1649
|
+
const lineEnd = statement.index + statement[0].length;
|
|
1650
|
+
out = `${out.slice(0, lineEnd)}\n${added}${out.slice(lineEnd)}`;
|
|
1651
|
+
write({ path: router, content: out });
|
|
1652
|
+
} else {
|
|
1653
|
+
const dest = destination(page, target, discovered);
|
|
1654
|
+
if (!dest) return no("unparsed");
|
|
1655
|
+
// A Next.js app router page brings what its folder keeps for it; Home's folder is the whole app's.
|
|
1656
|
+
const along = framework === "next" && routesBase(page.file).endsWith("app") && at !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
|
|
1657
|
+
const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
|
|
1658
|
+
for (const next of moved.values()) if (have.has(next)) return no("taken", next);
|
|
1659
|
+
for (const [from, next] of moved) {
|
|
1660
|
+
const src = CODE.test(from) ? text(from) : null;
|
|
1661
|
+
if (src == null) {
|
|
1662
|
+
write({ path: next, from });
|
|
1663
|
+
continue;
|
|
1664
|
+
}
|
|
1665
|
+
let out = respecified(src, from, next, moved, have);
|
|
1666
|
+
if (from === page.file) out = rebind(out);
|
|
1667
|
+
write(out === src ? { path: next, from } : { path: next, content: out });
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
for (const [f, next] of copies) {
|
|
1671
|
+
write({ path: next, from: f });
|
|
1672
|
+
if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
|
|
1673
|
+
}
|
|
1674
|
+
// Its route file (its address and SEO), copied with the new address.
|
|
1675
|
+
for (const f of own) {
|
|
1676
|
+
if (!reads.isRoute(f)) continue;
|
|
1677
|
+
const src = text(f) ?? "";
|
|
1678
|
+
const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
|
|
1679
|
+
write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at)}(")`), `$1${target}$2`) });
|
|
1680
|
+
if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
|
|
1681
|
+
}
|
|
1682
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
|
|
1683
|
+
const entry = { ...(request.drafts ? { draft: true } : {}), ...(request.name ? { name: String(request.name).trim().slice(0, 120) } : {}) };
|
|
1684
|
+
if (Object.keys(entry).length) pages[target] = entry;
|
|
1685
|
+
});
|
|
1686
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
if (action === "delete") {
|
|
1690
|
+
if (at === "/") return no("home");
|
|
1691
|
+
if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
|
|
1692
|
+
let target = null;
|
|
1693
|
+
if (live && request.redirect !== null) {
|
|
1694
|
+
if (request.redirect !== undefined) {
|
|
1695
|
+
target = normalisePath(request.redirect);
|
|
1696
|
+
if (within(target, at) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
|
|
1697
|
+
} else {
|
|
1698
|
+
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;
|
|
1699
|
+
target = target ?? "/";
|
|
1700
|
+
}
|
|
1701
|
+
if (!redirects) return no("no_redirects");
|
|
1702
|
+
}
|
|
1703
|
+
to = target;
|
|
1704
|
+
if (framework === "vite-react") {
|
|
1705
|
+
const router = page.router.file;
|
|
1706
|
+
const src = current(router) ?? "";
|
|
1707
|
+
// Its route element, and its line when nothing else is on it.
|
|
1708
|
+
let { start, end } = page.router;
|
|
1709
|
+
const lineStart = src.lastIndexOf("\n", start - 1) + 1;
|
|
1710
|
+
const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
|
|
1711
|
+
if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
|
|
1712
|
+
start = lineStart;
|
|
1713
|
+
end = Math.min(src.length, lineEnd + 1);
|
|
1714
|
+
}
|
|
1715
|
+
let out = src.slice(0, start) + src.slice(end);
|
|
1716
|
+
const comp = page.router.component;
|
|
1717
|
+
// Its import goes when nothing else in the file names it.
|
|
1718
|
+
const rest = blankStrings(stripComments(out));
|
|
1719
|
+
const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
|
|
1720
|
+
if (uses <= 1) {
|
|
1721
|
+
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");
|
|
1722
|
+
out = out.replace(re, "");
|
|
1723
|
+
if ([...(importers.get(page.file) ?? [])].every((f) => f === router)) write({ path: page.file, deleted: true });
|
|
1724
|
+
}
|
|
1725
|
+
write({ path: router, content: out });
|
|
1726
|
+
} else {
|
|
1727
|
+
const dir = dirname(page.file);
|
|
1728
|
+
const files = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
|
|
1729
|
+
for (const f of files) write({ path: f, deleted: true });
|
|
1730
|
+
}
|
|
1731
|
+
const content = ownedContent(page, { paths, text, importers });
|
|
1732
|
+
for (const f of content.files) {
|
|
1733
|
+
write({ path: f, deleted: true });
|
|
1734
|
+
if (collectionsAfter) delete collectionsAfter[f];
|
|
1735
|
+
}
|
|
1736
|
+
for (const f of linksTo(at, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
|
|
1737
|
+
const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
|
|
1738
|
+
delete pages[at];
|
|
1739
|
+
const before = { ...sendsOn };
|
|
1740
|
+
if (target) sendsOn[at] = target;
|
|
1741
|
+
if (target) repoint(sendsOn, at, target);
|
|
1742
|
+
else for (const [s, d] of Object.entries(sendsOn)) if (d === at) delete sendsOn[s];
|
|
1743
|
+
for (const k of new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
|
|
1744
|
+
});
|
|
1745
|
+
if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
if (collectionsAfter && JSON.stringify(collectionsAfter) !== JSON.stringify(collections)) {
|
|
1749
|
+
const sorted = Object.fromEntries(Object.entries(collectionsAfter).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
|
|
1750
|
+
write({ path: COLLECTIONS, content: `${JSON.stringify(sorted, null, 2)}\n` });
|
|
1751
|
+
}
|
|
1752
|
+
const files = [...writes.values()].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
1753
|
+
const message =
|
|
1754
|
+
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})` : ""}`;
|
|
1755
|
+
return { ok: true, action, path: at, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
/**
|
|
1759
|
+
* What can be done to each page of the code here, and why not (the menu's grey lines): per
|
|
1760
|
+
* address, `rename`, `duplicate` and `delete`, each `{ ok: true }` or `{ ok: false, reason }`.
|
|
1761
|
+
* `live`: the addresses on Live now (a live page needs the kit's redirects to move); `redirects`:
|
|
1762
|
+
* whether this code's build applies them. Cheaper than a plan: no writes are worked out.
|
|
1763
|
+
*/
|
|
1764
|
+
export function pageActions({ framework, paths, text, live = new Set(), found, importers }) {
|
|
1765
|
+
const kept = paths.filter((p) => !SKIP.test(p));
|
|
1766
|
+
const discovered = found ?? discover({ framework, paths: kept, text });
|
|
1767
|
+
const graph = importers ?? importGraph(kept, text);
|
|
1768
|
+
const pageFile = parsePageFile(text(PAGE_FILE));
|
|
1769
|
+
const redirects = kitRedirects({ framework, text });
|
|
1770
|
+
const reads = siteReads(kept, text, graph);
|
|
1771
|
+
/** @type {Record<string, { rename: Capability, duplicate: Capability, delete: Capability, under: number }>} */
|
|
1772
|
+
const out = {};
|
|
1773
|
+
const no = (reason, detail) => ({ ok: /** @type {const} */ (false), reason, ...(detail ? { detail } : {}) });
|
|
1774
|
+
const yes = { ok: /** @type {const} */ (true) };
|
|
1775
|
+
for (const page of discovered.pages) {
|
|
1776
|
+
if (page.path.includes(" ")) continue;
|
|
1777
|
+
const below = discovered.pages.filter((p) => under(p.path, page.path));
|
|
1778
|
+
const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
|
|
1779
|
+
if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
|
|
1780
|
+
out[page.path] = all(no("framework"));
|
|
1781
|
+
continue;
|
|
1782
|
+
}
|
|
1783
|
+
if (!pageFile.ok) {
|
|
1784
|
+
out[page.path] = all(no("invalid"));
|
|
1785
|
+
continue;
|
|
1786
|
+
}
|
|
1787
|
+
if (page.kind === "template") {
|
|
1788
|
+
out[page.path] = all(no("template"));
|
|
1789
|
+
continue;
|
|
1790
|
+
}
|
|
1791
|
+
if (!page.file || page.reason === "unparsed") {
|
|
1792
|
+
out[page.path] = all(no("unparsed"));
|
|
1793
|
+
continue;
|
|
1794
|
+
}
|
|
1795
|
+
const onLive = live.has(page.path);
|
|
1796
|
+
let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
|
|
1797
|
+
if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
|
|
1798
|
+
const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
|
|
1799
|
+
let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
|
|
1800
|
+
if (duplicate.ok) {
|
|
1801
|
+
const content = ownedContent(page, { paths: kept, text, importers: graph });
|
|
1802
|
+
const pageReads = reads.readsByFile.get(page.file) ?? { names: new Set(), entries: new Set() };
|
|
1803
|
+
const imported = new Set(reads.jsonOf.get(page.file) ?? []);
|
|
1804
|
+
if (content.unregistered.length) duplicate = no("content_unregistered", content.unregistered.join(", "));
|
|
1805
|
+
else if (content.unknown) duplicate = no("content_bound");
|
|
1806
|
+
else
|
|
1807
|
+
for (const f of content.files) {
|
|
1808
|
+
if (reads.isRoute(f) || imported.has(f)) continue;
|
|
1809
|
+
const collection = collectionOfFile(f, reads.collections);
|
|
1810
|
+
const id = f.slice(f.lastIndexOf("/") + 1, -5);
|
|
1811
|
+
const folder = (reads.byCollection.get(collection) ?? []).filter((x) => dirname(x) === dirname(f)).length > 1 || !reads.collections || !reads.collections[f];
|
|
1812
|
+
const bound = !folder || !(pageReads.entries.has(`${collection}/${id}`) || (pageReads.names.has(id) && id !== collection));
|
|
1813
|
+
if (bound) {
|
|
1814
|
+
duplicate = no("content_bound", f);
|
|
1815
|
+
break;
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
if (duplicate.ok) {
|
|
1819
|
+
const mine = ownCode(page, graph, reads.imports);
|
|
1820
|
+
for (const m of mine) {
|
|
1821
|
+
if (m === page.file) continue;
|
|
1822
|
+
const r = reads.readsByFile.get(m);
|
|
1823
|
+
if (r && (r.names.size || r.entries.size || r.helped.size || r.whole.size) && content.files.some((f) => !reads.isRoute(f))) {
|
|
1824
|
+
duplicate = no("content_bound", m);
|
|
1825
|
+
break;
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
out[page.path] = { rename, duplicate, delete: remove, under: below.length };
|
|
1831
|
+
}
|
|
1832
|
+
return { redirects, actions: out };
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
/**
|
|
1836
|
+
* The page file's redirects for a framework's build, without those whose address is a page now (a
|
|
1837
|
+
* page made where one used to send visitors on: the page wins). `skipped` names them.
|
|
1838
|
+
* Astro gets `[...path]` as it is here; a static Astro site needs it as one redirect per page
|
|
1839
|
+
* under the new address, which the Astro integration makes (astro.mjs). Next.js `:path*`; React
|
|
1840
|
+
* Router a route per address, `prefix` when everything under it goes along.
|
|
1841
|
+
*/
|
|
1842
|
+
export function redirectsFor(framework, pageFile, pagePaths = []) {
|
|
1843
|
+
const pages = new Set(pagePaths.map(normalisePath));
|
|
1844
|
+
const list = [];
|
|
1845
|
+
const skipped = [];
|
|
1846
|
+
for (const [source, destination] of Object.entries(pageFile.redirects ?? {})) {
|
|
1847
|
+
const prefix = REST.test(source);
|
|
1848
|
+
const base = prefix ? normalisePath(source.replace(REST, "")) : source;
|
|
1849
|
+
if (!prefix && pages.has(source)) {
|
|
1850
|
+
skipped.push(source);
|
|
1851
|
+
continue;
|
|
1852
|
+
}
|
|
1853
|
+
const destBase = prefix ? normalisePath(destination.replace(REST, "")) : destination;
|
|
1854
|
+
if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination, permanent: true });
|
|
1855
|
+
else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
|
|
1856
|
+
else list.push({ source, destination });
|
|
1857
|
+
}
|
|
1858
|
+
return { list, skipped };
|
|
1859
|
+
}
|