@unbase-app/pages 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/core.mjs ADDED
@@ -0,0 +1,1074 @@
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 } } }`. Absent is valid (no flags).
58
+ * @param {string | null | undefined} text
59
+ * @returns {{ ok: true, exists: boolean, pages: Record<string, { draft?: boolean }> } | { ok: false, exists: true, error: string, pages: {} }}
60
+ */
61
+ export function parsePageFile(text) {
62
+ if (text == null) return { ok: true, exists: false, pages: {} };
63
+ const fail = (error) => ({ ok: /** @type {const} */ (false), exists: true, error, pages: {} });
64
+ let data;
65
+ try {
66
+ data = JSON.parse(text);
67
+ } catch {
68
+ return fail("not valid JSON");
69
+ }
70
+ if (!isObject(data)) return fail("the file is not an object");
71
+ const pages = data.pages ?? {};
72
+ if (!isObject(pages)) return fail("`pages` is not an object");
73
+ /** @type {Record<string, { draft?: boolean }>} */
74
+ const out = {};
75
+ for (const [address, entry] of Object.entries(pages)) {
76
+ if (!address.startsWith("/")) return fail(`${address}: an address starts with /`);
77
+ if (!isObject(entry)) return fail(`${address}: not an object`);
78
+ if (entry.draft !== undefined && typeof entry.draft !== "boolean") return fail(`${address}: draft is true or false`);
79
+ out[normalisePath(address)] = entry.draft === undefined ? {} : { draft: entry.draft };
80
+ }
81
+ return { ok: true, exists: true, pages: out };
82
+ }
83
+
84
+ /** The addresses flagged as draft, sorted. */
85
+ export const draftPaths = (file) =>
86
+ Object.keys(file.pages)
87
+ .filter((p) => file.pages[p].draft === true)
88
+ .sort();
89
+
90
+ // ── The deployment context ─────────────────────────────────────────────────
91
+
92
+ const CONTEXTS = new Set(["production", "preview", "development"]);
93
+
94
+ /**
95
+ * Which build this is. Explicit first, then a dev server, then the host; anything else is
96
+ * production, so a draft only shows where a host says it is a preview. NODE_ENV is never read:
97
+ * previews are production-optimised builds too.
98
+ * @param {{ env?: Record<string, string | undefined>, command?: "build" | "dev" }} [input]
99
+ * @returns {{ context: "production" | "preview" | "development", source: string }}
100
+ */
101
+ export function deployContext({ env = {}, command = "build" } = {}) {
102
+ const own = env.UNBASE_DEPLOY_CONTEXT;
103
+ if (own) return CONTEXTS.has(own) ? { context: /** @type {any} */ (own), source: "UNBASE_DEPLOY_CONTEXT" } : { context: "production", source: `UNBASE_DEPLOY_CONTEXT=${own} (unknown)` };
104
+ if (command === "dev") return { context: "development", source: "dev server" };
105
+ const vercel = env.VERCEL_ENV;
106
+ if (vercel) return { context: vercel === "preview" ? "preview" : vercel === "development" ? "development" : "production", source: `VERCEL_ENV=${vercel}` };
107
+ if (env.NETLIFY === "true" && env.CONTEXT) {
108
+ const c = env.CONTEXT;
109
+ return { context: c === "deploy-preview" || c === "branch-deploy" ? "preview" : c === "dev" ? "development" : "production", source: `CONTEXT=${c}` };
110
+ }
111
+ return { context: "production", source: "no deployment context (counts as production)" };
112
+ }
113
+
114
+ // ── Reading code ───────────────────────────────────────────────────────────
115
+
116
+ /** Where a quoted string that starts at `i` ends (after its closing quote). One line for ' and ". */
117
+ function stringEnd(src, i) {
118
+ const q = src[i];
119
+ let j = i + 1;
120
+ while (j < src.length) {
121
+ const c = src[j];
122
+ if (c === "\\") {
123
+ j += 2;
124
+ continue;
125
+ }
126
+ if (c === q) return j + 1;
127
+ if (c === "\n" && q !== "`") return i + 1; // not a string after all (an apostrophe in text)
128
+ j++;
129
+ }
130
+ return src.length;
131
+ }
132
+
133
+ /** The source with its comments blanked out, so offsets stay the same. */
134
+ export function stripComments(src) {
135
+ let out = "";
136
+ let i = 0;
137
+ while (i < src.length) {
138
+ const c = src[i];
139
+ const d = src[i + 1];
140
+ if (c === "/" && d === "/") {
141
+ while (i < src.length && src[i] !== "\n") {
142
+ out += " ";
143
+ i++;
144
+ }
145
+ continue;
146
+ }
147
+ if (c === "/" && d === "*") {
148
+ const end = src.indexOf("*/", i + 2);
149
+ const stop = end < 0 ? src.length : end + 2;
150
+ out += src.slice(i, stop).replace(/[^\n]/g, " ");
151
+ i = stop;
152
+ continue;
153
+ }
154
+ if (c === '"' || c === "'" || c === "`") {
155
+ const j = stringEnd(src, i);
156
+ out += src.slice(i, j);
157
+ i = j;
158
+ continue;
159
+ }
160
+ out += c;
161
+ i++;
162
+ }
163
+ return out;
164
+ }
165
+
166
+ const dirname = (p) => (p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "");
167
+
168
+ function joinRelative(dir, spec) {
169
+ const parts = dir ? dir.split("/") : [];
170
+ for (const s of spec.split("/")) {
171
+ if (s === "." || s === "") continue;
172
+ if (s === "..") parts.pop();
173
+ else parts.push(s);
174
+ }
175
+ return parts.join("/");
176
+ }
177
+
178
+ /**
179
+ * A module specifier from `from` to a file of the app: relative, or `@/` for src/ (Lovable's and
180
+ * shadcn's alias). Null for a package or a file that is not there.
181
+ */
182
+ export function resolveImport(from, spec, have) {
183
+ let base;
184
+ if (spec.startsWith("@/")) base = `src/${spec.slice(2)}`;
185
+ else if (spec.startsWith("./") || spec.startsWith("../")) base = joinRelative(dirname(from), spec);
186
+ else return null;
187
+ base = base.replace(/\?.*$/, "");
188
+ for (const c of [base, ...EXTS.map((e) => base + e), ...EXTS.map((e) => `${base}/index${e}`)]) if (have.has(c)) return c;
189
+ return null;
190
+ }
191
+
192
+ const IMPORTS = [
193
+ /(?:import|export)\s+(?:type\s+)?[\w$*{}\s,]*?\s*from\s*["']([^"']+)["']/g,
194
+ /import\s*["']([^"']+)["']/g,
195
+ /import\(\s*["']([^"']+)["']\s*\)/g,
196
+ /require\(\s*["']([^"']+)["']\s*\)/g,
197
+ ];
198
+
199
+ /** Every file of the app another file imports, with who imports it. */
200
+ export function importGraph(paths, text) {
201
+ const have = new Set(paths);
202
+ /** @type {Map<string, Set<string>>} */
203
+ const importers = new Map();
204
+ for (const p of paths) {
205
+ if (!CODE.test(p) || SKIP.test(p)) continue;
206
+ const src = text(p);
207
+ if (!src) continue;
208
+ for (const re of IMPORTS) {
209
+ re.lastIndex = 0;
210
+ for (const m of src.matchAll(re)) {
211
+ const target = resolveImport(p, m[1], have);
212
+ if (!target || target === p) continue;
213
+ if (!importers.has(target)) importers.set(target, new Set());
214
+ importers.get(target).add(p);
215
+ }
216
+ }
217
+ }
218
+ return importers;
219
+ }
220
+
221
+ // ── Discovery ──────────────────────────────────────────────────────────────
222
+
223
+ /**
224
+ * @typedef {{ file: string, start: number, end: number, component: string, importKind: "default" | "lazy" }} RouteSite
225
+ * @typedef {{ path: string, kind: "file" | "route" | "template", file: string | null, reason?: "nested" | "unparsed", router?: RouteSite }} Page
226
+ */
227
+
228
+ const address = (segments) => normalisePath(segments.join("/"));
229
+ const unlisted = (s) => s.startsWith("_") || s.startsWith("@") || s.startsWith("(.");
230
+ const routeGroup = (s) => /^\([^.)][^)]*\)$/.test(s);
231
+
232
+ /** Astro: src/pages/**; a page per file, `[x]` a template, `_x` private, an endpoint (.ts) none. */
233
+ function astroPages(paths) {
234
+ /** @type {Page[]} */
235
+ const out = [];
236
+ const ext = /\.(astro|md|mdx|html)$/;
237
+ for (const p of paths) {
238
+ if (!p.startsWith("src/pages/") || !ext.test(p)) continue;
239
+ const segments = p.slice("src/pages/".length).replace(ext, "").split("/");
240
+ if (segments.some((s) => s.startsWith("_"))) continue;
241
+ if (segments.at(-1) === "index") segments.pop();
242
+ if (segments.length === 1 && /^(404|500)$/.test(segments[0])) continue;
243
+ out.push({ path: address(segments), kind: segments.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
244
+ }
245
+ return out;
246
+ }
247
+
248
+ /** Next.js: app/**\/page.* and pages/**, as unbase-projects' pages.ts read them. */
249
+ function nextPages(paths) {
250
+ /** @type {Page[]} */
251
+ const out = [];
252
+ const ext = /\.(tsx|ts|jsx|js|mdx|md)$/;
253
+ for (const base of ["app/", "src/app/"]) {
254
+ for (const p of paths) {
255
+ if (!p.startsWith(base)) continue;
256
+ const segments = p.slice(base.length).split("/");
257
+ const file = segments.pop();
258
+ if (!/^page\./.test(file) || !ext.test(file) || segments.some(unlisted)) continue;
259
+ const kept = segments.filter((s) => !routeGroup(s));
260
+ out.push({ path: address(kept), kind: kept.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
261
+ }
262
+ }
263
+ for (const base of ["pages/", "src/pages/"]) {
264
+ for (const p of paths) {
265
+ if (!p.startsWith(base) || !ext.test(p)) continue;
266
+ const segments = p.slice(base.length).replace(ext, "").split("/");
267
+ if (segments[0] === "api" || segments.some(unlisted)) continue;
268
+ if (segments.at(-1) === "index") segments.pop();
269
+ if (segments.length === 1 && /^(404|500)$/.test(segments[0])) continue;
270
+ out.push({ path: address(segments), kind: segments.some((s) => s.startsWith("[")) ? "template" : "file", file: p });
271
+ }
272
+ }
273
+ return out;
274
+ }
275
+
276
+ /** Where a JSX tag that starts after `from` ends, braces and strings skipped. */
277
+ function tagEnd(src, from) {
278
+ let depth = 0;
279
+ let i = from;
280
+ while (i < src.length) {
281
+ const c = src[i];
282
+ if (c === '"' || c === "'" || c === "`") {
283
+ i = stringEnd(src, i);
284
+ continue;
285
+ }
286
+ if (c === "{") depth++;
287
+ else if (c === "}") depth--;
288
+ else if (depth === 0 && c === "/" && src[i + 1] === ">") return { end: i + 2, selfClosing: true };
289
+ else if (depth === 0 && c === ">") return { end: i + 1, selfClosing: false };
290
+ i++;
291
+ }
292
+ return null;
293
+ }
294
+
295
+ /** The text inside the braces that open at `i`. */
296
+ function braced(src, i) {
297
+ let depth = 0;
298
+ for (let j = i; j < src.length; j++) {
299
+ const c = src[j];
300
+ if (c === '"' || c === "'" || c === "`") {
301
+ j = stringEnd(src, j) - 1;
302
+ continue;
303
+ }
304
+ if (c === "{") depth++;
305
+ else if (c === "}" && --depth === 0) return src.slice(i + 1, j);
306
+ }
307
+ return null;
308
+ }
309
+
310
+ /** A `path` attribute: its literal value, null when absent, false when not a literal. */
311
+ function pathAttr(attrs) {
312
+ const m = attrs.match(/(?:^|\s)path\s*=\s*/);
313
+ if (!m) return null;
314
+ const rest = attrs.slice(m.index + m[0].length);
315
+ const lit = rest.match(/^"([^"]*)"|^'([^']*)'|^\{\s*"([^"]*)"\s*\}|^\{\s*'([^']*)'\s*\}|^\{\s*`([^`$]*)`\s*\}/);
316
+ if (!lit) return false;
317
+ return lit.slice(1).find((v) => v !== undefined) ?? "";
318
+ }
319
+
320
+ /** The one component an element renders (`element={<About />}`, `Component={About}`), or null. */
321
+ function componentAttr(attrs) {
322
+ const comp = attrs.match(/(?:^|\s)Component\s*=\s*\{\s*([A-Z][\w$]*)\s*\}/);
323
+ if (comp) return comp[1];
324
+ const m = attrs.match(/(?:^|\s)element\s*=\s*\{/);
325
+ if (!m) return null;
326
+ const inner = braced(attrs, m.index + m[0].length - 1);
327
+ if (inner === null) return null;
328
+ const el = inner.trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/);
329
+ return el ? el[1] : null;
330
+ }
331
+
332
+ /** The components a router file imports, by name: a default import or React.lazy. */
333
+ function importedComponents(src) {
334
+ /** @type {Map<string, { spec: string, kind: "default" | "lazy" }>} */
335
+ const out = new Map();
336
+ 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" });
337
+ 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))
338
+ out.set(m[1], { spec: m[2], kind: "lazy" });
339
+ return out;
340
+ }
341
+
342
+ /**
343
+ * React Router: the JSX `<Route>` elements of every file that imports react-router(-dom), with
344
+ * their nesting (an index route takes its parent's path, a layout route without a path adds
345
+ * nothing), each traced to the file its component comes from. `*` is the catch-all (Not Found).
346
+ * @returns {{ pages: Page[], notFound: string | null }}
347
+ */
348
+ function reactRouterPages(paths, text, only = paths) {
349
+ const have = new Set(paths);
350
+ /** @type {Page[]} */
351
+ const pages = [];
352
+ let notFound = null;
353
+ for (const file of only) {
354
+ if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP.test(file)) continue;
355
+ const raw = text(file);
356
+ if (!raw || !raw.includes("<Route") || !/from\s*["']react-router(-dom)?["']/.test(raw)) continue;
357
+ const src = stripComments(raw);
358
+ const imports = importedComponents(src);
359
+ /** @type {{ at: number, close?: true }[]} */
360
+ const events = [];
361
+ for (const m of src.matchAll(/<Route(?=[\s/>])/g)) events.push({ at: m.index });
362
+ for (const m of src.matchAll(/<\/Route\s*>/g)) events.push({ at: m.index, close: true });
363
+ events.sort((a, b) => a.at - b.at);
364
+ /** @type {string[]} */
365
+ const stack = [];
366
+ for (const e of events) {
367
+ if (e.close) {
368
+ stack.pop();
369
+ continue;
370
+ }
371
+ const tag = tagEnd(src, e.at + "<Route".length);
372
+ if (!tag) break;
373
+ const attrs = src.slice(e.at + "<Route".length, tag.end - (tag.selfClosing ? 2 : 1));
374
+ const parent = stack.at(-1) ?? "";
375
+ const index = /(?:^|\s)index(?=\s|$|=\{\s*true\s*\})/.test(attrs);
376
+ const p = pathAttr(attrs);
377
+ const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
378
+ if (!tag.selfClosing) stack.push(typeof full === "string" ? full : parent);
379
+ if (full === null) continue; // a layout route: no address of its own
380
+ const component = componentAttr(attrs);
381
+ const imported = component ? imports.get(component) : undefined;
382
+ const target = imported ? resolveImport(file, imported.spec, have) : null;
383
+ if (full === false) {
384
+ pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
385
+ continue;
386
+ }
387
+ if (full === "/*" || full.endsWith("/*") || full === "*") {
388
+ if (full === "/*" && target) notFound = target;
389
+ continue;
390
+ }
391
+ /** @type {Page} */
392
+ const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
393
+ if (target && imported && component) page.router = { file, start: e.at, end: tag.end, component, importKind: imported.kind };
394
+ if (!tag.selfClosing) page.reason = "nested";
395
+ else if (!target) page.reason = "unparsed";
396
+ pages.push(page);
397
+ }
398
+ }
399
+ return { pages, notFound };
400
+ }
401
+
402
+ /**
403
+ * A router file's `code` without the `<Route … />` of each address in `drop` that it holds, as
404
+ * discovery found them (the same parser, so what was checked is what goes). `removed` names them;
405
+ * the plugin refuses the build when a draft's route was removed nowhere.
406
+ * @param {{ file: string, code: string, paths: string[], text: (path: string) => string | null, drop: string[] }} input
407
+ */
408
+ export function removeRoutes({ file, code, paths, text, drop }) {
409
+ const { pages } = reactRouterPages(paths, (p) => (p === file ? code : text(p)), [file]);
410
+ const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
411
+ spans.sort((a, b) => b.start - a.start);
412
+ let out = code;
413
+ for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
414
+ return { code: out, removed: spans.map((s) => s.path) };
415
+ }
416
+
417
+ /**
418
+ * The pages the code makes, sorted by address. Unknown frameworks make none here.
419
+ * @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null }} input
420
+ * @returns {{ pages: Page[], notFound: string | null }}
421
+ */
422
+ export function discover({ framework, paths, text }) {
423
+ const kept = paths.filter((p) => !SKIP.test(p));
424
+ const found =
425
+ framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : { pages: [], notFound: null };
426
+ const seen = new Set();
427
+ const pages = found.pages
428
+ .filter((p) => (seen.has(p.path) ? false : (seen.add(p.path), true)))
429
+ .sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
430
+ return { pages, notFound: found.notFound };
431
+ }
432
+
433
+ // ── Content a page owns ────────────────────────────────────────────────────
434
+
435
+ const CONTENT_JSON = /^src\/content\/(?!\.)(?!.*\/\.)[^]*\.json$/;
436
+ /** Where content collections are defined: naming one there is not using it. */
437
+ const CONTENT_CONFIG = /^src\/content(\.config|\/config)\.(ts|mts|js|mjs)$/;
438
+ /** Written by comment-modus: content file → its collection, where that is not its folder. */
439
+ const COLLECTIONS = "src/content/.schemas/collecties.json";
440
+
441
+ /** The names a content file goes by: its entry id (file name) and its collection. */
442
+ function contentNames(paths, text) {
443
+ /** @type {Map<string, Set<string>>} */
444
+ const files = new Map();
445
+ const add = (name, f) => {
446
+ if (!files.has(name)) files.set(name, new Set());
447
+ files.get(name).add(f);
448
+ };
449
+ let collections = {};
450
+ try {
451
+ collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
452
+ } catch {}
453
+ for (const f of paths) {
454
+ if (!CONTENT_JSON.test(f)) continue;
455
+ add(f.slice(f.lastIndexOf("/") + 1, -".json".length), f);
456
+ const named = collections[f];
457
+ add(typeof named === "string" ? named : f.slice("src/content/".length).split("/")[0].replace(/\.json$/, ""), f);
458
+ }
459
+ return files;
460
+ }
461
+
462
+ /** A content file's collection: as collecties.json says, else its first folder under src/content. */
463
+ function collectionOfFile(f, collections) {
464
+ const named = collections[f];
465
+ return typeof named === "string" ? named : f.slice("src/content/".length).split("/")[0].replace(/\.json$/, "");
466
+ }
467
+
468
+ /**
469
+ * The files only `page` uses: its own file, and every file it imports (however deep) that nothing
470
+ * outside that set imports. What these read is the page's; what any other file reads is not.
471
+ */
472
+ function ownCode(page, importers, imports) {
473
+ const own = new Set([page.file]);
474
+ // Forward from what is its own: a file joins once its last importer has (or is the router).
475
+ const queue = [page.file];
476
+ while (queue.length) {
477
+ for (const target of imports.get(queue.pop()) ?? []) {
478
+ if (own.has(target) || ![...importers.get(target)].every((f) => own.has(f) || f === page.router?.file)) continue;
479
+ own.add(target);
480
+ queue.push(target);
481
+ }
482
+ }
483
+ return own;
484
+ }
485
+
486
+ /** Astro's own reading functions: collection first, then (getEntry) the entry. */
487
+ const ASTRO_READS = ["getCollection", "getEntry", "getEntries"];
488
+
489
+ /**
490
+ * How the site reads content, as the editability manifest's `reads` say it (plan-editable F0):
491
+ * Astro's functions; the site's own functions that pass their first argument on as the collection
492
+ * (`getPagina(naam)`: `byName`); and those that read fixed content (`getEvenementen()` a whole
493
+ * collection, `getActieAgendaTeksten()` one entry: `fixed`). `code` is every code file without
494
+ * its comments.
495
+ */
496
+ function contentReads(paths, text) {
497
+ /** @type {Map<string, string>} */
498
+ const code = new Map();
499
+ for (const p of paths) {
500
+ if (!CODE.test(p) || SKIP.test(p)) continue;
501
+ const src = text(p);
502
+ if (src) code.set(p, stripComments(src));
503
+ }
504
+ const astro = ASTRO_READS.join("|");
505
+ const byName = new Set(ASTRO_READS);
506
+ /** The entry a reading function always reads: `getEntry(collectie, "pagina")` → "pagina". */
507
+ const entryOf = new Map();
508
+ /** @type {Map<string, { whole: Set<string>, entries: Set<string> }>} */
509
+ const fixed = new Map();
510
+ /** @type {Map<string, string>} */
511
+ const bodies = new Map();
512
+ /** Where each file's helpers have their bodies, [start, end): what a body reads, its callers read. */
513
+ const spans = new Map();
514
+ const DIRECT = new RegExp(`\\b(?:${astro})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
515
+ const addFixed = (name, whole, entry) => {
516
+ if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
517
+ if (entry) fixed.get(name).entries.add(`${whole}/${entry}`);
518
+ else fixed.get(name).whole.add(whole);
519
+ };
520
+ for (const [p, src] of code) {
521
+ if (!/\.(ts|mts|js|mjs)$/.test(p)) continue;
522
+ // Functions whether exported or not: a site's helpers may go through a module's own `enkel(collectie)`.
523
+ 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)) {
524
+ const name = m[1] ?? m[3];
525
+ const first = (m[2] ?? m[4] ?? "").split(",")[0]?.split(":")[0]?.trim() ?? "";
526
+ // The body: a block, or for an arrow the expression up to the end of its statement.
527
+ let at = m.index + m[0].length;
528
+ while (/\s/.test(src[at] ?? "")) at++;
529
+ const block = src.indexOf("{", at);
530
+ const braces = src[at] === "{" ? at : m[1] && block > 0 ? block : -1;
531
+ const body = braces >= 0 ? (braced(src, braces) ?? "") : src.slice(at, src.slice(at).search(/;|\n\s*\n|$/) + at);
532
+ const start = braces >= 0 ? braces + 1 : at;
533
+ if (!spans.has(p)) spans.set(p, []);
534
+ spans.get(p).push([start, start + body.length]);
535
+ if (first && new RegExp(`\\b(?:${astro})\\(\\s*${escape(first)}\\b`).test(body)) {
536
+ byName.add(name);
537
+ const entry = new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1];
538
+ if (entry) entryOf.set(name, entry);
539
+ }
540
+ bodies.set(name, body);
541
+ for (const d of body.matchAll(DIRECT)) addFixed(name, d[1], d[2]);
542
+ }
543
+ }
544
+ // A helper that calls one of the site's reading functions with a literal reads that content
545
+ // (`getVerlangensOverzicht = () => enkel("verlangensOverzicht", …)`): its entry, else the collection.
546
+ for (const [name, body] of bodies) {
547
+ for (const fn of byName) {
548
+ if (fn === name || ASTRO_READS.includes(fn)) continue;
549
+ for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
550
+ }
551
+ }
552
+ // A helper that calls a helper reads what that one reads (`getActieAgenda()` → `getActieAgendaTeksten()`).
553
+ // Each body's calls are read once and looked up, not searched for helper by helper.
554
+ const calls = new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))]));
555
+ for (let grew = true; grew; ) {
556
+ grew = false;
557
+ for (const [name, called] of calls) {
558
+ for (const other of called) {
559
+ const read = fixed.get(other);
560
+ if (other === name || !read) continue;
561
+ if (!fixed.has(name)) fixed.set(name, { whole: new Set(), entries: new Set() });
562
+ const mine = fixed.get(name);
563
+ const before = mine.whole.size + mine.entries.size;
564
+ read.whole.forEach((c) => mine.whole.add(c));
565
+ read.entries.forEach((e) => mine.entries.add(e));
566
+ if (mine.whole.size + mine.entries.size > before) grew = true;
567
+ }
568
+ }
569
+ }
570
+ const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
571
+ return { code, byName, byNameCall, entryOf, fixed, astro, spans };
572
+ }
573
+
574
+ /** A call: `name(`, not `obj.name(`. */
575
+ const CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
576
+ /** Every identifier, as `(?<![\w$.])name(?![\w$])` would find it. */
577
+ const IDENTIFIER = /(?<![\w$.])[A-Za-z_$][\w$]*/g;
578
+ /** A definition of a function or constant, by name. */
579
+ const DEFINITION = /function\s+([A-Za-z_$][\w$]*)|const\s+([A-Za-z_$][\w$]*)\s*=/g;
580
+
581
+ /** `src` with `ranges` ([start, end)) blanked, offsets kept: one pass however many there are. */
582
+ function blankRanges(src, ranges) {
583
+ if (!ranges.length) return src;
584
+ let out = "";
585
+ let at = 0;
586
+ for (const [start, end] of [...ranges].sort((a, b) => a[0] - b[0])) {
587
+ if (end <= at) continue;
588
+ const from = Math.max(start, at);
589
+ out += src.slice(at, from) + blank(src.slice(from, end));
590
+ at = end;
591
+ }
592
+ return out + src.slice(at);
593
+ }
594
+
595
+ /** Import statements: they name a helper, they do not read with it. */
596
+ const IMPORT_STATEMENT = /\bimport\s+(?:type\s+)?[\s\S]*?\bfrom\s*["'][^"'\n]+["']/g;
597
+
598
+ const blank = (s) => s.replace(/[^\n]/g, " ");
599
+
600
+ /**
601
+ * What a file reads by name: collections or entries (`getPagina("overOns")`), entries of one
602
+ * collection (`getEntry("pages", "funding")`: `entries`, as "pages/funding"), and the collections
603
+ * it reads whole (`getCollection("x")`, `getEntry("x", slug)`, `getEvenementen()`). Only calls of
604
+ * reading functions count: `invoer("organisatie")` names a form field. A helper's body is read for
605
+ * its callers, not for the file that defines it; a helper the file passes on as a value (not only
606
+ * calls) counts as read here too, as nobody can follow it further.
607
+ */
608
+ function readsIn(src, reads, path = null) {
609
+ const code = blankRanges(src, reads.spans?.get(path) ?? []).replace(IMPORT_STATEMENT, blank);
610
+ const names = new Set();
611
+ const entries = new Set();
612
+ const whole = new Set();
613
+ const helped = new Set();
614
+ for (const m of code.matchAll(reads.byNameCall)) {
615
+ const [, fn, first, entry, other] = m;
616
+ if (reads.entryOf?.has(fn)) entries.add(`${first}/${reads.entryOf.get(fn)}`);
617
+ else if (entry) entries.add(`${first}/${entry}`);
618
+ else if (other && ASTRO_READS.includes(fn)) whole.add(first);
619
+ else if (fn === "getCollection") whole.add(first);
620
+ else names.add(first);
621
+ }
622
+ // The file's names counted once, and the helpers among them looked up: one pass per file, however
623
+ // many helpers the site has (1,000 pages each with its own took 1.6 s searched one by one).
624
+ const mentions = new Map();
625
+ for (const [name] of code.matchAll(IDENTIFIER)) mentions.set(name, (mentions.get(name) ?? 0) + 1);
626
+ const defined = new Set(Array.from(code.matchAll(DEFINITION), (m) => m[1] ?? m[2]));
627
+ for (const [name, n] of mentions) {
628
+ const read = reads.fixed.get(name);
629
+ if (!read || n - (defined.has(name) ? 1 : 0) <= 0) continue;
630
+ read.whole.forEach((c) => whole.add(c));
631
+ read.entries.forEach((e) => helped.add(e));
632
+ }
633
+ return { names, entries, whole, helped };
634
+ }
635
+
636
+ /**
637
+ * What the whole site reads, which no page changes: once per set of files, not once per page (20
638
+ * pages each reading a real site's 300 files ran out of an Edge Function's CPU, 26-10). Kept by the import
639
+ * graph, which a registry or a build makes once from the same files.
640
+ * @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 }>}
641
+ */
642
+ const siteReadsOf = new WeakMap();
643
+
644
+ function siteReads(paths, text, importers) {
645
+ const kept = siteReadsOf.get(importers);
646
+ if (kept) return kept;
647
+ let collections = {};
648
+ try {
649
+ collections = JSON.parse(text(COLLECTIONS) ?? "{}") ?? {};
650
+ } catch {}
651
+ const reads = contentReads(paths, text);
652
+ const readsByFile = new Map();
653
+ for (const [p, src] of reads.code) if (!CONTENT_CONFIG.test(p)) readsByFile.set(p, readsIn(src, reads, p));
654
+ // How many files read each name, entry and collection: "read elsewhere" is the site's count
655
+ // less the page's own files', not a union of every other file made again for each page.
656
+ const counts = { names: new Map(), entries: new Map(), whole: new Map() };
657
+ const count = (kind, keys) => keys.forEach((k) => counts[kind].set(k, (counts[kind].get(k) ?? 0) + 1));
658
+ for (const r of readsByFile.values()) {
659
+ count("names", r.names);
660
+ count("entries", new Set([...r.entries, ...r.helped]));
661
+ count("whole", r.whole);
662
+ }
663
+ // The content files, each parsed once: by entry, by collection, by name, and the route files
664
+ // (`pad`, per page by contract: only ownedContent's last rule gives one to its page) by address.
665
+ const names = contentNames(paths, text);
666
+ const byEntry = new Map();
667
+ const byCollection = new Map();
668
+ const namesOf = new Map();
669
+ const routeOf = new Map();
670
+ const routes = new Set();
671
+ const push = (map, k, v) => (map.has(k) ? map.get(k).push(v) : map.set(k, [v]));
672
+ for (const f of paths) {
673
+ if (!CONTENT_JSON.test(f)) continue;
674
+ const c = collectionOfFile(f, collections);
675
+ push(byEntry, `${c}/${f.slice(f.lastIndexOf("/") + 1, -5)}`, f);
676
+ push(byCollection, c, f);
677
+ try {
678
+ const d = JSON.parse(text(f) ?? "null");
679
+ if (!isObject(d)) continue;
680
+ if (typeof (d.pad ?? d.path) === "string" && String(d.pad ?? d.path).startsWith("/")) routes.add(f);
681
+ for (const a of new Set([d.pad, d.path])) if (typeof a === "string") push(routeOf, a, f);
682
+ } catch {}
683
+ }
684
+ for (const [n, fs] of names) for (const f of fs) push(namesOf, f, n);
685
+ // Which JSON files each file imports, and what each file imports.
686
+ const jsonOf = new Map();
687
+ const imports = new Map();
688
+ for (const [target, by] of importers) {
689
+ for (const f of by) {
690
+ push(imports, f, target);
691
+ if (target.endsWith(".json")) push(jsonOf, f, target);
692
+ }
693
+ }
694
+ const site = { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute: (f) => routes.has(f), jsonOf, imports };
695
+ siteReadsOf.set(importers, site);
696
+ return site;
697
+ }
698
+
699
+ /**
700
+ * Whether a page reads content itself: it imports astro:content, or a data module (.ts, .js) that
701
+ * does, however deep. Components are not followed: a layout that reads the page's SEO is the
702
+ * layout's, and the route file covers that.
703
+ */
704
+ function readsContent(page, { paths, text }) {
705
+ const have = new Set(paths);
706
+ const seen = new Set();
707
+ const visit = (file) => {
708
+ if (seen.has(file)) return false;
709
+ seen.add(file);
710
+ const src = text(file) ?? "";
711
+ if (/from\s*["']astro:content["']/.test(src)) return true;
712
+ for (const m of src.matchAll(IMPORTS[0])) {
713
+ const target = resolveImport(file, m[1], have);
714
+ if (target && /\.(ts|mts|js|mjs)$/.test(target) && visit(target)) return true;
715
+ }
716
+ return false;
717
+ };
718
+ return visit(page.file);
719
+ }
720
+
721
+ /**
722
+ * The content files a page reads that no other code reads: JSON it imports, content it names by
723
+ * entry id or collection (`getEntry("pages", "funding")`, a helper's `getPagina("overOns")`), and
724
+ * the route file whose `pad`/`path` is its address. `shared` lists those another file also uses:
725
+ * drafting the page would leave that content live, so the draft is refused. `unregistered` lists
726
+ * the names the page reads content by that no content file goes by (a collection the site's
727
+ * generated `.schemas/collecties.json` does not list yet): what they read cannot be kept out
728
+ * either. `unknown` when the page reads content and none of it could be named: then nobody can
729
+ * say what to keep out.
730
+ */
731
+ export function ownedContent(page, { paths, text, importers }) {
732
+ const own = new Set();
733
+ const shared = new Set();
734
+ const unregistered = new Set();
735
+ if (!page.file) return { files: [], shared: [], unregistered: [], unknown: false };
736
+ const site = siteReads(paths, text, importers);
737
+ const { collections, names, readsByFile, counts, byEntry, byCollection, namesOf, routeOf, isRoute } = site;
738
+ for (const target of site.jsonOf.get(page.file) ?? []) {
739
+ const others = [...importers.get(target)].filter((f) => f !== page.file && f !== page.router?.file);
740
+ (others.length ? shared : own).add(target);
741
+ }
742
+ const fileOf = (entry) => {
743
+ const [collection, id] = entry.split("/");
744
+ return byEntry.get(`${collection}/${id}`) ?? [];
745
+ };
746
+ // What the page's own code reads; what every other file reads is the site's count less that.
747
+ const mine = ownCode(page, importers, site.imports);
748
+ const named = new Set();
749
+ const entries = new Set();
750
+ const helped = new Set();
751
+ const wholeMine = new Set();
752
+ const minus = { names: new Map(), entries: new Map(), whole: new Map() };
753
+ const less = (kind, keys) => keys.forEach((k) => minus[kind].set(k, (minus[kind].get(k) ?? 0) + 1));
754
+ for (const p of mine) {
755
+ const r = readsByFile.get(p);
756
+ if (!r) continue;
757
+ r.names.forEach((n) => (names.has(n) ? named.add(n) : unregistered.add(n)));
758
+ r.entries.forEach((e) => entries.add(e));
759
+ r.helped.forEach((e) => helped.add(e));
760
+ r.whole.forEach((c) => wholeMine.add(c));
761
+ less("names", r.names);
762
+ less("entries", new Set([...r.entries, ...r.helped]));
763
+ less("whole", r.whole);
764
+ }
765
+ const has = (kind) => ({ has: (k) => (counts[kind].get(k) ?? 0) - (minus[kind].get(k) ?? 0) > 0 });
766
+ const elsewhere = { names: has("names"), entries: has("entries"), whole: has("whole") };
767
+ const readElsewhere = (f) => elsewhere.whole.has(collectionOfFile(f, collections)) || (namesOf.get(f) ?? []).some((n) => elsewhere.names.has(n));
768
+ // What the page names itself is its subject: read elsewhere too, the draft cannot hide it.
769
+ 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);
770
+ for (const e of entries) for (const f of fileOf(e)) if (!isRoute(f)) (elsewhere.entries.has(e) || readElsewhere(f) ? shared : own).add(f);
771
+ // What comes through a helper or a whole collection is the page's only when nothing else reads it;
772
+ // otherwise it is the site's (menus, shared texts), live anyway, and no reason to refuse.
773
+ for (const e of helped) for (const f of fileOf(e)) if (!isRoute(f) && !elsewhere.entries.has(e) && !readElsewhere(f)) own.add(f);
774
+ 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);
775
+ const read = own.size > 0;
776
+ // The route file: per page by contract (read_settings), whatever reads the collection to find it.
777
+ for (const f of routeOf.get(page.path) ?? []) if (!shared.has(f)) own.add(f);
778
+ for (const f of shared) own.delete(f);
779
+ return {
780
+ files: [...own].sort(),
781
+ shared: [...shared].sort(),
782
+ unregistered: [...unregistered].sort(),
783
+ unknown: !read && !shared.size && !unregistered.size && readsContent(page, { paths, text }),
784
+ };
785
+ }
786
+
787
+ // ── Can a draft be kept out? ───────────────────────────────────────────────
788
+
789
+ /**
790
+ * Packages that draw a page's text into images (share images, cards). A picture of a draft's title
791
+ * cannot be searched for, so a site that makes them cannot have drafts until the kit knows how
792
+ * they are made (docs/plan-pages.md, what the kit can prove).
793
+ */
794
+ const MEDIA = ["satori", "@vercel/og", "astro-og-canvas", "og-img", "@resvg/resvg-js", "astro-opengraph-images"];
795
+
796
+ export function mediaGenerators(text) {
797
+ let pkg = null;
798
+ try {
799
+ pkg = JSON.parse(text("package.json") ?? "null");
800
+ } catch {}
801
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
802
+ return MEDIA.filter((m) => m in deps);
803
+ }
804
+
805
+ /**
806
+ * Packages that write a site's page list after the build, from its output (next-sitemap reads
807
+ * Next.js's manifests, where a draft's address still is): the kit cannot clean what they write.
808
+ */
809
+ const LIST_TOOLS = { next: ["next-sitemap"] };
810
+
811
+ export function listTools(framework, text) {
812
+ const tools = LIST_TOOLS[String(framework)] ?? [];
813
+ if (!tools.length) return [];
814
+ let pkg = null;
815
+ try {
816
+ pkg = JSON.parse(text("package.json") ?? "null");
817
+ } catch {}
818
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
819
+ return tools.filter((t) => t in deps);
820
+ }
821
+
822
+ /**
823
+ * @typedef {{ ok: true, path: string, page: Page, content: string[] } | { ok: false, path: string, reason: string, detail?: string }} DraftCheck
824
+ */
825
+
826
+ /**
827
+ * Whether `path` can be left out of a production build, and what goes with it. The same answer
828
+ * for the build plugin (which then does it) and for Unbase (which then allows it).
829
+ * @param {string} path
830
+ * @param {{ framework: string | null | undefined, paths: string[], text: (path: string) => string | null, found?: { pages: Page[], notFound: string | null }, importers?: Map<string, Set<string>> }} input
831
+ * @returns {DraftCheck}
832
+ */
833
+ export function draftCheck(path, { framework, paths, text, found, importers }) {
834
+ const at = normalisePath(path);
835
+ const no = (reason, detail) => ({ ok: /** @type {const} */ (false), path: at, reason, ...(detail ? { detail } : {}) });
836
+ if (!DRAFTABLE.includes(String(framework))) return no("framework");
837
+ if (at === "/") return no("home");
838
+ const media = mediaGenerators(text);
839
+ if (media.length) return no("generated_media", media.join(", "));
840
+ const lists = listTools(framework, text);
841
+ if (lists.length) return no("page_list", lists.join(", "));
842
+ const discovered = found ?? discover({ framework, paths, text });
843
+ const page = discovered.pages.find((p) => p.path === at);
844
+ if (!page) {
845
+ const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at));
846
+ return template ? no("template", template.path) : no("missing");
847
+ }
848
+ if (page.kind === "template") return no("template", page.path);
849
+ if (page.reason) return no(page.reason);
850
+ if (!page.file) return no("unparsed");
851
+ if (framework === "next") {
852
+ const beside = segmentFiles(page.file, paths);
853
+ if (beside.length) return no("segment", beside.join(", "));
854
+ }
855
+ const graph = importers ?? importGraph(paths, text);
856
+ const by = [...(graph.get(page.file) ?? [])].filter((f) => f !== page.router?.file);
857
+ if (by.length) return no("shared", by.sort().join(", "));
858
+ const twice = discovered.pages.find((p) => p !== page && p.file === page.file);
859
+ if (twice) return no("shared", twice.path);
860
+ const content = ownedContent(page, { paths, text, importers: graph });
861
+ if (content.shared.length) return no("shared", content.shared.join(", "));
862
+ // Content read by a name no file goes by: the site's generated list of collections is behind its
863
+ // code (a collection added since it was made). Making it again fixes this; nothing else does.
864
+ if (content.unregistered.length) return no("content_unregistered", content.unregistered.join(", "));
865
+ if (content.unknown) return no("content_unknown");
866
+ return { ok: true, path: at, page, content: content.files };
867
+ }
868
+
869
+ /**
870
+ * Next.js's special files beside an app router page (`app/x/page.tsx`): a layout, loading or
871
+ * not-found renders around the page, and an opengraph-image, icon, sitemap or route is a route of
872
+ * its own. What they say is not the page's to keep out, so the page cannot be a draft.
873
+ */
874
+ 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]+$/;
875
+
876
+ export function segmentFiles(file, paths) {
877
+ if (!/(^|\/)page\.[a-z]+$/.test(file)) return [];
878
+ const dir = dirname(file);
879
+ return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
880
+ }
881
+
882
+ /** "/blog/:slug" or "/blog/[slug]" against "/blog/hello". */
883
+ function templateMatches(template, path) {
884
+ const t = template.split("/");
885
+ const p = path.split("/");
886
+ 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));
887
+ return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
888
+ }
889
+
890
+ /**
891
+ * Every draft in the page file, checked. `failed` holds the ones a production build cannot keep
892
+ * out; a build refuses while there is one.
893
+ */
894
+ export function draftPlan({ framework, paths, text, pageFile }) {
895
+ if (!pageFile.ok) return { checks: [], failed: [{ ok: /** @type {const} */ (false), path: PAGE_FILE, reason: "invalid", detail: pageFile.error }] };
896
+ const found = discover({ framework, paths, text });
897
+ const importers = importGraph(paths, text);
898
+ const checks = draftPaths(pageFile).map((p) => draftCheck(p, { framework, paths, text, found, importers }));
899
+ return { checks, failed: checks.filter((c) => !c.ok), found, importers };
900
+ }
901
+
902
+ // ── Links ──────────────────────────────────────────────────────────────────
903
+
904
+ /** What a visitor's page is made from; not READMEs, scripts or config. */
905
+ const APP_SOURCE = /^(src|app|pages|components|lib)\//;
906
+
907
+ /**
908
+ * The files that name `path` as a link: a quoted address (with or without a trailing slash, an
909
+ * anchor or a query) in code or content, other than the page's own files (`own`: its file and the
910
+ * content it owns) and its route's `path`. Built at runtime (`/${slug}`) is not found.
911
+ */
912
+ export function linksTo(path, { paths, text, own = [] }) {
913
+ if (path === "/") return [];
914
+ const mine = new Set(own);
915
+ return [...(linkIndex(paths, text).get(path) ?? [])].filter((p) => !mine.has(p)).sort();
916
+ }
917
+
918
+ /**
919
+ * Every quoted address in the app's source, to the files that name it: read once per set of files,
920
+ * not once per page. The same quotes as a search for each address would find: an opening quote, the
921
+ * address, an optional trailing slash, anchor or query, and the same quote (the closing one may open
922
+ * the next); not a route's own `path` or `pad`.
923
+ * @type {WeakMap<(path: string) => string | null, { paths: string[], index: Map<string, Set<string>> }>}
924
+ */
925
+ const linkIndexOf = new WeakMap();
926
+ const QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
927
+
928
+ function linkIndex(paths, text) {
929
+ const kept = linkIndexOf.get(text);
930
+ if (kept?.paths === paths) return kept.index;
931
+ const index = new Map();
932
+ for (const p of paths) {
933
+ if (SKIP.test(p) || !APP_SOURCE.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
934
+ for (const [, , quoted] of (text(p) ?? "").matchAll(QUOTED_ADDRESS)) {
935
+ const bare = quoted.replace(/[#?][\s\S]*$/, "");
936
+ const address = bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare;
937
+ if (!index.has(address)) index.set(address, new Set());
938
+ index.get(address).add(p);
939
+ }
940
+ }
941
+ linkIndexOf.set(text, { paths, index });
942
+ return index;
943
+ }
944
+
945
+ // ── Kit installed ──────────────────────────────────────────────────────────
946
+
947
+ const CONFIGS = {
948
+ astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
949
+ "vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
950
+ next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
951
+ };
952
+
953
+ /** The files kitInstalled reads: the package and the build's config, relative to the app. */
954
+ export const kitFiles = (framework) => ["package.json", ...(CONFIGS[String(framework)] ?? [])];
955
+
956
+ /**
957
+ * The kit is a dependency, by one of the names that bring it (KITS), and the build's config uses
958
+ * that one, comments not counted.
959
+ */
960
+ export function kitInstalled({ framework, text }) {
961
+ let pkg = null;
962
+ try {
963
+ pkg = JSON.parse(text("package.json") ?? "null");
964
+ } catch {}
965
+ if (!pkg) return false;
966
+ const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
967
+ return (KITS[String(framework)] ?? []).some((name) => !!(pkg.dependencies?.[name] || pkg.devDependencies?.[name]) && configs.some((c) => c.includes(name)));
968
+ }
969
+
970
+ // ── Leak check ─────────────────────────────────────────────────────────────
971
+
972
+ const normal = (s) => s.replace(/\s+/g, " ");
973
+
974
+ /**
975
+ * Sentences in a text: runs of words and plain punctuation, four words or more, most of them
976
+ * plain words (not a class list such as "flex items-center px-4"). Each as its longest piece of
977
+ * plain ASCII without quotes, which any build writes the same way.
978
+ */
979
+ export function sentences(src) {
980
+ const out = [];
981
+ for (const m of normal(src).matchAll(/[\p{L}\p{N}][\p{L}\p{N} ,.!?;'’-]*/gu)) {
982
+ const run = m[0].trim();
983
+ const words = run.split(" ");
984
+ if (run.length < 24 || words.length < 4) continue;
985
+ // A word as people write it: no camelCase, no class name, no dotted name.
986
+ const plain = words.filter((w) => /^(\p{Lu}?\p{Ll}+|\p{Lu}+)[,.!?;]?$/u.test(w)).length;
987
+ if (plain / words.length < 0.75) continue;
988
+ const piece = run
989
+ .split(/['’]|[^\x20-\x7e]/)
990
+ .map((s) => s.trim())
991
+ .sort((a, b) => b.length - a.length)[0];
992
+ if (piece && piece.length >= 20 && piece.split(" ").length >= 3) out.push(piece);
993
+ }
994
+ return out;
995
+ }
996
+
997
+ /** The strings of a JSON file, depth first. */
998
+ function jsonStrings(text) {
999
+ const out = [];
1000
+ const walk = (v) => {
1001
+ if (typeof v === "string") out.push(v);
1002
+ else if (Array.isArray(v)) v.forEach(walk);
1003
+ else if (isObject(v)) Object.values(v).forEach(walk);
1004
+ };
1005
+ try {
1006
+ walk(JSON.parse(text));
1007
+ } catch {}
1008
+ return out;
1009
+ }
1010
+
1011
+ /**
1012
+ * Text only a draft page has: the sentences of its file and of the content it owns that no other
1013
+ * file of the app holds. A production build that still contains one of them has leaked the page.
1014
+ * At most `max`, longest first.
1015
+ */
1016
+ export function leakPrints(check, { paths, text, max = 24 }) {
1017
+ if (!check.ok) return [];
1018
+ const mine = new Set([check.page.file, ...check.content]);
1019
+ const candidates = new Set();
1020
+ // Comments never reach a visitor; only what the page says.
1021
+ const own = stripComments(text(check.page.file) ?? "").replace(/<!--[\s\S]*?-->/g, " ");
1022
+ for (const s of sentences(own)) candidates.add(s);
1023
+ for (const f of check.content) for (const v of jsonStrings(text(f) ?? "")) for (const s of sentences(v)) candidates.add(s);
1024
+ if (!candidates.size) return [];
1025
+ const others = paths
1026
+ .filter((p) => !mine.has(p) && !SKIP.test(p) && (CODE.test(p) || p.endsWith(".json")))
1027
+ .map((p) => normal(text(p) ?? ""))
1028
+ .join("\n");
1029
+ return [...candidates]
1030
+ .filter((s) => !others.includes(s))
1031
+ .sort((a, b) => b.length - a.length || (a < b ? -1 : 1))
1032
+ .slice(0, max);
1033
+ }
1034
+
1035
+ /** The prints a built file still holds. */
1036
+ export const leaksIn = (output, prints) => {
1037
+ const text = normal(output);
1038
+ return prints.filter((p) => text.includes(p));
1039
+ };
1040
+
1041
+ // ── Page lists in the output ───────────────────────────────────────────────
1042
+
1043
+ /** A sitemap without the draft addresses (any origin). */
1044
+ export function withoutInSitemap(xml, drafts) {
1045
+ return xml.replace(/<url>[\s\S]*?<\/url>/g, (block) => {
1046
+ const loc = block.match(/<loc>\s*([^<\s]+)\s*<\/loc>/)?.[1];
1047
+ if (!loc) return block;
1048
+ let path;
1049
+ try {
1050
+ path = normalisePath(new URL(loc, "https://x.invalid").pathname);
1051
+ } catch {
1052
+ return block;
1053
+ }
1054
+ return drafts.includes(path) ? "" : block;
1055
+ });
1056
+ }
1057
+
1058
+ /** comment-modus/pages.json without the draft addresses. */
1059
+ export function withoutInPageList(json, drafts) {
1060
+ const list = JSON.parse(json);
1061
+ return Array.isArray(list) ? JSON.stringify(list.filter((p) => !drafts.includes(normalisePath(p?.path ?? "")))) : json;
1062
+ }
1063
+
1064
+ /** comment-modus/content-map.json without the files a draft owns, wherever a file is a key. */
1065
+ export function withoutInContentMap(json, files) {
1066
+ const map = JSON.parse(json);
1067
+ if (!isObject(map)) return json;
1068
+ const gone = new Set(files);
1069
+ for (const [key, value] of Object.entries(map)) {
1070
+ if (isObject(value)) for (const f of Object.keys(value)) if (gone.has(f)) delete value[f];
1071
+ if (Array.isArray(value)) map[key] = value.filter((v) => !(typeof v === "string" && gone.has(v)));
1072
+ }
1073
+ return JSON.stringify(map);
1074
+ }