create-ailk 0.46.6 → 0.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +180 -43
  2. package/component-catalog.json +223 -285
  3. package/component-catalog.md +1 -1
  4. package/dist/apply-design.d.ts +26 -68
  5. package/dist/apply-design.js +150 -322
  6. package/dist/cli.js +152 -17
  7. package/dist/compare-chrome.d.ts +108 -0
  8. package/dist/compare-chrome.js +481 -0
  9. package/dist/compare-look.d.ts +94 -0
  10. package/dist/compare-look.js +378 -0
  11. package/dist/copy.js +1 -1
  12. package/dist/design-compile.d.ts +17 -21
  13. package/dist/design-compile.js +32 -56
  14. package/dist/design-files.d.ts +93 -0
  15. package/dist/design-files.js +312 -0
  16. package/dist/design-home.d.ts +4 -2
  17. package/dist/design-home.js +88 -6
  18. package/dist/design-names.d.ts +13 -0
  19. package/dist/design-names.js +76 -0
  20. package/dist/design-package.d.ts +46 -56
  21. package/dist/design-package.js +285 -288
  22. package/dist/design-presets.d.ts +41 -0
  23. package/dist/design-presets.js +83 -4
  24. package/dist/design-scaffold.d.ts +12 -2
  25. package/dist/design-scaffold.js +72 -34
  26. package/dist/generated/design-settings.d.ts +56 -0
  27. package/dist/generated/design-settings.js +237 -0
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +2 -2
  30. package/dist/inventory.d.ts +3 -2
  31. package/dist/inventory.js +10 -4
  32. package/dist/lib/design-checks.d.ts +46 -0
  33. package/dist/lib/design-checks.js +79 -1
  34. package/dist/lib/env-catalog.js +5 -1
  35. package/dist/lib/module-license-gate.d.ts +1 -1
  36. package/dist/lib/module-license-gate.js +1 -1
  37. package/dist/lib/render-verdict.d.ts +13 -1
  38. package/dist/lib/render-verdict.js +41 -1
  39. package/dist/look-hub.d.ts +44 -0
  40. package/dist/look-hub.js +130 -0
  41. package/dist/look-record.d.ts +35 -0
  42. package/dist/look-record.js +85 -0
  43. package/dist/look-samples.d.ts +66 -0
  44. package/dist/look-samples.js +456 -0
  45. package/dist/look-settings.d.ts +53 -0
  46. package/dist/look-settings.js +363 -0
  47. package/dist/module-architecture.js +12 -0
  48. package/dist/parse-args.d.ts +10 -6
  49. package/dist/parse-args.js +26 -13
  50. package/dist/programmatic.d.ts +1 -19
  51. package/dist/programmatic.js +65 -103
  52. package/dist/retired-design-bodies.d.ts +29 -0
  53. package/dist/retired-design-bodies.js +51 -0
  54. package/dist/seed-flows.d.ts +1 -1
  55. package/dist/seed-flows.js +12 -14
  56. package/dist/seed-workspace.d.ts +4 -1
  57. package/dist/seed-workspace.js +139 -17
  58. package/dist/site-chrome.d.ts +41 -41
  59. package/dist/site-chrome.js +50 -70
  60. package/dist/site-fonts.d.ts +10 -14
  61. package/dist/site-fonts.js +5 -1
  62. package/dist/starter-grid.d.ts +2 -2
  63. package/dist/strip-look-copies.d.ts +67 -0
  64. package/dist/strip-look-copies.js +591 -0
  65. package/dist/template-manifest.d.ts +6 -14
  66. package/dist/template-manifest.js +0 -9
  67. package/dist/template-record.d.ts +3 -1
  68. package/dist/template-record.js +3 -1
  69. package/dist/topology.d.ts +15 -0
  70. package/dist/topology.js +60 -0
  71. package/dist/update.d.ts +57 -1
  72. package/dist/update.js +742 -13
  73. package/package.json +3 -4
  74. package/site-templates/aliases/hub.TEMPLATE-MANIFEST.json +2 -31
  75. package/site-templates/designs/minimalism/DESIGN.md +163 -297
  76. package/site-templates/designs/minimalism/LOOK.md +42 -0
  77. package/site-templates/designs/minimalism/design.yaml +167 -0
  78. package/site-templates/designs/standard/DESIGN.md +145 -149
  79. package/site-templates/designs/standard/LOOK.md +42 -0
  80. package/site-templates/designs/standard/design.yaml +72 -0
  81. package/site-templates/marketing-site/TEMPLATE-MANIFEST.json +2 -31
  82. package/site-templates/marketing-site/TEMPLATE-MANIFEST.md +1 -25
  83. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.json +2 -31
  84. package/site-templates/marketing-site-free/TEMPLATE-MANIFEST.md +1 -25
  85. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.json +2 -31
  86. package/site-templates/shapes/local-business-service/TEMPLATE-MANIFEST.md +1 -25
  87. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.json +2 -31
  88. package/site-templates/shapes/organization-service/TEMPLATE-MANIFEST.md +1 -25
  89. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.json +2 -31
  90. package/site-templates/shapes/person-service/TEMPLATE-MANIFEST.md +1 -25
  91. package/site-templates/shapes/person-service/content/_site.mdx +0 -26
  92. package/templates/.claude/rules/extending.md +3 -2
  93. package/templates/.env.example +11 -4
  94. package/templates/CLAUDE.md +1 -1
  95. package/templates/DESIGN.md +145 -149
  96. package/templates/README.md +15 -16
  97. package/templates/apps/api/.env.example +29 -4
  98. package/templates/apps/api/CLAUDE.md +7 -4
  99. package/templates/apps/api/src/__tests__/vercel-handler.test.ts +176 -2
  100. package/templates/apps/api/src/lib/__mocks__/prisma.ts +30 -4
  101. package/templates/apps/api/src/vercel-handler.ts +32 -2
  102. package/templates/apps/mcp/.env.example +8 -0
  103. package/templates/apps/mcp/CLAUDE.md +5 -3
  104. package/templates/apps/web/.env.example +10 -3
  105. package/templates/apps/web/CLAUDE.md +31 -4
  106. package/templates/apps/web/app/[locale]/layout.tsx +141 -77
  107. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +13 -3
  108. package/templates/apps/web/app/not-found.tsx +11 -11
  109. package/templates/apps/web/auth.ts +48 -35
  110. package/templates/apps/web/jest.config.cjs +5 -0
  111. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +542 -10
  112. package/templates/apps/web/lib/__tests__/library-fonts.test.ts +35 -0
  113. package/templates/apps/web/lib/__tests__/page-chrome-navigation.test.ts +233 -0
  114. package/templates/apps/web/lib/__tests__/page-chrome.test.ts +123 -26
  115. package/templates/apps/web/lib/__tests__/section-look.test.ts +150 -0
  116. package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +19 -1
  117. package/templates/apps/web/lib/__tests__/site-navigation.test.ts +288 -0
  118. package/templates/apps/web/lib/__tests__/site-theme.test.ts +81 -289
  119. package/templates/apps/web/lib/deck-page.ts +3 -10
  120. package/templates/apps/web/lib/deploy-fonts.ts +12 -0
  121. package/templates/apps/web/lib/hub-site-config.ts +237 -29
  122. package/templates/apps/web/lib/library-fonts.ts +41 -0
  123. package/templates/apps/web/lib/mcp-oauth.ts +11 -4
  124. package/templates/apps/web/lib/page-chrome.ts +105 -20
  125. package/templates/apps/web/lib/section-look.ts +28 -0
  126. package/templates/apps/web/lib/site-design.ts +205 -0
  127. package/templates/apps/web/lib/site-navigation.ts +208 -0
  128. package/templates/apps/web/lib/site-theme-head.ts +98 -13
  129. package/templates/apps/web/lib/site-theme.ts +40 -62
  130. package/templates/apps/web/messages/en.json +0 -6
  131. package/templates/apps/web/next.config.mjs +213 -11
  132. package/templates/apps/web/package.json +2 -0
  133. package/templates/apps/web/site-pages.config.tsx +4 -2
  134. package/templates/content/_site.mdx +0 -26
  135. package/templates/design.yaml +75 -0
  136. package/templates/project.yaml +14 -0
  137. package/versions.json +52 -51
  138. package/site-templates/marketing-site/DESIGN.md +0 -259
  139. package/site-templates/marketing-site-free/DESIGN.md +0 -259
  140. package/site-templates/saas-product/DESIGN.md +0 -259
  141. package/templates/apps/web/lib/__tests__/deck-page.test.ts +0 -288
  142. package/templates/apps/web/lib/__tests__/site-theme-head.test.ts +0 -70
  143. package/templates/apps/web/lib/site-chrome.ts +0 -46
  144. package/templates/apps/web/lib/site-fonts.ts +0 -15
package/dist/update.js CHANGED
@@ -104,7 +104,7 @@
104
104
  * Pure module: no `import.meta.url` — the CLI supplies `templatesDir`, the
105
105
  * `adopt.ts` / `add-route.ts` split.
106
106
  */
107
- import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync, statSync, writeFileSync, } from "node:fs";
107
+ import { existsSync, mkdirSync, readFileSync, lstatSync, readdirSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, writeFileSync, } from "node:fs";
108
108
  import { createRequire } from "node:module";
109
109
  import { dirname, join, posix, relative, resolve, sep } from "node:path";
110
110
  import { pathToFileURL } from "node:url";
@@ -114,6 +114,10 @@ import { headingViolations, mdxBodyPages, mdxBodyRule, migrateBodyHeadings } fro
114
114
  import { buildScaffoldMarkers, isExcluded, isTextFile, renderTemplateFile, templateDestination } from "./copy.js";
115
115
  import { declinedRouteOfPath, readDeclinedRoutes } from "./declined-routes.js";
116
116
  import { deriveArchitecture } from "./derive-architecture.js";
117
+ import { DESIGN_GUIDE_FILE, DESIGN_SETTINGS_FILE, SYMLINK_REASON, isLegacyDesignMd, isSymlink, legacyBodyHash, legacyHeaderText, legacyProvenanceLines, } from "./design-files.js";
118
+ import { shippedDesigns } from "./design-names.js";
119
+ import { DESIGN_COLOR_KEYS_LIGHT, parseSettings, readDesignPackageText } from "./design-package.js";
120
+ import { removeThemeBlock, renderThemeBlock, spliceThemeBlock } from "./design-scaffold.js";
117
121
  import { computeModulePatches } from "./lib/apply-module-patches.js";
118
122
  import { EnvContractError, planEnvRows, readEnvContract, readManifestTopology, } from "./lib/declared-env.js";
119
123
  import { ENV_CATALOG } from "./lib/env-catalog.js";
@@ -125,18 +129,23 @@ import { mergeThreeWay } from "./lib/merge-three-way.js";
125
129
  import { deriveLevel } from "./lib/module-license-gate.js";
126
130
  import { LEVEL_LABEL } from "./lib/module-tier.js";
127
131
  import { publicTreeRemoved } from "./lib/site-modules.js";
132
+ import { SITE_MDX_PATH, carriesThemeKey, printable, retiredLookSources, themeBlockRemovable, } from "./look-hub.js";
128
133
  import { escapeBareBraces, findBareBraces } from "./mdx-braces.js";
129
134
  import { MODULE_SLICES } from "./module-architecture.js";
130
135
  import { MODULE_FLAGS_PATH, PAID_MCP_TOOLS_PATH, PAID_SECTIONS_PATH, levelMcpPackages, renderSitePaidSections, withLevelMcpPackages, writeModuleFlags, writePaidMcpTools, writePaidSectionsRegistry, } from "./paid-sections.js";
131
136
  import { ParseError } from "./parse-args.js";
137
+ import { RETIRED_DESIGN_BODIES } from "./retired-design-bodies.js";
132
138
  import { PAGE_DECISION_GUIDANCE, RoutesRefusedError, checkRoutes, customizationsRecord, isGenerated, writeRoutes } from "./routes.js";
133
139
  import { planSeamRefresh, seamRow, siteSeamRenders } from "./seam-refresh.js";
140
+ import { SPOKE_KEY_ENV_VAR } from "./seed-flows.js";
141
+ import { SITE_CHROME_PATH } from "./site-chrome.js";
142
+ import { SITE_FONTS_PATH } from "./site-fonts.js";
134
143
  import { SITE_LISTING_PATH } from "./site-listing-path.js";
135
- import { SITE_ROSTER_PATH, planServedRoster, readRosterPageRoutes } from "./site-roster.js";
144
+ import { SITE_ROSTER_PATH, planServedRoster, readRosterPageRoutes, readSiteRoster } from "./site-roster.js";
136
145
  import { substituteMarkers } from "./substitute.js";
137
146
  import { GATEABLE_SURFACES, excludedRoutePaths, isRemovedPublicRoutePath, resolveSurfaces, surfacesNamedByRoutes, } from "./surfaces.js";
138
147
  import { DATABASE_BOOT_FILES, ROOT_TOOL_FILES, TEMPLATE_RECORD_PATH, isRecordable, parseTemplateRecord, serializeTemplateRecord, sha256Hex, } from "./template-record.js";
139
- import { MCP_SEAM_PATH, MCP_SERVER_HUB, SPOKE_SEAM_FILES, TopologyError, isSpokeExcluded, readSpokeShape, spokeExclusions, } from "./topology.js";
148
+ import { MCP_SEAM_PATH, MCP_SERVER_HUB, SPOKE_SEAM_FILES, TopologyError, isSpokeExcluded, normalizeHubUrl, readSpokeShape, spokeExclusions, spokeOriginMismatch, } from "./topology.js";
140
149
  /** A refusal the CLI exits 2 on, thrown before anything is written. */
141
150
  export class UpdateRefusedError extends Error {
142
151
  exitCode = 2;
@@ -1434,6 +1443,9 @@ export async function updateSite(opts) {
1434
1443
  throw new UpdateRefusedError(err.message);
1435
1444
  throw err;
1436
1445
  }
1446
+ // #12477 D6 steps 1–3 — before any write: a site's look files go only once
1447
+ // the hub's read for it carries its look; else the run is refused.
1448
+ const lookSource = await checkLookSource(targetDir, opts.look, spoke !== undefined, opts.env ?? process.env, opts.fetchImpl ?? fetch);
1437
1449
  const excludedRoutes = excludedRoutePaths(header.surfaces);
1438
1450
  // #10774 D3 — a module-less surface the roster's page rows name but the header omits
1439
1451
  // (the /projects pair a 0.19.0 scaffold rostered without its route) is in
@@ -2582,6 +2594,23 @@ export async function updateSite(opts) {
2582
2594
  : (leftAloneReason.get(file) ?? "held back with another file"),
2583
2595
  }))
2584
2596
  .filter((entry) => entry.importers.length > 0);
2597
+ // #12477 D6 step 4 — the retired set, over this run's own plan and before
2598
+ // its first write: each look file a file this run leaves still imports is
2599
+ // held, as is site-chrome.ts while nav-config.ts stays.
2600
+ const writtenByRun = new Map(writes.filter((w) => notHeld(w.path)).map((w) => [w.path, w.bytes]));
2601
+ const removedByRun = new Set([
2602
+ ...(apiMove?.deletes ?? []),
2603
+ ...sliceRetirement.deletes.filter(notHeld),
2604
+ ...deletes.filter(notHeld),
2605
+ ]);
2606
+ const lookPlan = lookSource === undefined
2607
+ ? undefined
2608
+ : planLookRetirement(targetDir, (path) => {
2609
+ if (removedByRun.has(path))
2610
+ return undefined;
2611
+ const bytes = writtenByRun.get(path);
2612
+ return bytes !== undefined ? Buffer.from(bytes).toString("utf8") : diskText(path);
2613
+ });
2585
2614
  // ── Apply: writes and removals, then the record (D4 Order) ───────────
2586
2615
  // #9566 — the API move's removals first: a retired file at a boot-set
2587
2616
  // path is overwritten by the write that follows, never deleted after it.
@@ -2821,10 +2850,31 @@ export async function updateSite(opts) {
2821
2850
  throw err;
2822
2851
  review.push({ path: "apps/web/app/[locale]", reason: `route files not regenerated: ${err.message}` });
2823
2852
  }
2853
+ // #12468 D6 — a site's retired-format DESIGN.md: its settings move to
2854
+ // design.yaml, once, after the run's template-file writes.
2855
+ const designMove = moveDesignSettings(targetDir, opts.designsDir ?? join(dirname(resolve(opts.templatesDir)), "site-templates", "designs"));
2856
+ moved.added.push(...designMove.added);
2857
+ moved.added.sort();
2858
+ moved.updated.push(...designMove.updated);
2859
+ moved.removed.push(...designMove.removed);
2860
+ review.push(...designMove.review);
2861
+ // #12500 D7 — then, once, both colour sets, the retired pin and the design's version.
2862
+ const designUpgrade = upgradeDesignSettings(targetDir, lookPlan?.retired);
2863
+ moved.updated.push(...designUpgrade.updated.filter((path) => !moved.added.includes(path)));
2864
+ review.push(...designUpgrade.review.filter((row) => !review.some((seen) => seen.path === row.path && seen.reason === row.reason)));
2824
2865
  // The scaffold's `routes:check` preflight step runs the create-ailk its
2825
2866
  // root devDependencies pin; the files above are this version's rendering,
2826
2867
  // so the pin follows — an older generator would call them stale.
2827
2868
  const cliPin = moveCliPin(targetDir, version);
2869
+ // #12477 D6 step 4 — the retired look files, as the run's last writes.
2870
+ if (lookPlan !== undefined) {
2871
+ const retirement = applyLookRetirement(targetDir, lookPlan.retired);
2872
+ moved.removed.push(...retirement.removed);
2873
+ for (const path of retirement.updated)
2874
+ if (!moved.updated.includes(path))
2875
+ moved.updated.push(path);
2876
+ review.push(...lookPlan.review, ...retirement.review);
2877
+ }
2828
2878
  return {
2829
2879
  targetDir,
2830
2880
  version,
@@ -2860,6 +2910,7 @@ export async function updateSite(opts) {
2860
2910
  ...(servedRoster !== undefined && servedRoster.dropped.length > 0
2861
2911
  ? { rosterRowsDropped: servedRoster.dropped }
2862
2912
  : {}),
2913
+ ...(lookSource !== undefined ? { look: lookSource } : {}),
2863
2914
  };
2864
2915
  }
2865
2916
  /**
@@ -2920,9 +2971,653 @@ export async function loadSiteMdxParse(targetDir) {
2920
2971
  return undefined;
2921
2972
  }
2922
2973
  }
2974
+ /** Where `update` keeps a site's own edits to its retired-format DESIGN.md (#12468 SEC-12468-3). */
2975
+ const RETIRED_DESIGN_MD = "DESIGN.retired.md";
2976
+ /** `path` exists as a directory entry — a dangling symlink included. */
2977
+ function entryExists(path) {
2978
+ try {
2979
+ lstatSync(path);
2980
+ return true;
2981
+ }
2982
+ catch {
2983
+ return false;
2984
+ }
2985
+ }
2986
+ /**
2987
+ * #12468 D6 — move a site's settings out of its retired-format root
2988
+ * `DESIGN.md`, once. Every check runs before the first write:
2989
+ *
2990
+ * - a symlink at `design.yaml` or `DESIGN.md` → nothing written, a review row per link (SEC-12468-1);
2991
+ * - a `DESIGN.md` not in the retired format → never read or touched;
2992
+ * - a `design.yaml` already present → nothing written, a review row;
2993
+ * - otherwise `design.yaml` = the old provenance lines as `# ` lines, then the old
2994
+ * header byte for byte — the site's own values, never the shipped design's —
2995
+ * read back as a design (SEC-12468-6). The old file is then removed or replaced
2996
+ * by the recorded design's guide when its body is one create-ailk shipped, or
2997
+ * kept whole as `DESIGN.retired.md` when the site edited it (SEC-12468-3).
2998
+ *
2999
+ * The guide is copied only for a manifest `design` that is exactly a
3000
+ * `shippedDesigns()` name, from a path built from that listed name (SEC-12468-4).
3001
+ */
3002
+ function moveDesignSettings(siteDir, designsDir) {
3003
+ const result = {
3004
+ added: [],
3005
+ updated: [],
3006
+ removed: [],
3007
+ review: [],
3008
+ };
3009
+ const settingsPath = join(siteDir, DESIGN_SETTINGS_FILE);
3010
+ const guidePath = join(siteDir, DESIGN_GUIDE_FILE);
3011
+ const retiredPath = join(siteDir, RETIRED_DESIGN_MD);
3012
+ // ── Checks ──
3013
+ const links = [DESIGN_SETTINGS_FILE, DESIGN_GUIDE_FILE].filter((name) => isSymlink(join(siteDir, name)));
3014
+ if (links.length > 0) {
3015
+ result.review.push(...links.map((path) => ({ path, reason: SYMLINK_REASON })));
3016
+ return result;
3017
+ }
3018
+ if (!existsSync(guidePath))
3019
+ return result;
3020
+ if (!lstatSync(guidePath).isFile()) {
3021
+ result.review.push({
3022
+ path: DESIGN_GUIDE_FILE,
3023
+ reason: "not a regular file — update moves a site's settings only from a DESIGN.md file",
3024
+ });
3025
+ return result;
3026
+ }
3027
+ const old = readFileSync(guidePath, "utf8");
3028
+ if (!isLegacyDesignMd(old))
3029
+ return result;
3030
+ if (existsSync(settingsPath)) {
3031
+ result.review.push({
3032
+ path: DESIGN_GUIDE_FILE,
3033
+ reason: "in the retired settings format, and design.yaml already holds the settings — remove it, or apply a design to replace it with a guide",
3034
+ });
3035
+ return result;
3036
+ }
3037
+ const settings = legacyProvenanceLines(old) + legacyHeaderText(old);
3038
+ const bodyShipped = RETIRED_DESIGN_BODIES.has(legacyBodyHash(old));
3039
+ const retiredTaken = !bodyShipped && entryExists(retiredPath);
3040
+ let design;
3041
+ try {
3042
+ design = readSiteRoster(siteDir)?.doc["design"];
3043
+ }
3044
+ catch {
3045
+ design = undefined; // an unreadable manifest names no design: no guide is copied
3046
+ }
3047
+ const starter = shippedDesigns().find((name) => name === design);
3048
+ const guideSource = starter === undefined ? undefined : join(designsDir, starter, DESIGN_GUIDE_FILE);
3049
+ const guide = guideSource !== undefined && existsSync(guideSource) ? readFileSync(guideSource) : undefined;
3050
+ // ── Effects ──
3051
+ // #12500 D7 — the moved file is read as a design by `upgradeDesignSettings`,
3052
+ // under the rules it moves it forward to.
3053
+ writeFileSync(settingsPath, settings, { flag: "wx" });
3054
+ result.added.push(DESIGN_SETTINGS_FILE);
3055
+ if (retiredTaken) {
3056
+ result.review.push({
3057
+ path: DESIGN_GUIDE_FILE,
3058
+ reason: `in the retired settings format, with edits of its own; ${RETIRED_DESIGN_MD} already exists`,
3059
+ });
3060
+ return result;
3061
+ }
3062
+ if (bodyShipped) {
3063
+ rmSync(guidePath);
3064
+ }
3065
+ else {
3066
+ renameSync(guidePath, retiredPath);
3067
+ result.added.push(RETIRED_DESIGN_MD);
3068
+ result.review.push({
3069
+ path: RETIRED_DESIGN_MD,
3070
+ reason: "your edits to the old DESIGN.md, kept; its settings are now design.yaml",
3071
+ });
3072
+ }
3073
+ if (guide !== undefined) {
3074
+ writeFileSync(guidePath, guide, { flag: "wx" });
3075
+ (bodyShipped ? result.updated : result.added).push(DESIGN_GUIDE_FILE);
3076
+ }
3077
+ else {
3078
+ result.removed.push(DESIGN_GUIDE_FILE);
3079
+ }
3080
+ return result;
3081
+ }
3082
+ /**
3083
+ * #12500 D7 — the value the compile filled each dark key with before both
3084
+ * sets were required: what a site missing that key rendered, and so what it
3085
+ * gets, in the dark set's order.
3086
+ */
3087
+ const OLD_DARK_FALLBACKS = {
3088
+ "surface-dark": "bg-dark",
3089
+ "surface-secondary-dark": "bg-dark",
3090
+ "text-muted-dark": "fg-dark",
3091
+ "fg-on-brand-dark": "bg-dark",
3092
+ "accent-dark": "brand-dark",
3093
+ };
3094
+ /** The three texts the site-chrome generator wrote for the retired pin (#7742), removed exactly. */
3095
+ const PIN_VALUE_LINE = ' colorMode: "light",';
3096
+ const PIN_CHROME_TEXTS = [
3097
+ '// - colorMode: "light" → the site is pinned to light and shows no theme\n// switch; dark appears only as a deck ground.\n',
3098
+ ' colorMode?: "light";\n',
3099
+ `${PIN_VALUE_LINE}\n`,
3100
+ ];
3101
+ /** What a stopped move adds on a pinned site: the layout no longer reads the pin, so its page follows the visitor's mode. */
3102
+ const PIN_NOT_MOVED = ", so the site's retired colorMode pin was not moved either — its page now follows the visitor's light or dark mode until design.yaml reads and update runs again";
3103
+ /** A `design.yaml` layout's retired pin line, in each form YAML reads as the string light. */
3104
+ const PIN_DESIGN_LINE = /^ {2}colorMode: (?:light|"light"|'light')$/;
3105
+ /** The site path's lines for one top-level block: `[start, end)` of `key:` and its indented lines. */
3106
+ function topLevelBlock(lines, key, from = 0, to = lines.length) {
3107
+ const start = lines.findIndex((line, i) => i >= from && i < to && line === `${key}:`);
3108
+ if (start === -1)
3109
+ return undefined;
3110
+ let end = start + 1;
3111
+ while (end < to && (lines[end].startsWith(" ") || lines[end] === ""))
3112
+ end += 1;
3113
+ while (end > start + 1 && lines[end - 1] === "")
3114
+ end -= 1;
3115
+ return [start, end];
3116
+ }
3117
+ /**
3118
+ * The moved `design.yaml` text (#12500 D7): every missing dark key filled with
3119
+ * its old fallback; when `pinned`, the band set holding the resulting dark
3120
+ * values, the dark set set to the light one and the pin line gone; then
3121
+ * `version: 1` after `name:`. Every other line is kept as it is.
3122
+ */
3123
+ function upgradedDesignText(text, pinned) {
3124
+ const lines = text.split("\n");
3125
+ const colors = topLevelBlock(lines, "colors");
3126
+ if (colors !== undefined) {
3127
+ const entry = /^ {2}([a-z-]+): (.+)$/;
3128
+ const raw = new Map();
3129
+ let last = colors[0];
3130
+ for (let i = colors[0] + 1; i < colors[1]; i += 1) {
3131
+ const m = entry.exec(lines[i]);
3132
+ if (m !== null) {
3133
+ raw.set(m[1], m[2]);
3134
+ last = i;
3135
+ }
3136
+ }
3137
+ const added = [];
3138
+ for (const key of DESIGN_COLOR_KEYS_LIGHT) {
3139
+ const dark = `${key}-dark`;
3140
+ const from = OLD_DARK_FALLBACKS[dark];
3141
+ if (!raw.has(dark) && from !== undefined && raw.has(from)) {
3142
+ raw.set(dark, raw.get(from));
3143
+ added.push(` ${dark}: ${raw.get(from)}`);
3144
+ }
3145
+ }
3146
+ if (pinned && !DESIGN_COLOR_KEYS_LIGHT.some((key) => raw.has(`${key}-band`))) {
3147
+ for (const key of DESIGN_COLOR_KEYS_LIGHT) {
3148
+ const dark = raw.get(`${key}-dark`);
3149
+ if (dark !== undefined)
3150
+ added.push(` ${key}-band: ${dark}`);
3151
+ }
3152
+ for (let i = colors[0] + 1; i <= last; i += 1) {
3153
+ const m = entry.exec(lines[i]);
3154
+ const light = m === null ? undefined : raw.get(m[1].replace(/-dark$/, ""));
3155
+ if (m !== null && m[1].endsWith("-dark") && light !== undefined) {
3156
+ lines[i] = ` ${m[1]}: ${light}`;
3157
+ }
3158
+ }
3159
+ for (let i = 0; i < added.length; i += 1) {
3160
+ const m = entry.exec(added[i]);
3161
+ const light = m === null ? undefined : raw.get(m[1].replace(/-dark$/, ""));
3162
+ if (m !== null && m[1].endsWith("-dark") && light !== undefined) {
3163
+ added[i] = ` ${m[1]}: ${light}`;
3164
+ }
3165
+ }
3166
+ }
3167
+ lines.splice(last + 1, 0, ...added);
3168
+ }
3169
+ if (pinned) {
3170
+ const layout = topLevelBlock(lines, "layout");
3171
+ if (layout !== undefined) {
3172
+ const pin = lines.findIndex((line, i) => i > layout[0] && i < layout[1] && PIN_DESIGN_LINE.test(line));
3173
+ if (pin !== -1)
3174
+ lines.splice(pin, 1);
3175
+ }
3176
+ }
3177
+ const name = lines.findIndex((line) => /^name:/.test(line));
3178
+ if (name !== -1)
3179
+ lines.splice(name + 1, 0, "version: 1");
3180
+ return lines.join("\n");
3181
+ }
3182
+ /**
3183
+ * The pinned site's `_site.mdx` (#12500 D7): the `theme:` block with its band
3184
+ * set to the old dark palette and its dark palette set to the light one, and a
3185
+ * `brand:` dark palette set to a copy of its light one, so the root still
3186
+ * matches. `undefined` when there is nothing to change; a string reason when
3187
+ * either block is not in a form this rewrites exactly.
3188
+ */
3189
+ function upgradedSiteText(text, withTheme) {
3190
+ const lines = text.split("\n");
3191
+ const close = lines[0] === "---" ? lines.indexOf("---", 1) : -1;
3192
+ if (close === -1)
3193
+ return undefined;
3194
+ let next = text;
3195
+ // #12477 D6 — a block this run retires is not moved: it is about to go.
3196
+ const theme = withTheme ? topLevelBlock(lines, "theme", 1, close) : undefined;
3197
+ if (theme !== undefined) {
3198
+ const block = `${lines.slice(theme[0], theme[1]).join("\n")}\n`;
3199
+ let parsed;
3200
+ try {
3201
+ parsed = parseSettings(block, SITE_MDX_PATH)["theme"];
3202
+ if (renderThemeBlock(parsed) !== block)
3203
+ parsed = undefined;
3204
+ }
3205
+ catch {
3206
+ parsed = undefined;
3207
+ }
3208
+ // spliceThemeBlock also takes a blank line the block ends on: the block must be all it replaces.
3209
+ if (parsed === undefined || (lines[theme[1]] === "" && theme[1] < close)) {
3210
+ return {
3211
+ reason: "its theme: block is not in the form create-ailk writes, so it was left as it is — the page now follows the visitor's light or dark mode until its colours are changed: set theme.colors.band to its colors.dark and colors.dark to its colors.light",
3212
+ };
3213
+ }
3214
+ const { light, dark, band } = parsed.colors;
3215
+ if (band === undefined) {
3216
+ next = spliceThemeBlock(next, { ...parsed, colors: { light, dark: light, band: dark } }, SITE_MDX_PATH);
3217
+ }
3218
+ }
3219
+ const nextLines = next.split("\n");
3220
+ const nextClose = nextLines.indexOf("---", 1);
3221
+ const brand = topLevelBlock(nextLines, "brand", 1, nextClose);
3222
+ if (brand !== undefined) {
3223
+ const colors = nextLines.findIndex((line, i) => i > brand[0] && i < brand[1] && line === " colors:");
3224
+ if (colors !== -1) {
3225
+ let end = colors + 1;
3226
+ while (end < brand[1] && nextLines[end].startsWith(" "))
3227
+ end += 1;
3228
+ const palette = (mode) => {
3229
+ const at = nextLines.findIndex((line, i) => i > colors && i < end && line === ` ${mode}:`);
3230
+ if (at === -1)
3231
+ return undefined;
3232
+ let stop = at + 1;
3233
+ while (stop < end && nextLines[stop].startsWith(" "))
3234
+ stop += 1;
3235
+ return [at, stop];
3236
+ };
3237
+ const light = palette("light");
3238
+ const dark = palette("dark");
3239
+ const shaped = nextLines.slice(colors + 1, end).every((line) => /^ {4}(?:light|dark):$|^ {6}[A-Za-z]+: \S/.test(line));
3240
+ if (!shaped || (dark !== undefined && light === undefined)) {
3241
+ return {
3242
+ reason: "its brand: colours are not in a form this rewrites, so _site.mdx was left as it is — the page now follows the visitor's light or dark mode until brand.colors.dark is set to brand.colors.light and the theme: block is moved (theme.colors.band to its colors.dark, colors.dark to its colors.light)",
3243
+ };
3244
+ }
3245
+ if (light !== undefined) {
3246
+ const lightLines = nextLines.slice(light[0] + 1, light[1]);
3247
+ const darkLines = dark === undefined ? undefined : nextLines.slice(dark[0] + 1, dark[1]);
3248
+ const sorted = (rows) => [...rows].sort().join("\n");
3249
+ if (darkLines === undefined || sorted(darkLines) !== sorted(lightLines)) {
3250
+ if (dark === undefined)
3251
+ nextLines.splice(light[1], 0, " dark:", ...lightLines);
3252
+ else
3253
+ nextLines.splice(dark[0] + 1, dark[1] - dark[0] - 1, ...lightLines);
3254
+ next = nextLines.join("\n");
3255
+ }
3256
+ }
3257
+ }
3258
+ }
3259
+ return next === text ? undefined : { text: next };
3260
+ }
3261
+ /**
3262
+ * #12500 D7 — move a site's design settings forward, once, after
3263
+ * `moveDesignSettings`. Plan first, then check, then write:
3264
+ *
3265
+ * - **design steps** run only when the root `design.yaml` is a regular file
3266
+ * (a symlink or anything else: a review row and nothing written) with no
3267
+ * top-level `version:` — each missing dark key filled with its old fallback,
3268
+ * then `version: 1` after `name:`;
3269
+ * - **pinned steps** run while the retired pin's texts are present (the
3270
+ * generated `site-chrome.ts` line, or `design.yaml`'s `layout.colorMode:
3271
+ * light`), with or without a `design.yaml`: its band set takes the dark
3272
+ * values and its dark set the light ones; the generator's three pin texts
3273
+ * leave `site-chrome.ts`; and `_site.mdx`'s `theme:` and `brand:` blocks are
3274
+ * moved the same way when they are in the form create-ailk writes, else a
3275
+ * review row and `_site.mdx` untouched (SEC-12500-10).
3276
+ *
3277
+ * The moved `design.yaml` is read as a design before anything is written; when
3278
+ * it does not read, nothing is written and a review row carries the reader's
3279
+ * message. Each file is written only when it is a regular file, not a symlink,
3280
+ * and its real path sits inside the site's (SEC-12500-6); else a review row
3281
+ * names it. Each write replaces the whole file with text read from it.
3282
+ *
3283
+ * `retired` (#12477 D6) is the run's look retirement: a retired
3284
+ * `site-chrome.ts` is still read to decide the pin, so `design.yaml` moves as
3285
+ * on any pinned site, but loses no pin texts, and a retired `theme:` block is
3286
+ * not moved (no review row about it either); the `brand:` step still runs.
3287
+ */
3288
+ export function upgradeDesignSettings(siteDir, retired = new Set()) {
3289
+ const result = { updated: [], review: [] };
3290
+ const at = (rel) => join(siteDir, rel);
3291
+ // ── Plan ──
3292
+ const chromeText = existsSync(at(SITE_CHROME_PATH)) ? readFileSync(at(SITE_CHROME_PATH), "utf8") : undefined;
3293
+ const chromePinned = chromeText?.split("\n").includes(PIN_VALUE_LINE) ?? false;
3294
+ /** A review row that stops the move; on a pinned site it says what the stop costs (the pin no longer holds). */
3295
+ const stop = (reason, sitePinned) => {
3296
+ result.review.push({ path: DESIGN_SETTINGS_FILE, reason: sitePinned ? `${reason}${PIN_NOT_MOVED}` : reason });
3297
+ return result;
3298
+ };
3299
+ let designText;
3300
+ if (entryExists(at(DESIGN_SETTINGS_FILE))) {
3301
+ if (isSymlink(at(DESIGN_SETTINGS_FILE)))
3302
+ return stop(SYMLINK_REASON, chromePinned);
3303
+ if (!lstatSync(at(DESIGN_SETTINGS_FILE)).isFile()) {
3304
+ return stop("not a regular file — update moves a site's settings only in a design.yaml file", chromePinned);
3305
+ }
3306
+ designText = readFileSync(at(DESIGN_SETTINGS_FILE), "utf8");
3307
+ if (designText.split("\n").some((line) => /^version:/.test(line)))
3308
+ designText = undefined;
3309
+ }
3310
+ const designLines = designText?.split("\n") ?? [];
3311
+ const designLayout = topLevelBlock(designLines, "layout");
3312
+ const pinned = chromePinned ||
3313
+ (designLayout !== undefined && designLines.slice(designLayout[0], designLayout[1]).some((line) => PIN_DESIGN_LINE.test(line)));
3314
+ const writes = new Map();
3315
+ if (designText !== undefined) {
3316
+ const moved = upgradedDesignText(designText, pinned);
3317
+ try {
3318
+ readDesignPackageText(moved, at(DESIGN_SETTINGS_FILE));
3319
+ }
3320
+ catch (err) {
3321
+ return stop(`not moved to both colour sets and a design version (#12500) — it does not read as a design: ${err.message}`, pinned);
3322
+ }
3323
+ writes.set(DESIGN_SETTINGS_FILE, moved);
3324
+ }
3325
+ if (pinned && chromeText !== undefined && !retired.has(SITE_CHROME_PATH)) {
3326
+ const unpinned = PIN_CHROME_TEXTS.reduce((text, pin) => text.replace(pin, ""), chromeText);
3327
+ if (unpinned !== chromeText)
3328
+ writes.set(SITE_CHROME_PATH, unpinned);
3329
+ }
3330
+ if (pinned && existsSync(at(SITE_MDX_PATH))) {
3331
+ const site = upgradedSiteText(readFileSync(at(SITE_MDX_PATH), "utf8"), !retired.has(SITE_MDX_PATH));
3332
+ if (site !== undefined && "reason" in site)
3333
+ result.review.push({ path: SITE_MDX_PATH, reason: site.reason });
3334
+ else if (site !== undefined)
3335
+ writes.set(SITE_MDX_PATH, site.text);
3336
+ }
3337
+ // ── Check ──
3338
+ const siteReal = realpathSync(siteDir);
3339
+ for (const rel of [...writes.keys()]) {
3340
+ const path = at(rel);
3341
+ const inside = !isSymlink(path) && lstatSync(path).isFile() && realpathSync(path).startsWith(siteReal + sep);
3342
+ if (!inside) {
3343
+ writes.delete(rel);
3344
+ result.review.push({
3345
+ path: rel,
3346
+ reason: "not written — a symlink, or a path outside the site; update writes only regular files inside it, so this file still holds what #12500 moves",
3347
+ });
3348
+ }
3349
+ }
3350
+ // ── Effects ──
3351
+ for (const [rel, text] of writes) {
3352
+ writeFileSync(at(rel), text);
3353
+ result.updated.push(rel);
3354
+ }
3355
+ return result;
3356
+ }
3357
+ // ── #12477 D6 — the look files retire once the hub's read carries the look ─
3358
+ /** The hub's site read, the one the deployed site renders from. */
3359
+ const SITE_CONFIG_PATH = "/v1/content/site-config";
3360
+ /** The site read's bounds: one request, 10 s, 2 MB streamed. */
3361
+ const LOOK_CHECK_TIMEOUT_MS = 10_000;
3362
+ const LOOK_CHECK_MAX_BYTES = 2 * 1024 * 1024;
3363
+ /** The header the site's own read carries its spoke key in. */
3364
+ const LOOK_SPOKE_KEY_HEADER = "x-ailk-spoke-key";
3365
+ /** The site's navigation config: while it is there, #12403's import reads `site-chrome.ts`'s footer. */
3366
+ const NAV_CONFIG_FILE = "apps/web/lib/nav-config.ts";
3367
+ /** The readers of the retired files a site's own copy may still carry. */
3368
+ const LOOK_FILE_READERS = [
3369
+ "apps/web/app/[locale]/layout.tsx",
3370
+ "apps/web/app/not-found.tsx",
3371
+ "apps/web/lib/deck-page.ts",
3372
+ "apps/web/lib/site-theme-head.ts",
3373
+ "apps/web/site-pages.config.tsx",
3374
+ ];
3375
+ const LOOK_REFUSAL_HEAD = "this release retires the site's look files (content/_site.mdx theme:, apps/web/lib/site-chrome.ts, apps/web/lib/site-fonts.ts) — the site's look comes only from its hub design record.";
3376
+ function refuseLook(message) {
3377
+ throw new UpdateRefusedError(`${message} Nothing was written.`);
3378
+ }
3379
+ /** At most `max` bytes of `res`'s body, streamed; `undefined` past the bound. */
3380
+ async function boundedText(res, max) {
3381
+ if (res.body === null)
3382
+ return "";
3383
+ const reader = res.body.getReader();
3384
+ const chunks = [];
3385
+ let total = 0;
3386
+ for (;;) {
3387
+ const { done, value } = await reader.read();
3388
+ if (done)
3389
+ break;
3390
+ total += value.byteLength;
3391
+ if (total > max) {
3392
+ await reader.cancel();
3393
+ return undefined;
3394
+ }
3395
+ chunks.push(value);
3396
+ }
3397
+ return Buffer.concat(chunks).toString("utf8");
3398
+ }
3399
+ /** A host as printed: a valid hostname, else `<unexpected>`. */
3400
+ function printableHost(location) {
3401
+ try {
3402
+ const host = new URL(location ?? "").hostname;
3403
+ return /^[A-Za-z0-9.-]{1,253}$/.test(host) ? host : "<unexpected>";
3404
+ }
3405
+ catch {
3406
+ return "<unexpected>";
3407
+ }
3408
+ }
3409
+ /**
3410
+ * Steps 1–3 (#12477 D6), before any write: `undefined` when the site carries
3411
+ * none of the three look sources; else the hub's read for the site must
3412
+ * carry its look — one bounded GET of `<from>/v1/content/site-config` — or
3413
+ * the run is refused, naming what was seen.
3414
+ */
3415
+ async function checkLookSource(targetDir, look, isSpoke, env, fetchImpl) {
3416
+ // Step 1 — nothing to retire: no fetch, no line, whatever the flag says. A
3417
+ // site-chrome.ts an earlier passing run kept for the navigation import —
3418
+ // nav-config.ts still there, and no site file importing it any more — is
3419
+ // not one: step 4 would only hold it again, so it never refuses a run. One
3420
+ // a file still imports is a look source: the site still renders from it.
3421
+ const navigationHeld = existsSync(join(targetDir, ...NAV_CONFIG_FILE.split("/"))) &&
3422
+ lookFileImporters(targetDir, SITE_CHROME_PATH, siteTextOnDisk(targetDir)).length === 0;
3423
+ const sources = retiredLookSources(targetDir).filter((path) => !(navigationHeld && path === SITE_CHROME_PATH));
3424
+ if (sources.length === 0)
3425
+ return undefined;
3426
+ // Step 2 — no flag.
3427
+ if (look === undefined) {
3428
+ refuseLook(`${LOOK_REFUSAL_HEAD} Import it first (#12476's runbook), then run create-ailk update --look-from <the API origin the site reads>.`);
3429
+ }
3430
+ // Step 3 — the flag's origin, bound on a spoke to the hub its scaffold recorded.
3431
+ let origin;
3432
+ try {
3433
+ origin = normalizeHubUrl(look.from);
3434
+ }
3435
+ catch (err) {
3436
+ if (!(err instanceof TopologyError))
3437
+ throw err;
3438
+ refuseLook("--look-from must be an https: origin (http: only on a loopback host) with no path, query, fragment or credentials.");
3439
+ }
3440
+ if (isSpoke) {
3441
+ const mismatch = spokeOriginMismatch(targetDir, origin);
3442
+ if (mismatch !== undefined)
3443
+ refuseLook(`--look-from: ${mismatch}.`);
3444
+ }
3445
+ // A spoke key goes only to the origin bound above; a hub site sends none.
3446
+ const spokeKey = isSpoke ? env[SPOKE_KEY_ENV_VAR]?.trim() || undefined : undefined;
3447
+ let res;
3448
+ let text;
3449
+ try {
3450
+ res = await fetchImpl(`${origin}${SITE_CONFIG_PATH}`, {
3451
+ method: "GET",
3452
+ headers: {
3453
+ accept: "application/json",
3454
+ "cache-control": "no-cache",
3455
+ ...(spokeKey !== undefined && { [LOOK_SPOKE_KEY_HEADER]: spokeKey }),
3456
+ },
3457
+ redirect: "manual",
3458
+ signal: AbortSignal.timeout(LOOK_CHECK_TIMEOUT_MS),
3459
+ });
3460
+ text = res.status === 200 ? await boundedText(res, LOOK_CHECK_MAX_BYTES) : "";
3461
+ }
3462
+ catch {
3463
+ refuseLook(`the hub at ${origin} did not answer its site read within ${LOOK_CHECK_TIMEOUT_MS / 1000} s.`);
3464
+ }
3465
+ if (res.status >= 300 && res.status < 400) {
3466
+ refuseLook(`the hub at ${origin} answered its site read with a redirect to ${printableHost(res.headers.get("location"))}, which is not followed.`);
3467
+ }
3468
+ if (res.status === 401) {
3469
+ refuseLook(spokeKey !== undefined
3470
+ ? `the hub at ${origin} refused the site's spoke key — set AILK_SPOKE_KEY to the site's own.`
3471
+ : `the hub at ${origin} does not serve this site's own read without a spoke key — it has spokes or several workspaces; this site keeps its look files until the hub's own site read resolves its workspace (#12477 spec § 5.3, follow-up #12570).`);
3472
+ }
3473
+ if (res.status !== 200)
3474
+ refuseLook(`the hub at ${origin} answered its site read ${res.status}.`);
3475
+ if (text === undefined)
3476
+ refuseLook(`the hub at ${origin} answered its site read with more than 2 MB.`);
3477
+ let body;
3478
+ try {
3479
+ body = JSON.parse(text);
3480
+ }
3481
+ catch {
3482
+ refuseLook(`the hub at ${origin} answered its site read with a body that is not JSON.`);
3483
+ }
3484
+ const data = isPlainObject(body) && body["ok"] === true ? body["data"] : undefined;
3485
+ if (!isPlainObject(data) || !Object.hasOwn(data, "design")) {
3486
+ refuseLook(`the hub at ${origin} answered its site read with no site config.`);
3487
+ }
3488
+ const design = data["design"];
3489
+ if (design === null)
3490
+ refuseLook(`the hub at ${origin} holds no design record for this site — import it first (#12476's runbook).`);
3491
+ if (!isPlainObject(design))
3492
+ refuseLook(`the hub at ${origin} answered its site read with a design that is not a record.`);
3493
+ if (!isPlainObject(design["settings"])) {
3494
+ refuseLook(`the hub's design record for this site holds no look yet — import it first (#12476's runbook).`);
3495
+ }
3496
+ const version = design["version"];
3497
+ if (!Number.isInteger(version))
3498
+ refuseLook(`the hub at ${origin} answered its site read with a design version that is not a whole number.`);
3499
+ const record = isPlainObject(design["record"]) ? design["record"] : {};
3500
+ const from = isPlainObject(record["from"])
3501
+ ? { look: printable(record["from"]["look"], /^[a-z0-9-]{1,40}$/), version: printable(record["from"]["version"], /^[0-9A-Za-z.+-]{1,40}$/) }
3502
+ : null;
3503
+ return { origin, version: version, from };
3504
+ }
3505
+ /**
3506
+ * The site files whose text, as `textOf` answers it (`undefined`: the file is
3507
+ * not there), imports the retired look file `file`: by a relative or `@/`
3508
+ * specifier, or — a `paths` alias of the site's own resolving past both —
3509
+ * any other specifier ending in its `lib/` name. Every source file under
3510
+ * `apps/web` is read, the known readers first.
3511
+ */
3512
+ function lookFileImporters(targetDir, file, textOf) {
3513
+ const webFiles = [
3514
+ ...new Set([
3515
+ ...LOOK_FILE_READERS,
3516
+ ...[...listFilesUnder(targetDir, ["apps/web"])].filter((rel) => SOURCE_FILE.test(rel)),
3517
+ ]),
3518
+ ];
3519
+ const target = new Set([file]);
3520
+ const stem = file.replace(/^apps\/web\/lib\//, "").replace(/\.ts$/, "");
3521
+ return webFiles.filter((path) => {
3522
+ if (path === file)
3523
+ return false;
3524
+ const text = textOf(path);
3525
+ if (text === undefined)
3526
+ return false;
3527
+ if (importedHeldFiles(path, text, target).length > 0)
3528
+ return true;
3529
+ for (const match of codeLines(text.split("\n")).join("\n").matchAll(IMPORT_SPECIFIER)) {
3530
+ const specifier = match[1] ?? match[2] ?? match[3] ?? "";
3531
+ if (!isLocal(path, specifier) && new RegExp(`(^|/)lib/${stem}(\\.[cm]?[jt]sx?)?$`).test(specifier))
3532
+ return true;
3533
+ }
3534
+ return false;
3535
+ });
3536
+ }
3537
+ /** A site file's text on disk, or `undefined` when it is not there. */
3538
+ function siteTextOnDisk(targetDir) {
3539
+ return (path) => {
3540
+ const abs = join(targetDir, ...path.split("/"));
3541
+ return existsSync(abs) ? readFileSync(abs, "utf8") : undefined;
3542
+ };
3543
+ }
3544
+ /**
3545
+ * Step 4's plan (#12477 D6), made before any write over the run's own plan:
3546
+ * the run's retired set — each source step 4 removes — and a review row for
3547
+ * each it holds instead. `postRunText` answers a site file's text as this run
3548
+ * leaves it (`undefined` when the file will not be there).
3549
+ */
3550
+ function planLookRetirement(targetDir, postRunText) {
3551
+ const retired = new Set();
3552
+ const review = [];
3553
+ const siteReal = realpathSync(targetDir);
3554
+ const insideRegular = (rel) => {
3555
+ const abs = join(targetDir, ...rel.split("/"));
3556
+ return lstatSync(abs).isFile() && realpathSync(dirname(abs)).startsWith(siteReal + sep);
3557
+ };
3558
+ for (const file of retiredLookSources(targetDir)) {
3559
+ if (!insideRegular(file)) {
3560
+ review.push({ path: file, reason: "kept — not a regular file inside the site" });
3561
+ continue;
3562
+ }
3563
+ if (file === SITE_MDX_PATH) {
3564
+ const text = readFileSync(join(targetDir, ...file.split("/")), "utf8");
3565
+ if (!themeBlockRemovable(text, file) || carriesThemeKey(removeThemeBlock(text, file))) {
3566
+ review.push({ path: file, reason: "kept — its theme: key is not in the form create-ailk writes; remove it by hand" });
3567
+ }
3568
+ else {
3569
+ retired.add(file);
3570
+ }
3571
+ continue;
3572
+ }
3573
+ const importers = lookFileImporters(targetDir, file, postRunText);
3574
+ if (importers.length > 0) {
3575
+ review.push({ path: file, reason: `kept — still imported by ${importers.sort().join(", ")}` });
3576
+ continue;
3577
+ }
3578
+ if (file === SITE_CHROME_PATH && postRunText(NAV_CONFIG_FILE) !== undefined) {
3579
+ review.push({
3580
+ path: file,
3581
+ reason: "kept — the navigation import reads its footer until nav-config.ts is retired (#12404)",
3582
+ });
3583
+ continue;
3584
+ }
3585
+ retired.add(file);
3586
+ }
3587
+ return { retired, review };
3588
+ }
3589
+ /** Step 4's effects (#12477 D6), the run's last writes: each retired source removed. */
3590
+ function applyLookRetirement(targetDir, retired) {
3591
+ const removed = [];
3592
+ const updated = [];
3593
+ const review = [];
3594
+ for (const file of [SITE_CHROME_PATH, SITE_FONTS_PATH]) {
3595
+ if (!retired.has(file))
3596
+ continue;
3597
+ rmSync(join(targetDir, ...file.split("/")));
3598
+ removed.push(file);
3599
+ }
3600
+ if (retired.has(SITE_MDX_PATH)) {
3601
+ const abs = join(targetDir, ...SITE_MDX_PATH.split("/"));
3602
+ const text = readFileSync(abs, "utf8");
3603
+ const next = removeThemeBlock(text, SITE_MDX_PATH);
3604
+ // Read as the run's earlier steps left it; the block must still be the one the plan checked.
3605
+ if (next !== text && !carriesThemeKey(next)) {
3606
+ writeFileSync(abs, next);
3607
+ updated.push(SITE_MDX_PATH);
3608
+ }
3609
+ else {
3610
+ review.push({ path: SITE_MDX_PATH, reason: "kept — its theme: key is not in the form create-ailk writes; remove it by hand" });
3611
+ }
3612
+ }
3613
+ return { removed, updated, review };
3614
+ }
2923
3615
  /** The printed report (D9): one section per non-empty list, in order. */
2924
3616
  export function formatUpdateReport(result) {
2925
3617
  const lines = [`[create-ailk] update → ${result.targetDir}`];
3618
+ if (result.added.includes(DESIGN_SETTINGS_FILE)) {
3619
+ lines.push(`Design settings: ${DESIGN_GUIDE_FILE} → ${DESIGN_SETTINGS_FILE} (#12468)`);
3620
+ }
2926
3621
  if (result.backfilled !== undefined) {
2927
3622
  lines.push(`Record written from ${result.backfilled.version}: ${result.backfilled.files} files`);
2928
3623
  }
@@ -2940,6 +3635,11 @@ export function formatUpdateReport(result) {
2940
3635
  if (result.cliPin !== undefined) {
2941
3636
  lines.push(`create-ailk pin moved: ${result.cliPin.from} → ${result.cliPin.to}`);
2942
3637
  }
3638
+ // #12477 D6 step 5 — what replaced the retired look files.
3639
+ if (result.look !== undefined) {
3640
+ const { look } = result;
3641
+ lines.push(`Look: from the hub (version ${look.version} at ${look.origin}) — ${look.from === null ? "its own look." : `look "${look.from.look}" ${look.from.version}.`}`);
3642
+ }
2943
3643
  // #11147 — why a moved file's bytes were not the site's.
2944
3644
  const notes = new Map();
2945
3645
  for (const { path, version } of result.staleCopies ?? [])
@@ -3059,14 +3759,32 @@ export function formatUpdateReport(result) {
3059
3759
  export const UPDATE_HELP = `create-ailk update — bring template fixes into a site's copied app code.
3060
3760
 
3061
3761
  Usage:
3062
- create-ailk update [<target-dir>]
3762
+ create-ailk update [<target-dir>] [--look-from <origin>]
3063
3763
 
3064
3764
  Arguments:
3065
3765
  <target-dir> The existing site. Defaults to the current dir.
3066
3766
 
3067
3767
  Options:
3768
+ --look-from <origin> The API origin the site reads its config from. A
3769
+ site still carrying its look files
3770
+ (content/_site.mdx theme:, apps/web/lib/site-chrome.ts,
3771
+ apps/web/lib/site-fonts.ts) needs it: they are
3772
+ removed only once that origin's site read carries
3773
+ the site's look (imported into its hub design
3774
+ record). On a spoke it must be the AILK_API_URL
3775
+ apps/web/.env.local sets, and the read carries
3776
+ AILK_SPOKE_KEY; on a hub it carries no key.
3068
3777
  --help, -h Print this message.
3069
3778
 
3779
+ A site that still carries its look files is refused with no --look-from,
3780
+ naming the import: the site's look comes only from its hub design record.
3781
+ With it, one GET of <origin>/v1/content/site-config (no redirect, 10 s, 2 MB)
3782
+ must answer a design record holding a look; then the two files are removed and
3783
+ the theme: block leaves content/_site.mdx, every other byte kept, as the run's
3784
+ last writes, and the report names the look that replaced them. A file is kept
3785
+ instead, and listed under "Needs review", while a file the run leaves still
3786
+ imports it, or (site-chrome.ts) while apps/web/lib/nav-config.ts stays.
3787
+
3070
3788
  Reads .ailk-template-files.json (written beside .ailk-site-manifest.json by
3071
3789
  every template scaffold) to tell an untouched copy from an edit. An
3072
3790
  untouched apps/web, apps/api or apps/mcp file, or a root tools/jest file the
@@ -3160,17 +3878,28 @@ and review the diff after.
3160
3878
  `;
3161
3879
  /** Parse the argv AFTER the `update` word. Strict `node:util` parseArgs, like `parseAdoptArgs`. */
3162
3880
  export function parseUpdateArgs(argv) {
3163
- const parsed = parseArgs({
3164
- args: argv,
3165
- strict: true,
3166
- allowPositionals: true,
3167
- options: {
3168
- help: { type: "boolean", default: false, short: "h" },
3169
- },
3170
- });
3881
+ let parsed;
3882
+ try {
3883
+ parsed = parseArgs({
3884
+ args: argv,
3885
+ strict: true,
3886
+ allowPositionals: true,
3887
+ options: {
3888
+ "look-from": { type: "string" },
3889
+ help: { type: "boolean", default: false, short: "h" },
3890
+ },
3891
+ });
3892
+ }
3893
+ catch (err) {
3894
+ throw new ParseError(`update: ${err.message}`);
3895
+ }
3171
3896
  const [target, ...rest] = parsed.positionals;
3172
3897
  if (rest.length > 0) {
3173
3898
  throw new ParseError(`update takes at most one target directory, got ${parsed.positionals.length} arguments`);
3174
3899
  }
3175
- return { target, help: parsed.values.help === true };
3900
+ const lookFrom = parsed.values["look-from"];
3901
+ if (lookFrom !== undefined && lookFrom.trim() === "") {
3902
+ throw new ParseError("update: --look-from needs an origin");
3903
+ }
3904
+ return { target, lookFrom, help: parsed.values.help === true };
3176
3905
  }