@conloca/cli 0.2.6 → 0.2.7

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.
Files changed (2) hide show
  1. package/dist/conloca.js +1201 -441
  2. package/package.json +8 -8
package/dist/conloca.js CHANGED
@@ -2044,9 +2044,9 @@ function useColor() {
2044
2044
  var program = new Command;
2045
2045
 
2046
2046
  // src/commands/asset-add.ts
2047
- import { existsSync as existsSync7 } from "node:fs";
2048
- import { readFile as readFile12 } from "node:fs/promises";
2049
- import { basename as basename4, join as join15, relative as relative6, resolve as resolve8 } from "node:path";
2047
+ import { existsSync as existsSync8 } from "node:fs";
2048
+ import { readFile as readFile14 } from "node:fs/promises";
2049
+ import { basename as basename4, join as join17, relative as relative7, resolve as resolve8 } from "node:path";
2050
2050
  import { pathToFileURL as pathToFileURL2 } from "node:url";
2051
2051
  import { AssetOperations } from "@conloca/content-api/node";
2052
2052
 
@@ -2183,6 +2183,7 @@ function parseObjectEntries(objectText) {
2183
2183
  return null;
2184
2184
  const body = objectText.slice(1, -1);
2185
2185
  const entries = new Map;
2186
+ const shorthands = new Set;
2186
2187
  let hasSpread = false;
2187
2188
  let i = 0;
2188
2189
  while (i < body.length) {
@@ -2197,7 +2198,11 @@ function parseObjectEntries(objectText) {
2197
2198
  }
2198
2199
  const keyMatch = /^(?:([$A-Za-z_][$\w]*)|'([^']*)'|"([^"]*)")\s*:/.exec(body.slice(i));
2199
2200
  if (!keyMatch) {
2200
- i = skipValue(body, i);
2201
+ const end = skipValue(body, i);
2202
+ const word = body.slice(i, end).trim();
2203
+ if (/^[$A-Za-z_][$\w]*$/u.test(word))
2204
+ shorthands.add(word);
2205
+ i = end;
2201
2206
  continue;
2202
2207
  }
2203
2208
  const valueStart = i + keyMatch[0].length;
@@ -2205,7 +2210,7 @@ function parseObjectEntries(objectText) {
2205
2210
  entries.set(keyMatch[1] ?? keyMatch[2] ?? keyMatch[3] ?? "", body.slice(valueStart, valueEnd).trim());
2206
2211
  i = valueEnd;
2207
2212
  }
2208
- return { entries, hasSpread };
2213
+ return { entries, shorthands, hasSpread };
2209
2214
  }
2210
2215
  function stringLiteral(raw) {
2211
2216
  const match = /^(?:'([^'\\]*)'|"([^"\\]*)")$/.exec(raw.trim());
@@ -2230,6 +2235,127 @@ function callOptions(configText, name) {
2230
2235
 
2231
2236
  // src/lib/connect/astro-config.ts
2232
2237
  import { generateCode, parseExpression, parseModule } from "magicast";
2238
+
2239
+ // src/lib/is-record.ts
2240
+ function isRecord(value) {
2241
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2242
+ }
2243
+
2244
+ // src/lib/connect/site-domain.ts
2245
+ import { addressSiteName, isValidSiteBase } from "@conloca/content-api";
2246
+
2247
+ // src/lib/connect/step.ts
2248
+ import { mkdir, writeFile } from "node:fs/promises";
2249
+ import { dirname } from "node:path";
2250
+ var SCALAR_ARRAY = /^(.*)\[\n[^[\]{}]*?\n\s*\](.*)$/gm;
2251
+ var INLINE_ARRAY = /\[[^\n[\]{}]*[^\s[\]{}][^\n[\]{}]*\]/;
2252
+ var PRINT_WIDTH = 80;
2253
+ function jsonLike(before, value) {
2254
+ const indent = /^[ \t]+/m.exec(before)?.[0];
2255
+ let json = JSON.stringify(value, null, indent);
2256
+ if (INLINE_ARRAY.test(before)) {
2257
+ json = json.replace(SCALAR_ARRAY, (block, head, tail) => {
2258
+ const items = block.slice(head.length + 1, block.length - tail.length - 1).trim().split(/,\n\s*/);
2259
+ const line = `${head}[${items.join(", ")}]${tail}`;
2260
+ return line.length <= PRINT_WIDTH ? line : block;
2261
+ });
2262
+ }
2263
+ return `${json}${before.endsWith(`
2264
+ `) ? `
2265
+ ` : ""}`;
2266
+ }
2267
+ async function writeEdits(edits) {
2268
+ await Promise.all(edits.map(async (edit) => {
2269
+ await mkdir(dirname(edit.path), { recursive: true });
2270
+ await writeFile(edit.path, edit.after, "utf8");
2271
+ }));
2272
+ }
2273
+
2274
+ // src/lib/connect/site-domain.ts
2275
+ function isSitesConfig(value) {
2276
+ return isRecord(value) && isRecord(value.sites) && Object.values(value.sites).every((site) => isRecord(site) && Array.isArray(site.locales) && typeof site.defaultLocale === "string" && (site.domains === undefined || isRecord(site.domains)) && (site.base === undefined || typeof site.base === "string"));
2277
+ }
2278
+ function siteBase(base) {
2279
+ const leading = base === null || base.startsWith("/") ? base ?? "/" : `/${base}`;
2280
+ return leading.endsWith("/") ? leading : `${leading}/`;
2281
+ }
2282
+ function writeSiteAddress(input) {
2283
+ const { path, text, site } = input;
2284
+ const url = URL.canParse(site) ? new URL(site) : null;
2285
+ if (url?.protocol !== "https:") {
2286
+ return { state: "needs-you", message: `Astro's site must be an https URL, got ${site}`, edits: [] };
2287
+ }
2288
+ const base = siteBase(input.base);
2289
+ if (!isValidSiteBase(base)) {
2290
+ return {
2291
+ state: "needs-you",
2292
+ message: `Astro's base ${input.base} is not a path the editor can open`,
2293
+ edits: []
2294
+ };
2295
+ }
2296
+ let config;
2297
+ try {
2298
+ config = JSON.parse(text);
2299
+ } catch {
2300
+ return { state: "failed", message: `${path} is not valid JSON`, edits: [] };
2301
+ }
2302
+ if (!isSitesConfig(config)) {
2303
+ return { state: "failed", message: `${path} has no readable sites map`, edits: [] };
2304
+ }
2305
+ const name = addressSiteName(config);
2306
+ const entry = name === null ? undefined : config.sites[name];
2307
+ if (name === null || entry === undefined) {
2308
+ return {
2309
+ state: "needs-you",
2310
+ message: `${path} lists several sites and none is named default; add the domain to the right one yourself`,
2311
+ lines: [`"domains": { "<locale>": "${url.hostname}" }`, ...base === "/" ? [] : [`"base": "${base}"`]],
2312
+ edits: []
2313
+ };
2314
+ }
2315
+ const host = url.hostname;
2316
+ const locale = entry.defaultLocale;
2317
+ const domain = entry.domains?.[locale];
2318
+ const kept = [
2319
+ ...domain !== undefined && domain !== host ? [`domains.${locale} is ${domain}, not ${host}`] : [],
2320
+ ...entry.base !== undefined && entry.base !== base ? [`base is ${entry.base}, not ${base}`] : []
2321
+ ];
2322
+ if (kept.length === 0 && domain !== undefined && (entry.base !== undefined || base === "/")) {
2323
+ return { state: "done", message: `site '${name}' already lists ${host}`, edits: [] };
2324
+ }
2325
+ entry.domains = { ...entry.domains, [locale]: host };
2326
+ if (base !== "/" || entry.base !== undefined)
2327
+ entry.base = base;
2328
+ const edits = [{ path, before: text, after: jsonLike(text, config) }];
2329
+ if (kept.length > 0) {
2330
+ return {
2331
+ state: "differs",
2332
+ message: `site '${name}' in ${path}: ${kept.join("; ")} (kept yours)`,
2333
+ edits: [],
2334
+ replacement: edits
2335
+ };
2336
+ }
2337
+ return {
2338
+ state: "changed",
2339
+ message: `wrote ${host}${base === "/" ? "" : ` and base ${base}`} into site '${name}'`,
2340
+ edits
2341
+ };
2342
+ }
2343
+ function siteUrlOf(sitesText) {
2344
+ let config;
2345
+ try {
2346
+ config = JSON.parse(sitesText);
2347
+ } catch {
2348
+ return null;
2349
+ }
2350
+ if (!isSitesConfig(config))
2351
+ return null;
2352
+ const name = addressSiteName(config);
2353
+ const entry = name === null ? undefined : config.sites[name];
2354
+ const domain = entry?.domains?.[entry.defaultLocale];
2355
+ return domain === undefined ? null : `https://${domain}`;
2356
+ }
2357
+
2358
+ // src/lib/connect/astro-config.ts
2233
2359
  var REMOVED_OPTIONS = new Set([
2234
2360
  "buildToken",
2235
2361
  "publicBaseUrl",
@@ -2332,6 +2458,56 @@ function removedKeyOptions(text) {
2332
2458
  return null;
2333
2459
  return names.flatMap((name) => name !== null && REMOVED_OPTIONS.has(name) ? [name] : []);
2334
2460
  }
2461
+ function withoutPreviewBuildOptions(text, names) {
2462
+ let mod;
2463
+ try {
2464
+ mod = parseModule(text);
2465
+ } catch {
2466
+ return "computed";
2467
+ }
2468
+ const program = mod.$ast;
2469
+ if (program.type !== "Program")
2470
+ return "computed";
2471
+ const config = configObject(program);
2472
+ const value = config === null ? undefined : property(config, "integrations")?.value;
2473
+ const elements = value?.type === "ArrayExpression" ? value.elements : [];
2474
+ const call = elements[callIndex(elements, localName(importLocals(program), IMPORTS.editorPage))];
2475
+ const [options] = call?.type === "CallExpression" ? call.arguments : [];
2476
+ const previewBuild = options?.type === "ObjectExpression" ? property(options, "previewBuild")?.value : undefined;
2477
+ if (previewBuild?.type !== "ObjectExpression")
2478
+ return "computed";
2479
+ const removed = previewBuild.properties.filter((p) => names.has(propertyName(p) ?? ""));
2480
+ if (removed.length === 0)
2481
+ return null;
2482
+ previewBuild.properties = previewBuild.properties.filter((p) => !removed.includes(p));
2483
+ const callees = removed.flatMap((p) => p.type === "ObjectProperty" && p.value.type === "CallExpression" && p.value.callee.type === "Identifier" ? [p.value.callee.name] : []);
2484
+ const code = program.body.filter((statement) => statement.type !== "ImportDeclaration");
2485
+ for (const local of callees) {
2486
+ if (!namesIdentifier(code, local))
2487
+ delete mod.imports[local];
2488
+ }
2489
+ return { after: printModule(mod, text) };
2490
+ }
2491
+ var NOT_CODE = new Set([
2492
+ "loc",
2493
+ "start",
2494
+ "end",
2495
+ "original",
2496
+ "tokens",
2497
+ "comments",
2498
+ "leadingComments",
2499
+ "trailingComments",
2500
+ "extra"
2501
+ ]);
2502
+ function namesIdentifier(node, name) {
2503
+ if (Array.isArray(node))
2504
+ return node.some((child) => namesIdentifier(child, name));
2505
+ if (!isRecord(node))
2506
+ return false;
2507
+ if (node.type === "Identifier" && node.name === name)
2508
+ return true;
2509
+ return Object.entries(node).some(([key, child]) => !NOT_CODE.has(key) && namesIdentifier(child, name));
2510
+ }
2335
2511
  function pasteLines(repoUri) {
2336
2512
  return [
2337
2513
  `import react from '${IMPORTS.react.from}';`,
@@ -2554,6 +2730,45 @@ function readAstroSite(text) {
2554
2730
  const base = readAstroOption(text, "base");
2555
2731
  return site === undefined || base === undefined ? "computed" : { site, base };
2556
2732
  }
2733
+ function addAstroSiteStep(input) {
2734
+ const { path, text } = input;
2735
+ if (input.adapter !== "@astrojs/vercel" && input.adapter !== "@astrojs/netlify") {
2736
+ return { state: "skipped", message: `${input.adapter} needs no site for previews`, edits: [] };
2737
+ }
2738
+ const current = readAstroSite(text);
2739
+ if (current === "computed")
2740
+ return { state: "skipped", message: "astro.config computes its site", edits: [] };
2741
+ if (current.site !== null)
2742
+ return { state: "done", message: `astro.config sets site ${current.site}`, edits: [] };
2743
+ const given = input.siteUrl ?? siteUrlOf(input.sitesText);
2744
+ const parsed = given !== null && URL.canParse(given) ? new URL(given) : null;
2745
+ if (given !== null && parsed?.protocol !== "https:") {
2746
+ return { state: "needs-you", message: `Astro's site must be an https URL, got ${given}`, edits: [] };
2747
+ }
2748
+ const url = parsed?.origin ?? null;
2749
+ const shown = url ?? "<your production URL>";
2750
+ const message = `astro.config sets no site, so your own pages leave the preview (302) instead of staying in it; site: '${shown}' fixes that and also changes canonical, sitemap, RSS and Open Graph URLs on your live pages`;
2751
+ const lines = [`site: '${shown}',`];
2752
+ let config = null;
2753
+ try {
2754
+ config = url === null ? null : parseModule(text);
2755
+ } catch {
2756
+ config = null;
2757
+ }
2758
+ const program = config?.$ast;
2759
+ const object = program?.type === "Program" ? configObject(program) : null;
2760
+ if (config === null || object === null)
2761
+ return { state: "needs-you", message, lines, edits: [] };
2762
+ object.properties.unshift(...objectProperties(`site: '${url}'`));
2763
+ return {
2764
+ state: "differs",
2765
+ message,
2766
+ lines,
2767
+ edits: [],
2768
+ replacement: [{ path, before: text, after: printModule(config, text) }],
2769
+ question: `Set site to ${shown} in astro.config? It changes canonical, sitemap, RSS and Open Graph URLs on your live pages.`
2770
+ };
2771
+ }
2557
2772
  function dataSchemaLines(assetsPath) {
2558
2773
  return [
2559
2774
  "import { schemaTypia } from './typia-vite.mjs';",
@@ -2666,14 +2881,14 @@ function messageOf(error) {
2666
2881
  }
2667
2882
 
2668
2883
  // src/commands/data.ts
2669
- import { existsSync as existsSync6 } from "node:fs";
2670
- import { readFile as readFile11 } from "node:fs/promises";
2671
- import { join as join14, relative as relative5, resolve as resolve7 } from "node:path";
2884
+ import { existsSync as existsSync7 } from "node:fs";
2885
+ import { readFile as readFile13 } from "node:fs/promises";
2886
+ import { join as join16, relative as relative6, resolve as resolve7 } from "node:path";
2672
2887
 
2673
2888
  // src/lib/connect/data-schemas.ts
2674
2889
  import { existsSync as existsSync3 } from "node:fs";
2675
2890
  import { readFile as readFile2 } from "node:fs/promises";
2676
- import { dirname as dirname2, join as join3, relative, resolve as resolve3, sep } from "node:path";
2891
+ import { dirname as dirname3, join as join3, relative, resolve as resolve3, sep } from "node:path";
2677
2892
  import { parseModule as parseModule2 } from "magicast";
2678
2893
 
2679
2894
  // src/templates/project-files.ts
@@ -2856,18 +3071,13 @@ Working with a coding agent? \`.claude/skills/conloca/SKILL.md\` teaches it Conl
2856
3071
  `;
2857
3072
  }
2858
3073
 
2859
- // src/lib/is-record.ts
2860
- function isRecord(value) {
2861
- return typeof value === "object" && value !== null && !Array.isArray(value);
2862
- }
2863
-
2864
3074
  // src/lib/project-template.ts
2865
3075
  import { readFile } from "node:fs/promises";
2866
3076
  import { basename as basename2 } from "node:path";
2867
3077
 
2868
3078
  // src/lib/package-manager.ts
2869
3079
  import { existsSync as existsSync2 } from "node:fs";
2870
- import { dirname, join as join2, resolve as resolve2 } from "node:path";
3080
+ import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
2871
3081
  var PACKAGE_MANAGERS = ["bun", "npm", "pnpm", "yarn"];
2872
3082
  function isPackageManager(value) {
2873
3083
  return PACKAGE_MANAGERS.includes(value);
@@ -2918,13 +3128,13 @@ var LOCKFILES = [
2918
3128
  ];
2919
3129
  function lockfileInstall(projectDir, repoRoot, exists = existsSync2) {
2920
3130
  const root = resolve2(repoRoot);
2921
- for (let dir = resolve2(projectDir);; dir = dirname(dir)) {
3131
+ for (let dir = resolve2(projectDir);; dir = dirname2(dir)) {
2922
3132
  for (const [name, packageManager] of LOCKFILES) {
2923
3133
  const lockfile = join2(dir, name);
2924
3134
  if (exists(lockfile))
2925
3135
  return { packageManager, lockfile, installDir: dir };
2926
3136
  }
2927
- if (dir === root || dir === dirname(dir))
3137
+ if (dir === root || dir === dirname2(dir))
2928
3138
  return null;
2929
3139
  }
2930
3140
  }
@@ -2932,7 +3142,7 @@ function lockfileInstall(projectDir, repoRoot, exists = existsSync2) {
2932
3142
  // src/lib/project-template.ts
2933
3143
  var THIRD_PARTY_VERSIONS = {
2934
3144
  astro: "^7.3.1",
2935
- "@astrojs/node": "^11.1.5",
3145
+ "@astrojs/node": "11.1.9",
2936
3146
  "@astrojs/react": "^6.0.5",
2937
3147
  "@puckeditor/core": "^0.23.0",
2938
3148
  "@vitejs/plugin-react": "^5.2.0",
@@ -2942,8 +3152,35 @@ var THIRD_PARTY_VERSIONS = {
2942
3152
  "@ttsc/unplugin": "0.35.0",
2943
3153
  ttsc: "0.35.0"
2944
3154
  };
3155
+ var ADAPTER_VERSIONS = {
3156
+ "@astrojs/vercel": "11.0.18",
3157
+ "@astrojs/netlify": "8.2.11",
3158
+ "@astrojs/cloudflare": "14.3.2",
3159
+ "@astrojs/node": "11.1.9"
3160
+ };
2945
3161
  var DEV_ONLY = new Set(["@ttsc/unplugin", "ttsc"]);
2946
3162
  var MANIFEST_CANDIDATES = ["../package.json", "../../package.json"];
3163
+ async function withWorkspacePins(manifest, location) {
3164
+ const pinsOf = async (specs) => {
3165
+ if (specs === undefined)
3166
+ return;
3167
+ const pins = await Promise.all(Object.entries(specs).map(async ([name, spec]) => {
3168
+ if (!spec.startsWith("workspace:"))
3169
+ return [name, spec];
3170
+ const sibling = JSON.parse(await readFile(new URL(`../${basename2(name)}/package.json`, location), "utf-8"));
3171
+ if (typeof sibling.version !== "string") {
3172
+ throw new Error(`could not read the version of workspace package ${name}`);
3173
+ }
3174
+ return [name, sibling.version];
3175
+ }));
3176
+ return Object.fromEntries(pins);
3177
+ };
3178
+ const [dependencies, peerDependencies] = await Promise.all([
3179
+ pinsOf(manifest.dependencies),
3180
+ pinsOf(manifest.peerDependencies)
3181
+ ]);
3182
+ return { version: manifest.version, dependencies, peerDependencies };
3183
+ }
2947
3184
  async function readCliManifest() {
2948
3185
  for (const candidate of MANIFEST_CANDIDATES) {
2949
3186
  let manifest;
@@ -2953,11 +3190,7 @@ async function readCliManifest() {
2953
3190
  continue;
2954
3191
  }
2955
3192
  if (typeof manifest.version === "string") {
2956
- return {
2957
- version: manifest.version,
2958
- dependencies: manifest.dependencies,
2959
- peerDependencies: manifest.peerDependencies
2960
- };
3193
+ return withWorkspacePins({ version: manifest.version, dependencies: manifest.dependencies, peerDependencies: manifest.peerDependencies }, new URL(candidate, import.meta.url));
2961
3194
  }
2962
3195
  }
2963
3196
  throw new Error("could not read the version of @conloca/cli from its own package.json");
@@ -2970,8 +3203,7 @@ var SCAFFOLD_CONLOCA_PACKAGES = ["@conloca/astro-cms", "@conloca/content-api"];
2970
3203
  function conlocaRange(manifest, name) {
2971
3204
  if (name === "@conloca/cli")
2972
3205
  return manifest.version;
2973
- const declared = manifest.dependencies?.[name] ?? manifest.peerDependencies?.[name];
2974
- return declared?.startsWith("workspace:") ? manifest.version : declared;
3206
+ return manifest.dependencies?.[name] ?? manifest.peerDependencies?.[name];
2975
3207
  }
2976
3208
  function renderPackageJson(input) {
2977
3209
  const dependencies = {};
@@ -3059,7 +3291,7 @@ async function contentConfigStep(projectDir, schemasPath) {
3059
3291
  const { findContentConfig } = await import("@conloca/astro-cms/checks");
3060
3292
  const found = findContentConfig(projectDir);
3061
3293
  const path = found ?? join3(projectDir, "src", "content.config.ts");
3062
- const target = relative(dirname2(path), resolve3(projectDir, schemasPath).replace(/\.[cm]?[jt]sx?$/, ""));
3294
+ const target = relative(dirname3(path), resolve3(projectDir, schemasPath).replace(/\.[cm]?[jt]sx?$/, ""));
3063
3295
  const specifier = target.startsWith(`..${sep}`) ? target.split(sep).join("/") : `./${target.split(sep).join("/")}`;
3064
3296
  if (found === null) {
3065
3297
  const after = CONTENT_CONFIG_TEMPLATE.replace("'./schemas/data'", `'${specifier}'`);
@@ -3148,33 +3380,6 @@ async function wireDataSchemas(projectDir) {
3148
3380
  return edits.length === 0 && packages.length === 0 ? { state: "done", message: "the data schemas and the media folder are wired", edits, packages } : { state: "changed", message: notes.join("; "), edits, packages };
3149
3381
  }
3150
3382
 
3151
- // src/lib/connect/step.ts
3152
- import { mkdir, writeFile } from "node:fs/promises";
3153
- import { dirname as dirname3 } from "node:path";
3154
- var SCALAR_ARRAY = /^(.*)\[\n[^[\]{}]*?\n\s*\](.*)$/gm;
3155
- var INLINE_ARRAY = /\[[^\n[\]{}]*[^\s[\]{}][^\n[\]{}]*\]/;
3156
- var PRINT_WIDTH = 80;
3157
- function jsonLike(before, value) {
3158
- const indent = /^[ \t]+/m.exec(before)?.[0];
3159
- let json = JSON.stringify(value, null, indent);
3160
- if (INLINE_ARRAY.test(before)) {
3161
- json = json.replace(SCALAR_ARRAY, (block, head, tail) => {
3162
- const items = block.slice(head.length + 1, block.length - tail.length - 1).trim().split(/,\n\s*/);
3163
- const line = `${head}[${items.join(", ")}]${tail}`;
3164
- return line.length <= PRINT_WIDTH ? line : block;
3165
- });
3166
- }
3167
- return `${json}${before.endsWith(`
3168
- `) ? `
3169
- ` : ""}`;
3170
- }
3171
- async function writeEdits(edits) {
3172
- await Promise.all(edits.map(async (edit) => {
3173
- await mkdir(dirname3(edit.path), { recursive: true });
3174
- await writeFile(edit.path, edit.after, "utf8");
3175
- }));
3176
- }
3177
-
3178
3383
  // src/lib/data-write.ts
3179
3384
  import { join as join5 } from "node:path";
3180
3385
  import { FileSystemContentAPI as FileSystemContentAPI2 } from "@conloca/content-api/node";
@@ -3358,9 +3563,9 @@ async function readJsonInput(source, flag) {
3358
3563
 
3359
3564
  // src/commands/connect.ts
3360
3565
  import { execFile as execFileCallback2, spawn } from "node:child_process";
3361
- import { existsSync as existsSync5 } from "node:fs";
3362
- import { readFile as readFile10 } from "node:fs/promises";
3363
- import { join as join13, relative as relative4, resolve as resolve6, sep as sep2 } from "node:path";
3566
+ import { existsSync as existsSync6 } from "node:fs";
3567
+ import { readFile as readFile12 } from "node:fs/promises";
3568
+ import { join as join15, relative as relative5, resolve as resolve6, sep as sep3 } from "node:path";
3364
3569
  import { createInterface } from "node:readline/promises";
3365
3570
  import { promisify as promisify2 } from "node:util";
3366
3571
  import { EDITOR_HOST_PROTOCOL } from "@conloca/content-api/editor-host";
@@ -3401,14 +3606,216 @@ async function listAstroProjects(repoRoot) {
3401
3606
  return found;
3402
3607
  }
3403
3608
 
3609
+ // src/lib/connect/adapter.ts
3610
+ import { parseExpression as parseExpression2, parseModule as parseModule3 } from "magicast";
3611
+
3612
+ // src/lib/versions.ts
3613
+ import { readFile as readFile5 } from "node:fs/promises";
3614
+ import { dirname as dirname4, join as join7 } from "node:path";
3615
+ var D8_SINCE = "0.2.6-next.0";
3616
+ async function installedVersion(name, projectDir, installDir) {
3617
+ for (let dir = projectDir;; dir = dirname4(dir)) {
3618
+ const version = await readFile5(join7(dir, "node_modules", name, "package.json"), "utf8").then((text) => {
3619
+ let value;
3620
+ try {
3621
+ value = JSON.parse(text);
3622
+ } catch {
3623
+ return;
3624
+ }
3625
+ if (!isRecord(value))
3626
+ return;
3627
+ return typeof value.version === "string" ? value.version : null;
3628
+ }, () => {
3629
+ return;
3630
+ });
3631
+ if (version !== undefined)
3632
+ return version;
3633
+ if (dir === installDir || dir === dirname4(dir))
3634
+ return null;
3635
+ }
3636
+ }
3637
+ var NUMERIC = /^\d+$/;
3638
+ function compareIdentifiers(a, b) {
3639
+ const aNumeric = NUMERIC.test(a);
3640
+ const bNumeric = NUMERIC.test(b);
3641
+ if (aNumeric && bNumeric)
3642
+ return Number(a) - Number(b);
3643
+ if (aNumeric !== bNumeric)
3644
+ return aNumeric ? -1 : 1;
3645
+ return a < b ? -1 : a > b ? 1 : 0;
3646
+ }
3647
+ function compareVersions(a, b) {
3648
+ const [aCore = "", ...aPre] = a.split("+")[0]?.split("-") ?? [];
3649
+ const [bCore = "", ...bPre] = b.split("+")[0]?.split("-") ?? [];
3650
+ const aParts = aCore.split(".").map(Number);
3651
+ const bParts = bCore.split(".").map(Number);
3652
+ for (let i = 0;i < 3; i++) {
3653
+ const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
3654
+ if (diff !== 0)
3655
+ return diff;
3656
+ }
3657
+ const aIds = aPre.length > 0 ? aPre.join("-").split(".") : [];
3658
+ const bIds = bPre.length > 0 ? bPre.join("-").split(".") : [];
3659
+ if (aIds.length === 0 || bIds.length === 0)
3660
+ return bIds.length - aIds.length;
3661
+ for (let i = 0;i < Math.min(aIds.length, bIds.length); i++) {
3662
+ const diff = compareIdentifiers(aIds[i] ?? "", bIds[i] ?? "");
3663
+ if (diff !== 0)
3664
+ return diff;
3665
+ }
3666
+ return aIds.length - bIds.length;
3667
+ }
3668
+ function versionFloor(spec) {
3669
+ return spec.match(/\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/)?.[0] ?? null;
3670
+ }
3671
+ var SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"];
3672
+ function conlocaDependencies(manifest) {
3673
+ return SECTIONS.flatMap((section) => {
3674
+ const deps = manifest[section];
3675
+ if (!isRecord(deps))
3676
+ return [];
3677
+ return Object.entries(deps).flatMap(([name, spec]) => name.startsWith("@conloca/") && typeof spec === "string" ? [{ section, name, spec }] : []);
3678
+ });
3679
+ }
3680
+
3681
+ // src/lib/connect/adapter.ts
3682
+ var HOST_ADAPTERS = {
3683
+ vercel: { name: "@astrojs/vercel", call: "vercel" },
3684
+ netlify: { name: "@astrojs/netlify", call: "netlify" },
3685
+ cloudflare: { name: "@astrojs/cloudflare", call: "cloudflare" },
3686
+ node: { name: "@astrojs/node", call: "node" }
3687
+ };
3688
+ var ADAPTER_ASTRO_FLOORS = {
3689
+ "@astrojs/vercel": "7.0.0",
3690
+ "@astrojs/netlify": "7.0.0",
3691
+ "@astrojs/cloudflare": "7.2.0",
3692
+ "@astrojs/node": "7.2.1"
3693
+ };
3694
+ var needs = (message) => ({ state: "needs-you", message, edits: [] });
3695
+ function expression(code) {
3696
+ return parseExpression2(code).$ast;
3697
+ }
3698
+ function excludePreview(options, base) {
3699
+ const isr = property(options, "isr");
3700
+ if (isr === undefined || isr.value.type === "BooleanLiteral" && !isr.value.value)
3701
+ return false;
3702
+ const entry = `/^${`${base.replace(/\/+$/u, "")}/_conloca/preview`.replaceAll("/", "\\/")}(\\/.*)?$/`;
3703
+ if (isr.value.type === "BooleanLiteral") {
3704
+ const replaced = expression(`({ exclude: [${entry}] })`);
3705
+ if (replaced.type !== "ObjectExpression")
3706
+ return false;
3707
+ isr.value = replaced;
3708
+ return true;
3709
+ }
3710
+ if (isr.value.type !== "ObjectExpression")
3711
+ return false;
3712
+ const exclude = property(isr.value, "exclude");
3713
+ if (exclude === undefined) {
3714
+ isr.value.properties.push(...objectProperties(`exclude: [${entry}]`));
3715
+ return true;
3716
+ }
3717
+ if (exclude.value.type !== "ArrayExpression")
3718
+ return false;
3719
+ const listed = exclude.value.elements.some((e) => e?.type === "RegExpLiteral" && e.pattern.includes("_conloca"));
3720
+ const regex = expression(entry);
3721
+ if (listed || regex.type !== "RegExpLiteral")
3722
+ return false;
3723
+ exclude.value.elements.push(regex);
3724
+ return true;
3725
+ }
3726
+ function addAdapterStep(input) {
3727
+ const { path, text, host } = input;
3728
+ if (host === "cloudflare-d3" || host === "static-only") {
3729
+ return { state: "skipped", message: `${host} takes no adapter`, edits: [] };
3730
+ }
3731
+ const { name, call } = HOST_ADAPTERS[host];
3732
+ const floor = ADAPTER_ASTRO_FLOORS[name];
3733
+ if (input.astroVersion !== "" && compareVersions(input.astroVersion, floor) < 0) {
3734
+ return needs(`${name} needs astro ${floor} or later; this site has ${input.astroVersion}: update astro first`);
3735
+ }
3736
+ let mod;
3737
+ try {
3738
+ mod = parseModule3(text);
3739
+ } catch {
3740
+ return needs(`${path} does not parse, so connect does not add ${call}(): add it by hand`);
3741
+ }
3742
+ const program = mod.$ast;
3743
+ const config = program.type === "Program" ? configObject(program) : null;
3744
+ if (program.type !== "Program" || config === null) {
3745
+ return needs(`${path} is not a plain defineConfig({...}), so connect does not add ${call}(): add it by hand`);
3746
+ }
3747
+ const site = readAstroSite(text);
3748
+ const base = site === "computed" ? "/" : site.base ?? "/";
3749
+ const locals = importLocals(program);
3750
+ const notes = [];
3751
+ const adapter = property(config, "adapter");
3752
+ if (adapter === undefined) {
3753
+ const build = property(config, "build")?.value;
3754
+ const format = build?.type === "ObjectExpression" ? property(build, "format")?.value : undefined;
3755
+ const fileFormat = format?.type === "StringLiteral" && format.value === "file";
3756
+ if (host === "vercel" && fileFormat) {
3757
+ const warning = "build.format 'file' becomes 'directory' under @astrojs/vercel, so page addresses lose their .html";
3758
+ if (input.yes)
3759
+ return needs(`${warning}: remove the option, or run connect in a terminal to accept`);
3760
+ notes.push(`warning: ${warning}`);
3761
+ }
3762
+ const bound = locals.get(call);
3763
+ if (bound !== undefined && bound !== `${name}#default`) {
3764
+ return needs(`${path} already names something ${call}, so connect does not add ${name}: add it by hand`);
3765
+ }
3766
+ if (bound === undefined)
3767
+ mod.imports.$append({ from: name, imported: "default", local: call });
3768
+ config.properties.push(...objectProperties(host === "node" ? `adapter: ${call}({ mode: 'standalone' })` : `adapter: ${call}()`));
3769
+ notes.push(`added ${call}() from ${name}`);
3770
+ } else {
3771
+ const value = adapter.value;
3772
+ const callee = value.type === "CallExpression" && value.callee.type === "Identifier" ? value.callee.name : null;
3773
+ if (value.type !== "CallExpression" || callee === null || !locals.get(callee)?.startsWith(`${name}#`)) {
3774
+ return needs(`astro.config's adapter is not ${name}, which ${host} needs for draft previews; pass --host if ${host} is wrong`);
3775
+ }
3776
+ const [options] = value.arguments;
3777
+ if (host === "vercel" && options?.type === "ObjectExpression" && excludePreview(options, base)) {
3778
+ notes.push("excluded the preview route from isr");
3779
+ }
3780
+ }
3781
+ if (host === "netlify" && property(config, "session") === undefined) {
3782
+ config.properties.push(...objectProperties("session: false"));
3783
+ notes.push("session: false");
3784
+ }
3785
+ const security = property(config, "security");
3786
+ const needsDomains = security === undefined || security.value.type === "ObjectExpression" && property(security.value, "allowedDomains") === undefined;
3787
+ if (host === "node" && needsDomains && input.siteDomains.length === 0) {
3788
+ return needs("sites.json names no domain for security.allowedDomains, and without it every preview entry fails behind a TLS proxy: add the site's domains to sites.json, then run again");
3789
+ }
3790
+ if (host === "node") {
3791
+ const domains = input.siteDomains.map((hostname) => `{ hostname: ${JSON.stringify(hostname)}, protocol: 'https' }`);
3792
+ const allowed = `allowedDomains: [${domains.join(", ")}]`;
3793
+ if (security === undefined) {
3794
+ config.properties.push(...objectProperties(`security: { ${allowed} }`));
3795
+ notes.push("security.allowedDomains");
3796
+ } else if (security.value.type === "ObjectExpression" && property(security.value, "allowedDomains") === undefined) {
3797
+ security.value.properties.push(...objectProperties(allowed));
3798
+ notes.push("security.allowedDomains");
3799
+ }
3800
+ }
3801
+ const after = notes.length === 0 ? text : printModule(mod, text);
3802
+ const refusal = input.configRefusal?.(after, name, base) ?? null;
3803
+ if (refusal !== null)
3804
+ return needs(refusal);
3805
+ if (after === text) {
3806
+ return { state: "done", message: `astro.config has ${call}() with the options draft previews need`, edits: [] };
3807
+ }
3808
+ return { state: "changed", message: notes.join("; "), edits: [{ path, before: text, after }] };
3809
+ }
3810
+
3404
3811
  // src/lib/connect/cf-plan.ts
3405
3812
  import { findNodeAtLocation, parseTree } from "jsonc-parser";
3406
3813
 
3407
3814
  // src/lib/connect/preview-deploy.ts
3408
3815
  import { createHash } from "node:crypto";
3409
3816
  import { existsSync as existsSync4 } from "node:fs";
3410
- import { readFile as readFile5 } from "node:fs/promises";
3411
- import { basename as basename3, join as join7 } from "node:path";
3817
+ import { readFile as readFile6 } from "node:fs/promises";
3818
+ import { basename as basename3, join as join8 } from "node:path";
3412
3819
  import { applyEdits, modify, parse } from "jsonc-parser";
3413
3820
  var DISPATCHER_MAIN = ".conloca/dispatcher/index.mjs";
3414
3821
  var PREVIEW_LIMIT = { name: "conlocaPreviewLimit", simple: { limit: 60, period: 10 } };
@@ -3443,26 +3850,53 @@ function withoutPreviewLimit(block) {
3443
3850
  return null;
3444
3851
  return kept.length === 0 ? undefined : kept;
3445
3852
  }
3446
- function previewSetupOf(integration, astro, base) {
3853
+ function previewSetupOf(integration, astro, base, code) {
3447
3854
  if (integration.state !== "literal")
3448
3855
  return { kind: "off" };
3449
3856
  const raw = integration.entries.get("previewBuild");
3450
3857
  if (raw === undefined || raw.trim() === "false")
3451
3858
  return { kind: "off" };
3452
3859
  const prefix = `${(base ?? "/").replace(/\/+$/u, "")}/_conloca/preview`;
3453
- if (/\bseparate\s*:\s*true\b/u.test(raw))
3454
- return { kind: "d4", prefix };
3455
- const ownAdapter = astro.state === "literal" && astro.entries.has("adapter");
3456
- return /\badapter\b/u.test(raw) || ownAdapter ? { kind: "d2" } : { kind: "d3", prefix };
3860
+ const { separate, adapter: misplaced } = previewBuildKeys(raw);
3861
+ const refusal = "remove previewBuild.adapter: drafts render through the adapter in astro.config's adapter option";
3862
+ const adapter = siteAdapterOf(astro, code);
3863
+ if (separate && (adapter === "@astrojs/vercel" || adapter === "@astrojs/netlify")) {
3864
+ return {
3865
+ kind: "off",
3866
+ refusal: `previewBuild.separate is not supported with ${adapter}: the separate preview build would write its output where ${adapter} deploys the live site. Remove separate: true; with ${adapter} drafts render in the site's own build.`
3867
+ };
3868
+ }
3869
+ if (separate)
3870
+ return misplaced ? { kind: "d4", prefix, refusal } : { kind: "d4", prefix };
3871
+ if (misplaced)
3872
+ return { kind: "off", refusal };
3873
+ if (adapter === undefined)
3874
+ return { kind: "d3", prefix };
3875
+ return adapter === "other" ? { kind: "off" } : { kind: "d8", prefix, adapter };
3876
+ }
3877
+ function previewBuildKeys(raw) {
3878
+ const parsed = parseObjectEntries(raw.trim());
3879
+ if (parsed === null)
3880
+ return { separate: false, adapter: false };
3881
+ const adapter = parsed.entries.has("adapter") || parsed.shorthands.has("adapter");
3882
+ return { separate: parsed.entries.get("separate") === "true", adapter };
3883
+ }
3884
+ function siteAdapterOf(astro, code) {
3885
+ const own = astro.state === "literal" ? astro.entries.get("adapter") : undefined;
3886
+ if (own === undefined)
3887
+ return;
3888
+ const call = /^\s*([\w$]+)\s*\(/u.exec(own)?.[1];
3889
+ const source = call === undefined ? undefined : new RegExp(`\\bimport\\s+${call.replaceAll("$", "\\$")}\\s+from\\s+['"]([^'"]+)['"]`, "u").exec(code)?.[1];
3890
+ return Object.values(HOST_ADAPTERS).find((entry) => entry.name === source)?.name ?? "other";
3457
3891
  }
3458
3892
  async function readWranglerFile(projectDir) {
3459
- const jsonc = ["wrangler.jsonc", "wrangler.json"].map((name) => join7(projectDir, name)).find((path) => existsSync4(path));
3893
+ const jsonc = ["wrangler.jsonc", "wrangler.json"].map((name) => join8(projectDir, name)).find((path) => existsSync4(path));
3460
3894
  if (jsonc !== undefined)
3461
- return { kind: "jsonc", path: jsonc, text: await readFile5(jsonc, "utf8") };
3462
- const toml = join7(projectDir, "wrangler.toml");
3895
+ return { kind: "jsonc", path: jsonc, text: await readFile6(jsonc, "utf8") };
3896
+ const toml = join8(projectDir, "wrangler.toml");
3463
3897
  return existsSync4(toml) ? { kind: "toml", path: toml } : { kind: "none" };
3464
3898
  }
3465
- var needs = (message, lines = []) => ({
3899
+ var needs2 = (message, lines = []) => ({
3466
3900
  state: "needs-you",
3467
3901
  message,
3468
3902
  lines,
@@ -3486,7 +3920,7 @@ function d4Lines(buildCommand, exec) {
3486
3920
  function d4Step(input, file, config, prefix) {
3487
3921
  const name = basename3(file.path);
3488
3922
  if (!isRecord(config) || typeof config.name !== "string")
3489
- return needs(`${name} names no Cloudflare Worker`);
3923
+ return needs2(`${name} names no Cloudflare Worker`);
3490
3924
  const env = isRecord(config.env) ? config.env : {};
3491
3925
  let after = file.text;
3492
3926
  if (env.preview === undefined) {
@@ -3506,7 +3940,7 @@ function d4Step(input, file, config, prefix) {
3506
3940
  const scriptless = removed || config.main === undefined;
3507
3941
  if (scriptless && (listed === true || kept.length > 0)) {
3508
3942
  const entries = listed === true ? "run_worker_first: true" : kept.map(shown).join(", ");
3509
- return needs(`${name}: ${entries} needs a Worker script, and a separate preview deploy (D4) leaves the main deploy with none: remove ${listed === true ? "it" : "those entries"} (and the on-demand routes they serve), or set main to a script of your own`);
3943
+ return needs2(`${name}: ${entries} needs a Worker script, and a separate preview deploy (D4) leaves the main deploy with none: remove ${listed === true ? "it" : "those entries"} (and the on-demand routes they serve), or set main to a script of your own`);
3510
3944
  }
3511
3945
  if (removed)
3512
3946
  after = setIn(after, ["main"], undefined);
@@ -3531,65 +3965,125 @@ function d4Step(input, file, config, prefix) {
3531
3965
  edits
3532
3966
  };
3533
3967
  }
3534
- function previewDeployStep(input) {
3535
- const { file, setup } = input;
3536
- if (setup.kind !== "d3" && setup.kind !== "d4") {
3968
+ function d8Step(input, prefix, adapter) {
3969
+ if (adapter === "@astrojs/vercel") {
3970
+ return needs2("Vercel: rate-limit the preview route in the project firewall", [
3971
+ `Firewall → Add rule → If Request Path starts with ${prefix}/ → Rate Limit, ${PREVIEW_LIMIT.simple.limit} requests per ${PREVIEW_LIMIT.simple.period} seconds per IP → Deny`
3972
+ ]);
3973
+ }
3974
+ if (adapter === "@astrojs/netlify") {
3975
+ return needs2("Netlify: rate-limit the preview route", [
3976
+ `Rate limiting rule: path ${prefix}/*, 60 requests per 60 seconds per IP`,
3977
+ "every missing URL on this site, images included, runs your site's function"
3978
+ ]);
3979
+ }
3980
+ if (adapter === "@astrojs/node") {
3981
+ return needs2("your own server: drafts render in the site server", [
3982
+ "start the server with `node dist/server/entry.mjs`"
3983
+ ]);
3984
+ }
3985
+ const { file } = input;
3986
+ if (file.kind !== "jsonc") {
3987
+ return needs2(file.kind === "toml" ? "wrangler.toml can't carry the preview routing: convert it to wrangler.jsonc, then run `conloca connect` again" : "this project has no wrangler.jsonc for the preview routing");
3988
+ }
3989
+ const name = basename3(file.path);
3990
+ if (input.routes === null) {
3991
+ return needs2(`${name}: the preview routing needs the routes a build reports`, ["conloca connect --update --yes"]);
3992
+ }
3993
+ const base = prefix.slice(0, -"/_conloca/preview".length);
3994
+ const runtime = new Set([...previewOwnEntries(prefix), `${base}/_server-islands/*`]);
3995
+ if (input.routes.some((entry) => !runtime.has(entry))) {
3537
3996
  return {
3538
- state: "skipped",
3539
- message: "previewBuild serves no static-site preview (D3) or separate deploy (D4)",
3997
+ state: "done",
3998
+ message: `${name}: the Cloudflare Worker already gets every miss, the preview included`,
3540
3999
  edits: []
3541
4000
  };
3542
4001
  }
4002
+ const config = parse(file.text, [], { allowTrailingComma: true });
4003
+ if (!isRecord(config))
4004
+ return needs2(`${name} is not a JSON object`);
4005
+ const assets = isRecord(config.assets) ? config.assets : {};
4006
+ const listed = assets.run_worker_first;
4007
+ if (listed !== undefined && listed !== true && !Array.isArray(listed)) {
4008
+ return needs2(`${name} has its own run_worker_first; add ${JSON.stringify(input.routes)} to it`);
4009
+ }
4010
+ const current = Array.isArray(listed) ? listed : [];
4011
+ const missing = listed === true ? [] : input.routes.filter((entry) => !current.includes(entry));
4012
+ if (current.length + missing.length > MAX_WORKER_FIRST) {
4013
+ return needs2(`${name}: run_worker_first would have more than ${MAX_WORKER_FIRST} entries, Cloudflare's cap; merge some into wider patterns`);
4014
+ }
4015
+ let after = file.text;
4016
+ if (missing.length > 0)
4017
+ after = setIn(after, ["assets", "run_worker_first"], [...current, ...missing]);
4018
+ const handling = input.negotiate404 || assets.not_found_handling === "none" ? "none" : "404-page";
4019
+ if (assets.not_found_handling !== handling)
4020
+ after = setIn(after, ["assets", "not_found_handling"], handling);
4021
+ if (after === file.text) {
4022
+ return { state: "done", message: `${name} routes the preview through the Cloudflare adapter`, edits: [] };
4023
+ }
4024
+ return {
4025
+ state: "changed",
4026
+ message: `${name}: the preview runs on ${prefix}/* through the Cloudflare adapter, misses get ${handling === "none" ? 'the Cloudflare Worker (not_found_handling "none")' : "the 404 page"}`,
4027
+ edits: [{ path: file.path, before: file.text, after }]
4028
+ };
4029
+ }
4030
+ function previewDeployStep(input) {
4031
+ const { file, setup } = input;
4032
+ if (setup.kind === "off") {
4033
+ return { state: "skipped", message: "previewBuild serves no draft preview", edits: [] };
4034
+ }
4035
+ if (setup.kind === "d8")
4036
+ return d8Step(input, setup.prefix, setup.adapter);
3543
4037
  const pair = [setup.prefix, `${setup.prefix}/*`];
3544
4038
  const wanted = [...pair, ...(input.routes ?? []).filter((r) => !r.startsWith(setup.prefix))];
3545
4039
  if (file.kind === "none") {
3546
- return needs("this project has no wrangler.jsonc: draft previews of a static site run on Cloudflare Workers, so deploy it to Cloudflare Workers with one");
4040
+ return needs2("this project has no wrangler.jsonc: draft previews of a static site run on Cloudflare Workers, so deploy it to Cloudflare Workers with one");
3547
4041
  }
3548
4042
  if (file.kind === "toml") {
3549
- return needs("wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then run `conloca connect` again");
4043
+ return needs2("wrangler.toml can't carry the preview settings: convert it to wrangler.jsonc, then run `conloca connect` again");
3550
4044
  }
3551
4045
  const config = parse(file.text, [], { allowTrailingComma: true });
3552
4046
  const name = basename3(file.path);
3553
4047
  if (!isRecord(config))
3554
- return needs(`${name} is not a JSON object`);
4048
+ return needs2(`${name} is not a JSON object`);
3555
4049
  if (config.pages_build_output_dir !== undefined) {
3556
- return needs(`${name} configures Cloudflare Pages; draft previews need Cloudflare Workers with static assets`);
4050
+ return needs2(`${name} configures Cloudflare Pages; draft previews need Cloudflare Workers with static assets`);
3557
4051
  }
3558
4052
  if (setup.kind === "d4")
3559
4053
  return d4Step(input, file, config, setup.prefix);
3560
4054
  const envs = isRecord(config.env) ? config.env : {};
3561
4055
  for (const [envName, block] of Object.entries(envs)) {
3562
4056
  if (isRecord(block) && (block.main !== undefined || block.assets !== undefined)) {
3563
- return needs(`${name}: env.${envName} sets main or assets, which replaces the dispatcher's; remove them from the env block`);
4057
+ return needs2(`${name}: env.${envName} sets main or assets, which replaces the dispatcher's; remove them from the env block`);
3564
4058
  }
3565
4059
  }
3566
4060
  const assets = isRecord(config.assets) ? config.assets : {};
3567
4061
  if (config.main !== undefined && config.main !== DISPATCHER_MAIN) {
3568
- return needs(`${name} sets its own main (${shown(config.main)}); the preview dispatcher needs main: "${DISPATCHER_MAIN}"`);
4062
+ return needs2(`${name} sets its own main (${shown(config.main)}); the preview dispatcher needs main: "${DISPATCHER_MAIN}"`);
3569
4063
  }
3570
4064
  if (assets.not_found_handling === "single-page-application") {
3571
- return needs(`${name} uses single-page-application 404 handling, which serves index.html for every miss; previews need "404-page" (or "none")`);
4065
+ return needs2(`${name} uses single-page-application 404 handling, which serves index.html for every miss; previews need "404-page" (or "none")`);
3572
4066
  }
3573
4067
  const listed = assets.run_worker_first;
3574
4068
  const everything = listed === true;
3575
4069
  if (!everything && listed !== undefined && !(Array.isArray(listed) && listed.includes(`${setup.prefix}/*`))) {
3576
- return needs(`${name} has its own run_worker_first; add ${JSON.stringify(wanted)} to it`);
4070
+ return needs2(`${name} has its own run_worker_first; add ${JSON.stringify(wanted)} to it`);
3577
4071
  }
3578
4072
  const current = Array.isArray(listed) ? listed : [];
3579
4073
  const excluded = current.find((entry) => typeof entry === "string" && entry.startsWith("!") && entry.slice(1).startsWith(setup.prefix));
3580
4074
  if (typeof excluded === "string") {
3581
- return needs(`${name}: run_worker_first excludes the preview route (${excluded}); remove that entry`);
4075
+ return needs2(`${name}: run_worker_first excludes the preview route (${excluded}); remove that entry`);
3582
4076
  }
3583
4077
  const missing = everything ? [] : wanted.filter((entry) => !current.includes(entry));
3584
4078
  if (current.length + missing.length > MAX_WORKER_FIRST) {
3585
- return needs(`${name}: run_worker_first would have more than ${MAX_WORKER_FIRST} entries, Cloudflare's cap; merge some into wider patterns`);
4079
+ return needs2(`${name}: run_worker_first would have more than ${MAX_WORKER_FIRST} entries, Cloudflare's cap; merge some into wider patterns`);
3586
4080
  }
3587
4081
  if (assets.binding !== undefined && assets.binding !== "ASSETS") {
3588
- return needs(`${name} binds the assets as ${shown(assets.binding)}; the preview dispatcher reads them as ASSETS`);
4082
+ return needs2(`${name} binds the assets as ${shown(assets.binding)}; the preview dispatcher reads them as ASSETS`);
3589
4083
  }
3590
4084
  const directory = assets.directory;
3591
4085
  if (directory !== undefined && !(typeof directory === "string" && ["dist", "./dist", "dist/", "./dist/"].includes(directory))) {
3592
- return needs(`${name} serves ${shown(directory)}; the static site and the dispatcher are served from ./dist`);
4086
+ return needs2(`${name} serves ${shown(directory)}; the static site and the dispatcher are served from ./dist`);
3593
4087
  }
3594
4088
  let after = file.text;
3595
4089
  const wrote = [];
@@ -3688,18 +4182,18 @@ function sharedQuotaRoutes(routes, prefix) {
3688
4182
  }
3689
4183
 
3690
4184
  // src/lib/connect/framing.ts
3691
- import { readFile as readFile6 } from "node:fs/promises";
3692
- import { join as join9, relative as relative2 } from "node:path";
4185
+ import { readFile as readFile7 } from "node:fs/promises";
4186
+ import { join as join10, relative as relative2 } from "node:path";
3693
4187
  import { editorUiOrigin, parentRoot } from "@conloca/content-api/editor-host";
3694
4188
 
3695
4189
  // src/lib/project-module.ts
3696
4190
  import { createRequire } from "node:module";
3697
- import { join as join8 } from "node:path";
4191
+ import { join as join9 } from "node:path";
3698
4192
  import { pathToFileURL } from "node:url";
3699
4193
  async function importFromProject(projectDir, specifier) {
3700
4194
  let entry;
3701
4195
  try {
3702
- entry = createRequire(join8(projectDir, "package.json")).resolve(specifier);
4196
+ entry = createRequire(join9(projectDir, "package.json")).resolve(specifier);
3703
4197
  } catch {
3704
4198
  return "missing";
3705
4199
  }
@@ -3722,7 +4216,7 @@ async function loadFramingHelpers(projectDir) {
3722
4216
  }
3723
4217
  var HEADERS_FILE = "public/_headers";
3724
4218
  async function readText(path) {
3725
- return readFile6(path, "utf8").catch(() => null);
4219
+ return readFile7(path, "utf8").catch(() => null);
3726
4220
  }
3727
4221
  function vercelWithRules(text, snippets) {
3728
4222
  let vercel;
@@ -3757,11 +4251,11 @@ async function framingStep(projectDir, endpoint) {
3757
4251
  }
3758
4252
  const snippets = helpers.framingSnippets(editorRoot);
3759
4253
  const blockers = await helpers.findFramingBlockers(projectDir);
3760
- const headersPath = join9(projectDir, HEADERS_FILE);
3761
- const vercelPath = join9(projectDir, "vercel.json");
4254
+ const headersPath = join10(projectDir, HEADERS_FILE);
4255
+ const vercelPath = join10(projectDir, "vercel.json");
3762
4256
  const [headers, netlify, vercel] = await Promise.all([
3763
4257
  readText(headersPath),
3764
- readText(join9(projectDir, "netlify.toml")),
4258
+ readText(join10(projectDir, "netlify.toml")),
3765
4259
  readText(vercelPath)
3766
4260
  ]);
3767
4261
  const headersRule = netlify === null ? snippets.cloudflareHeaders : snippets.netlifyHeaders;
@@ -3820,9 +4314,107 @@ ${headersRule}`;
3820
4314
  };
3821
4315
  }
3822
4316
 
4317
+ // src/lib/connect/host.ts
4318
+ import { existsSync as existsSync5 } from "node:fs";
4319
+ import { readdir, readFile as readFile8, stat } from "node:fs/promises";
4320
+ import { dirname as dirname5, isAbsolute, join as join11, relative as relative3, sep as sep2 } from "node:path";
4321
+ import { parse as parse2 } from "jsonc-parser";
4322
+ var HOST_CHOICES = "vercel|netlify|cloudflare|node";
4323
+ var D2_ENTRY = ".conloca/preview-server/server/entry.mjs";
4324
+ var D8_ENTRY = "dist/server/entry.mjs";
4325
+ var NODE_ENTRIES = [D8_ENTRY, D2_ENTRY];
4326
+ var STARTER_MAX_BYTES = 1024 * 1024;
4327
+ function foldersUp(projectDir, repoRoot) {
4328
+ const folders = [];
4329
+ for (let dir = projectDir;; dir = dirname5(dir)) {
4330
+ const rel = relative3(repoRoot, dir);
4331
+ if (rel === ".." || rel.startsWith(`..${sep2}`) || isAbsolute(rel))
4332
+ break;
4333
+ folders.push(dir);
4334
+ if (rel === "" || dirname5(dir) === dir)
4335
+ break;
4336
+ }
4337
+ return folders;
4338
+ }
4339
+ var startsEntry = (text) => NODE_ENTRIES.some((entry) => text.includes(entry));
4340
+ function startsServer(name, text) {
4341
+ if (name.startsWith("Dockerfile")) {
4342
+ return text.split(`
4343
+ `).some((line) => /^\s*(CMD|ENTRYPOINT)\b/i.test(line) && startsEntry(line));
4344
+ }
4345
+ if (name === "Procfile" || name === "fly.toml")
4346
+ return startsEntry(text);
4347
+ const pkg = parse2(text);
4348
+ const scripts = isRecord(pkg) && isRecord(pkg.scripts) ? Object.values(pkg.scripts) : [];
4349
+ return scripts.some((script) => typeof script === "string" && startsEntry(script));
4350
+ }
4351
+ var isStarterFile = (name) => name.startsWith("Dockerfile") || ["Procfile", "fly.toml", "package.json"].includes(name);
4352
+ async function nodeStarters(dir) {
4353
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
4354
+ const names = entries.filter((entry) => entry.isFile()).map((entry) => entry.name).filter(isStarterFile);
4355
+ const starts = await Promise.all(names.map(async (name) => {
4356
+ const path = join11(dir, name);
4357
+ if ((await stat(path)).size > STARTER_MAX_BYTES)
4358
+ return false;
4359
+ return startsServer(name, await readFile8(path, "utf8"));
4360
+ }));
4361
+ return names.filter((_, index) => starts[index]).map((name) => join11(dir, name));
4362
+ }
4363
+ async function detectHost(input) {
4364
+ const UNKNOWN = {
4365
+ ok: false,
4366
+ reason: "unknown",
4367
+ message: `can't tell where this site deploys: pass --host ${HOST_CHOICES}`
4368
+ };
4369
+ if (input.flag !== undefined)
4370
+ return { ok: true, host: input.flag, evidence: ["--host"] };
4371
+ const folders = foldersUp(input.projectDir, input.repoRoot);
4372
+ if (folders.length === 0)
4373
+ return UNKNOWN;
4374
+ const wrangler = await readWranglerFile(input.projectDir);
4375
+ const name = (path) => relative3(input.repoRoot, path) || path;
4376
+ if (wrangler.kind === "jsonc") {
4377
+ const config = parse2(wrangler.text);
4378
+ if (isRecord(config) && config.main === DISPATCHER_MAIN) {
4379
+ return { ok: true, host: "cloudflare-d3", evidence: [name(wrangler.path)] };
4380
+ }
4381
+ }
4382
+ const evidence = [];
4383
+ const code = input.astroText.replace(/\/\*[\s\S]*?\*\/|\/\/.*$/gmu, "");
4384
+ const adapter = /@astrojs\/(vercel|netlify|cloudflare|node)\b/u.exec(code)?.[1];
4385
+ if (adapter === "vercel" || adapter === "netlify" || adapter === "cloudflare" || adapter === "node") {
4386
+ evidence.push({ host: adapter, source: "astro.config" });
4387
+ }
4388
+ const starters = await Promise.all(folders.map(nodeStarters));
4389
+ for (const [index, dir] of folders.entries()) {
4390
+ if (existsSync5(join11(dir, "vercel.json")))
4391
+ evidence.push({ host: "vercel", source: name(join11(dir, "vercel.json")) });
4392
+ if (existsSync5(join11(dir, "netlify.toml"))) {
4393
+ evidence.push({ host: "netlify", source: name(join11(dir, "netlify.toml")) });
4394
+ }
4395
+ for (const path of starters[index] ?? [])
4396
+ evidence.push({ host: "node", source: name(path), starter: true });
4397
+ }
4398
+ if (wrangler.kind !== "none")
4399
+ evidence.push({ host: "cloudflare", source: name(wrangler.path) });
4400
+ const [first] = evidence;
4401
+ const nodeUnstarted = evidence.every((item) => item.host === "node" && !item.starter);
4402
+ if (first === undefined || nodeUnstarted)
4403
+ return UNKNOWN;
4404
+ const other = evidence.find((item) => item.host !== first.host);
4405
+ if (other !== undefined) {
4406
+ return {
4407
+ ok: false,
4408
+ reason: "conflict",
4409
+ message: `${first.source} names ${first.host} but ${other.source} deploys to ${other.host}: pass --host ${HOST_CHOICES}`
4410
+ };
4411
+ }
4412
+ return { ok: true, host: first.host, evidence: evidence.map((item) => item.source) };
4413
+ }
4414
+
3823
4415
  // src/lib/connect/leftovers.ts
3824
- import { readdir, readFile as readFile7 } from "node:fs/promises";
3825
- import { join as join10, relative as relative3 } from "node:path";
4416
+ import { readdir as readdir2, readFile as readFile9 } from "node:fs/promises";
4417
+ import { join as join12, relative as relative4 } from "node:path";
3826
4418
 
3827
4419
  // src/lib/legacy-key.ts
3828
4420
  var LEGACY_KEY_NAME = "CONLOCA_BUILD_TOKEN";
@@ -3956,16 +4548,16 @@ function deletionDiff(path, text, deleted) {
3956
4548
 
3957
4549
  // src/lib/connect/leftovers.ts
3958
4550
  async function leftoversStep(repoRoot) {
3959
- const folder = join10(repoRoot, ".github", "workflows");
3960
- const names = (await readdir(folder).catch(() => [])).filter((name) => /\.ya?ml$/.test(name));
4551
+ const folder = join12(repoRoot, ".github", "workflows");
4552
+ const names = (await readdir2(folder).catch(() => [])).filter((name) => /\.ya?ml$/.test(name));
3961
4553
  names.sort();
3962
- const texts = await Promise.all(names.map((name) => readFile7(join10(folder, name), "utf8").catch(() => null)));
4554
+ const texts = await Promise.all(names.map((name) => readFile9(join12(folder, name), "utf8").catch(() => null)));
3963
4555
  const edits = [];
3964
4556
  const manual = [];
3965
4557
  for (const [index, name] of names.entries()) {
3966
- const path = join10(folder, name);
4558
+ const path = join12(folder, name);
3967
4559
  const text = texts[index] ?? null;
3968
- const finding = text === null ? null : legacyKeyFinding(relative3(repoRoot, path), text);
4560
+ const finding = text === null ? null : legacyKeyFinding(relative4(repoRoot, path), text);
3969
4561
  if (text === null || finding === null)
3970
4562
  continue;
3971
4563
  if (finding.deleted.length > 0) {
@@ -3993,80 +4585,9 @@ async function leftoversStep(repoRoot) {
3993
4585
  } : { state: "done", message: "no workflow names the old build key", edits: [] };
3994
4586
  }
3995
4587
 
3996
- // src/lib/connect/site-domain.ts
3997
- import { addressSiteName, isValidSiteBase } from "@conloca/content-api";
3998
- function isSitesConfig(value) {
3999
- return isRecord(value) && isRecord(value.sites) && Object.values(value.sites).every((site) => isRecord(site) && Array.isArray(site.locales) && typeof site.defaultLocale === "string" && (site.domains === undefined || isRecord(site.domains)) && (site.base === undefined || typeof site.base === "string"));
4000
- }
4001
- function siteBase(base) {
4002
- const leading = base === null || base.startsWith("/") ? base ?? "/" : `/${base}`;
4003
- return leading.endsWith("/") ? leading : `${leading}/`;
4004
- }
4005
- function writeSiteAddress(input) {
4006
- const { path, text, site } = input;
4007
- const url = URL.canParse(site) ? new URL(site) : null;
4008
- if (url?.protocol !== "https:") {
4009
- return { state: "needs-you", message: `Astro's site must be an https URL, got ${site}`, edits: [] };
4010
- }
4011
- const base = siteBase(input.base);
4012
- if (!isValidSiteBase(base)) {
4013
- return {
4014
- state: "needs-you",
4015
- message: `Astro's base ${input.base} is not a path the editor can open`,
4016
- edits: []
4017
- };
4018
- }
4019
- let config;
4020
- try {
4021
- config = JSON.parse(text);
4022
- } catch {
4023
- return { state: "failed", message: `${path} is not valid JSON`, edits: [] };
4024
- }
4025
- if (!isSitesConfig(config)) {
4026
- return { state: "failed", message: `${path} has no readable sites map`, edits: [] };
4027
- }
4028
- const name = addressSiteName(config);
4029
- const entry = name === null ? undefined : config.sites[name];
4030
- if (name === null || entry === undefined) {
4031
- return {
4032
- state: "needs-you",
4033
- message: `${path} lists several sites and none is named default; add the domain to the right one yourself`,
4034
- lines: [`"domains": { "<locale>": "${url.hostname}" }`, ...base === "/" ? [] : [`"base": "${base}"`]],
4035
- edits: []
4036
- };
4037
- }
4038
- const host = url.hostname;
4039
- const locale = entry.defaultLocale;
4040
- const domain = entry.domains?.[locale];
4041
- const kept = [
4042
- ...domain !== undefined && domain !== host ? [`domains.${locale} is ${domain}, not ${host}`] : [],
4043
- ...entry.base !== undefined && entry.base !== base ? [`base is ${entry.base}, not ${base}`] : []
4044
- ];
4045
- if (kept.length === 0 && domain !== undefined && (entry.base !== undefined || base === "/")) {
4046
- return { state: "done", message: `site '${name}' already lists ${host}`, edits: [] };
4047
- }
4048
- entry.domains = { ...entry.domains, [locale]: host };
4049
- if (base !== "/" || entry.base !== undefined)
4050
- entry.base = base;
4051
- const edits = [{ path, before: text, after: jsonLike(text, config) }];
4052
- if (kept.length > 0) {
4053
- return {
4054
- state: "differs",
4055
- message: `site '${name}' in ${path}: ${kept.join("; ")} (kept yours)`,
4056
- edits: [],
4057
- replacement: edits
4058
- };
4059
- }
4060
- return {
4061
- state: "changed",
4062
- message: `wrote ${host}${base === "/" ? "" : ` and base ${base}`} into site '${name}'`,
4063
- edits
4064
- };
4065
- }
4066
-
4067
4588
  // src/lib/sites-config.ts
4068
- import { readFile as readFile8, writeFile as writeFile2 } from "node:fs/promises";
4069
- import { join as join11 } from "node:path";
4589
+ import { readFile as readFile10, writeFile as writeFile2 } from "node:fs/promises";
4590
+ import { join as join13 } from "node:path";
4070
4591
  var DEFAULT_LOCALES = ["en"];
4071
4592
  function newSitesConfig(siteName) {
4072
4593
  return {
@@ -4075,11 +4596,11 @@ function newSitesConfig(siteName) {
4075
4596
  };
4076
4597
  }
4077
4598
  async function ensureSiteInSitesConfig(contentPath, siteName) {
4078
- const path = join11(contentPath, "sites.json");
4599
+ const path = join13(contentPath, "sites.json");
4079
4600
  let sitesConfig = { sites: {}, globalLocales: [...DEFAULT_LOCALES] };
4080
4601
  let existed = false;
4081
4602
  try {
4082
- const parsed = JSON.parse(await readFile8(path, "utf-8"));
4603
+ const parsed = JSON.parse(await readFile10(path, "utf-8"));
4083
4604
  if (parsed.sites) {
4084
4605
  sitesConfig = parsed;
4085
4606
  } else {
@@ -4095,59 +4616,25 @@ async function ensureSiteInSitesConfig(contentPath, siteName) {
4095
4616
  `, "utf-8");
4096
4617
  return { path, existed, added: true };
4097
4618
  }
4098
-
4099
- // src/lib/versions.ts
4100
- var NUMERIC = /^\d+$/;
4101
- function compareIdentifiers(a, b) {
4102
- const aNumeric = NUMERIC.test(a);
4103
- const bNumeric = NUMERIC.test(b);
4104
- if (aNumeric && bNumeric)
4105
- return Number(a) - Number(b);
4106
- if (aNumeric !== bNumeric)
4107
- return aNumeric ? -1 : 1;
4108
- return a < b ? -1 : a > b ? 1 : 0;
4109
- }
4110
- function compareVersions(a, b) {
4111
- const [aCore = "", ...aPre] = a.split("+")[0]?.split("-") ?? [];
4112
- const [bCore = "", ...bPre] = b.split("+")[0]?.split("-") ?? [];
4113
- const aParts = aCore.split(".").map(Number);
4114
- const bParts = bCore.split(".").map(Number);
4115
- for (let i = 0;i < 3; i++) {
4116
- const diff = (aParts[i] ?? 0) - (bParts[i] ?? 0);
4117
- if (diff !== 0)
4118
- return diff;
4119
- }
4120
- const aIds = aPre.length > 0 ? aPre.join("-").split(".") : [];
4121
- const bIds = bPre.length > 0 ? bPre.join("-").split(".") : [];
4122
- if (aIds.length === 0 || bIds.length === 0)
4123
- return bIds.length - aIds.length;
4124
- for (let i = 0;i < Math.min(aIds.length, bIds.length); i++) {
4125
- const diff = compareIdentifiers(aIds[i] ?? "", bIds[i] ?? "");
4126
- if (diff !== 0)
4127
- return diff;
4619
+ function siteDomainsOf(sitesText) {
4620
+ let parsed;
4621
+ try {
4622
+ parsed = JSON.parse(sitesText);
4623
+ } catch {
4624
+ return [];
4128
4625
  }
4129
- return aIds.length - bIds.length;
4130
- }
4131
- function versionFloor(spec) {
4132
- return spec.match(/\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?/)?.[0] ?? null;
4133
- }
4134
- var SECTIONS = ["dependencies", "devDependencies", "optionalDependencies"];
4135
- function conlocaDependencies(manifest) {
4136
- return SECTIONS.flatMap((section) => {
4137
- const deps = manifest[section];
4138
- if (!isRecord(deps))
4139
- return [];
4140
- return Object.entries(deps).flatMap(([name, spec]) => name.startsWith("@conloca/") && typeof spec === "string" ? [{ section, name, spec }] : []);
4141
- });
4626
+ const sites = isRecord(parsed) && isRecord(parsed.sites) ? Object.values(parsed.sites) : [];
4627
+ const domains = sites.flatMap((site) => isRecord(site) && isRecord(site.domains) ? Object.values(site.domains).filter((d) => typeof d === "string") : []);
4628
+ return [...new Set(domains)];
4142
4629
  }
4143
4630
 
4144
4631
  // src/commands/setup.ts
4145
- import { mkdir as mkdir2, readFile as readFile9, writeFile as writeFile3 } from "node:fs/promises";
4146
- import { join as join12, resolve as resolve5 } from "node:path";
4632
+ import { mkdir as mkdir2, readFile as readFile11, writeFile as writeFile3 } from "node:fs/promises";
4633
+ import { join as join14, resolve as resolve5 } from "node:path";
4147
4634
  import { stampSkill } from "@conloca/content-api/skill-stamp";
4148
4635
 
4149
4636
  // src/templates/conloca-skill.md
4150
- var conloca_skill_default = "---\nname: conloca\ndescription: Load when working on an Astro site using Conloca CMS — @conloca/* packages, .vxjson content, sites.json.\n---\n\n# Conloca CMS\n\nConloca stores pages as `.vxjson` files (visual pages built from Puck components) and `.mdx` files under `content/`, and\nrenders them through the `@conloca/astro-cms` Astro integration. The visual editor lives at `/__cms` on the dev server\nonly.\n\n## First move: `conloca doctor`\n\nFor any Conloca problem — blank page, 404 on a content page, editor not loading, build failure — run this before reading\nsource:\n\n```bash\nconloca doctor # human-readable report\nconloca doctor --json # single {ok, problems} object on stdout\n```\n\n`conloca <command>` in this skill means `npx @conloca/cli@<version> <command>`: use the exact version a Conloca prompt\ngave you, `@latest` when none did. Never run a different version than the prompt names.\n\nIt checks the content directory (sites.json complete, site directories present, every content file indexes cleanly) and,\nwhen an astro.config is present, the Astro wiring: content config, conlocaCMS import and options, react() order, peer\ndependencies, tsconfig jsx, prerender under server output, Conloca pages hidden behind a `src/pages` file, static pages\nwith no Conloca pages, and siteStyles. Each problem names the broken file and the fix. It is read-only and exits 1 on\nerrors; warnings alone exit 0.\n\nNew project from an empty directory? `conloca create <dir>` writes and installs the whole wired site. An existing Astro\nsite: `conloca connect` installs the packages, wires `astro.config` and writes the site's domain for the workspace\neditor; `conloca astro setup` only scaffolds the starter files.\n\n## Upgrading Conloca\n\nTo move a site to a newer Conloca release:\n\n1. In the site's folder run `npx @conloca/cli@latest upgrade` (or the exact version a Conloca prompt gave you). It\n raises each `@conloca/*` package to the version that CLI release pins in one install, applies the changes between\n versions, refreshes this skill and runs `conloca doctor`. `--dry-run` shows the diffs and changes nothing, `--json`\n prints one object on stdout, `--project <dir>` picks the site folder.\n2. Exit `2`: it lists what a person must change first; nothing was touched. Make those changes, then run it again.\n3. Exit `1`: it failed and put `package.json`, the lockfile and every changed file back. Fix what it names, run the\n install command its message gives when `node_modules` needs it, and run it again.\n4. A `SKILL.new.md` beside a skill means that skill had local edits, so the new text was written next to it: merge it\n into the skill by hand, then delete `SKILL.new.md`.\n5. Review `git diff`, run the build, then commit and push yourself — the command never commits or pushes.\n\nNever edit `@conloca/*` versions by hand: each package has its own version, and `upgrade` moves them to the versions one\nCLI release pins.\n\n## The files a working site needs\n\n- `astro.config.mjs` — registers `react()` and `conlocaCMS(...)`\n- `src/content.config.ts` — declares the content collections (without it every content page 404s)\n- `content/sites.json` — sites with their `locales` and `defaultLocale`, plus `globalLocales`\n- `src/puck.config.tsx` — registers the Puck components pages are built from\n- `src/layouts/Layout.astro` — the page layout content pages render into\n- `src/components/puck/*` and `src/schemas/data.ts` — starter components and data-collection schemas\n\nRun `conloca astro setup` inside an existing Astro project. It scaffolds the content config, components, schemas, page\nlayout, and content directories, preserving existing generated files. It adds the default site to `sites.json` when\nmissing. It prints the `astro.config` wiring rather than writing that file: merge the printed options into the existing\nconfig, then run `conloca doctor` to verify the result — or run `conloca connect`, which writes the wiring itself.\n`conloca init . <site-name>` adds another site to sites.json.\n\n## Install: the exact package set\n\n```bash\nnpm install @conloca/astro-cms @conloca/content-api @conloca/mdx @puckeditor/core @astrojs/react @vitejs/plugin-react typia\nnpm install -D ttsc @ttsc/unplugin\n```\n\n`@puckeditor/core` is what the generated components import — there is no other Puck package to install.\n\nttsc compiles with native TypeScript 7, and only one the site declares: a TypeScript 5 or 6 already installed (a\nworkspace root's) keeps the package manager from adding 7 as ttsc's peer. Add `typescript@^7.0.2`, or, keeping\nTypeScript 5 or 6 as `@astrojs/check` requires, an alias:\n`npm install -D typescript@^6.0.3 '@typescript/native@npm:typescript@^7.0.2'`.\n\n## Canonical astro.config.mjs\n\nThe minimal working config, matching what `conloca astro setup` prints:\n\n```js\nimport react from '@astrojs/react';\nimport { conlocaCMS } from '@conloca/astro-cms/node';\nimport { defineConfig } from 'astro/config';\nimport { schemaTypia } from './typia-vite.mjs';\n\nexport default defineConfig({\n integrations: [\n react(),\n conlocaCMS({\n contentRoot: './content',\n puckConfigPath: './src/puck.config.tsx',\n schemasPath: './src/schemas/data.ts',\n layout: './src/layouts/Layout.astro',\n }),\n ],\n vite: { plugins: [...schemaTypia()] },\n});\n```\n\n`react()` must come before `conlocaCMS()` — doctor checks the order. `src/schemas/data.ts` declares each data collection\nas a TypeScript type plus its generated Typia validator (`typia.plain.createValidatePrune<T>()`) and form metadata\n(`typia.json.schema<T>()`); `typia-vite.mjs` is the native transform that generates them, so it must stay in\n`vite.plugins`. And `src/content.config.ts`:\n\n```ts\nimport { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';\nimport { dataSchemas } from './schemas/data';\n\nexport const collections = {\n pages: conlocaPages(),\n ...conlocaData({ dataSchemas }),\n ...conlocaFragments(),\n};\n```\n\nEvery collection is declared here by name — content the config does not name fails the build instead of silently not\nbuilding.\n\n## Where errors appear\n\n- `astro dev` runs in the foreground: config and integration errors print to the terminal running it, and page errors\n also show in the browser error overlay. There is no separate log command — read that terminal.\n- A page referencing a Puck component type missing from puck.config.tsx serves HTTP 200 with a blank region and a clean\n browser console. The signal is `[Conloca] Page references N component type(s) missing from your Puck config: ...` in\n the dev-server or build terminal.\n- `conloca doctor` finds them before a build: C14 warns about every component type or prop a page stores that the Puck\n config does not declare.\n- The editor at `/__cms` exists only on the dev server. A production build without it is not a bug.\n\n## Writing content from the command line\n\nNever hand-write files under `content/`, and do not reach for HTTP endpoints: these commands write what the editor\nwrites, so the result is editable at `/__cms` right away. Each takes `--json` for a machine-readable result.\n\n```bash\nconloca page create --site default --collection pages --pathname /about --title 'About us' --content about.json\nconloca page update /about --description 'Who we are' --image /media/hero.jpg\nconloca data create site --name contact --data contact.json\nconloca data update site contact --data - < contact.json\nconloca asset add ~/Pictures/hero.jpg --alt 'Fresh bread on the counter'\n```\n\n- `page create` — a new page. `--content` takes Puck data `{ root, content, zones }` from a file or `-` (stdin), never\n inline JSON; `--description`, `--image`, `--canonical` and `--robots` fill its page settings.\n- `page update` — change an existing page, found by id or pathname; only the flags given change, and an empty value\n (`--robots ''`) clears a field.\n- `data create` / `data update` — a shared entry (contact details, a header menu): a JSON object from a file or\n `--data -`. `data update` replaces the entry's whole object: send every field, not just the changed one. Declare the\n collection's type in `src/schemas/data.ts`; the first `data create` wires the data schemas.\n- `asset add` — an image into the media folder; it prints the reference an image field stores, e.g. `/media/hero.jpg`.\n\nA layout reads a shared entry by name:\n\n```ts\nimport { getCollection } from 'astro:content';\nimport { conlocaDataEntry } from '@conloca/astro-cms/collections';\nimport { dataSchemas } from '../schemas/data';\n\nconst contact = conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'contact', 'en');\ncontact.phone; // typed by the `site` schema\n```\n\nA missing name, or one saved in several locales with none given, throws and fails the build instead of rendering empty.\n\nEntries a page's blocks list (team, testimonials) bind to the route with\n`routing.routes.<name>.dataBindings.collections`; a block's Puck `resolveData` then reads them from\n`metadata.collections.<name>`.\n\nAfter writing content, run the build: it validates every entry against its schema.\n\n## Routing\n\n- `layout: './src/layouts/Layout.astro'` alone injects a catch-all `/[...slug]` route over the `pages` collection, with\n `prerender: true` and `fallback: '404'`.\n- Passing `routing` replaces that default route entirely and the top-level `layout` is then ignored — name it per route\n instead: `routing: { routes: { pages: { pattern: '/[...slug]', layout: './src/layouts/Layout.astro' } } }`.\n- `routing: true` is the same default catch-all with no layout.\n- `fallback: '404'` returns a bare 404 when no content matches the pattern; `'passthrough'` hands the miss back to Astro\n so the site's own `/404` page renders, with a real 404 status.\n- Trap: a `src/pages` file always wins over a Conloca page at the same path, and Astro says nothing. Doctor warns when\n one hides a page; delete the file in the same change that makes the Conloca page live.\n\n## Adding Conloca to an existing Astro site\n\n- Switching to `output: 'server'`: first add `export const prerender = true` to every existing file under `src/pages/`,\n then flip the output — otherwise those pages silently stop being static. Doctor errors on files that miss it.\n- Existing `.mdx` content: set the site's `mdxPages` path in `content/sites.json` (relative to the project root, e.g.\n `./src/content/docs`). `.mdx` files under it surface in the CMS as pages of that site; the default locale lives at\n `<mdxPages>/<slug>.mdx`, other locales at `<mdxPages>/<locale>/<slug>.mdx`.\n- Plain `.md` files are never adopted — only `.mdx` and `.vxjson` are recognized as pages. Rename `.md` to `.mdx` to\n bring a file under management.\n\n## Converting an existing Astro page\n\nUse this when the user names existing `src/pages` routes to make editable. Convert only those routes.\n\n1. Run `conloca upgrade` (with the version your prompt gave, as defined above). Stop and report if it or\n `conloca doctor` fails: the commands below ship in that release.\n2. Run `conloca routes` and check each named route is listed. Dynamic routes (`[slug].astro`, content collection pages)\n and non-default-locale routes are out of scope and never listed.\n3. Before changing anything, run `conloca compare --reset --routes /a,/b` with exactly the routes the user named; it\n builds the site and saves a fresh baseline.\n4. Run `conloca components --json` to see the components the site already has.\n5. Port each section of the page to a React component in `src/components/puck/` whose editable text and images are\n fields. `.astro` components cannot be Puck components: port, do not reuse. Scoped `<style>` moves into a stylesheet\n listed in `siteStyles`; `<script>` and `client:` islands keep working through `withHydration()`; links stay links;\n images that become fields go into the assets folder with `conloca asset add`.\n6. Render the page through the layout the original used: point `conlocaCMS` (or a per-route layout) at it and adapt it\n to the props Conloca passes (`title`, `description`, `page`).\n7. Text from data files (like `src/data/*.ts`): per-page text goes into the page; values shared across pages go into\n data entries, moved once, on the first conversion that needs them. Every importer of those values (pages, layout,\n endpoints, browser components through props) then reads the same data entries, so there is one copy. Pages the user\n did not name may change only there, and their output must stay identical.\n8. The shared header and footer stay code in the layout. Their texts and links (menu items, footer links, contact\n details) move into a data entry the layout reads. Fragments are for prose blocks placed inside pages.\n9. Read a shared entry by a fixed name and fail the build when it is missing or duplicated:\n `conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'header', 'en').menu` throws in both cases.\n10. Write all content through the CLI: `conloca page create` / `conloca page update` (with `--content` and the metadata\n flags), `conloca data create` / `conloca data update`, `conloca asset add`. Never hand-write content files.\n11. Delete the old `.astro` file in the same change that makes the Conloca page live. A `src/pages` file always wins\n over a Conloca page at the same path, so the page cannot be seen before that; `conloca compare` is the check, not\n the browser.\n12. Run `conloca compare` again. Every route you did not convert must be identical (its linked stylesheets too); every\n converted route must keep its text, links, `<head>` tags and status; a route that became a Conloca page without\n being named fails. Fix and rerun until it passes, then run `conloca doctor`.\n13. Report every changed file, every page you were not asked to convert whose code changed, every allowed change\n `conloca compare` listed (for example island props that now carry shared values), and anything that could not be\n converted faithfully.\n\nThe workspace also has an MCP server for editing content remotely: pages, fragments and data entries on pushed branches.\nIt cannot change code, upload media or publish. Use the address the editor's prompt gives you; never guess or hardcode\none. Setup and limits: https://conloca.com/workspace-mcp/.\n\n## Custom Puck components\n\nFollow the generated examples in `src/components/puck/` — that is the one proven path:\n\n1. Write a render component plus a `ComponentConfig` wrapped in `withLayout` from `src/components/ComponentLayout.tsx`,\n mirroring the generated `HeadingComponent.tsx` / `Heading.tsx` pair.\n2. Register the component and its Props type in `src/puck.config.tsx`: add it to the `Components` type and the\n `components` map (and optionally a `categories` entry).\n3. Types come from `@puckeditor/core`. If `.tsx` components misrender or fail typecheck, set tsconfig\n `\"jsx\": \"react-jsx\"` — doctor's advisory warning covers this.\n\nA component referenced by stored content but not registered renders blank — see \"Where errors appear\".\n\n## Known limits — by design, do not fight them\n\n- MDX fragments render prose only.\n `Unknown component <X>: fragments render as plain content and cannot use React components.` is intentional: fragment\n content is treated as untrusted, so `{...}` expressions and `import`/`export` statements are rejected too. Do not try\n to sneak components in.\n- Unknown Puck component types render as nothing; the dev-server or build console names them. The fix is registering the\n type in `puck.config.tsx`, not editing the stored content.\n";
4637
+ var conloca_skill_default = "---\nname: conloca\ndescription: Load when working on an Astro site using Conloca CMS — @conloca/* packages, .vxjson content, sites.json.\n---\n\n# Conloca CMS\n\nConloca stores pages as `.vxjson` files (visual pages built from Puck components) and `.mdx` files under `content/`, and\nrenders them through the `@conloca/astro-cms` Astro integration. The visual editor lives at `/__cms` on the dev server\nonly.\n\n## First move: `conloca doctor`\n\nFor any Conloca problem — blank page, 404 on a content page, editor not loading, build failure — run this before reading\nsource:\n\n```bash\nconloca doctor # human-readable report\nconloca doctor --json # single {ok, problems} object on stdout\n```\n\n`conloca <command>` in this skill means `npx @conloca/cli@<version> <command>`: use the exact version a Conloca prompt\ngave you, `@latest` when none did. Never run a different version than the prompt names.\n\nIt checks the content directory (sites.json complete, site directories present, every content file indexes cleanly) and,\nwhen an astro.config is present, the Astro wiring: content config, conlocaCMS import and options, react() order, peer\ndependencies, tsconfig jsx, prerender under server output, Conloca pages hidden behind a `src/pages` file, static pages\nwith no Conloca pages, and siteStyles. Each problem names the broken file and the fix. It is read-only and exits 1 on\nerrors; warnings alone exit 0.\n\nNew project from an empty directory? `conloca create <dir>` writes and installs the whole wired site. An existing Astro\nsite: `conloca connect` installs the packages, wires `astro.config` and writes the site's domain for the workspace\neditor; `conloca astro setup` only scaffolds the starter files.\n\n## Upgrading Conloca\n\nTo move a site to a newer Conloca release:\n\n1. In the site's folder run `npx @conloca/cli@latest upgrade` (or the exact version a Conloca prompt gave you). It\n raises each `@conloca/*` package to the version that CLI release pins in one install, applies the changes between\n versions, refreshes this skill and runs `conloca doctor`. `--dry-run` shows the diffs and changes nothing, `--json`\n prints one object on stdout, `--project <dir>` picks the site folder.\n2. Exit `2`: it lists what a person must change first; nothing was touched. Make those changes, then run it again.\n3. Exit `1`: it failed and put `package.json`, the lockfile and every changed file back. Fix what it names, run the\n install command its message gives when `node_modules` needs it, and run it again.\n4. A `SKILL.new.md` beside a skill means that skill had local edits, so the new text was written next to it: merge it\n into the skill by hand, then delete `SKILL.new.md`.\n5. Review `git diff`, run the build, then commit and push yourself — the command never commits or pushes.\n\nNever edit `@conloca/*` versions by hand: each package has its own version, and `upgrade` moves them to the versions one\nCLI release pins.\n\nDraft previews: updating `@conloca/cloud-astro` moves a site that previewed from its own server (D2), or an\n`@astrojs/cloudflare` server-rendered site, to drafts rendered in the site's own build (d8) on its next build. `upgrade`\nmakes the edits explicit: the start command becomes `node dist/server/entry.mjs` and the `previewBuild` options d8\nignores go. Preview tabs opened before the update stop working; editors reopen Preview.\n\n## The files a working site needs\n\n- `astro.config.mjs` — registers `react()` and `conlocaCMS(...)`\n- `src/content.config.ts` — declares the content collections (without it every content page 404s)\n- `content/sites.json` — sites with their `locales` and `defaultLocale`, plus `globalLocales`\n- `src/puck.config.tsx` — registers the Puck components pages are built from\n- `src/layouts/Layout.astro` — the page layout content pages render into\n- `src/components/puck/*` and `src/schemas/data.ts` — starter components and data-collection schemas\n\nRun `conloca astro setup` inside an existing Astro project. It scaffolds the content config, components, schemas, page\nlayout, and content directories, preserving existing generated files. It adds the default site to `sites.json` when\nmissing. It prints the `astro.config` wiring rather than writing that file: merge the printed options into the existing\nconfig, then run `conloca doctor` to verify the result — or run `conloca connect`, which writes the wiring itself.\n`conloca init . <site-name>` adds another site to sites.json.\n\n## Install: the exact package set\n\n```bash\nnpm install @conloca/astro-cms @conloca/content-api @conloca/mdx @puckeditor/core @astrojs/react @vitejs/plugin-react typia\nnpm install -D ttsc @ttsc/unplugin\n```\n\n`@puckeditor/core` is what the generated components import — there is no other Puck package to install.\n\nttsc compiles with native TypeScript 7, and only one the site declares: a TypeScript 5 or 6 already installed (a\nworkspace root's) keeps the package manager from adding 7 as ttsc's peer. Add `typescript@^7.0.2`, or, keeping\nTypeScript 5 or 6 as `@astrojs/check` requires, an alias:\n`npm install -D typescript@^6.0.3 '@typescript/native@npm:typescript@^7.0.2'`.\n\n## Canonical astro.config.mjs\n\nThe minimal working config, matching what `conloca astro setup` prints:\n\n```js\nimport react from '@astrojs/react';\nimport { conlocaCMS } from '@conloca/astro-cms/node';\nimport { defineConfig } from 'astro/config';\nimport { schemaTypia } from './typia-vite.mjs';\n\nexport default defineConfig({\n integrations: [\n react(),\n conlocaCMS({\n contentRoot: './content',\n puckConfigPath: './src/puck.config.tsx',\n schemasPath: './src/schemas/data.ts',\n layout: './src/layouts/Layout.astro',\n }),\n ],\n vite: { plugins: [...schemaTypia()] },\n});\n```\n\n`react()` must come before `conlocaCMS()` — doctor checks the order. `src/schemas/data.ts` declares each data collection\nas a TypeScript type plus its generated Typia validator (`typia.plain.createValidatePrune<T>()`) and form metadata\n(`typia.json.schema<T>()`); `typia-vite.mjs` is the native transform that generates them, so it must stay in\n`vite.plugins`. And `src/content.config.ts`:\n\n```ts\nimport { conlocaData, conlocaFragments, conlocaPages } from '@conloca/astro-cms/node/content';\nimport { dataSchemas } from './schemas/data';\n\nexport const collections = {\n pages: conlocaPages(),\n ...conlocaData({ dataSchemas }),\n ...conlocaFragments(),\n};\n```\n\nEvery collection is declared here by name — content the config does not name fails the build instead of silently not\nbuilding.\n\n## Where errors appear\n\n- `astro dev` runs in the foreground: config and integration errors print to the terminal running it, and page errors\n also show in the browser error overlay. There is no separate log command — read that terminal.\n- A page referencing a Puck component type missing from puck.config.tsx serves HTTP 200 with a blank region and a clean\n browser console. The signal is `[Conloca] Page references N component type(s) missing from your Puck config: ...` in\n the dev-server or build terminal.\n- `conloca doctor` finds them before a build: C14 warns about every component type or prop a page stores that the Puck\n config does not declare.\n- The editor at `/__cms` exists only on the dev server. A production build without it is not a bug.\n\n## Writing content from the command line\n\nNever hand-write files under `content/`, and do not reach for HTTP endpoints: these commands write what the editor\nwrites, so the result is editable at `/__cms` right away. Each takes `--json` for a machine-readable result.\n\n```bash\nconloca page create --site default --collection pages --pathname /about --title 'About us' --content about.json\nconloca page update /about --description 'Who we are' --image /media/hero.jpg\nconloca data create site --name contact --data contact.json\nconloca data update site contact --data - < contact.json\nconloca asset add ~/Pictures/hero.jpg --alt 'Fresh bread on the counter'\n```\n\n- `page create` — a new page. `--content` takes Puck data `{ root, content, zones }` from a file or `-` (stdin), never\n inline JSON; `--description`, `--image`, `--canonical` and `--robots` fill its page settings.\n- `page update` — change an existing page, found by id or pathname; only the flags given change, and an empty value\n (`--robots ''`) clears a field.\n- `data create` / `data update` — a shared entry (contact details, a header menu): a JSON object from a file or\n `--data -`. `data update` replaces the entry's whole object: send every field, not just the changed one. Declare the\n collection's type in `src/schemas/data.ts`; the first `data create` wires the data schemas.\n- `asset add` — an image into the media folder; it prints the reference an image field stores, e.g. `/media/hero.jpg`.\n\nA layout reads a shared entry by name:\n\n```ts\nimport { getCollection } from 'astro:content';\nimport { conlocaDataEntry } from '@conloca/astro-cms/collections';\nimport { dataSchemas } from '../schemas/data';\n\nconst contact = conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'contact', 'en');\ncontact.phone; // typed by the `site` schema\n```\n\nA missing name, or one saved in several locales with none given, throws and fails the build instead of rendering empty.\n\nEntries a page's blocks list (team, testimonials) bind to the route with\n`routing.routes.<name>.dataBindings.collections`; a block's Puck `resolveData` then reads them from\n`metadata.collections.<name>`.\n\nAfter writing content, run the build: it validates every entry against its schema.\n\n## Routing\n\n- `layout: './src/layouts/Layout.astro'` alone injects a catch-all `/[...slug]` route over the `pages` collection, with\n `prerender: true` and `fallback: '404'`.\n- Passing `routing` replaces that default route entirely and the top-level `layout` is then ignored — name it per route\n instead: `routing: { routes: { pages: { pattern: '/[...slug]', layout: './src/layouts/Layout.astro' } } }`.\n- `routing: true` is the same default catch-all with no layout.\n- `fallback: '404'` returns a bare 404 when no content matches the pattern; `'passthrough'` hands the miss back to Astro\n so the site's own `/404` page renders, with a real 404 status.\n- Trap: a `src/pages` file always wins over a Conloca page at the same path, and Astro says nothing. Doctor warns when\n one hides a page; delete the file in the same change that makes the Conloca page live.\n\n## Adding Conloca to an existing Astro site\n\n- Switching to `output: 'server'`: first add `export const prerender = true` to every existing file under `src/pages/`,\n then flip the output — otherwise those pages silently stop being static. Doctor errors on files that miss it.\n- Existing `.mdx` content: set the site's `mdxPages` path in `content/sites.json` (relative to the project root, e.g.\n `./src/content/docs`). `.mdx` files under it surface in the CMS as pages of that site; the default locale lives at\n `<mdxPages>/<slug>.mdx`, other locales at `<mdxPages>/<locale>/<slug>.mdx`.\n- Plain `.md` files are never adopted — only `.mdx` and `.vxjson` are recognized as pages. Rename `.md` to `.mdx` to\n bring a file under management.\n\n## Converting an existing Astro page\n\nUse this when the user names existing `src/pages` routes to make editable. Convert only those routes.\n\n1. Run `conloca upgrade` (with the version your prompt gave, as defined above). Stop and report if it or\n `conloca doctor` fails: the commands below ship in that release.\n2. Run `conloca routes` and check each named route is listed. Dynamic routes (`[slug].astro`, content collection pages)\n and non-default-locale routes are out of scope and never listed.\n3. Before changing anything, run `conloca compare --reset --routes /a,/b` with exactly the routes the user named; it\n builds the site and saves a fresh baseline.\n4. Run `conloca components --json` to see the components the site already has.\n5. Port each section of the page to a React component in `src/components/puck/` whose editable text and images are\n fields. `.astro` components cannot be Puck components: port, do not reuse. Scoped `<style>` moves into a stylesheet\n listed in `siteStyles`; `<script>` and `client:` islands keep working through `withHydration()`; links stay links;\n images that become fields go into the assets folder with `conloca asset add`.\n6. Render the page through the layout the original used: point `conlocaCMS` (or a per-route layout) at it and adapt it\n to the props Conloca passes (`title`, `description`, `page`).\n7. Text from data files (like `src/data/*.ts`): per-page text goes into the page; values shared across pages go into\n data entries, moved once, on the first conversion that needs them. Every importer of those values (pages, layout,\n endpoints, browser components through props) then reads the same data entries, so there is one copy. Pages the user\n did not name may change only there, and their output must stay identical.\n8. The shared header and footer stay code in the layout. Their texts and links (menu items, footer links, contact\n details) move into a data entry the layout reads. Fragments are for prose blocks placed inside pages.\n9. Read a shared entry by a fixed name and fail the build when it is missing or duplicated:\n `conlocaDataEntry(dataSchemas, 'site', await getCollection('site'), 'header', 'en').menu` throws in both cases.\n10. Write all content through the CLI: `conloca page create` / `conloca page update` (with `--content` and the metadata\n flags), `conloca data create` / `conloca data update`, `conloca asset add`. Never hand-write content files.\n11. Delete the old `.astro` file in the same change that makes the Conloca page live. A `src/pages` file always wins\n over a Conloca page at the same path, so the page cannot be seen before that; `conloca compare` is the check, not\n the browser.\n12. Run `conloca compare` again. Every route you did not convert must be identical (its linked stylesheets too); every\n converted route must keep its text, links, `<head>` tags and status; a route that became a Conloca page without\n being named fails. Fix and rerun until it passes, then run `conloca doctor`.\n13. Report every changed file, every page you were not asked to convert whose code changed, every allowed change\n `conloca compare` listed (for example island props that now carry shared values), and anything that could not be\n converted faithfully.\n\nThe workspace also has an MCP server for editing content remotely: pages, fragments and data entries on pushed branches.\nIt cannot change code, upload media or publish. Use the address the editor's prompt gives you; never guess or hardcode\none. Setup and limits: https://conloca.com/workspace-mcp/.\n\n## Custom Puck components\n\nFollow the generated examples in `src/components/puck/` — that is the one proven path:\n\n1. Write a render component plus a `ComponentConfig` wrapped in `withLayout` from `src/components/ComponentLayout.tsx`,\n mirroring the generated `HeadingComponent.tsx` / `Heading.tsx` pair.\n2. Register the component and its Props type in `src/puck.config.tsx`: add it to the `Components` type and the\n `components` map (and optionally a `categories` entry).\n3. Types come from `@puckeditor/core`. If `.tsx` components misrender or fail typecheck, set tsconfig\n `\"jsx\": \"react-jsx\"` — doctor's advisory warning covers this.\n\nA component referenced by stored content but not registered renders blank — see \"Where errors appear\".\n\n## Known limits — by design, do not fight them\n\n- MDX fragments render prose only.\n `Unknown component <X>: fragments render as plain content and cannot use React components.` is intentional: fragment\n content is treated as untrusted, so `{...}` expressions and `import`/`export` statements are rejected too. Do not try\n to sneak components in.\n- Unknown Puck component types render as nothing; the dev-server or build console names them. The fix is registering the\n type in `puck.config.tsx`, not editing the stored content.\n";
4151
4638
 
4152
4639
  // src/commands/setup.ts
4153
4640
  var DEFAULT_SITE_NAME = "default";
@@ -4755,18 +5242,18 @@ async function setup(projectPath = ".", siteName = DEFAULT_SITE_NAME, options =
4755
5242
  const dataSchemas = options.dataSchemas !== false;
4756
5243
  try {
4757
5244
  const absolutePath = resolve5(projectPath);
4758
- const srcDir = join12(absolutePath, "src");
5245
+ const srcDir = join14(absolutePath, "src");
4759
5246
  console.log(`Setting up Conloca for Astro...
4760
5247
  `);
4761
- const contentDir = join12(absolutePath, "content");
5248
+ const contentDir = join14(absolutePath, "content");
4762
5249
  const dirs = [
4763
5250
  contentDir,
4764
- join12(contentDir, siteName, "pages"),
4765
- join12(srcDir, "components"),
4766
- join12(srcDir, "components", "puck"),
4767
- join12(srcDir, "layouts"),
4768
- ...dataSchemas ? [join12(srcDir, "schemas")] : [],
4769
- join12(absolutePath, ".claude", "skills", "conloca")
5251
+ join14(contentDir, siteName, "pages"),
5252
+ join14(srcDir, "components"),
5253
+ join14(srcDir, "components", "puck"),
5254
+ join14(srcDir, "layouts"),
5255
+ ...dataSchemas ? [join14(srcDir, "schemas")] : [],
5256
+ join14(absolutePath, ".claude", "skills", "conloca")
4770
5257
  ];
4771
5258
  for (const dir of dirs) {
4772
5259
  await mkdir2(dir, { recursive: true });
@@ -4775,29 +5262,29 @@ async function setup(projectPath = ".", siteName = DEFAULT_SITE_NAME, options =
4775
5262
  const skipped = [];
4776
5263
  async function writeIfNotExists(filePath, content, description) {
4777
5264
  try {
4778
- await readFile9(filePath);
5265
+ await readFile11(filePath);
4779
5266
  skipped.push(description);
4780
5267
  } catch {
4781
5268
  await writeFile3(filePath, content, "utf-8");
4782
5269
  created.push(description);
4783
5270
  }
4784
5271
  }
4785
- await writeIfNotExists(join12(srcDir, "components", "ComponentLayout.tsx"), COMPONENT_LAYOUT_TEMPLATE, "src/components/ComponentLayout.tsx");
4786
- await writeIfNotExists(join12(srcDir, "components", "Section.tsx"), SECTION_TEMPLATE, "src/components/Section.tsx");
4787
- await writeIfNotExists(join12(srcDir, "components", "puck", "HeadingComponent.tsx"), HEADING_COMPONENT_TEMPLATE, "src/components/puck/HeadingComponent.tsx");
4788
- await writeIfNotExists(join12(srcDir, "components", "puck", "Heading.tsx"), HEADING_TEMPLATE, "src/components/puck/Heading.tsx");
4789
- await writeIfNotExists(join12(srcDir, "components", "puck", "TextComponent.tsx"), TEXT_COMPONENT_TEMPLATE, "src/components/puck/TextComponent.tsx");
4790
- await writeIfNotExists(join12(srcDir, "components", "puck", "Text.tsx"), TEXT_TEMPLATE, "src/components/puck/Text.tsx");
4791
- await writeIfNotExists(join12(srcDir, "components", "puck", "Flex.tsx"), FLEX_TEMPLATE, "src/components/puck/Flex.tsx");
4792
- await writeIfNotExists(join12(srcDir, "components", "puck", "Grid.tsx"), GRID_TEMPLATE, "src/components/puck/Grid.tsx");
4793
- await writeIfNotExists(join12(srcDir, "puck.config.tsx"), PUCK_CONFIG_TEMPLATE, "src/puck.config.tsx");
5272
+ await writeIfNotExists(join14(srcDir, "components", "ComponentLayout.tsx"), COMPONENT_LAYOUT_TEMPLATE, "src/components/ComponentLayout.tsx");
5273
+ await writeIfNotExists(join14(srcDir, "components", "Section.tsx"), SECTION_TEMPLATE, "src/components/Section.tsx");
5274
+ await writeIfNotExists(join14(srcDir, "components", "puck", "HeadingComponent.tsx"), HEADING_COMPONENT_TEMPLATE, "src/components/puck/HeadingComponent.tsx");
5275
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Heading.tsx"), HEADING_TEMPLATE, "src/components/puck/Heading.tsx");
5276
+ await writeIfNotExists(join14(srcDir, "components", "puck", "TextComponent.tsx"), TEXT_COMPONENT_TEMPLATE, "src/components/puck/TextComponent.tsx");
5277
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Text.tsx"), TEXT_TEMPLATE, "src/components/puck/Text.tsx");
5278
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Flex.tsx"), FLEX_TEMPLATE, "src/components/puck/Flex.tsx");
5279
+ await writeIfNotExists(join14(srcDir, "components", "puck", "Grid.tsx"), GRID_TEMPLATE, "src/components/puck/Grid.tsx");
5280
+ await writeIfNotExists(join14(srcDir, "puck.config.tsx"), PUCK_CONFIG_TEMPLATE, "src/puck.config.tsx");
4794
5281
  if (dataSchemas) {
4795
- await writeIfNotExists(join12(srcDir, "schemas", "data.ts"), DATA_SCHEMAS_TEMPLATE, "src/schemas/data.ts");
4796
- await writeIfNotExists(join12(absolutePath, "typia-vite.mjs"), TYPIA_VITE_TEMPLATE, "typia-vite.mjs");
4797
- await writeIfNotExists(join12(absolutePath, "tsconfig.typia.json"), TYPIA_TSCONFIG_TEMPLATE, "tsconfig.typia.json");
5282
+ await writeIfNotExists(join14(srcDir, "schemas", "data.ts"), DATA_SCHEMAS_TEMPLATE, "src/schemas/data.ts");
5283
+ await writeIfNotExists(join14(absolutePath, "typia-vite.mjs"), TYPIA_VITE_TEMPLATE, "typia-vite.mjs");
5284
+ await writeIfNotExists(join14(absolutePath, "tsconfig.typia.json"), TYPIA_TSCONFIG_TEMPLATE, "tsconfig.typia.json");
4798
5285
  }
4799
- await writeIfNotExists(join12(srcDir, "layouts", "Layout.astro"), PAGE_LAYOUT_TEMPLATE, "src/layouts/Layout.astro");
4800
- await writeIfNotExists(join12(absolutePath, ".claude", "skills", "conloca", "SKILL.md"), stampSkill(conloca_skill_default, (await readCliManifest()).version), ".claude/skills/conloca/SKILL.md");
5286
+ await writeIfNotExists(join14(srcDir, "layouts", "Layout.astro"), PAGE_LAYOUT_TEMPLATE, "src/layouts/Layout.astro");
5287
+ await writeIfNotExists(join14(absolutePath, ".claude", "skills", "conloca", "SKILL.md"), stampSkill(conloca_skill_default, (await readCliManifest()).version), ".claude/skills/conloca/SKILL.md");
4801
5288
  const sites = await ensureSiteInSitesConfig(contentDir, siteName);
4802
5289
  if (sites.added) {
4803
5290
  created.push(sites.existed ? `content/sites.json (added site: ${siteName})` : "content/sites.json");
@@ -4904,7 +5391,7 @@ async function gitText(args, cwd) {
4904
5391
  }
4905
5392
  }
4906
5393
  async function readText2(path) {
4907
- return readFile10(path, "utf8").catch(() => null);
5394
+ return readFile12(path, "utf8").catch(() => null);
4908
5395
  }
4909
5396
  function listsWrangler(packageJson) {
4910
5397
  try {
@@ -4919,7 +5406,7 @@ function isStrings(value) {
4919
5406
  }
4920
5407
  async function readWorkerFirstList(projectDir) {
4921
5408
  try {
4922
- const value = JSON.parse(await readText2(join13(projectDir, ".conloca", "dispatcher", "run_worker_first.json")) ?? "");
5409
+ const value = JSON.parse(await readText2(join15(projectDir, ".conloca", "dispatcher", "run_worker_first.json")) ?? "");
4923
5410
  return isStrings(value) ? value : null;
4924
5411
  } catch {
4925
5412
  return null;
@@ -4936,14 +5423,14 @@ async function askPlan(io) {
4936
5423
  }
4937
5424
  }
4938
5425
  function isInside(path, folder) {
4939
- return path === folder || path.startsWith(`${folder}${sep2}`);
5426
+ return path === folder || path.startsWith(`${folder}${sep3}`);
4940
5427
  }
4941
5428
  async function pickProject(start, repoRoot, options, io) {
4942
- const projects = repoRoot === null ? ASTRO_CONFIG_FILES.filter((name) => existsSync5(join13(start, name))).slice(0, 1).map((name) => ({ dir: start, configFile: join13(start, name) })) : (await listAstroProjects(repoRoot)).map((project) => ({
4943
- dir: join13(repoRoot, project.dir),
4944
- configFile: join13(repoRoot, project.configFile)
5429
+ const projects = repoRoot === null ? ASTRO_CONFIG_FILES.filter((name) => existsSync6(join15(start, name))).slice(0, 1).map((name) => ({ dir: start, configFile: join15(start, name) })) : (await listAstroProjects(repoRoot)).map((project) => ({
5430
+ dir: join15(repoRoot, project.dir),
5431
+ configFile: join15(repoRoot, project.configFile)
4945
5432
  }));
4946
- const name = (dir) => relative4(start, dir) || ".";
5433
+ const name = (dir) => relative5(start, dir) || ".";
4947
5434
  if (options.project !== undefined) {
4948
5435
  const target = resolve6(start, options.project);
4949
5436
  const found = projects.find((project) => project.dir === target);
@@ -4970,8 +5457,8 @@ async function pickProject(start, repoRoot, options, io) {
4970
5457
  edits: []
4971
5458
  };
4972
5459
  }
4973
- async function packagesStep(projectDir, commands) {
4974
- const path = join13(projectDir, "package.json");
5460
+ async function packagesStep(projectDir, commands, extra = [], reinstall = []) {
5461
+ const path = join15(projectDir, "package.json");
4975
5462
  const text = await readText2(path);
4976
5463
  const unreadable = {
4977
5464
  id: "packages",
@@ -4993,10 +5480,13 @@ async function packagesStep(projectDir, commands) {
4993
5480
  const range = conlocaRange(cli, name);
4994
5481
  return range === undefined ? [] : [[name, range]];
4995
5482
  }),
4996
- ...PEER_PACKAGES.map((name) => [name, THIRD_PARTY_VERSIONS[name]])
5483
+ ...PEER_PACKAGES.map((name) => [name, THIRD_PARTY_VERSIONS[name]]),
5484
+ ...extra
4997
5485
  ];
4998
5486
  const missing = wanted.filter(([name]) => !(name in dependencies) && !(name in devDependencies));
4999
- if (missing.length === 0) {
5487
+ const updated = reinstall.filter(([name]) => !missing.some(([other]) => other === name));
5488
+ const installed = [...missing, ...updated];
5489
+ if (installed.length === 0) {
5000
5490
  return { id: "packages", result: { state: "done", message: "every package is in package.json", edits: [] } };
5001
5491
  }
5002
5492
  const entries = Object.entries({ ...dependencies, ...Object.fromEntries(missing) });
@@ -5006,16 +5496,19 @@ async function packagesStep(projectDir, commands) {
5006
5496
  id: "packages",
5007
5497
  result: {
5008
5498
  state: "changed",
5009
- message: `added ${missing.map(([name]) => name).join(", ")}`,
5010
- edits: [{ path, before: text, after: jsonLike(text, { ...manifest, dependencies: added }) }]
5499
+ message: [
5500
+ ...missing.length > 0 ? [`added ${missing.map(([name]) => name).join(", ")}`] : [],
5501
+ ...updated.map(([name, range]) => `updates ${name} to ${range}, the release with draft previews in the site build`)
5502
+ ].join("; "),
5503
+ edits: missing.length > 0 ? [{ path, before: text, after: jsonLike(text, { ...manifest, dependencies: added }) }] : []
5011
5504
  },
5012
- command: `${commands.add} ${missing.map(([name, range]) => `'${name}@${range}'`).join(" ")}`
5505
+ command: `${commands.add} ${installed.map(([name, range]) => `'${name}@${range}'`).join(" ")}`
5013
5506
  };
5014
5507
  }
5015
5508
  async function olderPackages(projectDir, cli) {
5016
5509
  let manifest;
5017
5510
  try {
5018
- manifest = JSON.parse(await readText2(join13(projectDir, "package.json")) ?? "");
5511
+ manifest = JSON.parse(await readText2(join15(projectDir, "package.json")) ?? "");
5019
5512
  } catch {
5020
5513
  return [];
5021
5514
  }
@@ -5028,6 +5521,111 @@ async function olderPackages(projectDir, cli) {
5028
5521
  return floor !== null && wanted !== null && compareVersions(floor, wanted) < 0 ? [`${name} ${floor}`] : [];
5029
5522
  });
5030
5523
  }
5524
+ var HOST_QUESTION = "Where does this site deploy? [vercel/netlify/cloudflare/node]";
5525
+ var STATIC_ONLY = "this host runs no functions: use a separate Cloudflare preview deploy (previewBuild: { separate: true }) or go without preview";
5526
+ var STATIC_NODE = "a static site on your own server has no server to render drafts: use a separate Cloudflare preview deploy (previewBuild: { separate: true }) or add @astrojs/node and start dist/server/entry.mjs, then run connect with --host node";
5527
+ function hasD8Refusals(value) {
5528
+ return isRecord(value) && typeof value.d8ConfigRefusal === "function" && typeof value.d8EdgeRefusal === "function";
5529
+ }
5530
+ var ADAPTER_HOSTS = {
5531
+ "@astrojs/vercel": "vercel",
5532
+ "@astrojs/netlify": "netlify",
5533
+ "@astrojs/cloudflare": "cloudflare",
5534
+ "@astrojs/node": "node"
5535
+ };
5536
+ function declaredFloor(manifestText, name) {
5537
+ let manifest;
5538
+ try {
5539
+ manifest = JSON.parse(manifestText ?? "");
5540
+ } catch {
5541
+ return null;
5542
+ }
5543
+ if (!isRecord(manifest))
5544
+ return null;
5545
+ const spec = [manifest.dependencies, manifest.devDependencies].map((deps) => isRecord(deps) ? deps[name] : undefined).find((value) => typeof value === "string");
5546
+ return typeof spec === "string" ? versionFloor(spec) : null;
5547
+ }
5548
+ function previewOff(result) {
5549
+ return { step: { id: "adapter", result }, preview: { kind: "off" }, extra: [], reinstall: [] };
5550
+ }
5551
+ function needsYou(message) {
5552
+ return { state: "needs-you", message, edits: [] };
5553
+ }
5554
+ async function adapterSetup(input) {
5555
+ const { preview, projectDir, options, io } = input;
5556
+ const keep = (step) => ({ step, preview, extra: [], reinstall: [] });
5557
+ const installed = (name) => installedVersion(name, projectDir, input.repoRoot);
5558
+ const loaded = await importFromProject(projectDir, "@conloca/cloud-astro/node");
5559
+ const configRefusal = hasD8Refusals(loaded) ? (text, name, base) => loaded.d8ConfigRefusal(text, name, base) ?? loaded.d8EdgeRefusal(undefined, text, name) : undefined;
5560
+ const addAdapter = async (host) => {
5561
+ const declared = declaredFloor(input.manifestText, HOST_ADAPTERS[host].name) !== null;
5562
+ const astroVersion = declared ? "" : await installed("astro") ?? declaredFloor(input.manifestText, "astro") ?? "";
5563
+ return addAdapterStep({
5564
+ path: input.configFile,
5565
+ text: input.text,
5566
+ host,
5567
+ siteDomains: siteDomainsOf(input.sitesText),
5568
+ astroVersion,
5569
+ yes: options.yes,
5570
+ ...configRefusal === undefined ? {} : { configRefusal }
5571
+ });
5572
+ };
5573
+ const interactive = io.isTTY && !options.yes && !options.dryRun;
5574
+ let answer = await detectHost({
5575
+ projectDir,
5576
+ repoRoot: input.repoRoot,
5577
+ astroText: input.text,
5578
+ ...options.host === undefined ? {} : { flag: options.host }
5579
+ });
5580
+ if (preview.kind === "d8") {
5581
+ const host = ADAPTER_HOSTS[preview.adapter];
5582
+ if (!answer.ok && answer.reason === "conflict")
5583
+ return previewOff(needsYou(answer.message));
5584
+ const matches = answer.ok && (answer.host === host || host === "cloudflare" && answer.host === "cloudflare-d3");
5585
+ if (answer.ok && !matches) {
5586
+ return previewOff(needsYou(`astro.config uses ${preview.adapter}, but ${answer.evidence.join(", ")} says the site deploys to ${answer.host}: pass --host ${host} if the adapter is right`));
5587
+ }
5588
+ if (!answer.ok && host === "node") {
5589
+ return previewOff(needsYou("can't tell that your own server starts dist/server/entry.mjs: pass --host node if it does"));
5590
+ }
5591
+ const current = await installed("@conloca/cloud-astro");
5592
+ if (current === null || compareVersions(current, D8_SINCE) < 0) {
5593
+ return previewOff(needsYou(`the installed @conloca/cloud-astro (${current ?? "none"}) renders no drafts in the site's own build: run conloca upgrade, then connect again`));
5594
+ }
5595
+ if (configRefusal === undefined) {
5596
+ return previewOff(needsYou("couldn't load the preview checks of this project's @conloca/cloud-astro: install its packages, then run connect again"));
5597
+ }
5598
+ return keep({ id: "adapter", result: await addAdapter(host) });
5599
+ }
5600
+ if (!answer.ok && answer.reason === "unknown" && interactive) {
5601
+ const reply = (await io.ask(HOST_QUESTION)).trim().toLowerCase();
5602
+ if (reply === "vercel" || reply === "netlify" || reply === "cloudflare" || reply === "node") {
5603
+ answer = { ok: true, host: reply, evidence: ["your answer"] };
5604
+ }
5605
+ }
5606
+ if (!answer.ok)
5607
+ return previewOff(needsYou(answer.message));
5608
+ const { host } = answer;
5609
+ if (host === "cloudflare" || host === "cloudflare-d3")
5610
+ return keep(null);
5611
+ if (host === "static-only")
5612
+ return previewOff(needsYou(STATIC_ONLY));
5613
+ if (host === "node")
5614
+ return previewOff(needsYou(STATIC_NODE));
5615
+ const result = await addAdapter(host);
5616
+ if (result.state !== "changed")
5617
+ return previewOff(result);
5618
+ const { name } = HOST_ADAPTERS[host];
5619
+ const current = await installed("@conloca/cloud-astro");
5620
+ const range = conlocaRange(await readCliManifest(), "@conloca/cloud-astro");
5621
+ const stale = range !== undefined && (current === null || compareVersions(current, D8_SINCE) < 0);
5622
+ return {
5623
+ step: { id: "adapter", result },
5624
+ preview: { kind: "d8", prefix: preview.prefix, adapter: name },
5625
+ extra: [[name, ADAPTER_VERSIONS[name]]],
5626
+ reinstall: stale ? [["@conloca/cloud-astro", range]] : []
5627
+ };
5628
+ }
5031
5629
  async function siteIdOf(sitesPath) {
5032
5630
  try {
5033
5631
  const parsed = JSON.parse(await readText2(sitesPath) ?? "");
@@ -5040,7 +5638,7 @@ async function buildStep(projectDir, siteId, command, io) {
5040
5638
  if (!await io.run(command, projectDir, { CONLOCA_CONNECT: "1" })) {
5041
5639
  return { state: "failed", message: `${command} failed; fix the build, then run connect again`, edits: [] };
5042
5640
  }
5043
- const folder = ["dist", join13("dist", "client")].map((output) => join13(projectDir, output, "_conloca", "editor")).find((candidate) => existsSync5(join13(candidate, "index.html")));
5641
+ const folder = ["dist", join15("dist", "client")].map((output) => join15(projectDir, output, "_conloca", "editor")).find((candidate) => existsSync6(join15(candidate, "index.html")));
5044
5642
  if (folder === undefined) {
5045
5643
  return {
5046
5644
  state: "failed",
@@ -5048,11 +5646,11 @@ async function buildStep(projectDir, siteId, command, io) {
5048
5646
  edits: []
5049
5647
  };
5050
5648
  }
5051
- const where = relative4(projectDir, folder);
5649
+ const where = relative5(projectDir, folder);
5052
5650
  const missing = { state: "failed", message: `${where}/conloca.json is missing or not JSON`, edits: [] };
5053
5651
  let info;
5054
5652
  try {
5055
- info = JSON.parse(await readText2(join13(folder, "conloca.json")) ?? "");
5653
+ info = JSON.parse(await readText2(join15(folder, "conloca.json")) ?? "");
5056
5654
  } catch {
5057
5655
  return missing;
5058
5656
  }
@@ -5075,7 +5673,7 @@ async function buildStep(projectDir, siteId, command, io) {
5075
5673
  return { state: "done", message: `the build wrote the editor page to ${where} for site ${siteId}`, edits: [] };
5076
5674
  }
5077
5675
  function patchOf(edit, start) {
5078
- const name = relative4(start, edit.path);
5676
+ const name = relative5(start, edit.path);
5079
5677
  return createTwoFilesPatch(edit.before === null ? "/dev/null" : name, name, edit.before ?? "", edit.after);
5080
5678
  }
5081
5679
  function exitCodeOf(report) {
@@ -5111,7 +5709,7 @@ async function runConnect(path, options, io) {
5111
5709
  id: "project",
5112
5710
  result: {
5113
5711
  state: "done",
5114
- message: repoUri === null ? `Astro project ${relative4(start, projectDir) || "."}; the editor needs the repository on GitHub, and this checkout has no GitHub origin` : `Astro project ${relative4(start, projectDir) || "."} in ${repoUri}`,
5712
+ message: repoUri === null ? `Astro project ${relative5(start, projectDir) || "."}; the editor needs the repository on GitHub, and this checkout has no GitHub origin` : `Astro project ${relative5(start, projectDir) || "."} in ${repoUri}`,
5115
5713
  edits: []
5116
5714
  }
5117
5715
  };
@@ -5119,7 +5717,7 @@ async function runConnect(path, options, io) {
5119
5717
  const to = cli.version;
5120
5718
  const older = await olderPackages(projectDir, cli);
5121
5719
  if (older.length > 0) {
5122
- const name = relative4(start, projectDir) || ".";
5720
+ const name = relative5(start, projectDir) || ".";
5123
5721
  const target = name === "." ? "" : ` ${name}`;
5124
5722
  const message = `this site's @conloca packages (${older.join(", ")}) are older than the versions this CLI (${to}) pins: upgrade them first`;
5125
5723
  console.log(`needs-you: ${message}`);
@@ -5138,14 +5736,7 @@ async function runConnect(path, options, io) {
5138
5736
  next: NEXT
5139
5737
  };
5140
5738
  }
5141
- const packages = await packagesStep(projectDir, commands);
5142
- if (!options.install && packages.command !== undefined) {
5143
- packages.result = { state: "skipped", message: `not installed (--no-install): run ${packages.command}`, edits: [] };
5144
- packages.command = undefined;
5145
- }
5146
- if (options.update)
5147
- packages.command = undefined;
5148
- const configText = await readFile10(picked.configFile, "utf8");
5739
+ const configText = await readFile12(picked.configFile, "utf8");
5149
5740
  const code = stripComments(configText);
5150
5741
  const cmsOptions = callOptions(code, "conlocaCMS");
5151
5742
  const config = {
@@ -5154,15 +5745,47 @@ async function runConnect(path, options, io) {
5154
5745
  };
5155
5746
  const starter = !options.update && cmsOptions.state === "no-call" && config.result.state === "changed";
5156
5747
  if (starter) {
5157
- const contentConfig = join13(projectDir, "src", "content.config.ts");
5158
- if (!existsSync5(contentConfig))
5748
+ const contentConfig = join15(projectDir, "src", "content.config.ts");
5749
+ if (!existsSync6(contentConfig))
5159
5750
  config.result.edits.push({ path: contentConfig, before: null, after: CONTENT_CONFIG });
5160
5751
  config.result.message += "; writes the starter components and Puck config (conloca astro setup)";
5161
5752
  }
5162
5753
  const rootOption = cmsOptions.state === "literal" ? stringLiteral(cmsOptions.entries.get("contentRoot") ?? "") : null;
5163
- const sitesPath = join13(rootOption === null ? contentRootOf(projectDir) : resolve6(projectDir, rootOption), "sites.json");
5754
+ const sitesPath = join15(rootOption === null ? contentRootOf(projectDir) : resolve6(projectDir, rootOption), "sites.json");
5164
5755
  const astroSite = readAstroSite(configText);
5165
- const site = options.siteUrl ?? (astroSite === "computed" ? null : astroSite.site);
5756
+ const found = previewSetupOf(callOptions(code, "conlocaCloud"), callOptions(code, "defineConfig"), astroSite === "computed" ? null : astroSite.base, code);
5757
+ const sitesText = await readText2(sitesPath) ?? "";
5758
+ const manifestPath = join15(projectDir, "package.json");
5759
+ const manifestText = await readText2(manifestPath);
5760
+ const wiredText = config.result.edits.find((edit) => edit.path === picked.configFile)?.after ?? configText;
5761
+ const adapterPlan = !options.update && (found.kind === "d3" || found.kind === "d8") ? await adapterSetup({
5762
+ preview: found.kind === "d8" ? found : { kind: "d3", prefix: found.prefix },
5763
+ projectDir,
5764
+ repoRoot: root,
5765
+ configFile: picked.configFile,
5766
+ text: wiredText,
5767
+ sitesText,
5768
+ manifestText,
5769
+ options,
5770
+ io
5771
+ }) : null;
5772
+ const preview = adapterPlan?.preview ?? found;
5773
+ const refusal = found.kind === "off" || found.kind === "d4" ? found.refusal : undefined;
5774
+ const refused = options.update ? undefined : refusal;
5775
+ const adapter = adapterPlan?.step ?? (refused === undefined ? null : { id: "adapter", result: needsYou(refused) });
5776
+ const adapterEdit = adapter?.result.edits.find((edit) => edit.path === picked.configFile);
5777
+ const siteStep = preview.kind === "d8" ? {
5778
+ id: "site",
5779
+ result: addAstroSiteStep({
5780
+ path: picked.configFile,
5781
+ text: adapterEdit?.after ?? wiredText,
5782
+ sitesText,
5783
+ adapter: preview.adapter,
5784
+ siteUrl: options.siteUrl
5785
+ })
5786
+ } : null;
5787
+ const proposed = siteStep?.result.state === "differs" ? siteUrlOf(sitesText) : null;
5788
+ const site = options.siteUrl ?? (astroSite === "computed" ? null : astroSite.site ?? proposed);
5166
5789
  let address;
5167
5790
  if (site === null) {
5168
5791
  address = {
@@ -5185,14 +5808,17 @@ async function runConnect(path, options, io) {
5185
5808
  edit.before = null;
5186
5809
  address = { id: "address", result };
5187
5810
  }
5811
+ const packages = await packagesStep(projectDir, commands, adapterPlan?.extra, adapterPlan?.reinstall);
5812
+ if (!options.install && packages.command !== undefined) {
5813
+ packages.result = { state: "skipped", message: `not installed (--no-install): run ${packages.command}`, edits: [] };
5814
+ packages.command = undefined;
5815
+ }
5816
+ if (options.update)
5817
+ packages.command = undefined;
5188
5818
  const framing = { id: "framing", result: await framingStep(projectDir, undefined) };
5189
5819
  const framingAfterInstall = !options.update && framing.result.state === "skipped" && packages.command !== undefined;
5190
5820
  const leftovers = { id: "leftovers", result: await leftoversStep(root) };
5191
5821
  const build = { id: "build", result: { state: "skipped", message: "", edits: [] } };
5192
- const preview = previewSetupOf(callOptions(code, "conlocaCloud"), callOptions(code, "defineConfig"), astroSite === "computed" ? null : astroSite.base);
5193
- const sitesText = await readText2(sitesPath) ?? "";
5194
- const manifestPath = join13(projectDir, "package.json");
5195
- const manifestText = await readText2(manifestPath);
5196
5822
  const recorded = recordedCfPlan(manifestText);
5197
5823
  const wranglerRunner = listsWrangler(manifestText) ? commands.exec : "npx";
5198
5824
  let plan = preview.kind === "d3" ? options.cfPlan ?? recorded : undefined;
@@ -5212,7 +5838,7 @@ async function runConnect(path, options, io) {
5212
5838
  });
5213
5839
  const wranglerBefore = await readWranglerFile(projectDir);
5214
5840
  const deploy = { id: "preview", result: previewStep(wranglerBefore, null) };
5215
- const withPreview = preview.kind === "d3" || preview.kind === "d4";
5841
+ const withPreview = preview.kind !== "off";
5216
5842
  const deferD3 = preview.kind === "d3" && plan === undefined;
5217
5843
  if (deferD3) {
5218
5844
  deploy.result = { state: "done", message: "the preview settings wait for your Cloudflare plan", edits: [] };
@@ -5226,7 +5852,18 @@ async function runConnect(path, options, io) {
5226
5852
  edits: [...deploy.result.edits, planEdit]
5227
5853
  };
5228
5854
  }
5229
- const steps = options.update ? [project, deploy, build] : [project, packages, config, address, framing, ...withPreview ? [deploy] : [], build, leftovers];
5855
+ const steps = options.update ? [project, deploy, build] : [
5856
+ project,
5857
+ packages,
5858
+ config,
5859
+ ...adapter === null ? [] : [adapter],
5860
+ ...siteStep === null ? [] : [siteStep],
5861
+ address,
5862
+ framing,
5863
+ ...withPreview ? [deploy] : [],
5864
+ build,
5865
+ leftovers
5866
+ ];
5230
5867
  for (const step of steps) {
5231
5868
  for (const edit of step.result.edits)
5232
5869
  console.log(patchOf(edit, start));
@@ -5244,7 +5881,18 @@ async function runConnect(path, options, io) {
5244
5881
  }
5245
5882
  if (starter)
5246
5883
  await setup(projectDir, DEFAULT_SITE_NAME, { dataSchemas: false });
5247
- await writeEdits(steps.flatMap((step) => step === packages ? [] : step.result.edits.filter((edit) => edit !== planEdit)));
5884
+ await writeEdits(steps.flatMap((step) => step === packages || step === adapter ? [] : step.result.edits.filter((edit) => edit !== planEdit)));
5885
+ const uninstalled = (adapterPlan?.extra.length ?? 0) > 0 && (packages.result.state === "failed" || packages.result.state === "skipped");
5886
+ if (adapter !== null && uninstalled) {
5887
+ adapter.result = {
5888
+ state: "needs-you",
5889
+ message: `${adapter.result.message} (not written: the adapter package is not installed)`,
5890
+ edits: []
5891
+ };
5892
+ if (siteStep !== null)
5893
+ siteStep.result = { ...siteStep.result, state: "needs-you", replacement: [] };
5894
+ } else if (adapter !== null)
5895
+ await writeEdits(adapter.result.edits);
5248
5896
  if (plan !== undefined && planEdit !== null) {
5249
5897
  const fresh = cfPlanEdit(manifestPath, await readText2(manifestPath) ?? "", plan);
5250
5898
  if (fresh !== null)
@@ -5257,7 +5905,7 @@ async function runConnect(path, options, io) {
5257
5905
  continue;
5258
5906
  for (const edit of replacement)
5259
5907
  console.log(patchOf(edit, start));
5260
- if (await io.confirm(`Replace your value (${step.result.message})?`)) {
5908
+ if (await io.confirm(step.result.question ?? `Replace your value (${step.result.message})?`)) {
5261
5909
  await writeEdits(replacement);
5262
5910
  step.result = { state: "changed", message: `replaced: ${step.result.message}`, edits: replacement };
5263
5911
  }
@@ -5282,6 +5930,11 @@ async function runConnect(path, options, io) {
5282
5930
  step.result.message += ` (not written: ${why})`;
5283
5931
  }
5284
5932
  }
5933
+ if (siteStep?.result.state === "differs" && !(accepted && io.isTTY && !options.yes))
5934
+ siteStep.result.state = "needs-you";
5935
+ if ((adapterPlan?.extra.length ?? 0) > 0 && adapter?.result.state === "needs-you") {
5936
+ deploy.result = { state: "skipped", message: "the deploy step follows once the adapter is written", edits: [] };
5937
+ }
5285
5938
  const siteId = await siteIdOf(sitesPath);
5286
5939
  const blocked = options.update ? undefined : [packages, config].find((step) => !["done", "changed", "differs"].includes(step.result.state));
5287
5940
  if (!options.build)
@@ -5293,7 +5946,8 @@ async function runConnect(path, options, io) {
5293
5946
  else
5294
5947
  build.result = await buildStep(projectDir, siteId, `${commands.run} build`, io);
5295
5948
  const planEdits = planEdit === null ? [] : [planEdit];
5296
- if (preview.kind === "d3" && plan !== undefined && build.result.state === "done") {
5949
+ const routed = preview.kind === "d3" && plan !== undefined || preview.kind === "d8" && preview.adapter === "@astrojs/cloudflare";
5950
+ if (routed && build.result.state === "done") {
5297
5951
  const routes = await readWorkerFirstList(projectDir);
5298
5952
  const shared = plan === "free" ? sharedQuotaRoutes(routes, preview.prefix) : [];
5299
5953
  if (routes === null) {
@@ -5343,11 +5997,11 @@ async function runConnect(path, options, io) {
5343
5997
  }
5344
5998
  const report = {
5345
5999
  ok: steps.every((step) => step.result.state !== "failed" && step.result.state !== "needs-you"),
5346
- project: relative4(start, projectDir) || ".",
6000
+ project: relative5(start, projectDir) || ".",
5347
6001
  siteId,
5348
6002
  packageManager,
5349
6003
  steps: steps.map((step) => {
5350
- const files = step.result.edits.map((edit) => relative4(start, edit.path));
6004
+ const files = step.result.edits.map((edit) => relative5(start, edit.path));
5351
6005
  return {
5352
6006
  id: step.id,
5353
6007
  state: step.result.state,
@@ -5434,7 +6088,7 @@ async function ensureDataWiring(projectDir, options) {
5434
6088
  `));
5435
6089
  }
5436
6090
  await writeEdits(wiring.edits);
5437
- const files = wiring.edits.map((edit) => relative5(dir, edit.path));
6091
+ const files = wiring.edits.map((edit) => relative6(dir, edit.path));
5438
6092
  if (wiring.packages.length === 0)
5439
6093
  return { files };
5440
6094
  const up = await gitText(["rev-parse", "--show-cdup"], dir);
@@ -5449,18 +6103,18 @@ async function ensureDataWiring(projectDir, options) {
5449
6103
  return { files };
5450
6104
  }
5451
6105
  async function undeclaredDataWarning(projectDir, collection) {
5452
- const configFile = ASTRO_CONFIG_FILES.map((name) => join14(projectDir, name)).find((path) => existsSync6(path));
6106
+ const configFile = ASTRO_CONFIG_FILES.map((name) => join16(projectDir, name)).find((path) => existsSync7(path));
5453
6107
  if (configFile === undefined)
5454
6108
  return null;
5455
- const options = callOptions(stripComments(await readFile11(configFile, "utf8")), "conlocaCMS");
6109
+ const options = callOptions(stripComments(await readFile13(configFile, "utf8")), "conlocaCMS");
5456
6110
  const schemasPath = options.state === "literal" ? stringLiteral(options.entries.get("schemasPath") ?? "") : null;
5457
6111
  if (schemasPath === null)
5458
6112
  return null;
5459
6113
  const path = resolve7(projectDir, schemasPath);
5460
- const text = await readFile11(path, "utf8");
6114
+ const text = await readFile13(path, "utf8");
5461
6115
  if (text.includes(`${collection}:`))
5462
6116
  return null;
5463
- return `${relative5(projectDir, path)} declares no data collection "${collection}", so the build fails on this entry. ` + "Add a type for it and a defineHostSchema entry to dataSchemas.";
6117
+ return `${relative6(projectDir, path)} declares no data collection "${collection}", so the build fails on this entry. ` + "Add a type for it and a defineHostSchema entry to dataSchemas.";
5464
6118
  }
5465
6119
  async function dataCreate(collection, directory, options) {
5466
6120
  const { json } = options;
@@ -5476,7 +6130,7 @@ async function dataCreate(collection, directory, options) {
5476
6130
  title: options.title,
5477
6131
  data
5478
6132
  }));
5479
- const relPath = relative5(process.cwd(), written.filePath);
6133
+ const relPath = relative6(process.cwd(), written.filePath);
5480
6134
  const warning = await undeclaredDataWarning(projectDir, collection).catch(() => null);
5481
6135
  if (json) {
5482
6136
  console.log(JSON.stringify({
@@ -5513,7 +6167,7 @@ async function dataUpdate(collection, ref, directory, options) {
5513
6167
  title: options.title,
5514
6168
  data
5515
6169
  }));
5516
- const relPath = relative5(process.cwd(), written.filePath);
6170
+ const relPath = relative6(process.cwd(), written.filePath);
5517
6171
  if (json) {
5518
6172
  console.log(JSON.stringify({ ok: true, id: written.id, path: relPath }));
5519
6173
  } else {
@@ -5527,10 +6181,10 @@ async function dataUpdate(collection, ref, directory, options) {
5527
6181
 
5528
6182
  // src/commands/asset-add.ts
5529
6183
  async function readMediaOptions(projectDir, json) {
5530
- const configFile = ASTRO_CONFIG_FILES.map((name) => join15(projectDir, name)).find((path) => existsSync7(path));
6184
+ const configFile = ASTRO_CONFIG_FILES.map((name) => join17(projectDir, name)).find((path) => existsSync8(path));
5531
6185
  if (configFile === undefined)
5532
6186
  fail(json, `no astro.config in ${projectDir}`);
5533
- const text = await readFile12(configFile, "utf8");
6187
+ const text = await readFile14(configFile, "utf8");
5534
6188
  const options = callOptions(stripComments(text), "conlocaCMS");
5535
6189
  const assetsPath = options.state === "literal" ? stringLiteral(options.entries.get("assetsPath") ?? "") : null;
5536
6190
  if (assetsPath === null)
@@ -5547,7 +6201,7 @@ async function assetAdd(file, directory, options) {
5547
6201
  const { json } = options;
5548
6202
  try {
5549
6203
  const projectDir = resolve8(directory);
5550
- const bytes = await readFile12(file).catch((error) => {
6204
+ const bytes = await readFile14(file).catch((error) => {
5551
6205
  if (error.code === "ENOENT")
5552
6206
  fail(json, `no file ${file}`);
5553
6207
  throw error;
@@ -5565,7 +6219,7 @@ async function assetAdd(file, directory, options) {
5565
6219
  const { filename, folder = "/" } = uploaded.asset;
5566
6220
  const stored = folder === "/" ? filename : `${folder.slice(1)}/${filename}`;
5567
6221
  const ref = `${refBase}/${stored}`;
5568
- const path = relative6(process.cwd(), join15(assetsFolder, stored));
6222
+ const path = relative7(process.cwd(), join17(assetsFolder, stored));
5569
6223
  if (json) {
5570
6224
  console.log(JSON.stringify({
5571
6225
  ok: true,
@@ -5588,14 +6242,14 @@ async function assetAdd(file, directory, options) {
5588
6242
  }
5589
6243
 
5590
6244
  // src/commands/compare.ts
5591
- import { existsSync as existsSync9 } from "node:fs";
5592
- import { copyFile, mkdir as mkdir3, readdir as readdir4, readFile as readFile16, rm, stat, writeFile as writeFile4 } from "node:fs/promises";
5593
- import { dirname as dirname4, join as join20, parse as parse2, relative as relative9, resolve as resolve9, sep as sep5 } from "node:path";
6245
+ import { existsSync as existsSync10 } from "node:fs";
6246
+ import { copyFile, mkdir as mkdir3, readdir as readdir5, readFile as readFile18, rm, stat as stat2, writeFile as writeFile4 } from "node:fs/promises";
6247
+ import { dirname as dirname6, join as join22, parse as parse3, relative as relative10, resolve as resolve9, sep as sep6 } from "node:path";
5594
6248
  import { readSitesConfig as readSitesConfig2 } from "@conloca/content-api/node";
5595
6249
 
5596
6250
  // src/lib/page-compare.ts
5597
- import { readdir as readdir2, readFile as readFile13 } from "node:fs/promises";
5598
- import { basename as basename5, extname, join as join16, relative as relative7, sep as sep3 } from "node:path";
6251
+ import { readdir as readdir3, readFile as readFile15 } from "node:fs/promises";
6252
+ import { basename as basename5, extname, join as join18, relative as relative8, sep as sep4 } from "node:path";
5599
6253
  import { parseHTML } from "linkedom";
5600
6254
  var TEXT_EXTENSIONS = new Set([".html", ".htm", ".xml", ".json", ".txt", ".svg", ".webmanifest", ".css"]);
5601
6255
  var BUNDLE_RELS = new Set(["stylesheet", "modulepreload", "preload", "prefetch"]);
@@ -5681,8 +6335,8 @@ async function compareOutputs(input) {
5681
6335
  const kind = input.convertedRoutes.has(route) ? "converted" : "untouched";
5682
6336
  const result = { route, kind, differences: [], allowed: [] };
5683
6337
  const [old, now] = await Promise.all([
5684
- readFile13(join16(input.baselineDir, file)),
5685
- readFile13(join16(input.currentDir, current))
6338
+ readFile15(join18(input.baselineDir, file)),
6339
+ readFile15(join18(input.currentDir, current))
5686
6340
  ]);
5687
6341
  if (!TEXT_EXTENSIONS.has(extname(file))) {
5688
6342
  if (!old.equals(now))
@@ -5731,7 +6385,7 @@ async function compareUntouched(dirs, oldText, newText, result, html) {
5731
6385
  result.differences.push(message);
5732
6386
  }
5733
6387
  async function readStylesheet(dir, href) {
5734
- const text = await readFile13(join16(dir, href.replace(/[?#].*$/, "")), "utf-8").catch(() => null);
6388
+ const text = await readFile15(join18(dir, href.replace(/[?#].*$/, "")), "utf-8").catch(() => null);
5735
6389
  return text === null ? null : normalizeOutput(text);
5736
6390
  }
5737
6391
  function withoutIslandProps(html) {
@@ -5777,12 +6431,12 @@ function without(list, other) {
5777
6431
  });
5778
6432
  }
5779
6433
  async function routeFiles(dir) {
5780
- const entries = await readdir2(dir, { recursive: true, withFileTypes: true });
6434
+ const entries = await readdir3(dir, { recursive: true, withFileTypes: true });
5781
6435
  const files = new Map;
5782
6436
  for (const entry of entries) {
5783
6437
  if (!entry.isFile())
5784
6438
  continue;
5785
- const file = relative7(dir, join16(entry.parentPath, entry.name)).split(sep3).join("/");
6439
+ const file = relative8(dir, join18(entry.parentPath, entry.name)).split(sep4).join("/");
5786
6440
  if (isComparedOutputFile(file))
5787
6441
  files.set(routeOfOutputFile(file), file);
5788
6442
  }
@@ -5790,7 +6444,7 @@ async function routeFiles(dir) {
5790
6444
  }
5791
6445
 
5792
6446
  // src/lib/site-routes.ts
5793
- import { join as join17 } from "node:path";
6447
+ import { join as join19 } from "node:path";
5794
6448
  import { ContentIndex, FileSystemReaderBackend } from "@conloca/content-api/node";
5795
6449
  var CONTENT_GLOB = "{**/*.{vxjson,mdx},data/**/*.json}";
5796
6450
  function pagesOf(index, contentRoot, sites) {
@@ -5807,7 +6461,7 @@ function pagesOf(index, contentRoot, sites) {
5807
6461
  defaultLocale: locale === sites.sites[site]?.defaultLocale,
5808
6462
  pathname: version.pathname,
5809
6463
  type: manifest.type,
5810
- file: join17(contentRoot, version.sourcePath ?? "")
6464
+ file: join19(contentRoot, version.sourcePath ?? "")
5811
6465
  });
5812
6466
  }
5813
6467
  }
@@ -5823,7 +6477,7 @@ async function readConlocaPages(contentRoot, sites) {
5823
6477
  async function readFileRoutes(projectDir, config, sites, site) {
5824
6478
  const { collectStaticPageRoutes, nonDefaultLocalesOf } = await import("@conloca/astro-cms/checks");
5825
6479
  const routes = await collectStaticPageRoutes({
5826
- pagesDir: join17(projectDir, "src", "pages"),
6480
+ pagesDir: join19(projectDir, "src", "pages"),
5827
6481
  serverOutput: config.serverOutput,
5828
6482
  nonDefaultLocales: nonDefaultLocalesOf(sites, site, config.i18n)
5829
6483
  });
@@ -5844,9 +6498,9 @@ function siteRoutes(fileRoutes, pages, site) {
5844
6498
  }
5845
6499
 
5846
6500
  // src/commands/doctor-astro.ts
5847
- import { existsSync as existsSync8 } from "node:fs";
5848
- import { readdir as readdir3, readFile as readFile15 } from "node:fs/promises";
5849
- import { join as join19, relative as relative8, sep as sep4 } from "node:path";
6501
+ import { existsSync as existsSync9 } from "node:fs";
6502
+ import { readdir as readdir4, readFile as readFile17 } from "node:fs/promises";
6503
+ import { join as join21, relative as relative9, sep as sep5 } from "node:path";
5850
6504
 
5851
6505
  // src/lib/page-components.ts
5852
6506
  import { isSlotContent } from "@conloca/astro-cms/checks";
@@ -5908,12 +6562,12 @@ function componentFindings(puckData, manifest) {
5908
6562
  }
5909
6563
 
5910
6564
  // src/lib/project-dependencies.ts
5911
- import { readFile as readFile14 } from "node:fs/promises";
5912
- import { join as join18 } from "node:path";
6565
+ import { readFile as readFile16 } from "node:fs/promises";
6566
+ import { join as join20 } from "node:path";
5913
6567
  async function readProjectDependencies(projectDir) {
5914
6568
  let raw;
5915
6569
  try {
5916
- raw = await readFile14(join18(projectDir, "package.json"), "utf-8");
6570
+ raw = await readFile16(join20(projectDir, "package.json"), "utf-8");
5917
6571
  } catch {
5918
6572
  return "missing";
5919
6573
  }
@@ -5938,7 +6592,7 @@ async function readProjectDependencies(projectDir) {
5938
6592
 
5939
6593
  // src/commands/doctor-astro.ts
5940
6594
  function findAstroConfig(projectDir) {
5941
- return ASTRO_CONFIG_FILES.map((name) => join19(projectDir, name)).find((path) => existsSync8(path));
6595
+ return ASTRO_CONFIG_FILES.map((name) => join21(projectDir, name)).find((path) => existsSync9(path));
5942
6596
  }
5943
6597
  function astroOutputOf(configText) {
5944
6598
  const keyMatch = /\boutput\s*:/.exec(configText);
@@ -6065,7 +6719,7 @@ async function checkContentConfig(projectDir) {
6065
6719
  level: "error",
6066
6720
  message: `no content config found — without it every CMS page 404s; create src/content.config.ts:
6067
6721
  ${CONTENT_CONFIG_SNIPPET}`,
6068
- path: join19(projectDir, "src", "content.config.ts")
6722
+ path: join21(projectDir, "src", "content.config.ts")
6069
6723
  });
6070
6724
  } else if (problem === "not-wired") {
6071
6725
  outcome.problems.push({
@@ -6232,7 +6886,7 @@ function checkReactIntegration(projectDir, configText, pkg) {
6232
6886
  outcome.problems.push({
6233
6887
  check: "C7",
6234
6888
  level: "error",
6235
- message: `@astrojs/react is not declared — no package.json found at ${join19(projectDir, "package.json")}; add @astrojs/react to the project's dependencies`
6889
+ message: `@astrojs/react is not declared — no package.json found at ${join21(projectDir, "package.json")}; add @astrojs/react to the project's dependencies`
6236
6890
  });
6237
6891
  } else if (pkg === "unreadable") {
6238
6892
  outcome.problems.push({
@@ -6315,10 +6969,10 @@ function checkPeers(pkg) {
6315
6969
  }
6316
6970
  async function checkTsconfigJsx(projectDir) {
6317
6971
  const outcome = outcomeOf("C9");
6318
- const path = join19(projectDir, "tsconfig.json");
6972
+ const path = join21(projectDir, "tsconfig.json");
6319
6973
  let raw;
6320
6974
  try {
6321
- raw = await readFile15(path, "utf-8");
6975
+ raw = await readFile17(path, "utf-8");
6322
6976
  } catch {
6323
6977
  outcome.problems.push({
6324
6978
  check: "C9",
@@ -6367,11 +7021,11 @@ async function checkPrerender(projectDir, configText) {
6367
7021
  outcome.skipped = "output is not 'server'";
6368
7022
  return outcome;
6369
7023
  }
6370
- const pagesDir = join19(projectDir, "src", "pages");
6371
- const names = await readdir3(pagesDir, { recursive: true }).catch(() => []);
7024
+ const pagesDir = join21(projectDir, "src", "pages");
7025
+ const names = await readdir4(pagesDir, { recursive: true }).catch(() => []);
6372
7026
  for (const name of names.filter((entry) => PAGE_FILE_RE.test(entry)).sort()) {
6373
- const filePath = join19(pagesDir, name);
6374
- const text = await readFile15(filePath, "utf-8").catch(() => null);
7027
+ const filePath = join21(pagesDir, name);
7028
+ const text = await readFile17(filePath, "utf-8").catch(() => null);
6375
7029
  if (text === null) {
6376
7030
  outcome.problems.push({
6377
7031
  check: "C10",
@@ -6407,7 +7061,7 @@ function checkHiddenPages(projectDir, options, fileRoutes, pages, site) {
6407
7061
  check: "C11",
6408
7062
  level: "warn",
6409
7063
  message: `${file} hides the Conloca page ${route} (${pageId}) — a src/pages file always wins over a Conloca page at the same path; delete the file in the same change that makes the Conloca page live`,
6410
- path: join19(projectDir, file)
7064
+ path: join21(projectDir, file)
6411
7065
  });
6412
7066
  }
6413
7067
  return outcome;
@@ -6430,7 +7084,7 @@ function checkHasPages(fileRoutes, pages) {
6430
7084
  return outcome;
6431
7085
  }
6432
7086
  async function readPuckData(file) {
6433
- const text = await readFile15(file, "utf-8").catch(() => null);
7087
+ const text = await readFile17(file, "utf-8").catch(() => null);
6434
7088
  if (text === null)
6435
7089
  return;
6436
7090
  try {
@@ -6463,7 +7117,7 @@ async function checkPageComponents(projectDir, options, pages) {
6463
7117
  }
6464
7118
  const contentRoot = contentRootOf(projectDir);
6465
7119
  for (const { page, puckData } of filled) {
6466
- const file = relative8(contentRoot, page.file).split(sep4).join("/");
7120
+ const file = relative9(contentRoot, page.file).split(sep5).join("/");
6467
7121
  for (const { component, field } of componentFindings(puckData, manifest)) {
6468
7122
  const fields = Object.keys(manifest.components[component]?.fields ?? {}).join(", ") || "none";
6469
7123
  outcome.problems.push({
@@ -6491,7 +7145,7 @@ async function checkSiteStyles(projectDir, cms, conlocaCloud, pages) {
6491
7145
  }
6492
7146
  if (pages.length === 0)
6493
7147
  return outcome;
6494
- const names = await readdir3(join19(projectDir, "src"), { recursive: true }).catch((error) => error.code === "ENOENT" ? [] : `src/ could not be read (${error.code ?? error.message})`);
7148
+ const names = await readdir4(join21(projectDir, "src"), { recursive: true }).catch((error) => error.code === "ENOENT" ? [] : `src/ could not be read (${error.code ?? error.message})`);
6495
7149
  if (typeof names === "string") {
6496
7150
  outcome.skipped = names;
6497
7151
  return outcome;
@@ -6499,7 +7153,7 @@ async function checkSiteStyles(projectDir, cms, conlocaCloud, pages) {
6499
7153
  const stylesheets = names.filter((name) => STYLESHEET_RE.test(name));
6500
7154
  if (stylesheets.length === 0)
6501
7155
  return outcome;
6502
- const first = stylesheets.reduce((a, b) => b < a ? b : a).split(sep4).join("/");
7156
+ const first = stylesheets.reduce((a, b) => b < a ? b : a).split(sep5).join("/");
6503
7157
  outcome.problems.push({
6504
7158
  check: "C15",
6505
7159
  level: "warn",
@@ -6517,7 +7171,7 @@ async function runAstroChecks(projectDir, sites, pages) {
6517
7171
  skipped: "no astro.config found"
6518
7172
  }));
6519
7173
  }
6520
- const source = await readFile15(configPath, "utf-8").catch(() => null);
7174
+ const source = await readFile17(configPath, "utf-8").catch(() => null);
6521
7175
  if (source === null) {
6522
7176
  const problem = {
6523
7177
  check: "C5",
@@ -6557,8 +7211,8 @@ function isBaseline(value) {
6557
7211
  return typeof value === "object" && value !== null && !Array.isArray(value) && isStringArray(value.chosenRoutes) && isStringArray(value.conlocaRoutes) && isStringArray(value.hiddenRoutes);
6558
7212
  }
6559
7213
  async function filesUnder(dir) {
6560
- const entries = await readdir4(dir, { recursive: true, withFileTypes: true }).catch(() => []);
6561
- return entries.filter((entry) => entry.isFile()).map((entry) => relative9(dir, join20(entry.parentPath, entry.name)).split(sep5).join("/"));
7214
+ const entries = await readdir5(dir, { recursive: true, withFileTypes: true }).catch(() => []);
7215
+ return entries.filter((entry) => entry.isFile()).map((entry) => relative10(dir, join22(entry.parentPath, entry.name)).split(sep6).join("/"));
6562
7216
  }
6563
7217
  async function compare(directory, options) {
6564
7218
  const { json } = options;
@@ -6566,7 +7220,7 @@ async function compare(directory, options) {
6566
7220
  const configPath = findAstroConfig(projectDir);
6567
7221
  if (configPath === undefined)
6568
7222
  fail(json, `no astro.config found in ${projectDir} — run it in the Astro project`);
6569
- const source = await readFile16(configPath, "utf-8").catch(() => null);
7223
+ const source = await readFile18(configPath, "utf-8").catch(() => null);
6570
7224
  if (source === null)
6571
7225
  fail(json, `could not read ${configPath} — check its file permissions`);
6572
7226
  const configText = stripComments(source);
@@ -6574,12 +7228,12 @@ async function compare(directory, options) {
6574
7228
  const notRoute = chosen?.find((route) => !route.startsWith("/"));
6575
7229
  if (notRoute !== undefined)
6576
7230
  fail(json, `--routes takes routes starting with /, separated by commas; got ${notRoute}`);
6577
- const baselineRoot = join20(projectDir, "node_modules", ".cache", "conloca-compare");
6578
- const baselinePath = join20(baselineRoot, "baseline.json");
6579
- const outputRoot = join20(baselineRoot, "output");
7231
+ const baselineRoot = join22(projectDir, "node_modules", ".cache", "conloca-compare");
7232
+ const baselinePath = join22(baselineRoot, "baseline.json");
7233
+ const outputRoot = join22(baselineRoot, "output");
6580
7234
  if (options.reset)
6581
7235
  await rm(baselineRoot, { recursive: true, force: true });
6582
- const baselineText = await readFile16(baselinePath, "utf-8").catch(() => null);
7236
+ const baselineText = await readFile18(baselinePath, "utf-8").catch(() => null);
6583
7237
  let baseline = null;
6584
7238
  if (baselineText !== null) {
6585
7239
  let parsed = null;
@@ -6599,16 +7253,16 @@ async function compare(directory, options) {
6599
7253
  if (site === undefined)
6600
7254
  fail(json, "no sites are configured in sites.json", "site");
6601
7255
  const startedAt = Date.now();
6602
- const packageManager = lockfileInstall(projectDir, parse2(projectDir).root)?.packageManager ?? "npm";
7256
+ const packageManager = lockfileInstall(projectDir, parse3(projectDir).root)?.packageManager ?? "npm";
6603
7257
  const buildCommand = `${packageManagerCommands(packageManager).run} build`;
6604
7258
  if (!await terminalIo(json).run(buildCommand, projectDir)) {
6605
7259
  fail(json, `${buildCommand} failed; fix the build, then run conloca compare again`);
6606
7260
  }
6607
- const serverLayout = existsSync9(join20(projectDir, "dist", "server")) && existsSync9(join20(projectDir, "dist", "client"));
7261
+ const serverLayout = existsSync10(join22(projectDir, "dist", "server")) && existsSync10(join22(projectDir, "dist", "client"));
6608
7262
  const outName = serverLayout ? "dist/client" : "dist";
6609
- const outDir = join20(projectDir, outName);
7263
+ const outDir = join22(projectDir, outName);
6610
7264
  const outFiles = await filesUnder(outDir);
6611
- const htmlTimes = await Promise.all(outFiles.filter((file) => file.endsWith(".html")).map(async (file) => (await stat(join20(outDir, file))).mtimeMs));
7265
+ const htmlTimes = await Promise.all(outFiles.filter((file) => file.endsWith(".html")).map(async (file) => (await stat2(join22(outDir, file))).mtimeMs));
6612
7266
  if (!htmlTimes.some((time) => time >= startedAt)) {
6613
7267
  fail(json, "the build wrote no fresh HTML to dist or dist/client; conloca compare reads only those folders");
6614
7268
  }
@@ -6621,8 +7275,8 @@ async function compare(directory, options) {
6621
7275
  const saved = outFiles.filter((file) => isComparedOutputFile(file) || file.startsWith("_astro/") && file.endsWith(".css"));
6622
7276
  await rm(baselineRoot, { recursive: true, force: true });
6623
7277
  await Promise.all(saved.map(async (file) => {
6624
- await mkdir3(dirname4(join20(outputRoot, file)), { recursive: true });
6625
- await copyFile(join20(outDir, file), join20(outputRoot, file));
7278
+ await mkdir3(dirname6(join22(outputRoot, file)), { recursive: true });
7279
+ await copyFile(join22(outDir, file), join22(outputRoot, file));
6626
7280
  }));
6627
7281
  const chosenRoutes = chosen ?? [];
6628
7282
  const hiddenRoutes = hiddenNow.map((route) => route.route);
@@ -6684,7 +7338,7 @@ async function compare(directory, options) {
6684
7338
  }
6685
7339
 
6686
7340
  // src/commands/components.ts
6687
- import { readFile as readFile17 } from "node:fs/promises";
7341
+ import { readFile as readFile19 } from "node:fs/promises";
6688
7342
  import { resolve as resolve10 } from "node:path";
6689
7343
  async function components(directory, options) {
6690
7344
  const { json } = options;
@@ -6692,7 +7346,7 @@ async function components(directory, options) {
6692
7346
  const configPath = findAstroConfig(projectDir);
6693
7347
  if (configPath === undefined)
6694
7348
  fail(json, `no astro.config found in ${projectDir} — run it in the Astro project`);
6695
- const source = await readFile17(configPath, "utf-8").catch(() => null);
7349
+ const source = await readFile19(configPath, "utf-8").catch(() => null);
6696
7350
  if (source === null)
6697
7351
  fail(json, `could not read ${configPath} — check its file permissions`);
6698
7352
  const result = await readSiteComponents(projectDir, callOptions(stripComments(source), "conlocaCMS"));
@@ -6717,23 +7371,23 @@ async function components(directory, options) {
6717
7371
 
6718
7372
  // src/commands/create.ts
6719
7373
  import { execFile as execFileCallback4, spawn as spawn2 } from "node:child_process";
6720
- import { mkdir as mkdir4, readdir as readdir6, writeFile as writeFile5 } from "node:fs/promises";
6721
- import { dirname as dirname6, join as join23, relative as relative10, resolve as resolve13 } from "node:path";
7374
+ import { mkdir as mkdir4, readdir as readdir7, writeFile as writeFile5 } from "node:fs/promises";
7375
+ import { dirname as dirname8, join as join25, relative as relative11, resolve as resolve13 } from "node:path";
6722
7376
  import { promisify as promisify4 } from "node:util";
6723
7377
 
6724
7378
  // src/commands/doctor.ts
6725
7379
  import { execFile as execFileCallback3 } from "node:child_process";
6726
- import { readdir as readdir5, readFile as readFile19, stat as stat2 } from "node:fs/promises";
6727
- import { join as join22, resolve as resolve12 } from "node:path";
7380
+ import { readdir as readdir6, readFile as readFile21, stat as stat3 } from "node:fs/promises";
7381
+ import { join as join24, resolve as resolve12 } from "node:path";
6728
7382
  import { promisify as promisify3 } from "node:util";
6729
7383
  import { invalidLocaleMessage, isContentLocale } from "@conloca/content-api/content-path";
6730
7384
  import { ContentIndex as ContentIndex2, FileSystemReaderBackend as FileSystemReaderBackend2 } from "@conloca/content-api/node";
6731
7385
 
6732
7386
  // src/commands/doctor-extensions.ts
6733
- import { existsSync as existsSync10 } from "node:fs";
6734
- import { readFile as readFile18 } from "node:fs/promises";
7387
+ import { existsSync as existsSync11 } from "node:fs";
7388
+ import { readFile as readFile20 } from "node:fs/promises";
6735
7389
  import { createRequire as createRequire2 } from "node:module";
6736
- import { dirname as dirname5, join as join21, resolve as resolve11 } from "node:path";
7390
+ import { dirname as dirname7, join as join23, resolve as resolve11 } from "node:path";
6737
7391
  import { pathToFileURL as pathToFileURL3 } from "node:url";
6738
7392
  var DOCTOR_CONTRACT_VERSION = 1;
6739
7393
  var SEAM_CHECK_ID = "EXT";
@@ -6753,10 +7407,10 @@ function resolveManifestPath(require2, projectDir, name) {
6753
7407
  } catch {
6754
7408
  let dir = projectDir;
6755
7409
  for (;; ) {
6756
- const candidate = join21(dir, "node_modules", name, "package.json");
6757
- if (existsSync10(candidate))
7410
+ const candidate = join23(dir, "node_modules", name, "package.json");
7411
+ if (existsSync11(candidate))
6758
7412
  return candidate;
6759
- const parent = dirname5(dir);
7413
+ const parent = dirname7(dir);
6760
7414
  if (parent === dir)
6761
7415
  return null;
6762
7416
  dir = parent;
@@ -6767,7 +7421,7 @@ async function discoverExtensions(projectDir) {
6767
7421
  const pkg = await readProjectDependencies(projectDir);
6768
7422
  if (pkg === "missing" || pkg === "unreadable")
6769
7423
  return [];
6770
- const require2 = createRequire2(join21(projectDir, "package.json"));
7424
+ const require2 = createRequire2(join23(projectDir, "package.json"));
6771
7425
  const manifests = [];
6772
7426
  for (const name of [...pkg.deps].sort()) {
6773
7427
  const manifestPath = resolveManifestPath(require2, projectDir, name);
@@ -6775,14 +7429,14 @@ async function discoverExtensions(projectDir) {
6775
7429
  continue;
6776
7430
  let manifest;
6777
7431
  try {
6778
- manifest = JSON.parse(await readFile18(manifestPath, "utf-8"));
7432
+ manifest = JSON.parse(await readFile20(manifestPath, "utf-8"));
6779
7433
  } catch {
6780
7434
  continue;
6781
7435
  }
6782
7436
  const entry = isRecord(manifest) && isRecord(manifest.conloca) ? manifest.conloca.doctor : undefined;
6783
7437
  if (typeof entry !== "string" || entry === "")
6784
7438
  continue;
6785
- manifests.push({ name, dir: dirname5(manifestPath), entry });
7439
+ manifests.push({ name, dir: dirname7(manifestPath), entry });
6786
7440
  }
6787
7441
  return manifests;
6788
7442
  }
@@ -6853,12 +7507,12 @@ function counted(count, noun) {
6853
7507
  return count === 1 ? `1 ${noun}` : `${count} ${noun}s`;
6854
7508
  }
6855
7509
  async function checkSitesFile(contentRoot) {
6856
- const path = join22(contentRoot, "sites.json");
7510
+ const path = join24(contentRoot, "sites.json");
6857
7511
  const problems = [];
6858
7512
  const outcome = { id: "C3", label: "sites.json is present and complete", problems };
6859
7513
  let raw;
6860
7514
  try {
6861
- raw = await readFile19(path, "utf-8");
7515
+ raw = await readFile21(path, "utf-8");
6862
7516
  } catch {
6863
7517
  problems.push({
6864
7518
  check: "C3",
@@ -6934,8 +7588,8 @@ async function checkSiteDirs(contentRoot, config) {
6934
7588
  return outcome;
6935
7589
  }
6936
7590
  for (const site of Object.keys(config.sites)) {
6937
- const pagesPath = join22(contentRoot, site, "pages");
6938
- const stats = await stat2(pagesPath).catch(() => null);
7591
+ const pagesPath = join24(contentRoot, site, "pages");
7592
+ const stats = await stat3(pagesPath).catch(() => null);
6939
7593
  if (!stats?.isDirectory()) {
6940
7594
  problems.push({
6941
7595
  check: "C4",
@@ -6945,7 +7599,7 @@ async function checkSiteDirs(contentRoot, config) {
6945
7599
  });
6946
7600
  }
6947
7601
  }
6948
- const entries = await readdir5(contentRoot, { withFileTypes: true }).catch(() => []);
7602
+ const entries = await readdir6(contentRoot, { withFileTypes: true }).catch(() => []);
6949
7603
  for (const entry of entries) {
6950
7604
  if (!entry.isDirectory() || RESERVED_CONTENT_DIRS.has(entry.name) || Object.hasOwn(config.sites, entry.name))
6951
7605
  continue;
@@ -6953,7 +7607,7 @@ async function checkSiteDirs(contentRoot, config) {
6953
7607
  check: "C4",
6954
7608
  level: "warn",
6955
7609
  message: `directory "${entry.name}" has no sites.json entry — any pages inside are invisible to the CMS`,
6956
- path: join22(contentRoot, entry.name)
7610
+ path: join24(contentRoot, entry.name)
6957
7611
  });
6958
7612
  }
6959
7613
  return outcome;
@@ -6973,7 +7627,7 @@ async function checkContentIndex(contentRoot, config) {
6973
7627
  check: "C12",
6974
7628
  level: "error",
6975
7629
  message: `${message} (${reason})`,
6976
- path: join22(contentRoot, path)
7630
+ path: join24(contentRoot, path)
6977
7631
  });
6978
7632
  }
6979
7633
  });
@@ -7074,7 +7728,7 @@ async function doctor(directory, options) {
7074
7728
  var execFile4 = promisify4(execFileCallback4);
7075
7729
  var SITE_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
7076
7730
  async function assertEmptyDirectory(directory) {
7077
- const entries = await readdir6(directory).catch((error) => {
7731
+ const entries = await readdir7(directory).catch((error) => {
7078
7732
  if (error.code === "ENOENT")
7079
7733
  return [];
7080
7734
  throw error;
@@ -7095,8 +7749,8 @@ async function writeTemplate(directory, name, pm, siteName) {
7095
7749
  [".github/workflows/conloca.yml", renderWorkflow(pm)]
7096
7750
  ];
7097
7751
  for (const [file, content] of files) {
7098
- const path = join23(directory, file);
7099
- await mkdir4(dirname6(path), { recursive: true });
7752
+ const path = join25(directory, file);
7753
+ await mkdir4(dirname8(path), { recursive: true });
7100
7754
  await writeFile5(path, content, "utf-8");
7101
7755
  }
7102
7756
  return files.map(([file]) => file);
@@ -7126,7 +7780,7 @@ async function writeHomePage(directory, contentRoot, siteName, name) {
7126
7780
  zones: {}
7127
7781
  }
7128
7782
  });
7129
- return relative10(directory, written.filePath);
7783
+ return relative11(directory, written.filePath);
7130
7784
  }
7131
7785
  function runInstall(pm, directory, quiet) {
7132
7786
  const [command, ...args] = packageManagerCommands(pm).install.split(" ");
@@ -7153,7 +7807,7 @@ async function buildProject(directory, name, pm, options) {
7153
7807
  const { json } = options;
7154
7808
  await assertEmptyDirectory(directory);
7155
7809
  await mkdir4(directory, { recursive: true });
7156
- const contentRoot = join23(directory, "content");
7810
+ const contentRoot = join25(directory, "content");
7157
7811
  const created = await withStdoutRedirected(json, async () => {
7158
7812
  const files = await writeTemplate(directory, name, pm, options.site);
7159
7813
  files.push(...await setup(directory, options.site));
@@ -7184,7 +7838,7 @@ Created ${name} in ${result.directory} (${result.created.length} files)`);
7184
7838
  const commands = packageManagerCommands(result.packageManager);
7185
7839
  console.log(`
7186
7840
  Next:`);
7187
- const step = relative10(process.cwd(), result.directory) || ".";
7841
+ const step = relative11(process.cwd(), result.directory) || ".";
7188
7842
  const target = step.startsWith("..") ? result.directory : step;
7189
7843
  console.log(` cd ${/\s/.test(target) ? `'${target}'` : target}`);
7190
7844
  if (result.install !== "done")
@@ -7231,11 +7885,11 @@ async function create(target, options) {
7231
7885
 
7232
7886
  // src/commands/init.ts
7233
7887
  import { mkdir as mkdir5 } from "node:fs/promises";
7234
- import { join as join24 } from "node:path";
7888
+ import { join as join26 } from "node:path";
7235
7889
  async function init(directory, siteName) {
7236
7890
  const contentPath = contentRootOf(directory);
7237
7891
  try {
7238
- const contentDirs = [contentPath, join24(contentPath, siteName, "pages"), join24(contentPath, "fragments", "shared")];
7892
+ const contentDirs = [contentPath, join26(contentPath, siteName, "pages"), join26(contentPath, "fragments", "shared")];
7239
7893
  for (const dir of contentDirs) {
7240
7894
  await mkdir5(dir, { recursive: true });
7241
7895
  console.log(` Created: ${dir}`);
@@ -7253,7 +7907,7 @@ async function init(directory, siteName) {
7253
7907
  ✓ Initialized Conloca content structure for site '${siteName}' in ${contentPath}`);
7254
7908
  console.log(`
7255
7909
  Next steps:`);
7256
- console.log(` 1. Create your first page in ${join24(contentPath, siteName, "pages")}`);
7910
+ console.log(` 1. Create your first page in ${join26(contentPath, siteName, "pages")}`);
7257
7911
  console.log(` 2. Run 'conloca doctor' to check the setup`);
7258
7912
  console.log(` 3. Point the conlocaCMS() contentRoot option at ${contentPath}`);
7259
7913
  } catch (error) {
@@ -7264,8 +7918,8 @@ Next steps:`);
7264
7918
  }
7265
7919
 
7266
7920
  // src/commands/page-create.ts
7267
- import { readFile as readFile20 } from "node:fs/promises";
7268
- import { relative as relative11, resolve as resolve14 } from "node:path";
7921
+ import { readFile as readFile22 } from "node:fs/promises";
7922
+ import { relative as relative12, resolve as resolve14 } from "node:path";
7269
7923
  function metaFlagsOf(options) {
7270
7924
  if (options.canonical && !URL.canParse(options.canonical.trim())) {
7271
7925
  throw new PageWriteError("invalid_input", "--canonical must be an absolute URL", "--canonical");
@@ -7299,11 +7953,11 @@ function toCliMessage(error, directory, options) {
7299
7953
  async function undeclaredCollectionWarning(directory, collection) {
7300
7954
  const { findContentConfig } = await import("@conloca/astro-cms/checks");
7301
7955
  const configPath = findContentConfig(resolve14(directory));
7302
- const text = configPath === null ? null : await readFile20(configPath, "utf-8").catch(() => null);
7956
+ const text = configPath === null ? null : await readFile22(configPath, "utf-8").catch(() => null);
7303
7957
  const declared = text === null ? null : declaredPageCollections(text);
7304
7958
  if (configPath === null || declared === null || declared.has(collection))
7305
7959
  return null;
7306
- return `${relative11(process.cwd(), configPath)} declares no page collection "${collection}", so the build fails on this page. Declare it with conlocaPages({ collection: '${collection}' }) and give it a route in conlocaCMS({ routing }).`;
7960
+ return `${relative12(process.cwd(), configPath)} declares no page collection "${collection}", so the build fails on this page. Declare it with conlocaPages({ collection: '${collection}' }) and give it a route in conlocaCMS({ routing }).`;
7307
7961
  }
7308
7962
  async function pageCreate(directory, options) {
7309
7963
  try {
@@ -7333,7 +7987,7 @@ async function createPage(directory, options) {
7333
7987
  }
7334
7988
  throw error;
7335
7989
  }
7336
- const relPath = relative11(process.cwd(), written.filePath);
7990
+ const relPath = relative12(process.cwd(), written.filePath);
7337
7991
  const warning = await undeclaredCollectionWarning(directory, options.collection).catch(() => null);
7338
7992
  if (json) {
7339
7993
  console.log(JSON.stringify({ ok: true, id: written.id, path: relPath, ...warning ? { warnings: [warning] } : {} }));
@@ -7347,7 +8001,7 @@ async function createPage(directory, options) {
7347
8001
  }
7348
8002
 
7349
8003
  // src/commands/page-update.ts
7350
- import { relative as relative12 } from "node:path";
8004
+ import { relative as relative13 } from "node:path";
7351
8005
  async function pageUpdate(ref, directory, options) {
7352
8006
  const { json } = options;
7353
8007
  try {
@@ -7360,7 +8014,7 @@ async function pageUpdate(ref, directory, options) {
7360
8014
  puckData,
7361
8015
  meta: metaFlagsOf(options)
7362
8016
  }));
7363
- const relPath = relative12(process.cwd(), written.filePath);
8017
+ const relPath = relative13(process.cwd(), written.filePath);
7364
8018
  if (json) {
7365
8019
  console.log(JSON.stringify({ ok: true, id: written.id, path: relPath }));
7366
8020
  } else {
@@ -7373,7 +8027,7 @@ async function pageUpdate(ref, directory, options) {
7373
8027
  }
7374
8028
 
7375
8029
  // src/commands/routes.ts
7376
- import { readFile as readFile21 } from "node:fs/promises";
8030
+ import { readFile as readFile23 } from "node:fs/promises";
7377
8031
  import { resolve as resolve15 } from "node:path";
7378
8032
  import { readSitesConfig as readSitesConfig3 } from "@conloca/content-api/node";
7379
8033
  async function routes(directory, options) {
@@ -7382,7 +8036,7 @@ async function routes(directory, options) {
7382
8036
  const configPath = findAstroConfig(projectDir);
7383
8037
  if (configPath === undefined)
7384
8038
  fail(json, `no astro.config found in ${projectDir} — run it in the Astro project`);
7385
- const source = await readFile21(configPath, "utf-8").catch(() => null);
8039
+ const source = await readFile23(configPath, "utf-8").catch(() => null);
7386
8040
  if (source === null)
7387
8041
  fail(json, `could not read ${configPath} — check its file permissions`);
7388
8042
  const configText = stripComments(source);
@@ -7410,14 +8064,14 @@ async function routes(directory, options) {
7410
8064
  }
7411
8065
 
7412
8066
  // src/commands/upgrade.ts
7413
- import { existsSync as existsSync12 } from "node:fs";
7414
- import { readFile as readFile24, rm as rm2, rmdir, writeFile as writeFile6 } from "node:fs/promises";
7415
- import { basename as basename6, dirname as dirname8, join as join27, relative as relative15, resolve as resolve16 } from "node:path";
8067
+ import { existsSync as existsSync13 } from "node:fs";
8068
+ import { readFile as readFile26, rm as rm2, rmdir, writeFile as writeFile6 } from "node:fs/promises";
8069
+ import { basename as basename6, dirname as dirname10, join as join29, relative as relative16, resolve as resolve17 } from "node:path";
7416
8070
 
7417
8071
  // src/lib/migrations.ts
7418
- import { existsSync as existsSync11 } from "node:fs";
7419
- import { readFile as readFile22 } from "node:fs/promises";
7420
- import { join as join25, relative as relative13 } from "node:path";
8072
+ import { existsSync as existsSync12 } from "node:fs";
8073
+ import { readdir as readdir8, readFile as readFile24 } from "node:fs/promises";
8074
+ import { join as join27, relative as relative14, resolve as resolve16 } from "node:path";
7421
8075
  var SEVERITY = ["done", "changed", "needs-you", "failed"];
7422
8076
  function removedNames(source) {
7423
8077
  const passed = removedKeyOptions(source);
@@ -7427,10 +8081,10 @@ function removedNames(source) {
7427
8081
  return [...REMOVED_OPTIONS].filter((name) => name !== "fragmentPreviewRoute" && new RegExp(`\\b${name}\\b`).test(code));
7428
8082
  }
7429
8083
  async function removedOptionsStep(projectDir, repoRoot) {
7430
- const path = ASTRO_CONFIG_FILES.map((name) => join25(projectDir, name)).find((file) => existsSync11(file));
8084
+ const path = ASTRO_CONFIG_FILES.map((name) => join27(projectDir, name)).find((file) => existsSync12(file));
7431
8085
  if (path === undefined)
7432
8086
  return null;
7433
- const text = await readFile22(path, "utf8");
8087
+ const text = await readFile24(path, "utf8");
7434
8088
  const names = removedNames(text);
7435
8089
  if (names.length === 0)
7436
8090
  return null;
@@ -7438,7 +8092,7 @@ async function removedOptionsStep(projectDir, repoRoot) {
7438
8092
  if (wired.edits.some((edit) => removedNames(edit.after).length === 0)) {
7439
8093
  return { state: "changed", message: wired.message, edits: wired.edits };
7440
8094
  }
7441
- const file = relative13(repoRoot, path);
8095
+ const file = relative14(repoRoot, path);
7442
8096
  return {
7443
8097
  state: "needs-you",
7444
8098
  message: `remove ${names.join(", ")} from conlocaCloud() in ${file}; @conloca/cloud-astro no longer accepts them`,
@@ -7473,7 +8127,113 @@ var dataSchemas = {
7473
8127
  description: "wire data entries and uploaded media: schemas, conlocaData() and the Typia packages",
7474
8128
  plan: ({ projectDir }) => wireDataSchemas(projectDir)
7475
8129
  };
7476
- var MIGRATIONS = [keyless, dataSchemas];
8130
+ var DEAD_PREVIEW_OPTIONS = new Set(["adapter", "config", "outDir", "required"]);
8131
+ var D8_NOTES = [
8132
+ "open preview tabs from before this upgrade stop working; editors reopen Preview",
8133
+ "the preview mode already changed when @conloca/cloud-astro was updated: the next build serves d8, or turns preview off while previewBuild.adapter remains"
8134
+ ];
8135
+ async function startCommandEdits(dirs) {
8136
+ const listed = await Promise.all(dirs.map(async (dir) => (await readdir8(dir, { withFileTypes: true }).catch(() => [])).filter((entry) => entry.isFile()).filter(({ name }) => isStarterFile(name)).map(({ name }) => join27(dir, name))));
8137
+ const paths = listed.flat();
8138
+ const texts = await Promise.all(paths.map((path) => readFile24(path, "utf8")));
8139
+ return paths.flatMap((path, index) => {
8140
+ const before = texts[index] ?? "";
8141
+ return before.includes(D2_ENTRY) ? [{ path, before, after: before.replaceAll(D2_ENTRY, D8_ENTRY) }] : [];
8142
+ });
8143
+ }
8144
+ var done = (message) => ({ state: "done", message, edits: [], packages: [] });
8145
+ var needs3 = (message) => ({ state: "needs-you", message, edits: [], packages: [] });
8146
+ var d8 = {
8147
+ id: "d8",
8148
+ package: "@conloca/cloud-astro",
8149
+ since: D8_SINCE,
8150
+ description: "move draft preview into the site's own build (d8)",
8151
+ async plan({ projectDir, repoRoot }) {
8152
+ const path = ASTRO_CONFIG_FILES.map((name) => join27(projectDir, name)).find((file) => existsSync12(file));
8153
+ if (path === undefined)
8154
+ return done("no astro.config");
8155
+ const text = await readFile24(path, "utf8");
8156
+ const code = stripComments(text);
8157
+ const integration = callOptions(code, "conlocaCloud");
8158
+ const raw = integration.state === "literal" ? integration.entries.get("previewBuild") : undefined;
8159
+ if (raw === undefined || raw.trim() === "false")
8160
+ return done("no draft preview build to move");
8161
+ const adapter = siteAdapterOf(callOptions(code, "defineConfig"), code);
8162
+ const keys = previewBuildKeys(raw);
8163
+ const own = parseObjectEntries(raw.trim());
8164
+ const previewAdapter = own === null ? undefined : siteAdapterOf({ state: "literal", entries: own.entries, hasSpread: false }, code);
8165
+ if (adapter === undefined && previewAdapter === "@astrojs/cloudflare" && !keys.separate) {
8166
+ return needs3([
8167
+ "a static site previews next to itself on Cloudflare (D3): remove previewBuild.adapter and run conloca connect",
8168
+ ...D8_NOTES
8169
+ ].join("; "));
8170
+ }
8171
+ if (adapter === undefined && keys.adapter && !keys.separate) {
8172
+ return needs3([
8173
+ "a static site on its own server has no same-address preview: use previewBuild: { separate: true } (a Cloudflare preview deploy) or remove previewBuild",
8174
+ ...D8_NOTES
8175
+ ].join("; "));
8176
+ }
8177
+ const file = relative14(repoRoot, path);
8178
+ const setup = previewSetupOf(integration, callOptions(code, "defineConfig"), null, code);
8179
+ if (setup.kind === "d4" && keys.adapter) {
8180
+ const dropped = withoutPreviewBuildOptions(text, new Set(["adapter"]));
8181
+ if (dropped === null)
8182
+ return done("no D2 preview server to move");
8183
+ if (dropped === "computed")
8184
+ return needs3(`remove adapter from previewBuild in conlocaCloud() in ${file}`);
8185
+ return {
8186
+ state: "changed",
8187
+ message: "removed previewBuild.adapter, which the build refuses: the separate preview deploy builds with the adapter in astro.config",
8188
+ edits: [{ path, before: text, after: dropped.after }],
8189
+ packages: []
8190
+ };
8191
+ }
8192
+ const d2 = setup.kind === "off" && setup.refusal !== undefined && !keys.separate;
8193
+ if (!d2 && setup.kind !== "d8")
8194
+ return done("no D2 preview server to move");
8195
+ const dropped = withoutPreviewBuildOptions(text, DEAD_PREVIEW_OPTIONS);
8196
+ if (dropped === "computed" && [...DEAD_PREVIEW_OPTIONS].some((name) => new RegExp(`\\b${name}\\s*:`, "u").test(raw))) {
8197
+ return needs3(`remove adapter, config, outDir and required from previewBuild in conlocaCloud() in ${file}: drafts render in the site's own build`);
8198
+ }
8199
+ let after = typeof dropped === "object" && dropped !== null ? dropped.after : text;
8200
+ const notes = after === text ? [] : ["removed the previewBuild options the site build ignores"];
8201
+ let starts = [];
8202
+ if (adapter === "@astrojs/node") {
8203
+ const cms = callOptions(code, "conlocaCMS");
8204
+ const root = cms.state === "literal" ? stringLiteral(cms.entries.get("contentRoot") ?? "") : null;
8205
+ const sites = join27(root === null ? contentRootOf(projectDir) : resolve16(projectDir, root), "sites.json");
8206
+ const sitesText = await readFile24(sites, "utf8").catch(() => "");
8207
+ const node = addAdapterStep({
8208
+ path,
8209
+ text: after,
8210
+ host: "node",
8211
+ siteDomains: siteDomainsOf(sitesText),
8212
+ astroVersion: "",
8213
+ yes: true
8214
+ });
8215
+ if (node.state === "needs-you")
8216
+ return needs3([node.message, ...D8_NOTES].join("; "));
8217
+ if (node.state === "changed")
8218
+ notes.push("added security.allowedDomains");
8219
+ after = node.edits[0]?.after ?? after;
8220
+ starts = await startCommandEdits(foldersUp(projectDir, repoRoot));
8221
+ if (starts.length > 0)
8222
+ notes.push(`the start command is now ${D8_ENTRY}`);
8223
+ for (const edit of starts) {
8224
+ if (edit.after.includes(".conloca/preview-server")) {
8225
+ notes.push(`${relative14(repoRoot, edit.path)} still names .conloca/preview-server: make sure dist/server is in the image`);
8226
+ }
8227
+ }
8228
+ }
8229
+ const edits = [...after === text ? [] : [{ path, before: text, after }], ...starts];
8230
+ if (edits.length === 0)
8231
+ return done("draft preview already renders in the site's own build (d8)");
8232
+ const reminder = adapter === "@astrojs/node" ? [`if your host's dashboard, or any other file, starts ${D2_ENTRY}, change it to ${D8_ENTRY}`] : [];
8233
+ return { state: "changed", message: [...notes, ...reminder, ...D8_NOTES].join("; "), edits, packages: [] };
8234
+ }
8235
+ };
8236
+ var MIGRATIONS = [keyless, dataSchemas, d8];
7477
8237
  function migrationsSince(floors, migrations = MIGRATIONS) {
7478
8238
  return migrations.filter((migration) => {
7479
8239
  const floor = floors.get(migration.package);
@@ -7482,10 +8242,10 @@ function migrationsSince(floors, migrations = MIGRATIONS) {
7482
8242
  }
7483
8243
 
7484
8244
  // src/lib/skills.ts
7485
- import { readFile as readFile23 } from "node:fs/promises";
7486
- import { dirname as dirname7, join as join26, relative as relative14 } from "node:path";
8245
+ import { readFile as readFile25 } from "node:fs/promises";
8246
+ import { dirname as dirname9, join as join28, relative as relative15 } from "node:path";
7487
8247
  import { isUneditedSkill, stampSkill as stampSkill2 } from "@conloca/content-api/skill-stamp";
7488
- var CONLOCA_SKILL_PATH = join26(".claude", "skills", "conloca", "SKILL.md");
8248
+ var CONLOCA_SKILL_PATH = join28(".claude", "skills", "conloca", "SKILL.md");
7489
8249
  var LEGACY_CONLOCA_SKILL_CHECKSUMS = [
7490
8250
  "12a3b71e53d712fb2245e157c99c088df3841dc1d2e6332a9e17f23d306a8159",
7491
8251
  "f879c60b510ddf2fd7af781d60dd8c5cd6b4b8c7cbd9057fbd4d70fac6222ead",
@@ -7508,7 +8268,7 @@ async function projectPackageSkill(projectDir) {
7508
8268
  }
7509
8269
  }
7510
8270
  async function refresh(skill) {
7511
- const before = await readFile23(skill.path, "utf8").catch(() => null);
8271
+ const before = await readFile25(skill.path, "utf8").catch(() => null);
7512
8272
  if (before?.replaceAll(`\r
7513
8273
  `, `
7514
8274
  `) === skill.text)
@@ -7516,16 +8276,16 @@ async function refresh(skill) {
7516
8276
  if (before === null || isUneditedSkill(before, skill.legacyChecksums)) {
7517
8277
  return { edit: { path: skill.path, before, after: skill.text } };
7518
8278
  }
7519
- const beside = join26(dirname7(skill.path), "SKILL.new.md");
8279
+ const beside = join28(dirname9(skill.path), "SKILL.new.md");
7520
8280
  return {
7521
- edit: { path: beside, before: await readFile23(beside, "utf8").catch(() => null), after: skill.text },
8281
+ edit: { path: beside, before: await readFile25(beside, "utf8").catch(() => null), after: skill.text },
7522
8282
  kept: beside
7523
8283
  };
7524
8284
  }
7525
8285
  async function planSkillRefresh(projectDir, version) {
7526
8286
  const skills = [
7527
8287
  {
7528
- path: join26(projectDir, CONLOCA_SKILL_PATH),
8288
+ path: join28(projectDir, CONLOCA_SKILL_PATH),
7529
8289
  text: stampSkill2(conloca_skill_default, version),
7530
8290
  legacyChecksums: LEGACY_CONLOCA_SKILL_CHECKSUMS
7531
8291
  }
@@ -7536,7 +8296,7 @@ async function planSkillRefresh(projectDir, version) {
7536
8296
  const skipped = packageSkill instanceof Error ? `; skipped the page of @conloca/cloud-astro, which failed to load (${packageSkill.message})` : "";
7537
8297
  const results = await Promise.all(skills.map(refresh));
7538
8298
  const edits = results.flatMap((result) => result.edit === undefined ? [] : [result.edit]);
7539
- const kept = results.flatMap((result) => result.kept === undefined ? [] : [relative14(projectDir, result.kept)]);
8299
+ const kept = results.flatMap((result) => result.kept === undefined ? [] : [relative15(projectDir, result.kept)]);
7540
8300
  if (kept.length > 0) {
7541
8301
  return {
7542
8302
  state: "differs",
@@ -7545,7 +8305,7 @@ async function planSkillRefresh(projectDir, version) {
7545
8305
  };
7546
8306
  }
7547
8307
  if (edits.length > 0) {
7548
- const paths = edits.map((edit) => relative14(projectDir, edit.path)).join(" and ");
8308
+ const paths = edits.map((edit) => relative15(projectDir, edit.path)).join(" and ");
7549
8309
  return { state: "changed", message: `refreshed ${paths}${skipped}`, edits };
7550
8310
  }
7551
8311
  return { state: "done", message: `the agent skills are current${skipped}`, edits };
@@ -7555,14 +8315,14 @@ async function planSkillRefresh(projectDir, version) {
7555
8315
  var OVERRIDE_FIELDS = ["overrides", "resolutions"];
7556
8316
  async function readManifest(path) {
7557
8317
  try {
7558
- const text = await readFile24(path, "utf8");
8318
+ const text = await readFile26(path, "utf8");
7559
8319
  const value = JSON.parse(text);
7560
8320
  return isRecord(value) ? { path, text, value } : null;
7561
8321
  } catch {
7562
8322
  return null;
7563
8323
  }
7564
8324
  }
7565
- function needsYou(message) {
8325
+ function needsYou2(message) {
7566
8326
  return { state: "needs-you", message, edits: [] };
7567
8327
  }
7568
8328
  function targetOf(cli, name) {
@@ -7573,7 +8333,7 @@ async function refusalOf(manifests, installed, installDir, cli) {
7573
8333
  const entries = manifests.flatMap((manifest) => conlocaDependencies(manifest.value));
7574
8334
  const pinned = entries.find((entry) => entry.spec.includes(":") || entry.spec.includes("/"));
7575
8335
  if (pinned !== undefined) {
7576
- return needsYou(`${pinned.name} is "${pinned.spec}", which a version range cannot replace: set it to a version, then run upgrade again`);
8336
+ return needsYou2(`${pinned.name} is "${pinned.spec}", which a version range cannot replace: set it to a version, then run upgrade again`);
7577
8337
  }
7578
8338
  for (const manifest of manifests) {
7579
8339
  const pnpm = manifest.value.pnpm;
@@ -7582,12 +8342,12 @@ async function refusalOf(manifests, installed, installDir, cli) {
7582
8342
  isRecord(pnpm) ? pnpm.overrides : undefined
7583
8343
  ];
7584
8344
  if (fields.some((field) => field !== undefined && JSON.stringify(field).includes("@conloca/"))) {
7585
- return needsYou(`${manifest.path} pins @conloca packages in overrides or resolutions: remove them first`);
8345
+ return needsYou2(`${manifest.path} pins @conloca packages in overrides or resolutions: remove them first`);
7586
8346
  }
7587
8347
  }
7588
- const workspace = await readFile24(join27(installDir, "pnpm-workspace.yaml"), "utf8").catch(() => "");
8348
+ const workspace = await readFile26(join29(installDir, "pnpm-workspace.yaml"), "utf8").catch(() => "");
7589
8349
  if (workspace.includes("@conloca/")) {
7590
- return needsYou("pnpm-workspace.yaml names @conloca packages (a catalog or override): remove them first");
8350
+ return needsYou2("pnpm-workspace.yaml names @conloca packages (a catalog or override): remove them first");
7591
8351
  }
7592
8352
  const floors = [
7593
8353
  ...entries.map((entry) => ({ name: entry.name, floor: versionFloor(entry.spec) })),
@@ -7596,7 +8356,7 @@ async function refusalOf(manifests, installed, installDir, cli) {
7596
8356
  for (const { name, floor } of floors) {
7597
8357
  const target = targetOf(cli, name);
7598
8358
  if (floor !== null && target !== null && compareVersions(floor, target) > 0) {
7599
- return needsYou(`${name} is at ${floor}, newer than ${target}, which this CLI (${cli.version}) pins; never moving a site back: run npx @conloca/cli@latest upgrade`);
8359
+ return needsYou2(`${name} is at ${floor}, newer than ${target}, which this CLI (${cli.version}) pins; never moving a site back: run npx @conloca/cli@latest upgrade`);
7600
8360
  }
7601
8361
  }
7602
8362
  return null;
@@ -7625,7 +8385,7 @@ function manifestEditsOf(manifests, ranges, added) {
7625
8385
  function reportOf(plan) {
7626
8386
  const { start, steps, report } = plan;
7627
8387
  report.steps = steps.map((step) => {
7628
- const files = step.result.edits.map((edit) => relative15(start, edit.path));
8388
+ const files = step.result.edits.map((edit) => relative16(start, edit.path));
7629
8389
  return {
7630
8390
  id: step.id,
7631
8391
  state: step.result.state,
@@ -7651,10 +8411,10 @@ async function runMigrationPlan(migration, projectDir, repoRoot) {
7651
8411
  }
7652
8412
  }
7653
8413
  async function planUpgrade(path, options, io, cli, migrations) {
7654
- const start = resolve16(path);
8414
+ const start = resolve17(path);
7655
8415
  const to = cli.version;
7656
8416
  const up = await gitText(["rev-parse", "--show-cdup"], start);
7657
- const gitRoot = up === null ? null : resolve16(start, up);
8417
+ const gitRoot = up === null ? null : resolve17(start, up);
7658
8418
  const report = {
7659
8419
  ok: false,
7660
8420
  project: ".",
@@ -7675,20 +8435,20 @@ async function planUpgrade(path, options, io, cli, migrations) {
7675
8435
  const found = lockfileInstall(projectDir, repoRoot);
7676
8436
  const install = found ?? {
7677
8437
  packageManager: "npm",
7678
- lockfile: join27(projectDir, "package-lock.json"),
8438
+ lockfile: join29(projectDir, "package-lock.json"),
7679
8439
  installDir: projectDir
7680
8440
  };
7681
8441
  const commands = packageManagerCommands(install.packageManager);
7682
- report.project = relative15(start, projectDir) || ".";
8442
+ report.project = relative16(start, projectDir) || ".";
7683
8443
  report.packageManager = install.packageManager;
7684
8444
  const steps = [
7685
8445
  { id: "project", result: { state: "done", message: `Astro project ${report.project}`, edits: [] } }
7686
8446
  ];
7687
8447
  const stop = (id, result) => reportOf({ start, steps: [...steps, { id, result }], report });
7688
- const project = await readManifest(join27(projectDir, "package.json"));
8448
+ const project = await readManifest(join29(projectDir, "package.json"));
7689
8449
  if (project === null)
7690
8450
  return stop("packages", { state: "failed", message: `no readable package.json in ${report.project}`, edits: [] });
7691
- const workspace = install.installDir === projectDir ? null : await readManifest(join27(install.installDir, "package.json"));
8451
+ const workspace = install.installDir === projectDir ? null : await readManifest(join29(install.installDir, "package.json"));
7692
8452
  const manifests = workspace === null ? [project] : [project, workspace];
7693
8453
  if (conlocaDependencies(project.value).length === 0) {
7694
8454
  return stop("packages", {
@@ -7758,16 +8518,7 @@ async function planUpgrade(path, options, io, cli, migrations) {
7758
8518
  }
7759
8519
  async function installedVersions(manifests, projectDir, installDir) {
7760
8520
  const names = new Set(manifests.flatMap((manifest) => conlocaDependencies(manifest.value).map((entry) => entry.name)));
7761
- return Promise.all([...names].map(async (name) => {
7762
- for (let dir = projectDir;; dir = dirname8(dir)) {
7763
- const manifest = await readManifest(join27(dir, "node_modules", name, "package.json"));
7764
- if (manifest !== null) {
7765
- return { name, version: typeof manifest.value.version === "string" ? manifest.value.version : null };
7766
- }
7767
- if (dir === installDir || dir === dirname8(dir))
7768
- return { name, version: null };
7769
- }
7770
- }));
8521
+ return Promise.all([...names].map(async (name) => ({ name, version: await installedVersion(name, projectDir, installDir) })));
7771
8522
  }
7772
8523
  async function versionsStep(plan) {
7773
8524
  const installed = await installedVersions(plan.manifests, plan.projectDir, plan.install.installDir);
@@ -7791,7 +8542,7 @@ async function applyMigration(migration, plan, save) {
7791
8542
  if (result.state !== "done" && result.state !== "changed") {
7792
8543
  return { ...result, state: "failed", message: `on writing: ${result.message}` };
7793
8544
  }
7794
- const current = await Promise.all(result.edits.map((edit) => readFile24(edit.path, "utf8").catch(() => null)));
8545
+ const current = await Promise.all(result.edits.map((edit) => readFile26(edit.path, "utf8").catch(() => null)));
7795
8546
  const stale = result.edits.filter((edit, index) => current[index] !== edit.before).map((edit) => edit.path);
7796
8547
  if (stale.length > 0)
7797
8548
  return { ...result, state: "failed", message: `${stale.join(", ")} changed since the dry run` };
@@ -7805,14 +8556,14 @@ async function applyUpgrade(plan, io) {
7805
8556
  const folders = new Set;
7806
8557
  const save = async (paths) => {
7807
8558
  const fresh = paths.filter((path) => !journal.has(path));
7808
- const contents = await Promise.all(fresh.map((path) => readFile24(path).catch((error) => {
8559
+ const contents = await Promise.all(fresh.map((path) => readFile26(path).catch((error) => {
7809
8560
  if (error.code === "ENOENT")
7810
8561
  return null;
7811
8562
  throw error;
7812
8563
  })));
7813
8564
  for (const [index, path] of fresh.entries()) {
7814
8565
  journal.set(path, contents[index] ?? null);
7815
- for (let dir = dirname8(path);!existsSync12(dir); dir = dirname8(dir))
8566
+ for (let dir = dirname10(path);!existsSync13(dir); dir = dirname10(dir))
7816
8567
  folders.add(dir);
7817
8568
  }
7818
8569
  };
@@ -7853,9 +8604,9 @@ async function applyUpgrade(plan, io) {
7853
8604
  const failed = steps.find((step) => step.result.state === "failed");
7854
8605
  if (failed !== undefined && (plan.manifestEdits.length > 0 || journal.size > saved)) {
7855
8606
  const lockfile = basename6(install.lockfile);
7856
- const created = plan.noLockfile && existsSync12(install.lockfile);
8607
+ const created = plan.noLockfile && existsSync13(install.lockfile);
7857
8608
  const unrestored = await restoreJournal(journal, folders);
7858
- report.unrestored = unrestored.map((path) => relative15(start, path));
8609
+ report.unrestored = unrestored.map((path) => relative16(start, path));
7859
8610
  report.restored = unrestored.length === 0;
7860
8611
  const reinstall = plan.noLockfile ? commands.install : commands.frozenInstall;
7861
8612
  const manifests = plan.manifests.length === 1 ? "package.json" : `${plan.manifests.length} package.json files`;
@@ -7874,7 +8625,7 @@ async function restoreJournal(journal, folders = []) {
7874
8625
  try {
7875
8626
  if (saved !== null)
7876
8627
  await writeFile6(path, saved);
7877
- else if (existsSync12(path))
8628
+ else if (existsSync13(path))
7878
8629
  await rm2(path);
7879
8630
  return [];
7880
8631
  } catch {
@@ -7908,6 +8659,7 @@ async function upgrade(path, options) {
7908
8659
  }
7909
8660
 
7910
8661
  // src/cli.ts
8662
+ var CONNECT_HOSTS = ["vercel", "netlify", "cloudflare", "node"];
7911
8663
  var program2 = new Command;
7912
8664
  program2.name("conloca").usage("<command> [options]").helpOption("-h, --help", "Show this help message").addHelpText("after", `
7913
8665
  Run 'conloca <command> --help' for help on a single command.`);
@@ -7977,16 +8729,22 @@ exists too (a server adapter), else dist. The baseline stays in
7977
8729
  node_modules/.cache until --reset. Never commits. Exits 1 when anything differs.`).action(async (path, options) => {
7978
8730
  await compare(path, { routes: options.routes, reset: options.reset === true, json: options.json === true });
7979
8731
  });
7980
- program2.command("connect").argument("[path]", "Folder of the Astro site, or of the repository holding it", ".").option("--project <dir>", "Astro project to set up, when the repository has several").option("--site-url <url>", "The address the site is deployed at, when astro.config sets no `site`").option("--yes", "Accept every change without asking (no terminal needed)").option("--dry-run", "Show the changes, write nothing").option("--no-install", "Do not install packages; print the command instead").option("--no-build", "Skip the local build check").option("--update", "Refresh the draft preview settings in wrangler.jsonc from a fresh build, and nothing else").addOption(new Option("--cf-plan <plan>", "Your Cloudflare Workers plan, for draft previews of a static site (asked on a terminal otherwise)").choices(["free", "paid"])).option("--negotiate-404", 'Send every miss to the draft preview dispatcher (not_found_handling "none"), for middleware that negotiates responses').option("--json", "One JSON report on stdout").description("Set up an Astro site's editor page for your workspace editor").addHelpText("after", `
8732
+ program2.command("connect").argument("[path]", "Folder of the Astro site, or of the repository holding it", ".").option("--project <dir>", "Astro project to set up, when the repository has several").option("--site-url <url>", "The address the site is deployed at, when astro.config sets no `site`").option("--yes", "Accept every change without asking (no terminal needed)").option("--dry-run", "Show the changes, write nothing").option("--no-install", "Do not install packages; print the command instead").option("--no-build", "Skip the local build check").option("--update", "Refresh the draft preview settings in wrangler.jsonc from a fresh build, and nothing else").addOption(new Option("--cf-plan <plan>", "Your Cloudflare Workers plan, for draft previews of a static site (asked on a terminal otherwise)").choices(["free", "paid"])).addOption(new Option("--host <host>", "Where the site deploys, for draft previews (detected from its files otherwise)").choices(CONNECT_HOSTS)).option("--negotiate-404", 'Send every miss to the draft preview dispatcher (not_found_handling "none"), for middleware that negotiates responses').option("--json", "One JSON report on stdout").description("Set up an Astro site's editor page for your workspace editor").addHelpText("after", `
7981
8733
  Adds @conloca/astro-cms, @conloca/cloud-astro and their React peers with the
7982
8734
  project's own package manager, wires react(), conlocaCMS() and conlocaCloud()
7983
8735
  into astro.config, writes the site's domain into sites.json, allows the
7984
8736
  workspace editor to frame the editor page where a committed header forbids
7985
8737
  it, builds the site once to prove the editor page is there, and removes the
7986
8738
  old build key from workflows. With previewBuild in conlocaCloud(), it also
7987
- writes the draft preview settings into wrangler.jsonc; --update refreshes only
7988
- those, from a fresh build, --cf-plan answers the plan question without a
7989
- terminal, and --negotiate-404 sends every miss to the preview dispatcher.
8739
+ finds where the site deploys (--host names it), adds that host's official
8740
+ Astro adapter so drafts render in the site's own build (Vercel, Netlify), and
8741
+ prints the host's deploy step, or writes the draft preview settings into
8742
+ wrangler.jsonc on Cloudflare; --update refreshes only those, from a fresh
8743
+ build, and never adds an adapter, --cf-plan answers the plan question without
8744
+ a terminal, and --negotiate-404 sends every miss to the preview dispatcher.
8745
+ On Vercel and Netlify, an astro.config without site gets site proposed from
8746
+ sites.json (or --site-url) and asked for first, since site changes canonical,
8747
+ sitemap, RSS and Open Graph URLs; --yes never writes it.
7990
8748
  Every change is shown as a diff first; in a terminal it asks before it writes
7991
8749
  (and, for a static site previewing next to itself, once for your Cloudflare
7992
8750
  plan), --yes accepts, and without a terminal or --yes nothing is written. A
@@ -7994,6 +8752,7 @@ value you set yourself is kept and reported as "differs".
7994
8752
  Never commits, pushes or deploys. A site whose @conloca packages are older
7995
8753
  than this CLI is handed to 'conloca upgrade' with nothing written (exit 2).
7996
8754
  Exits 0 when done, 1 when a step failed, 2 when a step needs you.`).action(async (path, options) => {
8755
+ const host = CONNECT_HOSTS.find((choice) => choice === options.host);
7997
8756
  await connect(path, {
7998
8757
  project: options.project,
7999
8758
  siteUrl: options.siteUrl,
@@ -8004,7 +8763,8 @@ Exits 0 when done, 1 when a step failed, 2 when a step needs you.`).action(async
8004
8763
  json: options.json === true,
8005
8764
  update: options.update === true,
8006
8765
  negotiate404: options.negotiate404 === true,
8007
- ...isCfPlan(options.cfPlan) ? { cfPlan: options.cfPlan } : {}
8766
+ ...isCfPlan(options.cfPlan) ? { cfPlan: options.cfPlan } : {},
8767
+ ...host === undefined ? {} : { host }
8008
8768
  });
8009
8769
  });
8010
8770
  program2.command("upgrade").argument("[path]", "Folder of the Astro site, or of the repository holding it", ".").option("--project <dir>", "Astro project to upgrade, when the repository has several").option("--dry-run", "Show the changes, write nothing").option("--json", "One JSON report on stdout").description("Bring every @conloca package of the site to the version this CLI pins").addHelpText("after", `