@unbase-app/cli 0.4.1 → 0.6.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/lib/readers.mjs CHANGED
@@ -92,15 +92,15 @@ async function textLocation(repo, app, files) {
92
92
  const g = groupOf(page);
93
93
  groups.set(g, [...groups.get(g) ?? [], page]);
94
94
  }
95
- const literal2 = /* @__PURE__ */ new Map();
95
+ const literal3 = /* @__PURE__ */ new Map();
96
96
  await Promise.all(
97
97
  spread(groups, PAGE_CAP).map(async (page) => {
98
98
  const source = await repo.read(join(app.path, `src/pages/${page}`));
99
- if (source !== null) literal2.set(page, literalText(source));
99
+ if (source !== null) literal3.set(page, literalText(source));
100
100
  })
101
101
  );
102
102
  const result = [...groups].map(([group, list]) => {
103
- const total = list.reduce((sum, p) => sum + (literal2.get(p) ?? 0), 0);
103
+ const total = list.reduce((sum, p) => sum + (literal3.get(p) ?? 0), 0);
104
104
  return { group, pages: list.length, literal: total, in: total > LITERAL_IN_CODE ? "code" : "content" };
105
105
  });
106
106
  const inCode = result.filter((g) => g.in === "code").length;
@@ -144,6 +144,8 @@ var astro = {
144
144
 
145
145
  // supabase/functions/_shared/framework-packages.ts
146
146
  var COMMENT_MODE = "@jens4m/comment-modus";
147
+ var COMMENT_LAYER = "@unbase-app/layer";
148
+ var COMMENT_MODES = [COMMENT_LAYER, COMMENT_MODE];
147
149
  var FRAMEWORK_PACKAGES = [
148
150
  {
149
151
  id: "astro",
@@ -152,7 +154,7 @@ var FRAMEWORK_PACKAGES = [
152
154
  config: "astro.config",
153
155
  call: "unbase()",
154
156
  agents: "agents/astro.md",
155
- replaces: [COMMENT_MODE, "@jens4m/unbase-pages"],
157
+ replaces: [COMMENT_LAYER, COMMENT_MODE, "@jens4m/unbase-pages"],
156
158
  // unbase({ project: commentModusConfig.project, … }): the config imports comment-modus.json.
157
159
  comments: { calls: ["unbase"], options: true, readsLink: false },
158
160
  schemas: "src/content/.schemas/"
@@ -270,9 +272,27 @@ function packageManager(repo, appPath, root) {
270
272
  const field2 = root?.pkg.packageManager;
271
273
  return typeof field2 === "string" ? field2.split("@")[0] || null : null;
272
274
  }
273
- function cmsOf(repo, app, root) {
274
- const deps = { ...root?.deps ?? {}, ...app.deps };
275
- const files = within(repo.paths, app.path);
275
+ function linkedOf(app, all) {
276
+ const byName = /* @__PURE__ */ new Map();
277
+ for (const a of all) if (typeof a.pkg.name === "string" && a.path !== app.path) byName.set(a.pkg.name, a);
278
+ const linked = [];
279
+ const seen = /* @__PURE__ */ new Set([app.path]);
280
+ const queue = [app];
281
+ while (queue.length) {
282
+ for (const dep of Object.keys(queue.shift().deps)) {
283
+ const found = byName.get(dep);
284
+ if (!found || seen.has(found.path)) continue;
285
+ seen.add(found.path);
286
+ linked.push(found);
287
+ queue.push(found);
288
+ }
289
+ }
290
+ return linked;
291
+ }
292
+ var allDeps = (app, root, linked) => ({ ...root?.deps ?? {}, ...Object.assign({}, ...linked.map((l) => l.deps)), ...app.deps });
293
+ function cmsOf(repo, app, root, linked) {
294
+ const deps = allDeps(app, root, linked);
295
+ const files = [app, ...linked].flatMap((a) => within(repo.paths, a.path));
276
296
  return CMS.filter((c) => Object.keys(deps).some((d) => c.deps.test(d)) || c.config && files.some((f) => c.config.test(f))).map(({ id, name }) => ({
277
297
  id,
278
298
  name
@@ -369,8 +389,8 @@ async function imageHostsOf(read, paths) {
369
389
  }
370
390
  return [];
371
391
  }
372
- function servicesOf(app, root) {
373
- const deps = Object.keys({ ...root?.deps ?? {}, ...app.deps });
392
+ function servicesOf(app, root, linked) {
393
+ const deps = Object.keys(allDeps(app, root, linked));
374
394
  return [...CMS, ...SERVICES].filter((s) => deps.some((d) => s.deps.test(d))).map(({ id, name }) => ({ id, name }));
375
395
  }
376
396
  async function detect(repo, branch, truncated, appPath) {
@@ -407,9 +427,11 @@ async function detect(repo, branch, truncated, appPath) {
407
427
  }
408
428
  if (!chosen) return { ...empty, app_path: "", framework: !all.length && repo.paths.includes("index.html") ? HTML : null };
409
429
  const fw = frameworkOf(chosen.deps);
430
+ const linked = linkedOf(chosen, all);
410
431
  const adapter = fw ? ADAPTERS.find((a) => a.framework === fw.id) ?? null : null;
411
432
  const found = adapter ? await adapter.detect(repo, chosen) : { text: null, site: null, project: null };
412
- const cmRange = chosen.deps[COMMENT_MODE] ?? root?.deps[COMMENT_MODE];
433
+ const cmName = COMMENT_MODES.find((n) => chosen.deps[n] ?? root?.deps[n]);
434
+ const cmRange = cmName ? chosen.deps[cmName] ?? root?.deps[cmName] : void 0;
413
435
  const carrier = fw && frameworkPackage(fw.id)?.comments ? frameworkPackage(fw.id).packages[0] ?? null : null;
414
436
  const carried = !!carrier && !!(chosen.deps[carrier] ?? root?.deps[carrier]) && !found.commentsOff;
415
437
  const { settings, truncated: settingsTruncated } = await settingsOf(repo, chosen.path, fw?.id ?? null);
@@ -420,130 +442,119 @@ async function detect(repo, branch, truncated, appPath) {
420
442
  framework: fw ? { id: fw.id, name: fw.name, ...versionOf(chosen.deps[fw.dep]) } : null,
421
443
  adapter: adapter?.id ?? null,
422
444
  package_manager: packageManager(repo, chosen.path, root),
423
- cms: cmsOf(repo, chosen, root),
445
+ cms: cmsOf(repo, chosen, root, linked),
424
446
  comment_modus: cmRange || carried ? { state: "installed", version: cmRange ? versionOf(cmRange).version : null, site: found.site, project: found.project } : { state: "absent" },
425
447
  text: found.text,
426
448
  settings,
427
449
  settings_truncated: settingsTruncated,
428
- services: servicesOf(chosen, root),
450
+ services: servicesOf(chosen, root, linked),
429
451
  image_hosts: imageHosts,
430
452
  other_host: otherHostOf(repo.paths, chosen.path)
431
453
  };
432
454
  }
433
455
 
434
- // supabase/functions/_shared/html-head.ts
435
- var headPointer = (field2) => `/head/${field2}`;
436
- var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
437
- function decodeValue(raw) {
438
- return raw.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&([a-z]+);/gi, (m, n) => ENTITIES[n.toLowerCase()] ?? m).replace(/\s+/g, " ").trim();
439
- }
440
- function tagsIn(html, from, until) {
441
- const out = [];
442
- let i = from;
443
- while (i < until) {
444
- const lt = html.indexOf("<", i);
445
- if (lt < 0 || lt >= until) break;
446
- if (html.startsWith("<!--", lt)) {
447
- const close = html.indexOf("-->", lt + 4);
448
- i = close < 0 ? until : close + 3;
449
- continue;
450
- }
451
- const name = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(lt, lt + 64))?.[1];
452
- if (!name) {
453
- i = lt + 1;
454
- continue;
455
- }
456
- const attrs = [];
457
- let j = lt + 1 + name.length;
458
- let end = -1;
459
- while (j < html.length) {
460
- const c = html[j];
461
- if (c === ">") {
462
- end = j + 1;
463
- break;
464
- }
465
- if (/[\s/]/.test(c)) {
466
- j++;
467
- continue;
468
- }
469
- const m = /^([^\s"'>/=]+)(\s*=\s*)?/.exec(html.slice(j, j + 256));
470
- if (!m) {
471
- j++;
472
- continue;
473
- }
474
- j += m[0].length;
475
- if (!m[2]) {
476
- attrs.push({ name: m[1].toLowerCase(), value: "", start: j, end: j, quote: null });
477
- continue;
478
- }
479
- const q = html[j];
480
- if (q === '"' || q === "'") {
481
- const close = html.indexOf(q, j + 1);
482
- if (close < 0) break;
483
- attrs.push({ name: m[1].toLowerCase(), value: html.slice(j + 1, close), start: j + 1, end: close, quote: q });
484
- j = close + 1;
485
- } else {
486
- const bare = /^[^\s>]*/.exec(html.slice(j))[0];
487
- attrs.push({ name: m[1].toLowerCase(), value: bare, start: j, end: j + bare.length, quote: null });
488
- j += bare.length;
456
+ // supabase/functions/unbase-projects/settings-content.ts
457
+ var PAGE_FIELDS = {
458
+ title: { name: "titel", kind: "text" },
459
+ description: { name: "beschrijving", kind: "text" },
460
+ socialImage: { name: "ogImage", kind: "image" },
461
+ noindex: { name: "noindex", kind: "boolean" },
462
+ siteSearch: { name: "zoeken", kind: "boolean" }
463
+ };
464
+ var SITE_FIELDS = {
465
+ name: { name: "naam", kind: "text" },
466
+ description: { name: "beschrijving", kind: "text" },
467
+ language: { name: "taal", kind: "text" },
468
+ faviconLight: { name: "favicon", kind: "image" },
469
+ faviconDark: { name: "faviconDonker", kind: "image" },
470
+ socialImage: { name: "ogImage", kind: "image" },
471
+ analyticsId: { name: "googleAnalytics", kind: "text" }
472
+ };
473
+ var CONTENT = "src/content";
474
+ var SCHEMAS = `${CONTENT}/.schemas`;
475
+ var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
476
+ var AT_ONCE2 = 8;
477
+ var MAX_ROUTE_FILES = 300;
478
+ async function inTurns(items, work) {
479
+ const out = new Array(items.length);
480
+ let next = 0;
481
+ await Promise.all(
482
+ Array.from({ length: Math.min(AT_ONCE2, items.length) }, async () => {
483
+ while (next < items.length) {
484
+ const i = next++;
485
+ out[i] = await work(items[i]);
489
486
  }
490
- }
491
- if (end < 0) break;
492
- out.push({ name: name.toLowerCase(), start: lt, end, attrs });
493
- i = end;
494
- if (/^(script|style)$/i.test(name)) {
495
- const close = html.toLowerCase().indexOf(`</${name.toLowerCase()}`, end);
496
- i = close < 0 ? until : close;
497
- }
498
- }
487
+ })
488
+ );
499
489
  return out;
500
490
  }
501
- var attrOf = (tag, name) => tag.attrs.find((a) => a.name === name);
502
- var spanOf = (a) => ({ start: a.start, end: a.end, mode: "attr", quote: a.quote });
503
- var plain = (raw) => !/[{}]|<%|%>/.test(raw);
504
- function readHead(html) {
505
- const out = {};
506
- const lower = html.toLowerCase();
507
- const headAt = lower.search(/<head[\s>]/);
508
- const bodyAt = lower.search(/<body[\s>]/);
509
- const headEnd = lower.indexOf("</head");
510
- const until = headEnd >= 0 ? headEnd : bodyAt >= 0 ? bodyAt : html.length;
511
- if (headAt < 0) return out;
512
- const htmlTag = tagsIn(html, 0, headAt).find((t) => t.name === "html");
513
- const lang = htmlTag && attrOf(htmlTag, "lang");
514
- if (lang && lang.value.trim() && plain(lang.value)) out.language = { value: decodeValue(lang.value), spans: [spanOf(lang)] };
515
- const tags = tagsIn(html, headAt, until);
516
- const metas = tags.filter((t) => t.name === "meta");
517
- const meta = (key) => metas.filter((t) => [attrOf(t, "name")?.value, attrOf(t, "property")?.value].some((v) => v?.trim().toLowerCase() === key)).map((t) => attrOf(t, "content")).filter((a) => !!a);
518
- const fromMeta = (key, copies) => {
519
- const found = meta(key);
520
- if (found.length !== 1 || !plain(found[0].value) || !found[0].value.trim()) return void 0;
521
- const value = decodeValue(found[0].value);
522
- return { value, spans: [spanOf(found[0]), ...copiesOf(value, copies)] };
523
- };
524
- const copiesOf = (value, keys) => keys.flatMap((k) => meta(k)).filter((a) => plain(a.value) && decodeValue(a.value) === value).map(spanOf);
525
- const titles = tags.filter((t) => t.name === "title");
526
- if (titles.length === 1) {
527
- const t = titles[0];
528
- const close = lower.indexOf("</title", t.end);
529
- const raw = close >= 0 ? html.slice(t.end, close) : "";
530
- if (close >= 0 && raw.trim() && !raw.includes("<") && plain(raw)) {
531
- const value = decodeValue(raw);
532
- out.title = { value, spans: [{ start: t.end, end: close, mode: "text", quote: null }, ...copiesOf(value, ["og:title", "twitter:title"])] };
533
- }
491
+ var parse = (text) => {
492
+ if (text === null) return null;
493
+ try {
494
+ return JSON.parse(text);
495
+ } catch {
496
+ return null;
534
497
  }
535
- const description = fromMeta("description", ["og:description", "twitter:description"]);
536
- if (description) out.description = description;
537
- const image = fromMeta("og:image", ["twitter:image"]);
538
- if (image) out.image = image;
539
- const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
540
- const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
541
- for (const [field2, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
542
- const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
543
- const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
544
- if (href && href.value.trim() && plain(href.value)) out[field2] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
498
+ };
499
+ function valueOf(v, kind) {
500
+ if (kind === "boolean") return typeof v === "boolean" ? String(v) : null;
501
+ return typeof v === "string" ? v : null;
502
+ }
503
+ function fieldsOf(names, data, allowed, file, base) {
504
+ const fields = {};
505
+ for (const [field2, { name, kind }] of Object.entries(names)) {
506
+ const value = valueOf(data?.[name], kind);
507
+ const there = data?.[name] !== void 0;
508
+ if (there && value === null) continue;
509
+ if (!there && !allowed[name]) continue;
510
+ fields[field2] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
545
511
  }
546
- return out;
512
+ return fields;
513
+ }
514
+ async function contentSettings(repo, appPath) {
515
+ const at3 = (p) => join(appPath, p);
516
+ const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at3(SCHEMAS)}/`) && p.endsWith(".schema.json"));
517
+ if (!schemaPaths.length) return null;
518
+ const named = (p) => p.slice(at3(SCHEMAS).length + 1, -".schema.json".length);
519
+ const schemas = /* @__PURE__ */ new Map();
520
+ const [legacyMap, map, ...read] = await inTurns([at3(`${SCHEMAS}/collecties.json`), at3(`${SCHEMAS}/collections.json`), ...schemaPaths], (p) => repo.read(p));
521
+ schemaPaths.forEach((p, i) => {
522
+ const s = parse(read[i] ?? null);
523
+ if (s && typeof s === "object") schemas.set(named(p), s);
524
+ });
525
+ const elsewhere = { ...parse(legacyMap ?? null) ?? {}, ...parse(map ?? null) ?? {} };
526
+ const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at3(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at3(SCHEMAS)}/`));
527
+ const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at3(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
528
+ const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
529
+ const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
530
+ const pages = {};
531
+ let routes = null;
532
+ if (routeCollection) {
533
+ const [collection, schema] = routeCollection;
534
+ const allowed = schema.properties.seo?.properties ?? {};
535
+ const files = filesOf(collection).slice(0, MAX_ROUTE_FILES);
536
+ const datas = await inTurns(files, async (p) => parse(await repo.read(p)));
537
+ files.forEach((file, i) => {
538
+ const data = datas[i];
539
+ if (!data || typeof data.pad !== "string" || !ROUTE.test(data.pad)) return;
540
+ const seo = data.seo && typeof data.seo === "object" && !Array.isArray(data.seo) ? data.seo : {};
541
+ pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
542
+ });
543
+ const dir = files[0] ? files[0].slice(appPath ? appPath.length + 1 : 0).replace(/\/[^/]+$/, "") : `${CONTENT}/${collection}`;
544
+ const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
545
+ routes = { dir, fields, ...schema["x-item-fields"] === true ? { itemFields: true } : {} };
546
+ }
547
+ const siteCollection = [...schemas].find(([, s]) => (s["x-settings"] ?? s["x-instellingen"]) === "site");
548
+ let site = null;
549
+ const siteFile = siteCollection && filesOf(siteCollection[0])[0];
550
+ if (siteCollection && siteFile) {
551
+ const data = parse(await repo.read(siteFile));
552
+ if (data && typeof data === "object" && !Array.isArray(data)) {
553
+ site = fieldsOf(SITE_FIELDS, data, siteCollection[1].properties ?? {}, siteFile.slice(appPath ? appPath.length + 1 : 0), "");
554
+ }
555
+ }
556
+ if (!Object.keys(pages).length && !routes && !site) return null;
557
+ return { pages, routes, site };
547
558
  }
548
559
 
549
560
  // supabase/functions/_shared/pages-core.mjs
@@ -552,16 +563,23 @@ __export(pages_core_exports, {
552
563
  DRAFTABLE: () => DRAFTABLE,
553
564
  KIT: () => KIT,
554
565
  KITS: () => KITS,
566
+ OBJECT_ROUTES_SINCE: () => OBJECT_ROUTES_SINCE,
555
567
  PAGE_ACTION_FRAMEWORKS: () => PAGE_ACTION_FRAMEWORKS,
556
568
  PAGE_FILE: () => PAGE_FILE,
569
+ PAGE_OPERATIONS: () => PAGE_OPERATIONS,
557
570
  REDIRECTS_SINCE: () => REDIRECTS_SINCE,
571
+ adapterOf: () => adapterOf,
572
+ createCapability: () => createCapability,
573
+ createdAddress: () => createdAddress,
558
574
  deployContext: () => deployContext,
559
575
  discover: () => discover,
560
576
  draftCheck: () => draftCheck,
561
577
  draftPaths: () => draftPaths,
562
578
  draftPlan: () => draftPlan,
579
+ dynamicSegment: () => dynamicSegment,
563
580
  folderPaths: () => folderPaths,
564
581
  importGraph: () => importGraph,
582
+ isPattern: () => isPattern,
565
583
  kitFiles: () => kitFiles,
566
584
  kitInstalled: () => kitInstalled,
567
585
  kitRedirects: () => kitRedirects,
@@ -579,35 +597,154 @@ __export(pages_core_exports, {
579
597
  planRedirect: () => planRedirect,
580
598
  redirectsFor: () => redirectsFor,
581
599
  removeRoutes: () => removeRoutes,
600
+ requestOf: () => requestOf,
582
601
  resolveImport: () => resolveImport,
602
+ routeTest: () => routeTest,
583
603
  segmentFiles: () => segmentFiles,
584
604
  sentences: () => sentences,
585
605
  siteRedirectList: () => siteRedirectList,
586
606
  siteRedirects: () => siteRedirects,
587
607
  slugOf: () => slugOf,
588
608
  stripComments: () => stripComments,
609
+ templateMatches: () => templateMatches,
610
+ templateTest: () => templateTest,
589
611
  validAddress: () => validAddress,
590
612
  withoutInContentMap: () => withoutInContentMap,
591
613
  withoutInPageList: () => withoutInPageList,
592
614
  withoutInSitemap: () => withoutInSitemap
593
615
  });
616
+
617
+ // supabase/functions/_shared/pages-address.mjs
618
+ var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
619
+ function normalisePath(p) {
620
+ const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
621
+ return s || "/";
622
+ }
623
+ function slugOf(name) {
624
+ return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
625
+ }
626
+ var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
627
+ function validAddress(p) {
628
+ const at3 = normalisePath(p);
629
+ if (at3.length > 200) return false;
630
+ if (at3 === "/") return true;
631
+ return at3.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
632
+ }
633
+ var isPattern = (path) => /[[\]:*]/.test(path);
634
+ function dynamicSegment(segment) {
635
+ if (segment === "*") return { name: "", rest: true };
636
+ const bracket = segment.match(/^\[{1,2}(\.\.\.)?([^\]]+?)\]{1,2}$/);
637
+ if (bracket) return { name: (
638
+ /** @type {string} */
639
+ bracket[2]
640
+ ), rest: !!bracket[1] };
641
+ const colon = segment.match(/^:([^?]+)\??$/);
642
+ return colon ? { name: (
643
+ /** @type {string} */
644
+ colon[1]
645
+ ), rest: false } : null;
646
+ }
647
+ function routeTest(pattern) {
648
+ let re = "";
649
+ for (const segment of pattern.split("/").filter(Boolean)) {
650
+ const d = dynamicSegment(segment);
651
+ if (!d) {
652
+ re += `/${escape(segment)}`;
653
+ continue;
654
+ }
655
+ const optional = segment.startsWith("[[") || segment.endsWith("?");
656
+ if (d.rest) re += optional ? "(?:/[^/]+)*" : "(?:/[^/]+)+";
657
+ else re += optional ? "(?:/[^/]+)?" : "/[^/]+";
658
+ }
659
+ return new RegExp(`^${re || "/"}/?$`);
660
+ }
661
+ function templateMatches(template, path) {
662
+ const t = template.split("/");
663
+ const p = path.split("/");
664
+ 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));
665
+ return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
666
+ }
667
+ function redirectMatches(source, path) {
668
+ if (!/\[|:/.test(source)) return false;
669
+ const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => i % 2 ? part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+" : escape(part)).join("")}$`);
670
+ return re.test(path);
671
+ }
672
+ function templateTest(pattern) {
673
+ const segment = (s) => /^\[\[?\.\.\./.test(s) || s === "*" ? ".+" : /^\[.+\]$/.test(s) || s.startsWith(":") ? "[^/]+" : escape(s);
674
+ return new RegExp(`^${pattern.split("/").map(segment).join("/")}$`);
675
+ }
676
+
677
+ // supabase/functions/_shared/pages-core.mjs
594
678
  var PAGE_FILE = "unbase.pages.json";
595
679
  var KIT = "@unbase-app/pages";
596
- var KITS = {
597
- astro: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
598
- "vite-react": [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
599
- next: ["@unbase-app/next"]
680
+ var ADAPTERS2 = {
681
+ astro: {
682
+ kits: [KIT, "@unbase-app/astro", "@jens4m/unbase-pages"],
683
+ configs: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
684
+ listTools: [],
685
+ discover: (kept) => ({ pages: astroPages(kept), notFound: null }),
686
+ acts: true,
687
+ routeLines: false,
688
+ segments: false,
689
+ configSources: astroConfigSources,
690
+ configRedirects: astroConfigRedirects,
691
+ starter: astroStarter
692
+ },
693
+ "vite-react": {
694
+ kits: [KIT, "@unbase-app/vite", "@jens4m/unbase-pages"],
695
+ configs: ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
696
+ listTools: [],
697
+ discover: (kept, text) => reactRouterPages(kept, text),
698
+ acts: true,
699
+ routeLines: true,
700
+ segments: false,
701
+ redirect: ({ prefix, source, base, destBase }) => ({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix }),
702
+ canCreate: (discovered, kept, text) => siblingRoutes(discovered, text).length ? { ok: true } : { ok: false, reason: "routes_unread" },
703
+ starter: reactRouterStarter
704
+ },
705
+ next: {
706
+ kits: ["@unbase-app/next"],
707
+ configs: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"],
708
+ listTools: ["next-sitemap"],
709
+ discover: (kept) => ({ pages: nextPages(kept), notFound: null }),
710
+ acts: true,
711
+ routeLines: false,
712
+ segments: true,
713
+ configSources: nextConfigSources,
714
+ configRedirects: nextConfigRedirects,
715
+ redirect: ({ prefix, source, destination: destination2, base, destBase }) => ({
716
+ source: prefix ? `${base === "/" ? "" : base}/:path*` : source,
717
+ destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination2,
718
+ permanent: true
719
+ }),
720
+ canCreate: (discovered, kept) => discovered.pages.some((p) => p.file && routesBase(p.file)) || kept.some((p) => /^(src\/)?app\/layout\.(tsx|jsx|js|ts)$/.test(p)) ? { ok: true } : { ok: false, reason: "unparsed" },
721
+ starter: nextStarter
722
+ },
723
+ html: {
724
+ kits: [],
725
+ configs: [],
726
+ listTools: [],
727
+ discover: (kept) => ({ pages: htmlPages(kept), notFound: null }),
728
+ acts: true,
729
+ routeLines: false,
730
+ segments: false,
731
+ destination: (page, to) => htmlDestination(page, to),
732
+ folderDirs: (at3, below) => below.length && below.every((p) => p.file?.startsWith(`${at3.slice(1)}/`)) ? [at3.slice(1)] : null,
733
+ links: (p) => /\.html?$/.test(p),
734
+ relativeLinks: true,
735
+ canCreate: (discovered) => discovered.pages.length ? { ok: true } : { ok: false, reason: "unparsed" },
736
+ starter: htmlStarter
737
+ }
600
738
  };
739
+ var adapterOf = (framework) => Object.prototype.hasOwnProperty.call(ADAPTERS2, String(framework)) ? ADAPTERS2[String(framework)] : null;
740
+ var FRAMEWORKS2 = Object.keys(ADAPTERS2);
741
+ var KITS = Object.fromEntries(FRAMEWORKS2.filter((f) => ADAPTERS2[f].kits.length).map((f) => [f, ADAPTERS2[f].kits]));
601
742
  var DRAFTABLE = Object.keys(KITS);
602
743
  var EXTS = [".tsx", ".ts", ".jsx", ".js", ".mjs", ".mts", ".astro", ".vue", ".svelte", ".json"];
603
744
  var CODE = /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html)$/;
604
745
  var SKIP2 = /(^|\/)(node_modules|dist|build|\.git|\.astro|\.next|\.vercel|\.output)(\/|$)/;
605
746
  var isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
606
- var escape = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
607
- function normalisePath(p) {
608
- const s = `/${String(p)}`.replace(/\/{2,}/g, "/").replace(/\/+$/, "");
609
- return s || "/";
610
- }
747
+ var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
611
748
  function parsePageFile(text) {
612
749
  if (text == null) return { ok: true, exists: false, pages: {}, folders: {}, redirects: {} };
613
750
  const fail = (error) => ({ ok: (
@@ -877,14 +1014,212 @@ function importedComponents(src) {
877
1014
  out.set(m[1], { spec: m[2], kind: "lazy" });
878
1015
  return out;
879
1016
  }
1017
+ var ROUTER_CALL = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/g;
1018
+ var MAKES_ROUTER = /\b(?:create(?:Browser|Hash|Memory|Static)Router|useRoutes)\s*\(/;
1019
+ var IMPORTS_ROUTER = /from\s*["']react-router(-dom)?["']/;
1020
+ var skipWs = (src, i) => {
1021
+ while (i < src.length && /\s/.test(src[i])) i++;
1022
+ return i;
1023
+ };
1024
+ function closing(src, i) {
1025
+ let depth = 0;
1026
+ for (let j = i; j < src.length; j++) {
1027
+ const c = src[j];
1028
+ if (c === '"' || c === "'" || c === "`") {
1029
+ j = stringEnd(src, j) - 1;
1030
+ continue;
1031
+ }
1032
+ if (c === "{" || c === "[" || c === "(") depth++;
1033
+ else if ((c === "}" || c === "]" || c === ")") && --depth === 0) return j + 1;
1034
+ }
1035
+ return src.length;
1036
+ }
1037
+ function valueEnd(src, i, end) {
1038
+ let depth = 0;
1039
+ while (i < end) {
1040
+ const c = src[i];
1041
+ if (c === '"' || c === "'" || c === "`") {
1042
+ i = stringEnd(src, i);
1043
+ continue;
1044
+ }
1045
+ if (c === "{" || c === "[" || c === "(") depth++;
1046
+ else if (c === "}" || c === "]" || c === ")") {
1047
+ if (depth === 0) return i;
1048
+ depth--;
1049
+ } else if (c === "," && depth === 0) return i;
1050
+ i++;
1051
+ }
1052
+ return i;
1053
+ }
1054
+ function arrayElements(src, at3) {
1055
+ const end = closing(src, at3) - 1;
1056
+ const out = [];
1057
+ let i = at3 + 1;
1058
+ while (i < end) {
1059
+ i = skipWs(src, i);
1060
+ if (i >= end) break;
1061
+ if (src[i] === ",") {
1062
+ i++;
1063
+ continue;
1064
+ }
1065
+ const stop = valueEnd(src, i, end);
1066
+ let e = stop;
1067
+ while (e > i && /\s/.test(src[e - 1])) e--;
1068
+ if (e > i) out.push({ start: i, end: src[i] === "{" ? closing(src, i) : e });
1069
+ i = stop;
1070
+ }
1071
+ return out;
1072
+ }
1073
+ function objectEntries(src, at3) {
1074
+ const end = closing(src, at3) - 1;
1075
+ const out = [];
1076
+ let i = at3 + 1;
1077
+ while (i < end) {
1078
+ i = skipWs(src, i);
1079
+ if (i >= end) break;
1080
+ if (src[i] === ",") {
1081
+ i++;
1082
+ continue;
1083
+ }
1084
+ const stop = valueEnd(src, i, end);
1085
+ const key = src.slice(i, stop).match(/^(["']?)([A-Za-z_$][\w$]*)\1\s*:\s*/);
1086
+ if (key) {
1087
+ const valueStart = i + key[0].length;
1088
+ let e = stop;
1089
+ while (e > valueStart && /\s/.test(src[e - 1])) e--;
1090
+ out.push({ key: key[2], valueStart, valueEnd: e });
1091
+ }
1092
+ i = stop;
1093
+ }
1094
+ return out;
1095
+ }
1096
+ function literalString(value) {
1097
+ const lit = value.trim().match(/^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/);
1098
+ return lit ? lit.slice(1).find((v) => v !== void 0) ?? "" : false;
1099
+ }
1100
+ function arrayDeclared(src, name) {
1101
+ const m = new RegExp(`(?:^|[;\\s])(?:export\\s+)?(?:const|let|var)\\s+${escape2(name)}\\s*(?::[^=;]+)?=\\s*`).exec(src);
1102
+ if (!m) return null;
1103
+ const at3 = skipWs(src, m.index + m[0].length);
1104
+ return src[at3] === "[" ? at3 : null;
1105
+ }
1106
+ function defaultArray(src) {
1107
+ const m = src.match(/\bexport\s+default\s+/);
1108
+ if (!m) return null;
1109
+ const at3 = skipWs(src, m.index + m[0].length);
1110
+ if (src[at3] === "[") return at3;
1111
+ const name = src.slice(at3).match(/^([A-Za-z_$][\w$]*)\s*;?/)?.[1];
1112
+ return name ? arrayDeclared(src, name) : null;
1113
+ }
1114
+ function importOf(src, name) {
1115
+ for (const m of src.matchAll(/import\s+(?:([A-Za-z_$][\w$]*)\s*,?\s*)?(?:\{([^}]*)\})?\s*from\s*["']([^"']+)["']/g)) {
1116
+ if (m[1] === name) return { spec: m[3], exported: null };
1117
+ for (const part of (m[2] ?? "").split(",")) {
1118
+ const [exported, local] = part.trim().split(/\s+as\s+/);
1119
+ if ((local ?? exported) === name && exported) return { spec: m[3], exported };
1120
+ }
1121
+ }
1122
+ return null;
1123
+ }
1124
+ function routeArrays(paths, text, have) {
1125
+ const out = /* @__PURE__ */ new Map();
1126
+ const add = (f, at3) => out.set(f, [.../* @__PURE__ */ new Set([...out.get(f) ?? [], at3])]);
1127
+ for (const file of paths) {
1128
+ if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP2.test(file)) continue;
1129
+ const raw = text(file);
1130
+ if (!raw || !IMPORTS_ROUTER.test(raw) || !MAKES_ROUTER.test(raw)) continue;
1131
+ const src = stripComments(raw);
1132
+ for (const m of src.matchAll(ROUTER_CALL)) {
1133
+ const i = skipWs(src, m.index + m[0].length);
1134
+ if (src[i] === "[") {
1135
+ add(file, i);
1136
+ continue;
1137
+ }
1138
+ const name = src.slice(i).match(/^([A-Za-z_$][\w$]*)\s*[,)]/)?.[1];
1139
+ if (!name) continue;
1140
+ const local = arrayDeclared(src, name);
1141
+ if (local !== null) {
1142
+ add(file, local);
1143
+ continue;
1144
+ }
1145
+ const imp = importOf(src, name);
1146
+ const target = imp ? resolveImport(file, imp.spec, have) : null;
1147
+ const other = target ? text(target) : null;
1148
+ if (!other) continue;
1149
+ const tsrc = stripComments(other);
1150
+ const at3 = imp.exported ? arrayDeclared(tsrc, imp.exported) : defaultArray(tsrc);
1151
+ if (at3 !== null) add(target, at3);
1152
+ }
1153
+ }
1154
+ return out;
1155
+ }
1156
+ function routeObjectPages({ file, src, at: at3, parent, have, imports, pages, found }) {
1157
+ for (const el of arrayElements(src, at3)) {
1158
+ if (src[el.start] !== "{") continue;
1159
+ const entries = objectEntries(src, el.start);
1160
+ const value = (key) => {
1161
+ const e = entries.find((x) => x.key === key);
1162
+ return e ? src.slice(e.valueStart, e.valueEnd) : null;
1163
+ };
1164
+ const index = /^true$/.test((value("index") ?? "").trim());
1165
+ const pathValue = value("path");
1166
+ const p = pathValue === null ? null : literalString(pathValue);
1167
+ const full = index ? normalisePath(parent) : p === null ? null : p === false ? false : p.startsWith("/") ? normalisePath(p) : normalisePath(`${parent}/${p}`);
1168
+ const childrenEntry = entries.find((x) => x.key === "children");
1169
+ const childAt = childrenEntry && src[childrenEntry.valueStart] === "[" ? childrenEntry.valueStart : null;
1170
+ const children = childAt !== null && arrayElements(src, childAt).length > 0;
1171
+ let component = null;
1172
+ let importKind = null;
1173
+ let target = null;
1174
+ let spec = null;
1175
+ const comp = (value("Component") ?? "").trim().match(/^([A-Z][\w$]*)$/)?.[1] ?? (value("element") ?? "").trim().match(/^<([A-Z][\w$]*)\b[^<]*\/>$/)?.[1];
1176
+ if (comp) {
1177
+ const imported = imports.get(comp);
1178
+ if (imported) {
1179
+ component = comp;
1180
+ importKind = imported.kind;
1181
+ target = resolveImport(file, imported.spec, have);
1182
+ }
1183
+ } else {
1184
+ const lazy = (value("lazy") ?? "").match(/import\(\s*(["'])([^"']+)\1\s*\)/);
1185
+ if (lazy) {
1186
+ spec = lazy[2];
1187
+ importKind = "inline";
1188
+ target = resolveImport(file, spec, have);
1189
+ }
1190
+ }
1191
+ if (full === false) pages.push({ path: `${normalisePath(parent)} (unknown)`, kind: "route", file: target, reason: "unparsed" });
1192
+ else if (full !== null) {
1193
+ if (full === "/*" || full.endsWith("/*") || full === "*") {
1194
+ if (full === "/*" && target) found.notFound = target;
1195
+ } else {
1196
+ const page = { path: full, kind: /(^|\/)(:|\*)|\?(\/|$)/.test(full) ? "template" : "route", file: target };
1197
+ if (target && importKind) page.router = { file, start: el.start, end: el.end, component, importKind, object: true, ...spec ? { spec } : {} };
1198
+ if (children) page.reason = "nested";
1199
+ else if (!target) page.reason = "unparsed";
1200
+ pages.push(page);
1201
+ }
1202
+ }
1203
+ if (childAt !== null) routeObjectPages({ file, src, at: childAt, parent: typeof full === "string" ? full : parent, have, imports, pages, found });
1204
+ }
1205
+ }
880
1206
  function reactRouterPages(paths, text, only = paths) {
881
1207
  const have = new Set(paths);
882
1208
  const pages = [];
883
- let notFound = null;
1209
+ const found = { notFound: null };
1210
+ const arrays = routeArrays(paths, text, have);
1211
+ for (const file of only) {
1212
+ const starts = arrays.get(file);
1213
+ if (!starts?.length) continue;
1214
+ const src = stripComments(text(file) ?? "");
1215
+ const imports = importedComponents(src);
1216
+ for (const at3 of starts) routeObjectPages({ file, src, at: at3, parent: "", have, imports, pages, found });
1217
+ }
1218
+ let notFound = found.notFound;
884
1219
  for (const file of only) {
885
1220
  if (!/\.(tsx|jsx|ts|js)$/.test(file) || SKIP2.test(file)) continue;
886
1221
  const raw = text(file);
887
- if (!raw || !raw.includes("<Route") || !/from\s*["']react-router(-dom)?["']/.test(raw)) continue;
1222
+ if (!raw || !raw.includes("<Route") || !IMPORTS_ROUTER.test(raw)) continue;
888
1223
  const src = stripComments(raw);
889
1224
  const imports = importedComponents(src);
890
1225
  const events = [];
@@ -926,9 +1261,17 @@ function reactRouterPages(paths, text, only = paths) {
926
1261
  }
927
1262
  return { pages, notFound };
928
1263
  }
1264
+ function routeSpan(src, router) {
1265
+ if (!router.object) return { start: router.start, end: router.end };
1266
+ let end = router.end;
1267
+ let i = router.end;
1268
+ while (i < src.length && (src[i] === " " || src[i] === " ")) i++;
1269
+ if (src[i] === ",") end = i + 1;
1270
+ return { start: router.start, end };
1271
+ }
929
1272
  function removeRoutes({ file, code, paths, text, drop }) {
930
1273
  const { pages } = reactRouterPages(paths, (p) => p === file ? code : text(p), [file]);
931
- const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...p.router }));
1274
+ const spans = pages.filter((p) => drop.includes(p.path) && p.router && !p.reason).map((p) => ({ path: p.path, ...routeSpan(code, p.router) }));
932
1275
  spans.sort((a, b) => b.start - a.start);
933
1276
  let out = code;
934
1277
  for (const s of spans) out = out.slice(0, s.start) + out.slice(s.end);
@@ -936,7 +1279,7 @@ function removeRoutes({ file, code, paths, text, drop }) {
936
1279
  }
937
1280
  function discover({ framework, paths, text }) {
938
1281
  const kept = paths.filter((p) => !SKIP2.test(p));
939
- const found = framework === "astro" ? { pages: astroPages(kept), notFound: null } : framework === "next" ? { pages: nextPages(kept), notFound: null } : framework === "vite-react" ? reactRouterPages(kept, text) : framework === "html" ? { pages: htmlPages(kept), notFound: null } : { pages: [], notFound: null };
1282
+ const found = adapterOf(framework)?.discover(kept, text) ?? { pages: [], notFound: null };
940
1283
  const seen = /* @__PURE__ */ new Set();
941
1284
  const pages = found.pages.filter((p) => seen.has(p.path) ? false : (seen.add(p.path), true)).sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
942
1285
  return { pages, notFound: found.notFound };
@@ -1008,7 +1351,7 @@ function contentReads(paths, text) {
1008
1351
  for (; ; ) {
1009
1352
  let grew = false;
1010
1353
  if (names.length) {
1011
- const naming = new RegExp(names.map(escape).join("|"));
1354
+ const naming = new RegExp(names.map(escape2).join("|"));
1012
1355
  for (const [p, src] of files) {
1013
1356
  if (picked.has(p) || !naming.test(src)) continue;
1014
1357
  picked.add(p);
@@ -1038,8 +1381,8 @@ function parseCode(p, src) {
1038
1381
  const body = braces >= 0 ? braced(code, braces) ?? "" : code.slice(at3, code.slice(at3).search(/;|\n\s*\n|$/) + at3);
1039
1382
  const start = braces >= 0 ? braces + 1 : at3;
1040
1383
  const naming = ASTRO_NAMED.test(body);
1041
- const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape(first)}\\b`).test(body));
1042
- const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : void 0;
1384
+ const byName = !!(naming && first && new RegExp(`\\b(?:${ASTRO_READS.join("|")})\\(\\s*${escape2(first)}\\b`).test(body));
1385
+ const entry = byName ? new RegExp(`\\bgetEntry\\(\\s*${escape2(first)}\\s*,\\s*["']([^"'\\n]+)["']`).exec(body)?.[1] : void 0;
1043
1386
  const direct = naming ? Array.from(body.matchAll(DIRECT), (d) => [d[1], d[2]]) : [];
1044
1387
  fns.push({ name, start, end: start + body.length, body, byName, entry, direct });
1045
1388
  }
@@ -1076,7 +1419,7 @@ function readsOver(files, parsed = /* @__PURE__ */ new Map()) {
1076
1419
  for (const [name, body] of bodies) {
1077
1420
  for (const fn of byName) {
1078
1421
  if (fn === name || ASTRO_READS.includes(fn) || !body.includes(fn)) continue;
1079
- for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
1422
+ for (const c of body.matchAll(new RegExp(`(?<![\\w$.])${escape2(fn)}\\(\\s*["']([^"'\\n]+)["']`, "g"))) addFixed(name, c[1], entryOf.get(fn));
1080
1423
  }
1081
1424
  }
1082
1425
  const calls = fixed2.size ? new Map([...bodies].map(([name, body]) => [name, new Set(Array.from(body.matchAll(CALL), (m) => m[1]))])) : /* @__PURE__ */ new Map();
@@ -1095,8 +1438,8 @@ function readsOver(files, parsed = /* @__PURE__ */ new Map()) {
1095
1438
  }
1096
1439
  }
1097
1440
  }
1098
- const helpers = fixed2.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed2.keys()].sort((a, b) => b.length - a.length).map(escape).join("|")})(?![\\w$])`, "g") : null;
1099
- const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
1441
+ const helpers = fixed2.size ? new RegExp(`(?<![\\w$.])(?:${[...fixed2.keys()].sort((a, b) => b.length - a.length).map(escape2).join("|")})(?![\\w$])`, "g") : null;
1442
+ const byNameCall = new RegExp(`(?<![\\w$.])(${[...byName].map(escape2).join("|")})\\(\\s*["']([^"'\\n]+)["']\\s*(?:,\\s*(?:["']([^"'\\n]+)["']|([^)\\s])))?`, "g");
1100
1443
  return { code, byName, byNameCall, entryOf, fixed: fixed2, astro: astro2, spans, helpers };
1101
1444
  }
1102
1445
  var CALL = /(?<![\w$.])([A-Za-z_$][\w$]*)\s*\(/g;
@@ -1274,9 +1617,8 @@ function mediaGenerators(text) {
1274
1617
  const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
1275
1618
  return MEDIA.filter((m) => m in deps);
1276
1619
  }
1277
- var LIST_TOOLS = { next: ["next-sitemap"] };
1278
1620
  function listTools(framework, text) {
1279
- const tools = LIST_TOOLS[String(framework)] ?? [];
1621
+ const tools = adapterOf(framework)?.listTools ?? [];
1280
1622
  if (!tools.length) return [];
1281
1623
  let pkg = null;
1282
1624
  try {
@@ -1307,7 +1649,8 @@ function draftCheck(path, { framework, paths, text, found, importers }) {
1307
1649
  if (page.kind === "template") return no("template", page.path);
1308
1650
  if (page.reason) return no(page.reason);
1309
1651
  if (!page.file) return no("unparsed");
1310
- if (framework === "next") {
1652
+ if (page.router?.object && !kitAtLeast({ framework, text }, OBJECT_ROUTES_SINCE)) return no("kit_old", "route objects");
1653
+ if (adapterOf(framework)?.segments) {
1311
1654
  const beside = segmentFiles(page.file, paths);
1312
1655
  if (beside.length) return no("segment", beside.join(", "));
1313
1656
  }
@@ -1328,12 +1671,6 @@ function segmentFiles(file, paths) {
1328
1671
  const dir = dirname(file);
1329
1672
  return paths.filter((p) => p !== file && dirname(p) === dir && SEGMENT_FILE.test(p.slice(dir ? dir.length + 1 : 0))).sort();
1330
1673
  }
1331
- function templateMatches(template, path) {
1332
- const t = template.split("/");
1333
- const p = path.split("/");
1334
- 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));
1335
- return t.length === p.length && t.every((s, i) => s === p[i] || /^(\[|:)/.test(s));
1336
- }
1337
1674
  function draftPlan({ framework, paths, text, pageFile }) {
1338
1675
  if (!pageFile.ok) return { checks: [], failed: [{ ok: (
1339
1676
  /** @type {const} */
@@ -1345,34 +1682,44 @@ function draftPlan({ framework, paths, text, pageFile }) {
1345
1682
  return { checks, failed: checks.filter((c) => !c.ok), found, importers };
1346
1683
  }
1347
1684
  var APP_SOURCE = /^(src|app|pages|components|lib)\//;
1348
- function linksTo(path, { paths, text, own = [] }) {
1685
+ function linksTo(path, { paths, text, own = [], framework = null }) {
1349
1686
  if (path === "/") return [];
1350
1687
  const mine = new Set(own);
1351
- return [...linkIndex(paths, text).get(path) ?? []].filter((p) => !mine.has(p)).sort();
1688
+ return [...linkIndex(paths, text, adapterOf(framework)).get(path) ?? []].filter((p) => !mine.has(p)).sort();
1352
1689
  }
1353
1690
  var linkIndexOf = /* @__PURE__ */ new WeakMap();
1354
1691
  var QUOTED_ADDRESS = /(?<!(?:path|pad)"?\s*[=:]\s*\{?\s*)(["'`])(\/[^"'`]*)(?=\1)/g;
1355
- function linkIndex(paths, text) {
1356
- const kept = linkIndexOf.get(text);
1692
+ function linkIndex(paths, text, adapter = null) {
1693
+ const kind = adapter?.links ? "site" : "app";
1694
+ const kept = linkIndexOf.get(text)?.[kind];
1357
1695
  if (kept?.paths === paths) return kept.index;
1358
1696
  const index = /* @__PURE__ */ new Map();
1697
+ const add = (address2, p) => {
1698
+ if (!index.has(address2)) index.set(address2, /* @__PURE__ */ new Set());
1699
+ index.get(address2).add(p);
1700
+ };
1701
+ const linkFile = adapter?.links ?? ((p) => APP_SOURCE.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
1359
1702
  for (const p of paths) {
1360
- if (SKIP2.test(p) || !APP_SOURCE.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
1361
- for (const [, , quoted] of (text(p) ?? "").matchAll(QUOTED_ADDRESS)) {
1703
+ if (SKIP2.test(p) || !linkFile(p)) continue;
1704
+ const raw = text(p) ?? "";
1705
+ const src = blankRanges(raw, codeRanges(raw, p));
1706
+ for (const [, , quoted] of src.matchAll(QUOTED_ADDRESS)) {
1362
1707
  const bare = quoted.replace(/[#?][\s\S]*$/, "");
1363
- const address2 = bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare;
1364
- if (!index.has(address2)) index.set(address2, /* @__PURE__ */ new Set());
1365
- index.get(address2).add(p);
1708
+ add(bare.length > 1 && bare.endsWith("/") ? bare.slice(0, -1) : bare, p);
1709
+ }
1710
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) {
1711
+ for (const [, , , url] of src.matchAll(URL_ATTRIBUTE)) {
1712
+ const bare = url.replace(/[#?][\s\S]*$/, "");
1713
+ if (!relativeUrl(url) || !bare) continue;
1714
+ const address2 = servedAddress(resolvedUrl(dirname(p), bare), bare.endsWith("/"));
1715
+ if (address2 !== null) add(address2, p);
1716
+ }
1366
1717
  }
1367
1718
  }
1368
- linkIndexOf.set(text, { paths, index });
1719
+ linkIndexOf.set(text, { ...linkIndexOf.get(text) ?? {}, [kind]: { paths, index } });
1369
1720
  return index;
1370
1721
  }
1371
- var CONFIGS = {
1372
- astro: ["astro.config.mjs", "astro.config.ts", "astro.config.js", "astro.config.mts", "astro.config.cjs"],
1373
- "vite-react": ["vite.config.ts", "vite.config.js", "vite.config.mjs", "vite.config.mts"],
1374
- next: ["next.config.ts", "next.config.mjs", "next.config.js", "next.config.mts", "next.config.cjs"]
1375
- };
1722
+ var CONFIGS = Object.fromEntries(FRAMEWORKS2.filter((f) => ADAPTERS2[f].configs.length).map((f) => [f, ADAPTERS2[f].configs]));
1376
1723
  var kitFiles = (framework) => ["package.json", ...CONFIGS[String(framework)] ?? []];
1377
1724
  function kitInstalled({ framework, text }) {
1378
1725
  let pkg = null;
@@ -1455,7 +1802,7 @@ function withoutInContentMap(json, files) {
1455
1802
  }
1456
1803
  return JSON.stringify(map);
1457
1804
  }
1458
- var PAGE_ACTION_FRAMEWORKS = ["astro", "next", "vite-react"];
1805
+ var PAGE_ACTION_FRAMEWORKS = FRAMEWORKS2.filter((f) => ADAPTERS2[f].acts);
1459
1806
  var 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" };
1460
1807
  function lowestVersion(spec) {
1461
1808
  if (typeof spec !== "string" || /^(file|link|workspace|git|github|https?|npm):/.test(spec.trim())) return null;
@@ -1467,6 +1814,10 @@ var atLeast = (have, want) => {
1467
1814
  return true;
1468
1815
  };
1469
1816
  function kitRedirects({ framework, text }) {
1817
+ return kitAtLeast({ framework, text }, REDIRECTS_SINCE);
1818
+ }
1819
+ var OBJECT_ROUTES_SINCE = { "@unbase-app/vite": "0.4.0", "@unbase-app/pages": "0.5.0" };
1820
+ function kitAtLeast({ framework, text }, since) {
1470
1821
  if (!kitInstalled({ framework, text })) return false;
1471
1822
  let pkg = null;
1472
1823
  try {
@@ -1476,21 +1827,11 @@ function kitRedirects({ framework, text }) {
1476
1827
  const configs = (CONFIGS[String(framework)] ?? []).map((c) => stripComments(text(c) ?? ""));
1477
1828
  return (KITS[String(framework)] ?? []).some((name) => {
1478
1829
  const spec = pkg?.dependencies?.[name] ?? pkg?.devDependencies?.[name];
1479
- const since = REDIRECTS_SINCE[name];
1830
+ const want = since[name];
1480
1831
  const have = lowestVersion(spec);
1481
- return !!since && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(since));
1832
+ return !!want && !!have && configs.some((c) => c.includes(name)) && atLeast(have, lowestVersion(want));
1482
1833
  });
1483
1834
  }
1484
- function slugOf(name) {
1485
- return String(name).normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 80);
1486
- }
1487
- var SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]*$/;
1488
- function validAddress(p) {
1489
- const at3 = normalisePath(p);
1490
- if (at3.length > 200) return false;
1491
- if (at3 === "/") return true;
1492
- return at3.slice(1).split("/").every((s) => SEGMENT.test(s) && s !== "index" && !/^(404|500)$/.test(s));
1493
- }
1494
1835
  var under = (path, at3) => at3 === "/" ? path !== "/" : path.startsWith(`${at3}/`);
1495
1836
  var within2 = (path, at3) => path === at3 || under(path, at3);
1496
1837
  var moveAddress = (path, from, to) => path === from ? to : normalisePath(`${to}${path.slice(from === "/" ? 0 : from.length)}`);
@@ -1503,30 +1844,28 @@ function siteRedirects({ framework, text }) {
1503
1844
  for (const r of Array.isArray(v?.redirects) ? v.redirects : []) if (typeof r?.source === "string") out.add(normalisePath(r.source));
1504
1845
  } catch {
1505
1846
  }
1506
- for (const c of CONFIGS[String(framework)] ?? []) {
1507
- const src = stripComments(text(c) ?? "");
1508
- if (framework === "astro") {
1509
- const at3 = src.search(/\bredirects\s*:\s*\{/);
1510
- if (at3 < 0) continue;
1511
- const body = braced(src, src.indexOf("{", at3)) ?? "";
1512
- for (const m of body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)) out.add(normalisePath(m[1]));
1513
- } else if (framework === "next") {
1514
- for (const m of src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)) out.add(normalisePath(m[1]));
1515
- }
1847
+ const adapter = adapterOf(framework);
1848
+ for (const c of adapter?.configs ?? []) {
1849
+ if (!adapter.configSources) continue;
1850
+ for (const source of adapter.configSources(stripComments(text(c) ?? ""))) out.add(normalisePath(source));
1516
1851
  }
1517
1852
  return out;
1518
1853
  }
1854
+ function astroConfigSources(src) {
1855
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
1856
+ if (at3 < 0) return [];
1857
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
1858
+ return [...body.matchAll(/["'](\/[^"'\n]*)["']\s*:/g)].map((m) => m[1]);
1859
+ }
1860
+ function nextConfigSources(src) {
1861
+ return [...src.matchAll(/source\s*:\s*["'](\/[^"'\n]*)["']/g)].map((m) => m[1]);
1862
+ }
1519
1863
  function sends(source, path) {
1520
1864
  if (REST.test(source)) {
1521
1865
  const base = normalisePath(source.replace(REST, ""));
1522
1866
  return within2(path, base);
1523
1867
  }
1524
- return source === path || matchesPattern(source, path);
1525
- }
1526
- function matchesPattern(source, path) {
1527
- if (!/\[|:/.test(source)) return false;
1528
- const re = new RegExp(`^${source.split(/(\[\.\.\.[^\]]+\]|\[[^\]]+\]|:[A-Za-z_]\w*\*?)/).map((part, i) => i % 2 ? part.startsWith("[...") || part.endsWith("*") ? ".*" : "[^/]+" : escape(part)).join("")}$`);
1529
- return re.test(path);
1868
+ return source === path || redirectMatches(source, path);
1530
1869
  }
1531
1870
  function changedPageFile(before, change) {
1532
1871
  let data = {};
@@ -1599,7 +1938,42 @@ function respecified(src, was, now, moves, have) {
1599
1938
  }
1600
1939
  var QUOTED = /(["'`])(\/[^"'`\n]*?)(?=\1)/g;
1601
1940
  var MD_LINK = /(\]\()(\/[^)\s]*)(\))/g;
1602
- function relinked(src, from, to, markdown) {
1941
+ function codeRanges(src, file) {
1942
+ const out = [];
1943
+ if (/\.mdx?$/.test(file)) {
1944
+ let at3 = 0;
1945
+ let open = null;
1946
+ let start = 0;
1947
+ for (const line of src.split("\n")) {
1948
+ const fence = line.match(/^ {0,3}(`{3,}|~{3,})/);
1949
+ if (!open && fence) {
1950
+ open = fence[1];
1951
+ start = at3;
1952
+ } else if (open && fence && fence[1][0] === open[0] && fence[1].length >= open.length && !line.slice(fence[0].length).trim()) {
1953
+ out.push([start, at3 + line.length]);
1954
+ open = null;
1955
+ }
1956
+ at3 += line.length + 1;
1957
+ }
1958
+ if (open) out.push([start, src.length]);
1959
+ for (const m of blankRanges(src, out).matchAll(/(`+)(?!`)(.+?)(?<!`)\1(?!`)/g)) out.push([m.index, m.index + m[0].length]);
1960
+ }
1961
+ if (/\.(html?|astro|mdx)$/.test(file)) for (const m of src.matchAll(/<(pre|code)\b[\s\S]*?<\/\1\s*>/gi)) out.push([m.index, m.index + m[0].length]);
1962
+ return out.sort((a, b) => a[0] - b[0]);
1963
+ }
1964
+ function outside(src, ranges, change) {
1965
+ if (!ranges.length) return change(src);
1966
+ let out = "";
1967
+ let at3 = 0;
1968
+ for (const [start, end] of ranges) {
1969
+ if (end <= at3) continue;
1970
+ out += change(src.slice(at3, Math.max(at3, start))) + src.slice(Math.max(at3, start), end);
1971
+ at3 = end;
1972
+ }
1973
+ return out + change(src.slice(at3));
1974
+ }
1975
+ function relinked(src, from, to, file) {
1976
+ const markdown = /\.mdx?$/.test(file);
1603
1977
  const swap = (address2) => {
1604
1978
  const bare = address2.replace(/[#?][\s\S]*$/, "");
1605
1979
  const tail = address2.slice(bare.length);
@@ -1609,10 +1983,13 @@ function relinked(src, from, to, markdown) {
1609
1983
  if (from !== "/" && clean.startsWith(`${from}/`)) return `${to === "/" ? "" : to}${clean.slice(from.length)}${slash}${tail}`;
1610
1984
  return address2;
1611
1985
  };
1612
- let out = src.replace(QUOTED, (m, q, address2) => `${q}${swap(address2)}`);
1613
- if (markdown) out = out.replace(MD_LINK, (m, a, address2, b) => `${a}${swap(address2)}${b}`);
1614
- return out;
1986
+ return outside(src, codeRanges(src, file), (piece) => {
1987
+ let out = piece.replace(QUOTED, (m, q, address2) => `${q}${swap(address2)}`);
1988
+ if (markdown) out = out.replace(MD_LINK, (m, a, address2, b) => `${a}${swap(address2)}${b}`);
1989
+ return out;
1990
+ });
1615
1991
  }
1992
+ var linkFileOf = (adapter) => adapter?.links ?? ((p) => APP_SOURCE.test(p) && !CONTENT_CONFIG.test(p) && (CODE.test(p) || CONTENT_JSON.test(p)));
1616
1993
  function blankStrings(src) {
1617
1994
  let out = "";
1618
1995
  let i = 0;
@@ -1648,6 +2025,105 @@ function destination(page, to, discovered) {
1648
2025
  const newDir = `${base}${to === "/" ? "" : to}`;
1649
2026
  return { file: index || to === "/" ? `${newDir}/index${ext}` : `${newDir}${ext}`, dir: oldDir, newDir, folder: index };
1650
2027
  }
2028
+ function htmlDestination(page, to) {
2029
+ const folder = /(^|\/)index\.html?$/.test(page.file);
2030
+ const dir = folder ? dirname(page.file) : page.file;
2031
+ if (to.endsWith(".html") || to.endsWith(".htm")) {
2032
+ if (folder) return null;
2033
+ return { file: to.slice(1), dir, newDir: to.slice(1), folder: false };
2034
+ }
2035
+ return { file: `${to.slice(1)}/index.html`, dir, newDir: to.slice(1), folder };
2036
+ }
2037
+ var URL_ATTRIBUTE = /(\s(?:href|src|action|poster)\s*=\s*)(["'])([^"']*)\2/gi;
2038
+ var relativeUrl = (url) => !!url && !/^(?:[a-z][a-z0-9+.-]*:|\/|#|\?|\{|\$)/i.test(url);
2039
+ function resolvedUrl(dir, url) {
2040
+ const segments = dir ? dir.split("/") : [];
2041
+ for (const s of url.split("/")) {
2042
+ if (s === "..") segments.pop();
2043
+ else if (s && s !== ".") segments.push(s);
2044
+ }
2045
+ return segments.join("/");
2046
+ }
2047
+ function servedAddress(path, slash) {
2048
+ if (path === "" || path === "index.html" || path === "index.htm") return "/";
2049
+ if (/\/index\.html?$/.test(path)) return `/${path.replace(/\/index\.html?$/, "")}`;
2050
+ if (slash || /\.html?$/.test(path) || !/\.[a-z0-9]+$/i.test(path.split("/").pop() ?? "")) return `/${path}`;
2051
+ return null;
2052
+ }
2053
+ function relativeTo(dir, target) {
2054
+ const from = dir ? dir.split("/") : [];
2055
+ const folder = target === "" || target.endsWith("/");
2056
+ const parts = target.replace(/\/$/, "").split("/").filter(Boolean);
2057
+ const tdir = folder ? parts : parts.slice(0, -1);
2058
+ const base = folder ? "" : parts.at(-1) ?? "";
2059
+ let i = 0;
2060
+ while (i < from.length && i < tdir.length && from[i] === tdir[i]) i++;
2061
+ const rest = tdir.slice(i);
2062
+ const out = `${"../".repeat(from.length - i)}${rest.length ? `${rest.join("/")}/` : ""}${base}`;
2063
+ return out || "./";
2064
+ }
2065
+ function htmlRelinked(src, was, now, change, moved) {
2066
+ return src.replace(URL_ATTRIBUTE, (m, lead, q, url) => {
2067
+ if (!relativeUrl(url)) return m;
2068
+ const bare = url.replace(/[#?][\s\S]*$/, "");
2069
+ if (!bare) return m;
2070
+ const tail = url.slice(bare.length);
2071
+ const slash = bare.endsWith("/");
2072
+ const path = resolvedUrl(dirname(was), bare);
2073
+ let target = null;
2074
+ const address2 = servedAddress(path, slash);
2075
+ if (change && address2 !== null && (address2 === change.from || under(address2, change.from))) {
2076
+ const next2 = moveAddress(address2, change.from, change.to);
2077
+ const index = /(^|\/)index\.html?$/.test(path);
2078
+ if (next2.endsWith(".html") || next2.endsWith(".htm")) target = next2.slice(1);
2079
+ else if (index) target = next2 === "/" ? "index.html" : `${next2.slice(1)}/index.html`;
2080
+ else target = next2 === "/" ? "" : `${next2.slice(1)}/`;
2081
+ if (!slash && !index && !target.endsWith("/") && !/\.html?$/.test(target)) target = target.replace(/\/$/, "");
2082
+ } else if (moved?.has(path)) target = moved.get(path);
2083
+ else if (was === now) return m;
2084
+ else target = slash && path ? `${path}/` : path;
2085
+ const next = relativeTo(dirname(now), target);
2086
+ return next === bare ? m : `${lead}${q}${next}${tail}${q}`;
2087
+ });
2088
+ }
2089
+ function htmlStarter({ discovered, text, target, name, segments, files, fileTaken, no }) {
2090
+ const shellPage = discovered.pages.find((p) => p.path === "/") ?? discovered.pages.find((p) => p.file);
2091
+ const shell = shellPage ? text(shellPage.file) : null;
2092
+ if (!shell) return no("unparsed");
2093
+ const file = /\.html?$/.test(target) ? target.slice(1) : `${segments}/index.html`;
2094
+ if (fileTaken(file)) return no("taken", file);
2095
+ const esc = (s) => String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
2096
+ const h1 = mostClass(discovered.pages.map((p) => text(p.file) ?? ""), "h1", "class");
2097
+ const heading = `<h1${h1 ? ` class="${esc(h1)}"` : ""}>${esc(name)}</h1>`;
2098
+ let out = shell;
2099
+ out = /<title\b[^>]*>[\s\S]*?<\/title>/i.test(out) ? out.replace(/(<title\b[^>]*>)[\s\S]*?(<\/title>)/i, `$1${esc(name)}$2`) : out.replace(/(\s*)<\/head>/i, `$1 <title>${esc(name)}</title>$1</head>`);
2100
+ out = out.replace(/[ \t]*<meta\s[^>]*name\s*=\s*["']description["'][^>]*>[ \t]*\r?\n?/i, "");
2101
+ const indentAt = (i) => out.slice(out.lastIndexOf("\n", i - 1) + 1, i).match(/^[ \t]*/)?.[0] ?? "";
2102
+ const main = /(<main\b[^>]*>)([\s\S]*?)(<\/main>)/i.exec(out);
2103
+ if (main) {
2104
+ const indent = indentAt(main.index);
2105
+ out = `${out.slice(0, main.index)}${main[1]}
2106
+ ${indent} ${heading}
2107
+ ${indent}${main[3]}${out.slice(main.index + main[0].length)}`;
2108
+ } else {
2109
+ const body = /(<body\b[^>]*>)([\s\S]*?)(<\/body>)/i.exec(out);
2110
+ if (!body) return no("unparsed");
2111
+ const inner = body[2];
2112
+ const header = /<header\b[\s\S]*?<\/header>/i.exec(inner);
2113
+ const footer = /<footer\b[\s\S]*?<\/footer>/i.exec(inner);
2114
+ const indent = inner.match(/\n([ \t]*)\S/)?.[1] ?? " ";
2115
+ const start = header ? header.index + header[0].length : 0;
2116
+ const end = footer ? footer.index : inner.length;
2117
+ const scripts = [...inner.slice(start, end).matchAll(/<script\b[\s\S]*?<\/script>/gi)].map((m) => m[0]);
2118
+ const block = ["<main>", ` ${heading}`, "</main>", ...scripts].map((l) => `${indent}${l}`).join("\n");
2119
+ const head = header ? inner.slice(0, start) : "";
2120
+ const tail = footer ? `
2121
+ ${indent}${inner.slice(end)}` : inner.match(/\s*$/)?.[0] ?? "\n";
2122
+ out = `${out.slice(0, body.index)}${body[1]}${head}
2123
+ ${block}${tail}${body[3]}${out.slice(body.index + body[0].length)}`;
2124
+ }
2125
+ files.push({ path: file, content: htmlRelinked(out, shellPage.file, file, null, null) });
2126
+ }
1651
2127
  function appSegmentOwn(dir, paths) {
1652
2128
  return paths.filter((p) => {
1653
2129
  if (dirname(p) === dir) return true;
@@ -1658,6 +2134,16 @@ function appSegmentOwn(dir, paths) {
1658
2134
  }
1659
2135
  var componentName = (address2) => (lastOf(address2) || "Home").split(/[^A-Za-z0-9]+/).filter(Boolean).map((w) => w[0].toUpperCase() + w.slice(1)).join("").replace(/^(\d)/, "Page$1") || "Page";
1660
2136
  function routePathAttr(src, router) {
2137
+ if (router.object) {
2138
+ const clean = stripComments(src);
2139
+ const entry = objectEntries(clean, router.start).find((e) => e.key === "path");
2140
+ if (!entry) return null;
2141
+ const raw = src.slice(entry.valueStart, entry.valueEnd);
2142
+ const value2 = literalString(raw);
2143
+ if (value2 === false) return null;
2144
+ const start = entry.valueStart + 1;
2145
+ return { value: value2, start, end: start + value2.length };
2146
+ }
1661
2147
  const tag = src.slice(router.start, router.end);
1662
2148
  const m = tag.match(/(\s)path\s*=\s*(?:"([^"]*)"|'([^']*)'|\{\s*"([^"]*)"\s*\}|\{\s*'([^']*)'\s*\})/);
1663
2149
  if (!m) return null;
@@ -1665,25 +2151,51 @@ function routePathAttr(src, router) {
1665
2151
  const valueAt = router.start + m.index + m[0].indexOf(value, m[0].indexOf("=") + 1);
1666
2152
  return { value, start: valueAt, end: valueAt + value.length };
1667
2153
  }
2154
+ function routeCopy({ src, router, routerFile, attr, value, name, file, original }) {
2155
+ let tag = src.slice(router.start, attr.start) + value + src.slice(attr.end, router.end);
2156
+ let statement = null;
2157
+ let added = null;
2158
+ if (router.importKind === "inline") {
2159
+ tag = tag.replace(/(import\(\s*)(["'])([^"']+)\2/, (m, lead, q, spec) => `${lead}${q}${specFor(routerFile, file, spec, original)}${q}`);
2160
+ } else {
2161
+ const comp = router.component;
2162
+ statement = router.importKind === "lazy" ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape2(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m")) : src.match(new RegExp(`^.*import\\s+${escape2(comp)}\\b[^\\n]*$`, "m"));
2163
+ if (!statement) return { ok: false, reason: "unparsed", detail: "its import" };
2164
+ added = statement[0].replace(new RegExp(`(?<![\\w$])${escape2(comp)}(?![\\w$])`), name).replace(/(["'])([^"']+)\1/, (m, q, spec) => `${q}${specFor(routerFile, file, spec, original)}${q}`);
2165
+ tag = tag.replace(new RegExp(`(<|\\{\\s*|Component\\s*:\\s*)${escape2(comp)}(?![\\w$])`, "g"), `$1${name}`);
2166
+ }
2167
+ const indent = src.slice(src.lastIndexOf("\n", router.start) + 1, router.start).match(/^\s*/)?.[0] ?? "";
2168
+ let out = `${src.slice(0, router.end)}${router.object ? "," : ""}
2169
+ ${indent}${tag}${src.slice(router.end)}`;
2170
+ if (statement) {
2171
+ const lineEnd = statement.index + statement[0].length;
2172
+ out = `${out.slice(0, lineEnd)}
2173
+ ${added}${out.slice(lineEnd)}`;
2174
+ }
2175
+ return { ok: true, code: out };
2176
+ }
1668
2177
  function planPage(request, input) {
1669
2178
  const { framework, text } = input;
2179
+ const adapter = adapterOf(framework);
1670
2180
  const paths = input.paths.filter((p) => !SKIP2.test(p));
1671
- const no = (reason, detail) => ({ ok: (
2181
+ const no = (reason, detail2) => ({ ok: (
1672
2182
  /** @type {const} */
1673
2183
  false
1674
- ), reason, ...detail ? { detail } : {} });
2184
+ ), reason, ...detail2 ? { detail: detail2 } : {} });
1675
2185
  const action = request.action;
1676
- if (!["rename", "duplicate", "delete"].includes(action)) return no("invalid", action);
1677
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
2186
+ if (!["rename", "duplicate", "delete", "create"].includes(action)) return no("invalid", action);
2187
+ if (!adapter?.acts) return no("framework");
1678
2188
  const at3 = normalisePath(request.path);
1679
2189
  const discovered = input.found ?? discover({ framework, paths, text });
2190
+ if (action === "create") return planCreate(request, { framework, paths, text, discovered });
1680
2191
  const page = discovered.pages.find((p) => p.path === at3);
1681
2192
  if (!page && action === "rename" && discovered.pages.some((p) => under(p.path, at3))) return planFolder(request, { framework, paths, text, discovered, importers: input.importers });
1682
2193
  if (!page) {
1683
2194
  const template = discovered.pages.find((p) => p.kind === "template" && templateMatches(p.path, at3));
1684
2195
  return template ? no("template", template.path) : no("missing");
1685
2196
  }
1686
- if (page.kind === "template") return no("template", page.path);
2197
+ const detail = page.kind === "template" && action === "delete" && !adapter?.routeLines ? input.details?.[at3] ?? null : null;
2198
+ if (page.kind === "template" && !detail) return no("template", page.path);
1687
2199
  if (!page.file || page.reason === "unparsed") return no("unparsed");
1688
2200
  const pageFile = parsePageFile(text(PAGE_FILE));
1689
2201
  if (!pageFile.ok) return no("invalid", pageFile.error);
@@ -1717,11 +2229,11 @@ function planPage(request, input) {
1717
2229
  if (!validAddress(target) || target === "/") return no("address", target);
1718
2230
  if (target !== at3 && within2(target, at3)) return no("address", target);
1719
2231
  if (target !== at3 && taken(target)) return no("taken", target);
1720
- if (target !== at3 && live && !redirects) return no("no_redirects");
2232
+ if (target !== at3 && live && (!redirects || page.router?.object)) return no("no_redirects", page.router?.object ? "route objects" : void 0);
1721
2233
  to = target;
1722
2234
  const moved = /* @__PURE__ */ new Map();
1723
2235
  if (target !== at3) {
1724
- if (framework === "vite-react") {
2236
+ if (adapter?.routeLines) {
1725
2237
  const src = text(page.router.file) ?? "";
1726
2238
  const attr = routePathAttr(src, page.router);
1727
2239
  if (!attr) return no("unparsed", "index route");
@@ -1732,7 +2244,7 @@ function planPage(request, input) {
1732
2244
  write({ path: page.router.file, content: src.slice(0, attr.start) + rel + src.slice(attr.end) });
1733
2245
  }
1734
2246
  } else {
1735
- const dest = destination(page, target, discovered);
2247
+ const dest = (adapter?.destination ?? destination)(page, target, discovered);
1736
2248
  if (!dest) return no("unparsed");
1737
2249
  for (const p of paths) if (p.startsWith(`${dest.dir}/`)) moved.set(p, `${dest.newDir}/${p.slice(dest.dir.length + 1)}`);
1738
2250
  moved.set(page.file, dest.file);
@@ -1751,12 +2263,14 @@ function planPage(request, input) {
1751
2263
  if (out !== src) write({ path: p, content: out });
1752
2264
  }
1753
2265
  }
2266
+ const linkFile = linkFileOf(adapter);
1754
2267
  for (const p of paths) {
1755
- if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
2268
+ if (!linkFile(p)) continue;
1756
2269
  const where = moved.get(p) ?? p;
1757
2270
  const src = current(where);
1758
2271
  if (!src) continue;
1759
- const out = relinked(src, at3, target, /\.mdx?$/.test(p));
2272
+ let out = relinked(src, at3, target, p);
2273
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at3, to: target }, moved);
1760
2274
  if (out === src) continue;
1761
2275
  write({ path: where, content: out });
1762
2276
  if (!moved.has(p)) links.add(where);
@@ -1790,7 +2304,7 @@ function planPage(request, input) {
1790
2304
  if (!writes.size) return no("same");
1791
2305
  }
1792
2306
  if (action === "duplicate") {
1793
- if (framework === "vite-react" && page.reason === "nested") return no("nested");
2307
+ if (adapter?.routeLines && page.reason === "nested") return no("nested");
1794
2308
  let target;
1795
2309
  if (request.to != null) {
1796
2310
  target = normalisePath(request.to);
@@ -1848,8 +2362,8 @@ function planPage(request, input) {
1848
2362
  const rebind = (src) => {
1849
2363
  let out = src;
1850
2364
  for (const r of rebinds) {
1851
- 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`);
1852
- else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads2.byName].map(escape).join("|")})\\(\\s*)(["'])${escape(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
2365
+ if (r.kind === "entry") out = out.replace(new RegExp(`(\\bgetEntry\\(\\s*["']${escape2(r.collection)}["']\\s*,\\s*)(["'])${escape2(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
2366
+ else out = out.replace(new RegExp(`((?<![\\w$.])(?:${[...reads2.byName].map(escape2).join("|")})\\(\\s*)(["'])${escape2(r.name)}\\2`, "g"), `$1$2${r.next}$2`);
1853
2367
  }
1854
2368
  for (const [f, next] of copies) {
1855
2369
  if (!imported.has(f)) continue;
@@ -1857,7 +2371,7 @@ function planPage(request, input) {
1857
2371
  }
1858
2372
  return out;
1859
2373
  };
1860
- if (framework === "vite-react") {
2374
+ if (adapter?.routeLines) {
1861
2375
  const router = page.router.file;
1862
2376
  const src = current(router) ?? "";
1863
2377
  const attr = routePathAttr(src, page.router);
@@ -1868,28 +2382,18 @@ function planPage(request, input) {
1868
2382
  const file = freeFile(dirname(page.file), name, ext);
1869
2383
  const original = text(page.file) ?? "";
1870
2384
  write({ path: file, content: rebind(respecified(original, page.file, file, /* @__PURE__ */ new Map([[page.file, file]]), have)) });
1871
- const comp = page.router.component;
1872
- const statement = page.router.importKind === "lazy" ? src.match(new RegExp(`^.*(?:const|let|var)\\s+${escape(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*$`, "m")) : src.match(new RegExp(`^.*import\\s+${escape(comp)}\\b[^\\n]*$`, "m"));
1873
- if (!statement) return no("unparsed", "its import");
1874
- 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}`);
1875
2385
  const value = attr.value.startsWith("/") ? target : (() => {
1876
2386
  const parent = normalisePath(at3.slice(0, at3.length - normalisePath(attr.value).length));
1877
2387
  return parent === "/" ? target.slice(1) : under(target, parent) ? target.slice(parent.length + 1) : null;
1878
2388
  })();
1879
2389
  if (value === null) return no("unparsed", "a route inside another route keeps its parent");
1880
- 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}`);
1881
- const indent = src.slice(src.lastIndexOf("\n", page.router.start) + 1, page.router.start).match(/^\s*/)?.[0] ?? "";
1882
- const at1 = page.router.end;
1883
- let out = `${src.slice(0, at1)}
1884
- ${indent}${newTag}${src.slice(at1)}`;
1885
- const lineEnd = statement.index + statement[0].length;
1886
- out = `${out.slice(0, lineEnd)}
1887
- ${added}${out.slice(lineEnd)}`;
1888
- write({ path: router, content: out });
2390
+ const added = routeCopy({ src, router: page.router, routerFile: router, attr, value, name, file, original: page.file });
2391
+ if (!added.ok) return added;
2392
+ write({ path: router, content: added.code });
1889
2393
  } else {
1890
- const dest = destination(page, target, discovered);
2394
+ const dest = (adapter?.destination ?? destination)(page, target, discovered);
1891
2395
  if (!dest) return no("unparsed");
1892
- const along = framework === "next" && routesBase(page.file).endsWith("app") && at3 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
2396
+ const along = adapter?.segments && routesBase(page.file).endsWith("app") && at3 !== "/" ? appSegmentOwn(dest.dir, paths) : [page.file];
1893
2397
  const moved = new Map(along.map((p) => [p, p === page.file ? dest.file : `${dest.newDir}/${p.slice(dest.dir.length + 1)}`]));
1894
2398
  for (const next of moved.values()) if (have.has(next)) return no("taken", next);
1895
2399
  for (const [from, next] of moved) {
@@ -1900,6 +2404,7 @@ ${added}${out.slice(lineEnd)}`;
1900
2404
  }
1901
2405
  let out = respecified(src, from, next, moved, have);
1902
2406
  if (from === page.file) out = rebind(out);
2407
+ if (adapter?.relativeLinks && /\.html?$/.test(from)) out = htmlRelinked(out, from, next, null, moved);
1903
2408
  write(out === src ? { path: next, from } : { path: next, content: out });
1904
2409
  }
1905
2410
  }
@@ -1911,7 +2416,7 @@ ${added}${out.slice(lineEnd)}`;
1911
2416
  if (!reads2.isRoute(f)) continue;
1912
2417
  const src = text(f) ?? "";
1913
2418
  const next = freeFile(dirname(f), target.slice(1).replace(/\//g, "-") || "home", ".json");
1914
- write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape(at3)}(")`), `$1${target}$2`) });
2419
+ write({ path: next, content: src.replace(new RegExp(`("(?:pad|path)"\\s*:\\s*")${escape2(at3)}(")`), `$1${target}$2`) });
1915
2420
  if (collectionsAfter && typeof collectionsAfter[f] === "string") collectionsAfter[next] = collectionsAfter[f];
1916
2421
  }
1917
2422
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
@@ -1923,22 +2428,23 @@ ${added}${out.slice(lineEnd)}`;
1923
2428
  if (action === "delete") {
1924
2429
  if (at3 === "/") return no("home");
1925
2430
  if (below.length || page.reason === "nested") return no("nested", below.map((p) => p.path).join(", "));
2431
+ const gone = detail ? [...new Set((request.addresses ?? []).map(normalisePath))].filter((p) => templateMatches(at3, p)).sort() : [at3];
1926
2432
  let target = null;
1927
- if (live && request.redirect !== null) {
2433
+ if (live && gone.length && request.redirect !== null) {
1928
2434
  if (request.redirect !== void 0) {
1929
2435
  target = normalisePath(request.redirect);
1930
- if (within2(target, at3) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
2436
+ if (within2(target, at3) || gone.includes(target) || !discovered.pages.some((p) => p.path === target && p.kind !== "template")) return no("address", target);
1931
2437
  } else {
1932
2438
  for (let p = parentOf(at3); p !== null && target === null; p = parentOf(p)) if (discovered.pages.some((q) => q.path === p && q.kind !== "template")) target = p;
1933
2439
  target = target ?? "/";
1934
2440
  }
1935
- if (!redirects) return no("no_redirects");
2441
+ if (!redirects || page.router?.object) return no("no_redirects", page.router?.object ? "route objects" : void 0);
1936
2442
  }
1937
2443
  to = target;
1938
- if (framework === "vite-react") {
2444
+ if (adapter?.routeLines) {
1939
2445
  const router = page.router.file;
1940
2446
  const src = current(router) ?? "";
1941
- let { start, end } = page.router;
2447
+ let { start, end } = routeSpan(src, page.router);
1942
2448
  const lineStart = src.lastIndexOf("\n", start - 1) + 1;
1943
2449
  const lineEnd = src.indexOf("\n", end) < 0 ? src.length : src.indexOf("\n", end);
1944
2450
  if (!src.slice(lineStart, start).trim() && !src.slice(end, lineEnd).trim()) {
@@ -1947,31 +2453,42 @@ ${added}${out.slice(lineEnd)}`;
1947
2453
  }
1948
2454
  let out = src.slice(0, start) + src.slice(end);
1949
2455
  const comp = page.router.component;
1950
- const rest = blankStrings(stripComments(out));
1951
- const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape(comp)}(?![\\w$])`, "g"))].length;
1952
- if (uses <= 1) {
1953
- 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");
1954
- out = out.replace(re, "");
2456
+ if (page.router.importKind === "inline") {
1955
2457
  if ([...importers.get(page.file) ?? []].every((f) => f === router)) write({ path: page.file, deleted: true });
2458
+ } else {
2459
+ const rest = blankStrings(stripComments(out));
2460
+ const uses = [...rest.matchAll(new RegExp(`(?<![\\w$.])${escape2(comp)}(?![\\w$])`, "g"))].length;
2461
+ if (uses <= 1) {
2462
+ const re = page.router.importKind === "lazy" ? new RegExp(`^.*(?:const|let|var)\\s+${escape2(comp)}\\s*=\\s*(?:React\\.)?lazy\\([^\\n]*\\n`, "m") : new RegExp(`^\\s*import\\s+${escape2(comp)}\\s+from\\s*["'][^"']+["'];?[^\\n]*\\n`, "m");
2463
+ out = out.replace(re, "");
2464
+ if ([...importers.get(page.file) ?? []].every((f) => f === router)) write({ path: page.file, deleted: true });
2465
+ }
1956
2466
  }
1957
2467
  write({ path: router, content: out });
1958
2468
  } else {
1959
2469
  const dir = dirname(page.file);
1960
- const files2 = framework === "next" && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
2470
+ const files2 = adapter?.segments && routesBase(page.file).endsWith("app") ? appSegmentOwn(dir, paths) : [page.file];
1961
2471
  for (const f of files2) write({ path: f, deleted: true });
1962
2472
  }
2473
+ const keep = new Set(detail?.keep ?? []);
1963
2474
  const content = ownedContent(page, { paths, text, importers });
1964
- for (const f of content.files) {
2475
+ const owned = content.files.filter((f) => !keep.has(f));
2476
+ for (const f of owned) {
1965
2477
  write({ path: f, deleted: true });
1966
2478
  if (collectionsAfter) delete collectionsAfter[f];
1967
2479
  }
1968
- for (const f of linksTo(at3, { paths, text, own: [page.file, ...content.files] })) unlinked.add(f);
2480
+ for (const f of linksTo(at3, { paths, text, own: [page.file, ...owned], framework })) unlinked.add(f);
2481
+ const was = (d) => d === at3 || !!detail && templateMatches(at3, d);
1969
2482
  const pageFileText = changedPageFile(text(PAGE_FILE), (pages, sendsOn) => {
1970
- delete pages[at3];
2483
+ for (const key of Object.keys(pages)) if (was(key)) delete pages[key];
1971
2484
  const before = { ...sendsOn };
1972
- if (target) sendsOn[at3] = target;
1973
- if (target) repoint(sendsOn, at3, target);
1974
- else for (const [s, d] of Object.entries(sendsOn)) if (d === at3) delete sendsOn[s];
2485
+ if (target) {
2486
+ for (const p of gone) sendsOn[p] = target;
2487
+ for (const p of gone) repoint(sendsOn, p, target);
2488
+ if (detail) {
2489
+ for (const [s, d] of Object.entries(sendsOn)) if (was(d)) s === target ? delete sendsOn[s] : sendsOn[s] = target;
2490
+ }
2491
+ } else for (const [s, d] of Object.entries(sendsOn)) if (was(d)) delete sendsOn[s];
1975
2492
  for (const k of /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(sendsOn)])) if (before[k] !== sendsOn[k]) redirectChanges[k] = sendsOn[k] ?? null;
1976
2493
  });
1977
2494
  if (pageFileText !== null) write({ path: PAGE_FILE, content: pageFileText });
@@ -1987,6 +2504,267 @@ ${added}${out.slice(lineEnd)}`;
1987
2504
  const message = action === "rename" ? to === at3 ? `Unbase: rename ${at3}` : `Unbase: move ${at3} to ${to}` : action === "duplicate" ? `Unbase: duplicate ${at3} as ${to}` : `Unbase: delete ${at3}${to ? ` (visitors go to ${to})` : ""}`;
1988
2505
  return { ok: true, action, path: at3, to, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [...unlinked].sort(), moves, renamed, message };
1989
2506
  }
2507
+ function mostClass(sources, tag, attr, keep = () => true) {
2508
+ const count = /* @__PURE__ */ new Map();
2509
+ for (const src of sources) {
2510
+ for (const m of src.matchAll(new RegExp(`<${tag}\\b[^>]*\\s${attr}="([^"{]+)"`, "g"))) {
2511
+ const c = m[1].trim();
2512
+ if (c && keep(c)) count.set(c, (count.get(c) ?? 0) + 1);
2513
+ }
2514
+ }
2515
+ return [...count].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1))[0]?.[0] ?? null;
2516
+ }
2517
+ var holdsWidth = (c) => /(^|\s)(container|wrap|wrapper|inner|max-w-\S+|mx-auto)(\s|$)/.test(c);
2518
+ var literal = (s) => JSON.stringify(String(s));
2519
+ function siblingRoutes(discovered, text) {
2520
+ return discovered.pages.filter((p) => {
2521
+ if (p.kind !== "route" || p.reason || !p.router || !p.file) return false;
2522
+ const attr = routePathAttr(text(p.router.file) ?? "", p.router);
2523
+ return !!attr && attr.value !== "*" && !attr.value.endsWith("/*");
2524
+ });
2525
+ }
2526
+ function createCapability({ framework, paths, text, found }) {
2527
+ const no = (reason, detail) => ({ ok: (
2528
+ /** @type {const} */
2529
+ false
2530
+ ), reason, ...detail ? { detail } : {} });
2531
+ const adapter = adapterOf(framework);
2532
+ if (!adapter?.acts) return no("framework");
2533
+ const pageFile = parsePageFile(text(PAGE_FILE));
2534
+ if (!pageFile.ok) return no("invalid", pageFile.error);
2535
+ const kept = paths.filter((p) => !SKIP2.test(p));
2536
+ const discovered = found ?? discover({ framework, paths: kept, text });
2537
+ return adapter.canCreate?.(discovered, kept, text) ?? { ok: true };
2538
+ }
2539
+ function wrapOfPage(src) {
2540
+ const imports = [...src.matchAll(/^import\s+(?:([A-Za-z_$][\w$]*)\s*(?:,\s*\{([^}]*)\})?|\{([^}]*)\})\s+from\s+["']([^"']+)["'];?[^\n]*$/gm)].map((m) => ({
2541
+ line: m[0],
2542
+ names: [m[1], ...(m[2] ?? m[3] ?? "").split(",").map((x) => x.trim().split(/\s+as\s+/).pop())].filter(Boolean)
2543
+ }));
2544
+ const used = (n) => new RegExp(`<${escape2(n)}[\\s/>]`).test(src);
2545
+ const names = imports.flatMap((i) => i.names);
2546
+ const lineOf = (n) => imports.find((i) => i.names.includes(n))?.line;
2547
+ const layout = names.find((n) => /Layout$/.test(n) && used(n)) ?? null;
2548
+ if (layout) return { key: `layout:${lineOf(layout)}`, layout, header: null, footer: null, outer: null, imports: [lineOf(layout)] };
2549
+ const header = names.find((n) => /^(Header|Navbar|NavBar|Nav|Navigation|SiteHeader)$/.test(n) && used(n)) ?? null;
2550
+ const footer = names.find((n) => /^(Footer|SiteFooter)$/.test(n) && used(n)) ?? null;
2551
+ if (!header && !footer) return { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
2552
+ const outer = src.match(/return\s*\(\s*<([a-z][\w-]*)((?:\s+className="[^"]*")?)\s*>/);
2553
+ const imports2 = [...new Set([header, footer].filter(Boolean).map(lineOf))];
2554
+ const outerTag = outer ? `${outer[1]}${outer[2]}` : null;
2555
+ return { key: `chrome:${imports2.join("|")}:${outerTag}`, layout: null, header, footer, outer: outerTag, imports: imports2 };
2556
+ }
2557
+ function wrapOfPages(sources) {
2558
+ const seen = /* @__PURE__ */ new Map();
2559
+ for (const src of sources) {
2560
+ const w = wrapOfPage(src);
2561
+ const had = seen.get(w.key) ?? { n: 0, w };
2562
+ had.n++;
2563
+ seen.set(w.key, had);
2564
+ }
2565
+ const best = [...seen.values()].sort((a, b) => b.n - a.n || (a.w.key === "none" ? 1 : b.w.key === "none" ? -1 : 0))[0];
2566
+ return best?.w ?? { key: "none", layout: null, header: null, footer: null, outer: null, imports: [] };
2567
+ }
2568
+ function astroStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2569
+ const own = discovered.pages.filter((p) => p.file && p.file.startsWith("src/pages/") && p.file.endsWith(".astro"));
2570
+ const sources = own.map((p) => text(p.file) ?? "");
2571
+ const layouts = /* @__PURE__ */ new Map();
2572
+ own.forEach((p, i) => {
2573
+ for (const m of sources[i].matchAll(/import\s+([A-Za-z_$][\w$]*)\s+from\s+["']([^"']*layouts?\/[^"']+\.astro)["']/g)) {
2574
+ const spec = m[2];
2575
+ const abs = spec.startsWith(".") ? joinRelative(dirname(p.file), spec) : spec.replace(/^[@~]\//, "src/").replace(/^@layouts\//, "src/layouts/");
2576
+ const seen = layouts.get(abs) ?? { n: 0, local: m[1], alias: spec.startsWith(".") ? null : spec };
2577
+ seen.n++;
2578
+ layouts.set(abs, seen);
2579
+ }
2580
+ });
2581
+ const best = [...layouts].sort((a, b) => b[1].n - a[1].n || (a[0] < b[0] ? -1 : 1))[0];
2582
+ const file = paths.some((p) => p.startsWith(`src/pages/${segments}/`)) ? `src/pages/${segments}/index.astro` : `src/pages/${segments}.astro`;
2583
+ if (fileTaken(file)) return no("taken", file);
2584
+ const h1 = mostClass(sources, "h1", "class");
2585
+ const box = mostClass(sources, "(?:main|section|div)", "class", holdsWidth);
2586
+ const heading = `<h1${h1 ? ` class=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2587
+ const body = [`<main${box ? ` class=${literal(box)}` : ""}>`, ` ${heading}`, "</main>"];
2588
+ let src;
2589
+ if (best) {
2590
+ const [abs, use] = best;
2591
+ const layoutSrc = text(abs) ?? "";
2592
+ const tag = /^[A-Z]/.test(use.local) ? use.local : "Layout";
2593
+ const spec = use.alias ?? relativeSpec(file, abs);
2594
+ const metadata = /\bmetadata\b/.test(layoutSrc) && !/\btitle\s*[?:]/.test(layoutSrc);
2595
+ const props = metadata ? " metadata={metadata}" : /\btitle\b/.test(layoutSrc) ? ` title={${literal(name)}}` : "";
2596
+ const front = [`import ${tag} from ${literal(spec)};`, ...metadata ? [`const metadata = { title: ${literal(name)} };`] : []];
2597
+ src = ["---", ...front, "---", "", `<${tag}${props}>`, ...body.map((l) => ` ${l}`), `</${tag}>`, ""].join("\n");
2598
+ } else {
2599
+ src = [
2600
+ "---",
2601
+ `const title = ${literal(name)};`,
2602
+ "---",
2603
+ "",
2604
+ `<html lang="en">`,
2605
+ " <head>",
2606
+ ` <meta charset="utf-8" />`,
2607
+ ` <meta name="viewport" content="width=device-width" />`,
2608
+ " <title>{title}</title>",
2609
+ " </head>",
2610
+ " <body>",
2611
+ ...body.map((l) => ` ${l}`),
2612
+ " </body>",
2613
+ "</html>",
2614
+ ""
2615
+ ].join("\n");
2616
+ }
2617
+ files.push({ path: file, content: src });
2618
+ }
2619
+ function nextStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2620
+ const own = discovered.pages.filter((p) => p.file && routesBase(p.file));
2621
+ const sources = own.map((p) => text(p.file) ?? "");
2622
+ const inApp = own.find((p) => routesBase(p.file).endsWith("app"));
2623
+ const inPages = own.find((p) => !routesBase(p.file).endsWith("app"));
2624
+ const appBase = inApp ? routesBase(inApp.file) : paths.some((p) => /^src\/app\/layout\./.test(p)) ? "src/app" : paths.some((p) => /^app\/layout\./.test(p)) ? "app" : null;
2625
+ const pagesBase = inPages ? routesBase(inPages.file) : null;
2626
+ const exts = own.map((p) => p.file.slice(p.file.lastIndexOf("."))).filter((e) => /^\.(tsx|jsx|js)$/.test(e));
2627
+ const ext = exts.includes(".tsx") || !exts.length ? ".tsx" : exts.includes(".jsx") ? ".jsx" : ".js";
2628
+ const typed = ext === ".tsx";
2629
+ const h1 = mostClass(sources, "h1", "className");
2630
+ const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
2631
+ const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2632
+ if (appBase) {
2633
+ const file = `${appBase}/${segments}/page${ext}`;
2634
+ if (fileTaken(file)) return no("taken", file);
2635
+ const lines = [
2636
+ ...typed ? [`import type { Metadata } from "next";`, ""] : [],
2637
+ `export const metadata${typed ? ": Metadata" : ""} = { title: ${literal(name)} };`,
2638
+ "",
2639
+ "export default function Page() {",
2640
+ " return (",
2641
+ ` <main${box ? ` className=${literal(box)}` : ""}>`,
2642
+ ` ${heading}`,
2643
+ " </main>",
2644
+ " );",
2645
+ "}",
2646
+ ""
2647
+ ];
2648
+ files.push({ path: file, content: lines.join("\n") });
2649
+ } else if (pagesBase) {
2650
+ const file = paths.some((p) => p.startsWith(`${pagesBase}/${segments}/`)) ? `${pagesBase}/${segments}/index${ext}` : `${pagesBase}/${segments}${ext}`;
2651
+ if (fileTaken(file)) return no("taken", file);
2652
+ const lines = [
2653
+ `import Head from "next/head";`,
2654
+ "",
2655
+ "export default function Page() {",
2656
+ " return (",
2657
+ " <>",
2658
+ " <Head>",
2659
+ ` <title>{${literal(name)}}</title>`,
2660
+ " </Head>",
2661
+ ` <main${box ? ` className=${literal(box)}` : ""}>`,
2662
+ ` ${heading}`,
2663
+ " </main>",
2664
+ " </>",
2665
+ " );",
2666
+ "}",
2667
+ ""
2668
+ ];
2669
+ files.push({ path: file, content: lines.join("\n") });
2670
+ } else return no("unparsed");
2671
+ }
2672
+ function reactRouterStarter({ discovered, text, paths, target, name, segments, files, fileTaken, no }) {
2673
+ const siblings = siblingRoutes(discovered, text);
2674
+ const parent = parentOf(target);
2675
+ const placement = (p) => {
2676
+ const src2 = text(p.router.file) ?? "";
2677
+ const attr2 = routePathAttr(src2, p.router);
2678
+ if (!attr2) return null;
2679
+ if (attr2.value.startsWith("/")) return { src: src2, attr: attr2, value: target };
2680
+ const base = normalisePath(p.path.slice(0, p.path.length - normalisePath(attr2.value).length));
2681
+ if (base !== "/" && !under(target, base)) return null;
2682
+ return { src: src2, attr: attr2, value: base === "/" ? target.slice(1) : target.slice(base.length + 1) };
2683
+ };
2684
+ const ranked = [...siblings.filter((p) => parentOf(p.path) === parent), ...siblings.filter((p) => parentOf(p.path) === "/"), ...siblings];
2685
+ const sibling = ranked.find((p) => placement(p));
2686
+ if (!sibling) return no("routes_unread");
2687
+ const { src, attr, value } = placement(sibling);
2688
+ const router = sibling.router.file;
2689
+ let comp = componentName(target);
2690
+ for (let n = 2; new RegExp(`(?<![\\w$])${comp}(?![\\w$])`).test(src) && n < 100; n++) comp = `${componentName(target)}${n}`;
2691
+ const ext = sibling.file.slice(sibling.file.lastIndexOf("."));
2692
+ let file = `${dirname(sibling.file)}/${comp}${ext}`;
2693
+ for (let n = 2; fileTaken(file) && n < 100; n++) file = `${dirname(sibling.file)}/${comp}${n}${ext}`;
2694
+ const wrap = wrapOfPages(siblings.filter((p) => dirname(p.file) === dirname(sibling.file)).map((p) => text(p.file) ?? ""));
2695
+ const sources = siblings.map((p) => text(p.file) ?? "");
2696
+ const h1 = mostClass(sources, "h1", "className");
2697
+ const box = mostClass(sources, "(?:main|section|div)", "className", holdsWidth);
2698
+ const heading = `<h1${h1 ? ` className=${literal(h1)}` : ""}>{${literal(name)}}</h1>`;
2699
+ const main = (indent) => [`${indent}<main${box ? ` className=${literal(box)}` : ""}>`, `${indent} ${heading}`, `${indent}</main>`];
2700
+ let jsx;
2701
+ const wrapImports = wrap.imports;
2702
+ if (wrap.layout) jsx = [` <${wrap.layout}>`, ...main(" "), ` </${wrap.layout}>`];
2703
+ else if (wrap.header || wrap.footer) {
2704
+ const open = wrap.outer ? `<${wrap.outer}>` : "<>";
2705
+ const close = wrap.outer ? `</${wrap.outer.split(/\s/)[0]}>` : "</>";
2706
+ jsx = [` ${open}`, ...wrap.header ? [` <${wrap.header} />`] : [], ...main(" "), ...wrap.footer ? [` <${wrap.footer} />`] : [], ` ${close}`];
2707
+ } else jsx = main(" ");
2708
+ const page = [...wrapImports, ...wrapImports.length ? [""] : [], `export default function ${comp}() {`, " return (", ...jsx, " );", "}", ""].join("\n");
2709
+ files.push({ path: file, content: page });
2710
+ const added = routeCopy({ src, router: sibling.router, routerFile: router, attr, value, name: comp, file, original: sibling.file });
2711
+ if (!added.ok) return added;
2712
+ files.push({ path: router, content: added.code });
2713
+ }
2714
+ function planCreate(request, { framework, paths, text, discovered }) {
2715
+ const no = (reason, detail) => ({ ok: (
2716
+ /** @type {const} */
2717
+ false
2718
+ ), reason, ...detail ? { detail } : {} });
2719
+ const target = normalisePath(request.path);
2720
+ const name = String(request.name ?? "").trim().slice(0, 120) || componentName(target);
2721
+ if (target === "/" || !validAddress(target)) return no("address", target);
2722
+ const capability = createCapability({ framework, paths, text, found: discovered });
2723
+ if (!capability.ok) return capability;
2724
+ const pageFile = parsePageFile(text(PAGE_FILE));
2725
+ const ownRedirects = siteRedirects({ framework, text });
2726
+ if (discovered.pages.some((q) => q.path === target) || [...ownRedirects].some((s) => sends(s, target))) return no("taken", target);
2727
+ const have = new Set(paths);
2728
+ const files = [];
2729
+ const fileTaken = (f) => have.has(f) || files.some((w) => w.path === f);
2730
+ const segments = target.slice(1);
2731
+ const refused = adapterOf(framework)?.starter?.({ discovered, text, paths, target, name, segments, files, fileTaken, no });
2732
+ if (refused) return refused;
2733
+ const pageFileText = changedPageFile(text(PAGE_FILE), (pages) => {
2734
+ pages[target] = { ...pages[target] ?? {}, ...request.drafts ? { draft: true } : {}, name };
2735
+ });
2736
+ if (pageFileText !== null && pageFile.ok) files.push({ path: PAGE_FILE, content: pageFileText });
2737
+ files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
2738
+ return { ok: true, action: "create", path: target, to: target, files, redirects: {}, links: [], unlinked: [], moves: [], renamed: [], message: `Unbase: new page ${target}` };
2739
+ }
2740
+ var PAGE_OPERATIONS = ["create_page", "rename", "move", "duplicate", "delete", "rename_folder", "reorder", "set_page", "set_site"];
2741
+ function createdAddress(op) {
2742
+ const slug = slugOf(op?.slug ?? op?.name ?? "");
2743
+ if (!slug) return null;
2744
+ const parent = op.parent ? normalisePath(op.parent) : "/";
2745
+ return normalisePath(`${parent === "/" ? "" : parent}/${slug}`);
2746
+ }
2747
+ function requestOf(op) {
2748
+ if (!op || typeof op !== "object") return null;
2749
+ switch (op.op) {
2750
+ case "create_page": {
2751
+ const path = createdAddress(op);
2752
+ return path ? { action: "create", path, name: op.name } : null;
2753
+ }
2754
+ case "rename":
2755
+ return { action: "rename", path: op.path, name: op.name };
2756
+ case "move":
2757
+ return { action: "rename", path: op.path, to: op.to };
2758
+ case "rename_folder":
2759
+ return { action: "rename", path: op.path, ...op.to !== void 0 ? { to: op.to } : {}, ...op.name !== void 0 ? { name: op.name } : {} };
2760
+ case "duplicate":
2761
+ return { action: "duplicate", path: op.path, ...op.to !== void 0 ? { to: op.to } : {}, ...op.name !== void 0 ? { name: op.name } : {} };
2762
+ case "delete":
2763
+ return { action: "delete", path: op.path, ...op.redirect !== void 0 ? { redirect: op.redirect } : {} };
2764
+ default:
2765
+ return null;
2766
+ }
2767
+ }
1990
2768
  function folderPaths(pages) {
1991
2769
  const own = new Set(pages.map((p) => p.path));
1992
2770
  const out = /* @__PURE__ */ new Set();
@@ -2019,6 +2797,7 @@ function folderDirs(at3, below) {
2019
2797
  return dirs.size ? [...dirs].sort() : null;
2020
2798
  }
2021
2799
  function planFolder(request, { framework, paths, text, discovered, importers: given }) {
2800
+ const adapter = adapterOf(framework);
2022
2801
  const no = (reason, detail) => ({ ok: (
2023
2802
  /** @type {const} */
2024
2803
  false
@@ -2034,7 +2813,7 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2034
2813
  const ownRedirects = siteRedirects({ framework, text });
2035
2814
  if (target !== at3 && (discovered.pages.some((p) => within2(p.path, target)) || [...ownRedirects].some((s) => sends(s, target)))) return no("taken", target);
2036
2815
  const live = request.live === true;
2037
- if (target !== at3 && live && !kitRedirects({ framework, text })) return no("no_redirects");
2816
+ if (target !== at3 && live && (!kitRedirects({ framework, text }) || below.some((p) => p.router?.object))) return no("no_redirects");
2038
2817
  const have = new Set(paths);
2039
2818
  const writes = /* @__PURE__ */ new Map();
2040
2819
  const write = (w) => writes.set(w.path, w);
@@ -2043,7 +2822,7 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2043
2822
  const moved = /* @__PURE__ */ new Map();
2044
2823
  const redirectChanges = {};
2045
2824
  if (target !== at3) {
2046
- if (framework === "vite-react") {
2825
+ if (adapter?.routeLines) {
2047
2826
  const edits = /* @__PURE__ */ new Map();
2048
2827
  for (const p of below) {
2049
2828
  if (!p.router) return no("unparsed", p.path);
@@ -2066,10 +2845,10 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2066
2845
  write({ path: file, content: out });
2067
2846
  }
2068
2847
  } else {
2069
- const dirs = folderDirs(at3, below);
2848
+ const dirs = (adapter?.folderDirs ?? folderDirs)(at3, below);
2070
2849
  if (!dirs) return no("unparsed", at3);
2071
2850
  for (const dir of dirs) {
2072
- const newDir = `${dirname(dir)}/${lastOf(target)}`;
2851
+ const newDir = dirname(dir) ? `${dirname(dir)}/${lastOf(target)}` : lastOf(target);
2073
2852
  for (const p of paths) if (p.startsWith(`${dir}/`)) moved.set(p, `${newDir}/${p.slice(dir.length + 1)}`);
2074
2853
  }
2075
2854
  for (const [, next] of moved) if (have.has(next) && !moved.has(next)) return no("taken", next);
@@ -2089,12 +2868,14 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2089
2868
  if (out !== src) write({ path: p, content: out });
2090
2869
  }
2091
2870
  }
2871
+ const linkFile = linkFileOf(adapter);
2092
2872
  for (const p of paths) {
2093
- if (!APP_SOURCE.test(p) || CONTENT_CONFIG.test(p) || !(CODE.test(p) || CONTENT_JSON.test(p))) continue;
2873
+ if (!linkFile(p)) continue;
2094
2874
  const where = moved.get(p) ?? p;
2095
2875
  const src = current(where);
2096
2876
  if (!src) continue;
2097
- const out = relinked(src, at3, target, /\.mdx?$/.test(p));
2877
+ let out = relinked(src, at3, target, p);
2878
+ if (adapter?.relativeLinks && /\.html?$/.test(p)) out = htmlRelinked(out, p, where, { from: at3, to: target }, moved);
2098
2879
  if (out === src) continue;
2099
2880
  write({ path: where, content: out });
2100
2881
  if (!moved.has(p)) links.add(where);
@@ -2131,7 +2912,8 @@ function planFolder(request, { framework, paths, text, discovered, importers: gi
2131
2912
  const message = target === at3 ? `Unbase: rename ${at3}` : `Unbase: move ${at3} to ${target}`;
2132
2913
  return { ok: true, action: "rename", path: at3, to: target, files, redirects: redirectChanges, links: [...links].sort(), unlinked: [], moves, renamed, message, folder: true };
2133
2914
  }
2134
- function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers }) {
2915
+ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(), found, importers, details = {} }) {
2916
+ const adapter = adapterOf(framework);
2135
2917
  const kept = paths.filter((p) => !SKIP2.test(p));
2136
2918
  const discovered = found ?? discover({ framework, paths: kept, text });
2137
2919
  const graph = importers ?? importGraph(kept, text);
@@ -2151,7 +2933,7 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2151
2933
  if (page.path.includes(" ")) continue;
2152
2934
  const below = discovered.pages.filter((p) => under(p.path, page.path));
2153
2935
  const all = (c) => ({ rename: c, duplicate: c, delete: c, under: below.length });
2154
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) {
2936
+ if (!adapter?.acts) {
2155
2937
  out[page.path] = all(no("framework"));
2156
2938
  continue;
2157
2939
  }
@@ -2160,7 +2942,8 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2160
2942
  continue;
2161
2943
  }
2162
2944
  if (page.kind === "template") {
2163
- out[page.path] = all(no("template"));
2945
+ const detail = !!details[page.path] && !adapter?.routeLines && !!page.file && page.reason !== "unparsed";
2946
+ out[page.path] = detail ? { rename: no("template"), duplicate: no("template"), delete: below.length ? no("nested", below.map((p) => p.path).join(", ")) : yes, under: below.length } : all(no("template"));
2164
2947
  continue;
2165
2948
  }
2166
2949
  if (!page.file || page.reason === "unparsed") {
@@ -2168,10 +2951,10 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2168
2951
  continue;
2169
2952
  }
2170
2953
  const onLive = live.has(page.path);
2171
- let rename = page.path === "/" ? no("home") : onLive && !redirects ? no("no_redirects") : yes;
2172
- if (rename.ok && framework === "vite-react" && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
2954
+ let rename = page.path === "/" ? no("home") : onLive && (!redirects || page.router?.object) ? no("no_redirects", page.router?.object ? "route objects" : void 0) : yes;
2955
+ if (rename.ok && adapter?.routeLines && !routePathAttr(text(page.router.file) ?? "", page.router)) rename = no("unparsed", "index route");
2173
2956
  const remove = page.path === "/" ? no("home") : below.length || page.reason === "nested" ? no("nested", below.map((p) => p.path).join(", ")) : yes;
2174
- let duplicate = framework === "vite-react" && page.reason === "nested" ? no("nested") : yes;
2957
+ let duplicate = adapter?.routeLines && page.reason === "nested" ? no("nested") : yes;
2175
2958
  if (duplicate.ok) {
2176
2959
  const content = ownedContent(page, { paths: kept, text, importers: graph });
2177
2960
  const pageReads = reads2.readsByFile.get(page.file) ?? { names: /* @__PURE__ */ new Set(), entries: /* @__PURE__ */ new Set() };
@@ -2207,13 +2990,13 @@ function pageActions({ framework, paths, text, live = /* @__PURE__ */ new Set(),
2207
2990
  const folders = {};
2208
2991
  for (const at3 of folderPaths(discovered.pages)) {
2209
2992
  const below = discovered.pages.filter((p) => under(p.path, at3));
2210
- let rename = !PAGE_ACTION_FRAMEWORKS.includes(String(framework)) ? no("framework") : !pageFile.ok ? no("invalid") : yes;
2211
- if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && !redirects) rename = no("no_redirects");
2212
- if (rename.ok && framework === "vite-react" && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
2213
- if (rename.ok && framework !== "vite-react" && !folderDirs(at3, below)) rename = no("unparsed", at3);
2993
+ let rename = !adapter?.acts ? no("framework") : !pageFile.ok ? no("invalid") : yes;
2994
+ if (rename.ok && below.some((p) => live.has(p.path) || p.kind === "template") && (!redirects || below.some((p) => p.router?.object))) rename = no("no_redirects");
2995
+ if (rename.ok && adapter?.routeLines && below.some((p) => !p.router || !routePathAttr(text(p.router.file) ?? "", p.router))) rename = no("unparsed", "index route");
2996
+ if (rename.ok && !adapter?.routeLines && !(adapter?.folderDirs ?? folderDirs)(at3, below)) rename = no("unparsed", at3);
2214
2997
  folders[at3] = { rename, under: below.length };
2215
2998
  }
2216
- return { redirects, actions: out, folders };
2999
+ return { redirects, actions: out, folders, create: createCapability({ framework, paths: kept, text, found: discovered }) };
2217
3000
  }
2218
3001
  function redirectsFor(framework, pageFile, pagePaths = []) {
2219
3002
  const pages = new Set(pagePaths.map(normalisePath));
@@ -2227,9 +3010,8 @@ function redirectsFor(framework, pageFile, pagePaths = []) {
2227
3010
  continue;
2228
3011
  }
2229
3012
  const destBase = prefix ? normalisePath(destination2.replace(REST, "")) : destination2;
2230
- if (framework === "next") list.push({ source: prefix ? `${base === "/" ? "" : base}/:path*` : source, destination: prefix ? `${destBase === "/" ? "" : destBase}/:path*` : destination2, permanent: true });
2231
- else if (framework === "vite-react") list.push({ path: prefix ? `${base === "/" ? "" : base}/*` : source, from: base, to: destBase, prefix });
2232
- else list.push({ source, destination: destination2 });
3013
+ const shape = adapterOf(framework)?.redirect;
3014
+ list.push(shape ? shape({ prefix, source, destination: destination2, base, destBase }) : { source, destination: destination2 });
2233
3015
  }
2234
3016
  return { list, skipped };
2235
3017
  }
@@ -2242,21 +3024,25 @@ function siteRedirectList({ framework, text }) {
2242
3024
  }
2243
3025
  } catch {
2244
3026
  }
2245
- for (const c of CONFIGS[String(framework)] ?? []) {
2246
- const src = stripComments(text(c) ?? "");
2247
- if (framework === "astro") {
2248
- const at3 = src.search(/\bredirects\s*:\s*\{/);
2249
- if (at3 < 0) continue;
2250
- const body = braced(src, src.indexOf("{", at3)) ?? "";
2251
- const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
2252
- for (const m of body.matchAll(entry)) out.push({ from: m[1], to: m[2] ?? m[3], file: c });
2253
- } else if (framework === "next") {
2254
- for (const m of src.matchAll(/\{[^{}]*\}/g)) {
2255
- const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
2256
- const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
2257
- if (from && to) out.push({ from, to, file: c });
2258
- }
2259
- }
3027
+ const adapter = adapterOf(framework);
3028
+ for (const c of adapter?.configs ?? []) {
3029
+ if (adapter.configRedirects) out.push(...adapter.configRedirects(stripComments(text(c) ?? ""), c));
3030
+ }
3031
+ return out;
3032
+ }
3033
+ function astroConfigRedirects(src, file) {
3034
+ const at3 = src.search(/\bredirects\s*:\s*\{/);
3035
+ if (at3 < 0) return [];
3036
+ const body = braced(src, src.indexOf("{", at3)) ?? "";
3037
+ const entry = /["'](\/[^"'\n]*)["']\s*:\s*(?:["']([^"'\n]+)["']|\{[^{}]*?\bdestination\s*:\s*["']([^"'\n]+)["'][^{}]*\})/g;
3038
+ return [...body.matchAll(entry)].map((m) => ({ from: m[1], to: m[2] ?? m[3], file }));
3039
+ }
3040
+ function nextConfigRedirects(src, file) {
3041
+ const out = [];
3042
+ for (const m of src.matchAll(/\{[^{}]*\}/g)) {
3043
+ const from = m[0].match(/\bsource\s*:\s*["'](\/[^"'\n]*)["']/)?.[1];
3044
+ const to = m[0].match(/\bdestination\s*:\s*["']([^"'\n]+)["']/)?.[1];
3045
+ if (from && to) out.push({ from, to, file });
2260
3046
  }
2261
3047
  return out;
2262
3048
  }
@@ -2267,13 +3053,14 @@ function redirectEnd(p) {
2267
3053
  return { base, prefix, key: prefix ? `${base === "/" ? "" : base}/[...path]` : base };
2268
3054
  }
2269
3055
  function planRedirect(request, { framework, paths, text, found }) {
3056
+ const adapter = adapterOf(framework);
2270
3057
  const no = (reason, detail) => ({ ok: (
2271
3058
  /** @type {const} */
2272
3059
  false
2273
3060
  ), reason, ...detail ? { detail } : {} });
2274
3061
  const action = request.action;
2275
3062
  if (!["add", "change", "remove"].includes(action)) return no("invalid", action);
2276
- if (!PAGE_ACTION_FRAMEWORKS.includes(String(framework))) return no("framework");
3063
+ if (!adapter?.acts) return no("framework");
2277
3064
  const pageFile = parsePageFile(text(PAGE_FILE));
2278
3065
  if (!pageFile.ok) return no("invalid", pageFile.error);
2279
3066
  const from = redirectEnd(request.from);
@@ -2632,34 +3419,13 @@ function siteMetaFields(src) {
2632
3419
  const computed = {};
2633
3420
  const named = !!object && ["applicationName", "openGraph/siteName"].some((p) => at(object, p.split("/")) !== void 0);
2634
3421
  for (const [k, f] of Object.entries(wanted)) {
2635
- if (f) fields[k] = f;
2636
- else if (k !== "name" || named) computed[k] = "computed";
2637
- }
2638
- return { fields, refused: null, computed };
2639
- }
2640
-
2641
- // supabase/functions/unbase-projects/settings.ts
2642
- var PAGE_FIELDS = {
2643
- title: { name: "titel", kind: "text" },
2644
- description: { name: "beschrijving", kind: "text" },
2645
- socialImage: { name: "ogImage", kind: "image" },
2646
- noindex: { name: "noindex", kind: "boolean" },
2647
- siteSearch: { name: "zoeken", kind: "boolean" }
2648
- };
2649
- var SITE_FIELDS = {
2650
- name: { name: "naam", kind: "text" },
2651
- description: { name: "beschrijving", kind: "text" },
2652
- language: { name: "taal", kind: "text" },
2653
- faviconLight: { name: "favicon", kind: "image" },
2654
- faviconDark: { name: "faviconDonker", kind: "image" },
2655
- socialImage: { name: "ogImage", kind: "image" },
2656
- analyticsId: { name: "googleAnalytics", kind: "text" }
2657
- };
2658
- var CONTENT = "src/content";
2659
- var SCHEMAS = `${CONTENT}/.schemas`;
2660
- var ROUTE = /^\/([^/]+(\/[^/]+)*)?$/;
2661
- var AT_ONCE2 = 8;
2662
- var MAX_ROUTE_FILES = 300;
3422
+ if (f) fields[k] = f;
3423
+ else if (k !== "name" || named) computed[k] = "computed";
3424
+ }
3425
+ return { fields, refused: null, computed };
3426
+ }
3427
+
3428
+ // supabase/functions/unbase-projects/settings-next.ts
2663
3429
  var NEXT_AT_ONCE = 16;
2664
3430
  function limited(n) {
2665
3431
  let running = 0;
@@ -2676,109 +3442,6 @@ function limited(n) {
2676
3442
  }
2677
3443
  };
2678
3444
  }
2679
- async function inTurns(items, work) {
2680
- const out = new Array(items.length);
2681
- let next = 0;
2682
- await Promise.all(
2683
- Array.from({ length: Math.min(AT_ONCE2, items.length) }, async () => {
2684
- while (next < items.length) {
2685
- const i = next++;
2686
- out[i] = await work(items[i]);
2687
- }
2688
- })
2689
- );
2690
- return out;
2691
- }
2692
- var parse = (text) => {
2693
- if (text === null) return null;
2694
- try {
2695
- return JSON.parse(text);
2696
- } catch {
2697
- return null;
2698
- }
2699
- };
2700
- function valueOf(v, kind) {
2701
- if (kind === "boolean") return typeof v === "boolean" ? String(v) : null;
2702
- return typeof v === "string" ? v : null;
2703
- }
2704
- function fieldsOf(names, data, allowed, file, base) {
2705
- const fields = {};
2706
- for (const [field2, { name, kind }] of Object.entries(names)) {
2707
- const value = valueOf(data?.[name], kind);
2708
- const there = data?.[name] !== void 0;
2709
- if (there && value === null) continue;
2710
- if (!there && !allowed[name]) continue;
2711
- fields[field2] = { file, pointer: `${base}/${name}`, kind, exists: there, value };
2712
- }
2713
- return fields;
2714
- }
2715
- var VITE_DOCUMENT = "index.html";
2716
- var HEAD_SETTINGS = [
2717
- ["name", "title", "text"],
2718
- ["description", "description", "text"],
2719
- ["language", "language", "text"],
2720
- ["faviconLight", "favicon", "image"],
2721
- ["faviconDark", "faviconDark", "image"],
2722
- ["socialImage", "image", "image"]
2723
- ];
2724
- async function viteSettings(repo, appPath) {
2725
- const text = await repo.read(join(appPath, VITE_DOCUMENT));
2726
- if (text === null) return null;
2727
- const head = readHead(text);
2728
- const site = {};
2729
- for (const [field2, at3, kind] of HEAD_SETTINGS) {
2730
- const found = head[at3];
2731
- if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at3), kind, exists: true, value: found.value };
2732
- }
2733
- return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
2734
- }
2735
- async function readSettings(repo, appPath, framework = null) {
2736
- if (framework === "vite-react") return viteSettings(repo, appPath);
2737
- if (framework === "next") return nextSettings(repo, appPath);
2738
- const at3 = (p) => join(appPath, p);
2739
- const schemaPaths = repo.paths.filter((p) => p.startsWith(`${at3(SCHEMAS)}/`) && p.endsWith(".schema.json"));
2740
- if (!schemaPaths.length) return null;
2741
- const named = (p) => p.slice(at3(SCHEMAS).length + 1, -".schema.json".length);
2742
- const schemas = /* @__PURE__ */ new Map();
2743
- const [legacyMap, map, ...read] = await inTurns([at3(`${SCHEMAS}/collecties.json`), at3(`${SCHEMAS}/collections.json`), ...schemaPaths], (p) => repo.read(p));
2744
- schemaPaths.forEach((p, i) => {
2745
- const s = parse(read[i] ?? null);
2746
- if (s && typeof s === "object") schemas.set(named(p), s);
2747
- });
2748
- const elsewhere = { ...parse(legacyMap ?? null) ?? {}, ...parse(map ?? null) ?? {} };
2749
- const jsonFiles = repo.paths.filter((p) => p.startsWith(`${at3(CONTENT)}/`) && p.endsWith(".json") && !p.startsWith(`${at3(SCHEMAS)}/`));
2750
- const collectionOf = (p) => elsewhere[p.slice(appPath ? appPath.length + 1 : 0)] ?? p.slice(at3(CONTENT).length + 1).split("/")[0].replace(/\.json$/, "");
2751
- const filesOf = (collection) => jsonFiles.filter((p) => collectionOf(p) === collection);
2752
- const routeCollection = [...schemas].find(([, s]) => s.properties?.pad && s.properties?.seo);
2753
- const pages = {};
2754
- let routes = null;
2755
- if (routeCollection) {
2756
- const [collection, schema] = routeCollection;
2757
- const allowed = schema.properties.seo?.properties ?? {};
2758
- const files = filesOf(collection).slice(0, MAX_ROUTE_FILES);
2759
- const datas = await inTurns(files, async (p) => parse(await repo.read(p)));
2760
- files.forEach((file, i) => {
2761
- const data = datas[i];
2762
- if (!data || typeof data.pad !== "string" || !ROUTE.test(data.pad)) return;
2763
- const seo = data.seo && typeof data.seo === "object" && !Array.isArray(data.seo) ? data.seo : {};
2764
- pages[data.pad] = fieldsOf(PAGE_FIELDS, seo, allowed, file.slice(appPath ? appPath.length + 1 : 0), "/seo");
2765
- });
2766
- const dir = files[0] ? files[0].slice(appPath ? appPath.length + 1 : 0).replace(/\/[^/]+$/, "") : `${CONTENT}/${collection}`;
2767
- const fields = Object.entries(PAGE_FIELDS).filter(([, { name }]) => allowed[name]).map(([field2, { name, kind }]) => ({ field: field2, pointer: `/seo/${name}`, kind }));
2768
- routes = { dir, fields };
2769
- }
2770
- const siteCollection = [...schemas].find(([, s]) => (s["x-settings"] ?? s["x-instellingen"]) === "site");
2771
- let site = null;
2772
- const siteFile = siteCollection && filesOf(siteCollection[0])[0];
2773
- if (siteCollection && siteFile) {
2774
- const data = parse(await repo.read(siteFile));
2775
- if (data && typeof data === "object" && !Array.isArray(data)) {
2776
- site = fieldsOf(SITE_FIELDS, data, siteCollection[1].properties ?? {}, siteFile.slice(appPath ? appPath.length + 1 : 0), "");
2777
- }
2778
- }
2779
- if (!Object.keys(pages).length && !routes && !site) return null;
2780
- return { pages, routes, site };
2781
- }
2782
3445
  var NEXT_PAGE = /^(src\/)?app\/(.*\/)?page\.(tsx|ts|jsx|js)$/;
2783
3446
  var NEXT_ROOT_LAYOUT = /^(src\/)?app\/layout\.(tsx|ts|jsx|js)$/;
2784
3447
  var CMS_DEPTH = 2;
@@ -2871,6 +3534,153 @@ async function nextSettings(repo, appPath) {
2871
3534
  return { pages: out, routes: null, site, refused };
2872
3535
  }
2873
3536
 
3537
+ // supabase/functions/_shared/html-head.ts
3538
+ var headPointer = (field2) => `/head/${field2}`;
3539
+ var ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
3540
+ function decodeValue(raw) {
3541
+ return raw.replace(/&#x([0-9a-f]+);/gi, (_, h) => String.fromCodePoint(parseInt(h, 16))).replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d))).replace(/&([a-z]+);/gi, (m, n) => ENTITIES[n.toLowerCase()] ?? m).replace(/\s+/g, " ").trim();
3542
+ }
3543
+ function tagsIn(html, from, until) {
3544
+ const out = [];
3545
+ let i = from;
3546
+ while (i < until) {
3547
+ const lt = html.indexOf("<", i);
3548
+ if (lt < 0 || lt >= until) break;
3549
+ if (html.startsWith("<!--", lt)) {
3550
+ const close = html.indexOf("-->", lt + 4);
3551
+ i = close < 0 ? until : close + 3;
3552
+ continue;
3553
+ }
3554
+ const name = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(lt, lt + 64))?.[1];
3555
+ if (!name) {
3556
+ i = lt + 1;
3557
+ continue;
3558
+ }
3559
+ const attrs = [];
3560
+ let j = lt + 1 + name.length;
3561
+ let end = -1;
3562
+ while (j < html.length) {
3563
+ const c = html[j];
3564
+ if (c === ">") {
3565
+ end = j + 1;
3566
+ break;
3567
+ }
3568
+ if (/[\s/]/.test(c)) {
3569
+ j++;
3570
+ continue;
3571
+ }
3572
+ const m = /^([^\s"'>/=]+)(\s*=\s*)?/.exec(html.slice(j, j + 256));
3573
+ if (!m) {
3574
+ j++;
3575
+ continue;
3576
+ }
3577
+ j += m[0].length;
3578
+ if (!m[2]) {
3579
+ attrs.push({ name: m[1].toLowerCase(), value: "", start: j, end: j, quote: null });
3580
+ continue;
3581
+ }
3582
+ const q = html[j];
3583
+ if (q === '"' || q === "'") {
3584
+ const close = html.indexOf(q, j + 1);
3585
+ if (close < 0) break;
3586
+ attrs.push({ name: m[1].toLowerCase(), value: html.slice(j + 1, close), start: j + 1, end: close, quote: q });
3587
+ j = close + 1;
3588
+ } else {
3589
+ const bare = /^[^\s>]*/.exec(html.slice(j))[0];
3590
+ attrs.push({ name: m[1].toLowerCase(), value: bare, start: j, end: j + bare.length, quote: null });
3591
+ j += bare.length;
3592
+ }
3593
+ }
3594
+ if (end < 0) break;
3595
+ out.push({ name: name.toLowerCase(), start: lt, end, attrs });
3596
+ i = end;
3597
+ if (/^(script|style)$/i.test(name)) {
3598
+ const close = html.toLowerCase().indexOf(`</${name.toLowerCase()}`, end);
3599
+ i = close < 0 ? until : close;
3600
+ }
3601
+ }
3602
+ return out;
3603
+ }
3604
+ var attrOf = (tag, name) => tag.attrs.find((a) => a.name === name);
3605
+ var spanOf = (a) => ({ start: a.start, end: a.end, mode: "attr", quote: a.quote });
3606
+ var plain = (raw) => !/[{}]|<%|%>/.test(raw);
3607
+ function readHead(html) {
3608
+ const out = {};
3609
+ const lower = html.toLowerCase();
3610
+ const headAt = lower.search(/<head[\s>]/);
3611
+ const bodyAt = lower.search(/<body[\s>]/);
3612
+ const headEnd = lower.indexOf("</head");
3613
+ const until = headEnd >= 0 ? headEnd : bodyAt >= 0 ? bodyAt : html.length;
3614
+ if (headAt < 0) return out;
3615
+ const htmlTag = tagsIn(html, 0, headAt).find((t) => t.name === "html");
3616
+ const lang = htmlTag && attrOf(htmlTag, "lang");
3617
+ if (lang && lang.value.trim() && plain(lang.value)) out.language = { value: decodeValue(lang.value), spans: [spanOf(lang)] };
3618
+ const tags = tagsIn(html, headAt, until);
3619
+ const metas = tags.filter((t) => t.name === "meta");
3620
+ const meta = (key) => metas.filter((t) => [attrOf(t, "name")?.value, attrOf(t, "property")?.value].some((v) => v?.trim().toLowerCase() === key)).map((t) => attrOf(t, "content")).filter((a) => !!a);
3621
+ const fromMeta = (key, copies) => {
3622
+ const found = meta(key);
3623
+ if (found.length !== 1 || !plain(found[0].value) || !found[0].value.trim()) return void 0;
3624
+ const value = decodeValue(found[0].value);
3625
+ return { value, spans: [spanOf(found[0]), ...copiesOf(value, copies)] };
3626
+ };
3627
+ const copiesOf = (value, keys) => keys.flatMap((k) => meta(k)).filter((a) => plain(a.value) && decodeValue(a.value) === value).map(spanOf);
3628
+ const titles = tags.filter((t) => t.name === "title");
3629
+ if (titles.length === 1) {
3630
+ const t = titles[0];
3631
+ const close = lower.indexOf("</title", t.end);
3632
+ const raw = close >= 0 ? html.slice(t.end, close) : "";
3633
+ if (close >= 0 && raw.trim() && !raw.includes("<") && plain(raw)) {
3634
+ const value = decodeValue(raw);
3635
+ out.title = { value, spans: [{ start: t.end, end: close, mode: "text", quote: null }, ...copiesOf(value, ["og:title", "twitter:title"])] };
3636
+ }
3637
+ }
3638
+ const description = fromMeta("description", ["og:description", "twitter:description"]);
3639
+ if (description) out.description = description;
3640
+ const image = fromMeta("og:image", ["twitter:image"]);
3641
+ if (image) out.image = image;
3642
+ const icons = tags.filter((t) => t.name === "link" && (attrOf(t, "rel")?.value ?? "").toLowerCase().split(/\s+/).includes("icon"));
3643
+ const dark = (t) => /prefers-color-scheme\s*:\s*dark/i.test(attrOf(t, "media")?.value ?? "");
3644
+ for (const [field2, list] of [["favicon", icons.filter((t) => !dark(t))], ["faviconDark", icons.filter(dark)]]) {
3645
+ const href = list.length === 1 ? attrOf(list[0], "href") : void 0;
3646
+ const type = list.length === 1 ? attrOf(list[0], "type")?.value.trim().toLowerCase() : void 0;
3647
+ if (href && href.value.trim() && plain(href.value)) out[field2] = { value: decodeValue(href.value), spans: [spanOf(href)], ...type ? { type } : {} };
3648
+ }
3649
+ return out;
3650
+ }
3651
+
3652
+ // supabase/functions/unbase-projects/settings-vite.ts
3653
+ var VITE_DOCUMENT = "index.html";
3654
+ var HEAD_SETTINGS = [
3655
+ ["name", "title", "text"],
3656
+ ["description", "description", "text"],
3657
+ ["language", "language", "text"],
3658
+ ["faviconLight", "favicon", "image"],
3659
+ ["faviconDark", "faviconDark", "image"],
3660
+ ["socialImage", "image", "image"]
3661
+ ];
3662
+ async function viteSettings(repo, appPath) {
3663
+ const text = await repo.read(join(appPath, VITE_DOCUMENT));
3664
+ if (text === null) return null;
3665
+ const head = readHead(text);
3666
+ const site = {};
3667
+ for (const [field2, at3, kind] of HEAD_SETTINGS) {
3668
+ const found = head[at3];
3669
+ if (found) site[field2] = { file: VITE_DOCUMENT, pointer: headPointer(at3), kind, exists: true, value: found.value };
3670
+ }
3671
+ return Object.keys(site).length ? { pages: {}, routes: null, site } : null;
3672
+ }
3673
+
3674
+ // supabase/functions/unbase-projects/settings.ts
3675
+ var SETTINGS_READERS = {
3676
+ "vite-react": viteSettings,
3677
+ next: nextSettings
3678
+ };
3679
+ async function readSettings(repo, appPath, framework = null) {
3680
+ const reader = framework && Object.hasOwn(SETTINGS_READERS, framework) ? SETTINGS_READERS[framework] : contentSettings;
3681
+ return reader(repo, appPath);
3682
+ }
3683
+
2874
3684
  // supabase/functions/unbase-projects/pages.ts
2875
3685
  var MAX_PAGES = 2e3;
2876
3686
  var registryFiles = (path) => /\.(astro|tsx|jsx|ts|js|mjs|cjs|mts|cts|vue|svelte|md|mdx|html)$/.test(path) || /(^|\/)(opengraph-image|twitter-image|icon|apple-icon)\d*\.(png|jpe?g|gif|svg|ico|webp|avif)$/.test(path) || /^src\/content\/[\s\S]*\.json$/.test(path) || path === "package.json" || path === PAGE_FILE;
@@ -3106,8 +3916,8 @@ function edited(file, text, change) {
3106
3916
  for (const p of [...policies].sort((a, b) => b.start - a.start)) {
3107
3917
  const next = change(p.value);
3108
3918
  if (next === p.value) continue;
3109
- const literal2 = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
3110
- out = `${out.slice(0, p.start)}${literal2}${out.slice(p.end)}`;
3919
+ const literal3 = file.endsWith("vercel.json") ? JSON.stringify(next) : next;
3920
+ out = `${out.slice(0, p.start)}${literal3}${out.slice(p.end)}`;
3111
3921
  }
3112
3922
  return out;
3113
3923
  }
@@ -3145,7 +3955,7 @@ function cspElsewhere(path, text) {
3145
3955
  // supabase/functions/_shared/binding.mjs
3146
3956
  var binding_exports = {};
3147
3957
  __export(binding_exports, {
3148
- ADAPTERS: () => ADAPTERS2,
3958
+ ADAPTERS: () => ADAPTERS3,
3149
3959
  ASTRO: () => ASTRO,
3150
3960
  GATE_COLLECTIONS: () => GATE_COLLECTIONS,
3151
3961
  GATE_PAGES: () => GATE_PAGES,
@@ -3165,6 +3975,7 @@ __export(binding_exports, {
3165
3975
  imageShows: () => imageShows,
3166
3976
  itemsIn: () => itemsIn,
3167
3977
  loaded: () => loaded,
3978
+ newFieldShows: () => newFieldShows,
3168
3979
  newItemShows: () => newItemShows,
3169
3980
  noCopiedContent: () => noCopiedContent,
3170
3981
  parseHtml: () => parseHtml,
@@ -3213,10 +4024,10 @@ var NEXT = {
3213
4024
  // next/image: `/_next/image?url=%2Fimages%2Fbike.jpg&w=640&q=75`.
3214
4025
  images: [{ query: "url" }]
3215
4026
  };
3216
- var ADAPTERS2 = { astro: ASTRO, next: NEXT };
4027
+ var ADAPTERS3 = { astro: ASTRO, next: NEXT };
3217
4028
  var CODE3 = /\.(astro|tsx?|jsx?|mts|mjs|vue|svelte|mdx?)$/;
3218
4029
  var CONFIG2 = /content\.config\./;
3219
- var escape2 = (s) => s.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
4030
+ var escape3 = (s) => s.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&");
3220
4031
  var escapeText = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3221
4032
  var stripComments2 = (code) => code.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:"'`\\])\/\/.*$/gm, "$1");
3222
4033
  function balanced(code, open) {
@@ -3237,13 +4048,13 @@ function balanced(code, open) {
3237
4048
  }
3238
4049
  return null;
3239
4050
  }
3240
- var literal = (s) => {
4051
+ var literal2 = (s) => {
3241
4052
  const t = s.trim();
3242
4053
  const m = t.match(/^(["'`])([\s\S]*)\1$/);
3243
4054
  return m && (m[1] === "`" || !m[2].includes(m[1])) ? m[2] : null;
3244
4055
  };
3245
4056
  var fixed = (s) => {
3246
- const v = literal(s);
4057
+ const v = literal2(s);
3247
4058
  return v !== null && !v.includes("${") ? v : null;
3248
4059
  };
3249
4060
  function argumentsOf(inner) {
@@ -3278,7 +4089,7 @@ function readerFunctionFiles(adapter, paths, root = "") {
3278
4089
  function readerFunctions({ files, adapter, root = "" }) {
3279
4090
  const out = [];
3280
4091
  for (const shape of helperShapes(adapter)) {
3281
- const calls = new RegExp(`\\b(${shape.calls.map(escape2).join("|")})\\s*\\(\\s*([^,)]+)\\s*(?:,\\s*([^,)]+))?`);
4092
+ const calls = new RegExp(`\\b(${shape.calls.map(escape3).join("|")})\\s*\\(\\s*([^,)]+)\\s*(?:,\\s*([^,)]+))?`);
3282
4093
  for (const { path, text } of files) {
3283
4094
  if (!path.startsWith(root)) continue;
3284
4095
  const rel = path.slice(root.length);
@@ -3293,7 +4104,7 @@ function readerFunctions({ files, adapter, root = "" }) {
3293
4104
  const call = body.match(calls);
3294
4105
  if (!call) continue;
3295
4106
  const which = (arg) => {
3296
- const lit = literal(arg);
4107
+ const lit = literal2(arg);
3297
4108
  if (lit !== null) return { name: lit };
3298
4109
  const i = params.indexOf(arg.trim());
3299
4110
  return i >= 0 ? { arg: i } : null;
@@ -3309,11 +4120,11 @@ function readerFunctions({ files, adapter, root = "" }) {
3309
4120
  }
3310
4121
  function directReads(shape, text) {
3311
4122
  if (shape.kind === "call") {
3312
- const re = new RegExp(`(?:${shape.names.map(escape2).join("|")})\\s*[${escape2(shape.open)}]\\s*["'\`]([^"'\`\\n]+)["'\`]`, "g");
4123
+ const re = new RegExp(`(?:${shape.names.map(escape3).join("|")})\\s*[${escape3(shape.open)}]\\s*["'\`]([^"'\`\\n]+)["'\`]`, "g");
3313
4124
  return Array.from(text.matchAll(re), (m) => m[1]);
3314
4125
  }
3315
4126
  if (shape.kind === "folder") {
3316
- const root = escape2(shape.root);
4127
+ const root = escape3(shape.root);
3317
4128
  const re = new RegExp(`["'\`]${root}["'\`]\\s*,\\s*["'\`]([^"'\`\\n]+)["'\`]|["'\`]${root}/([^"'\`/\\n]+)["'\`/]`, "g");
3318
4129
  return Array.from(text.matchAll(re), (m) => m[1] ?? m[2]);
3319
4130
  }
@@ -3322,9 +4133,9 @@ function directReads(shape, text) {
3322
4133
  function readsPattern(adapter, collection) {
3323
4134
  const parts = [];
3324
4135
  for (const s of shapes(adapter)) {
3325
- const name = escape2(collection);
3326
- if (s.kind === "call") parts.push(`(?:${s.names.map(escape2).join("|")})\\s*[${escape2(s.open)}]\\s*["'\`]${name}["'\`]`);
3327
- if (s.kind === "folder") parts.push(`["'\`]${escape2(s.root)}["'\`]\\s*,\\s*["'\`]${name}["'\`]|["'\`]${escape2(s.root)}/${name}["'\`/]`);
4136
+ const name = escape3(collection);
4137
+ if (s.kind === "call") parts.push(`(?:${s.names.map(escape3).join("|")})\\s*[${escape3(s.open)}]\\s*["'\`]${name}["'\`]`);
4138
+ if (s.kind === "folder") parts.push(`["'\`]${escape3(s.root)}["'\`]\\s*,\\s*["'\`]${name}["'\`]|["'\`]${escape3(s.root)}/${name}["'\`/]`);
3328
4139
  }
3329
4140
  return new RegExp(parts.length ? parts.join("|") : "(?!)");
3330
4141
  }
@@ -3337,7 +4148,7 @@ function reads({ files, adapter, collections, functions }) {
3337
4148
  if (!collectionName(r.collection) || keep && !keep.has(r.collection)) return;
3338
4149
  out.set(JSON.stringify([r.file, r.collection, r.via, r.call ?? "", r.entry ?? ""]), r);
3339
4150
  };
3340
- const callOf = helpers.length ? new RegExp(`(?<![\\w$.])(${[...new Set(helpers.map((h) => h.call))].map(escape2).join("|")})\\s*\\(`, "g") : null;
4151
+ const callOf = helpers.length ? new RegExp(`(?<![\\w$.])(${[...new Set(helpers.map((h) => h.call))].map(escape3).join("|")})\\s*\\(`, "g") : null;
3341
4152
  for (const { path, text } of files) {
3342
4153
  if (!CODE3.test(path) || CONFIG2.test(path) || !text) continue;
3343
4154
  for (const s of shapes(adapter)) for (const name of directReads(s, text)) add({ file: path, collection: name, via: s.kind });
@@ -3719,11 +4530,11 @@ function elementsOf(html) {
3719
4530
  };
3720
4531
  const body = find(root, "body") ?? root;
3721
4532
  const out = [];
3722
- const outside = (e) => OUT.test(e.tag) || e.attrs.id === "comment-modus" || e.attrs.id === "comment-modus-schil" || "data-cm-ignore" in e.attrs || "data-cm-negeer" in e.attrs || "data-unbase-layer" in e.attrs;
4533
+ const outside2 = (e) => OUT.test(e.tag) || e.attrs.id === "comment-modus" || e.attrs.id === "comment-modus-schil" || "data-cm-ignore" in e.attrs || "data-cm-negeer" in e.attrs || "data-unbase-layer" in e.attrs;
3723
4534
  const walk = (n, place, depth) => {
3724
4535
  const seen = /* @__PURE__ */ new Map();
3725
4536
  for (const c of n.children) {
3726
- if (typeof c === "string" || outside(c)) continue;
4537
+ if (typeof c === "string" || outside2(c)) continue;
3727
4538
  const k = seen.get(c.tag) ?? 0;
3728
4539
  seen.set(c.tag, k + 1);
3729
4540
  const at3 = `${place ? `${place}/` : ""}${c.tag}:${k}`;
@@ -3895,7 +4706,7 @@ function fieldUse({ text, fields }) {
3895
4706
  if (FIELD_NAME.test(name)) taken.add(name);
3896
4707
  }
3897
4708
  }
3898
- return (fields ?? []).map((f) => f.key).filter((k, i, all) => FIELD_NAME.test(k) && all.indexOf(k) === i).filter((k) => taken.has(k) || new RegExp(`\\??\\.\\s*${escape2(k)}(?![\\w$])|\\[\\s*["'\`]${escape2(k)}["'\`]\\s*\\]`).test(code));
4709
+ return (fields ?? []).map((f) => f.key).filter((k, i, all) => FIELD_NAME.test(k) && all.indexOf(k) === i).filter((k) => taken.has(k) || new RegExp(`\\??\\.\\s*${escape3(k)}(?![\\w$])|\\[\\s*["'\`]${escape3(k)}["'\`]\\s*\\]`).test(code));
3899
4710
  }
3900
4711
  var isCode = (path) => CODE3.test(path) && !CONFIG2.test(path);
3901
4712
  function importedBy(importers) {
@@ -4056,16 +4867,18 @@ function tagsIn2(text) {
4056
4867
  var untag = (text) => String(text ?? "").replace(TAG, "").replace(TAG_CHAR, "").replace(/\uDB40(?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC01-\uDC7F]/g, "");
4057
4868
  function tagItem({ collection, id, data, fields = [] }) {
4058
4869
  const esc = (k) => k.replace(/~/g, "~0").replace(/\//g, "~1");
4059
- const walk = (value, pointer, field2) => {
4870
+ const walk = (value, pointer, field2, picture = false) => {
4060
4871
  if (typeof value === "string") {
4061
4872
  const v = value.trim();
4062
4873
  if (!field2 || !TAGGED_TYPES.includes(field2.type) || !v || /[\u{E0000}-\u{E007F}]/u.test(value) || /^(?:[a-z][a-z0-9+.-]*:|\/|#|www\.)/i.test(v)) return value;
4874
+ if (picture || !new RegExp("\\p{L}", "u").test(v)) return value;
4063
4875
  const tag = tagOf({ collection, id, pointer });
4064
4876
  return tag ? value + tag : value;
4065
4877
  }
4066
4878
  if (Array.isArray(value)) return field2?.type === "list" ? value.map((v, i) => walk(v, `${pointer}/${i}`, { type: "group", fields: field2.fields ?? [] })) : value;
4067
4879
  if (value && typeof value === "object" && field2 && (field2.type === "group" || field2.type === "item")) {
4068
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v, `${pointer}/${esc(k)}`, (field2.fields ?? []).find((f) => f.key === k) ?? null)]));
4880
+ const pictureGroup = field2.type === "group" && (field2.fields ?? []).some((f) => f.type === "image");
4881
+ return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, walk(v, `${pointer}/${esc(k)}`, (field2.fields ?? []).find((f) => f.key === k) ?? null, pictureGroup)]));
4069
4882
  }
4070
4883
  return value;
4071
4884
  };
@@ -4247,20 +5060,42 @@ function itemsIn({ html, collections, adapter, uses = {}, formats = [] }) {
4247
5060
  };
4248
5061
  const bind = (it, pointer, extra = {}) => ({ binding: { collection: it.collection, item: it.id, field: pointer }, key: keyOf(it, pointer), ...extra });
4249
5062
  const ownText = (node) => node.children.filter((c) => typeof c === "string").join("");
5063
+ const escKey = (k) => k.replace(/~/g, "~0").replace(/\//g, "~1");
5064
+ const slots = (it, type) => {
5065
+ const out2 = [];
5066
+ for (const f of it.fields) {
5067
+ if (!reads2(it.collection, f.key)) continue;
5068
+ if (f.type === type) out2.push({ pointer: `/${escKey(f.key)}`, value: it.data?.[f.key] });
5069
+ else if (f.type === "group") {
5070
+ for (const g of f.fields ?? []) if (g.type === type) out2.push({ pointer: `/${escKey(f.key)}/${escKey(g.key)}`, value: it.data?.[f.key]?.[g.key] });
5071
+ }
5072
+ }
5073
+ return out2.map((s) => ({ ...s, value: s.value && typeof s.value === "object" && typeof s.value.src === "string" ? s.value.src : s.value }));
5074
+ };
5075
+ const itemOfNode = (node) => {
5076
+ const own = new Set(Object.values(node.attrs).flatMap((v) => tagsIn2(v).map((r) => `${r.collection}/${r.id}`)));
5077
+ return own.size === 1 ? [...own][0] : own.size ? null : cardItem(node.parent);
5078
+ };
4250
5079
  for (const e of elementsOf(root)) {
4251
5080
  const node = e.node;
5081
+ if (node.tag === "a" && typeof node.attrs.href === "string" && node.attrs.href.trim()) {
5082
+ const href = untag(node.attrs.href).trim();
5083
+ const itemKey2 = itemOfNode(node);
5084
+ const it2 = itemKey2 ? items.get(itemKey2) : null;
5085
+ const fit = it2 ? slots(it2, "link").filter((s) => typeof s.value === "string" && s.value.trim() === href) : [];
5086
+ if (it2 && fit.length === 1 && it2.file) stamp(node, { "data-unbase-cms": `${it2.collection}/${it2.id}`, "data-unbase-cms-href": keyOf(it2, fit[0].pointer) });
5087
+ }
4252
5088
  if (node.tag === "img") {
4253
5089
  const src = node.attrs.src ?? "";
4254
5090
  if (!src) continue;
4255
- const own2 = new Set(Object.values(node.attrs).flatMap((v) => tagsIn2(v).map((r) => `${r.collection}/${r.id}`)));
4256
- const itemKey2 = own2.size === 1 ? [...own2][0] : own2.size ? null : cardItem(node.parent);
4257
- const showing = (it3) => it3.fields.filter((f) => f.type === "image" && reads2(it3.collection, f.key) && imageShows(src, it3.data?.[f.key], adapter)).map((f) => f.key);
5091
+ const itemKey2 = itemOfNode(node);
5092
+ const showing = (it3) => slots(it3, "image").filter((s) => imageShows(src, s.value, adapter)).map((s) => s.pointer);
4258
5093
  const it2 = itemKey2 ? items.get(itemKey2) : null;
4259
5094
  if (it2) {
4260
5095
  const fit = showing(it2);
4261
- if (fit.length === 1) list(e, { text: "", ...bind(it2, `/${fit[0]}`, { image: true }) }, it2);
5096
+ if (fit.length === 1) list(e, { text: "", ...bind(it2, fit[0], { image: true }) }, it2);
4262
5097
  else if (fit.length > 1) list(e, { text: "", reason: "ambiguous", candidates: fit.length }, it2);
4263
- else if (it2.fields.some((f) => f.type === "image" && reads2(it2.collection, f.key))) list(e, { text: "", reason: "unproven" }, it2);
5098
+ else if (slots(it2, "image").length) list(e, { text: "", reason: "unproven" }, it2);
4264
5099
  } else {
4265
5100
  const anywhere = [...items.values()].flatMap((x) => showing(x));
4266
5101
  if (anywhere.length) list(e, { text: "", reason: anywhere.length > 1 ? "ambiguous" : "unproven", candidates: anywhere.length }, null);
@@ -4342,6 +5177,40 @@ function itemsIn({ html, collections, adapter, uses = {}, formats = [] }) {
4342
5177
  const bound = elements.filter((e) => e.binding).length;
4343
5178
  return { html: untag(out), elements, bound, unbound: elements.length - bound, cards };
4344
5179
  }
5180
+ var addedKind = (f) => TAGGED_TYPES.includes(f.type) ? "text" : f.type === "image" || f.type === "group" && (f.fields ?? []).some((g) => g.type === "image") ? "image" : null;
5181
+ function newFieldShows({ collection, added, draft, renders, collections, adapter, uses = {}, formats = [] }) {
5182
+ const withItem = collections.map((c) => c.name === collection ? { ...c, items: [...(c.items ?? []).filter((i) => i.id !== draft.id), { id: draft.id, file: draft.file, data: draft.data }] } : c);
5183
+ const pages = renders.filter((r) => typeof r.html === "string" && r.html.length > 0);
5184
+ const bound = new Map(pages.map((p) => [p.path, itemsIn({ html: p.html, collections: withItem, adapter, uses, formats }).elements]));
5185
+ const textOfPage = new Map(pages.map((p) => [p.path, untag(wholeText(parseHtml(p.html)))]));
5186
+ const stemOfPath = (p) => (String(p ?? "").split(/[?#]/)[0].split("/").pop() ?? "").replace(/\.[^.]+$/, "").toLowerCase();
5187
+ const pictureAt = (f) => {
5188
+ const v = draft.data?.[f.key];
5189
+ if (f.type === "image") return typeof v === "string" ? v : typeof v?.src === "string" ? v.src : null;
5190
+ const sub = (f.fields ?? []).find((g) => g.type === "image");
5191
+ return sub && typeof v?.[sub.key] === "string" ? v[sub.key] : null;
5192
+ };
5193
+ return added.map((f) => {
5194
+ const kind = addedKind(f);
5195
+ const base = { key: f.key, type: f.type, bound: false, live: false, pages: [] };
5196
+ if (!kind) return { ...base, shows: null, reason: "unchecked" };
5197
+ const value = kind === "text" ? draft.data?.[f.key] : pictureAt(f);
5198
+ if (typeof value !== "string" || !value.trim()) return { ...base, shows: null, reason: "no-test-value" };
5199
+ if (!pages.length) return { ...base, shows: null, reason: "not-rendered" };
5200
+ const shown2 = [];
5201
+ let isBound = false;
5202
+ let live = false;
5203
+ for (const p of pages) {
5204
+ const mine = (bound.get(p.path) ?? []).filter((e) => e.binding && e.binding.collection === collection && e.binding.item === draft.id && (e.binding.field === `/${f.key}` || e.binding.field.startsWith(`/${f.key}/`)));
5205
+ const seen = mine.length > 0 || (kind === "text" ? (textOfPage.get(p.path) ?? "").includes(collapse(untag(value))) : [...p.html.matchAll(/<(?:img|source)\b[^>]*>/gi)].some((m) => m[0].toLowerCase().includes(stemOfPath(value))));
5206
+ if (!seen) continue;
5207
+ shown2.push(p.path);
5208
+ if (mine.length) isBound = true;
5209
+ if (mine.some((e) => e.exact)) live = true;
5210
+ }
5211
+ return { ...base, shows: shown2.length > 0, bound: isBound, live, pages: shown2, ...shown2.length && !isBound ? { reason: "unbound" } : {} };
5212
+ });
5213
+ }
4345
5214
  export {
4346
5215
  binding_exports as binding,
4347
5216
  pages_core_exports as core,