create-ailk 0.40.1 → 0.40.2

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 (57) hide show
  1. package/README.md +26 -4
  2. package/dist/add-module.d.ts +2 -1
  3. package/dist/add-module.js +17 -1
  4. package/dist/cutover.d.ts +7 -3
  5. package/dist/cutover.js +8 -3
  6. package/dist/lib/declared-env.d.ts +5 -1
  7. package/dist/lib/declared-env.js +6 -1
  8. package/dist/lib/env-catalog.d.ts +3 -2
  9. package/dist/lib/env-catalog.js +4 -8
  10. package/dist/module-architecture.js +0 -1
  11. package/dist/programmatic.js +18 -9
  12. package/dist/remove-module.js +1 -1
  13. package/dist/seam-refresh.d.ts +60 -0
  14. package/dist/seam-refresh.js +214 -0
  15. package/dist/spoke-checkout.d.ts +12 -3
  16. package/dist/spoke-checkout.js +14 -5
  17. package/dist/sync-routes.d.ts +10 -1
  18. package/dist/sync-routes.js +61 -6
  19. package/dist/template-record.d.ts +14 -2
  20. package/dist/template-record.js +60 -22
  21. package/dist/topology.js +3 -4
  22. package/dist/update.d.ts +13 -1
  23. package/dist/update.js +100 -8
  24. package/package.json +3 -3
  25. package/templates/.env.example +6 -0
  26. package/templates/.github/workflows/ci.yml +3 -0
  27. package/templates/apps/api/.env.example +12 -0
  28. package/templates/apps/api/CLAUDE.md +10 -7
  29. package/templates/apps/mcp/CLAUDE.md +25 -5
  30. package/templates/apps/web/.env.example +7 -1
  31. package/templates/apps/web/CLAUDE.md +29 -13
  32. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
  33. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +10 -3
  34. package/templates/apps/web/app/llms.txt/route.ts +13 -3
  35. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +15 -7
  36. package/templates/apps/web/auth.config.tsx +2 -0
  37. package/templates/apps/web/auth.ts +28 -4
  38. package/templates/apps/web/jest.config.cjs +1 -1
  39. package/templates/apps/web/lib/__tests__/auth-email.test.ts +21 -0
  40. package/templates/apps/web/lib/__tests__/docs-path.test.ts +20 -2
  41. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +17 -10
  42. package/templates/apps/web/lib/__tests__/relay.test.ts +127 -12
  43. package/templates/apps/web/lib/__tests__/server-api.test.ts +72 -7
  44. package/templates/apps/web/lib/__tests__/services-path.test.ts +22 -1
  45. package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +33 -5
  46. package/templates/apps/web/lib/auth-email.ts +19 -0
  47. package/templates/apps/web/lib/docs-path.ts +1 -1
  48. package/templates/apps/web/lib/hub-site-config.ts +11 -8
  49. package/templates/apps/web/lib/mcp-oauth.ts +123 -17
  50. package/templates/apps/web/lib/relay.ts +48 -9
  51. package/templates/apps/web/lib/server-api.ts +37 -4
  52. package/templates/apps/web/lib/services-path.ts +1 -1
  53. package/templates/apps/web/messages/en.json +10 -8
  54. package/templates/apps/web/middleware.ts +4 -2
  55. package/templates/apps/web/src/lib/routes.ts +13 -0
  56. package/templates/tools/declared-env.ts +6 -1
  57. package/versions.json +51 -51
package/README.md CHANGED
@@ -545,6 +545,19 @@ merge-file` against the recorded version's own copy as the base. A clean
545
545
  site's own: skipped as a site edit, never overwritten, and counted under
546
546
  **Held as site edits, not in the record**.
547
547
 
548
+ - A topology seam — `apps/web/lib/topology.generated.ts`, the `(authed)`
549
+ group's `signed-out-gate.generated.tsx`, `apps/web/lib/api-origin.generated.ts`
550
+ and `apps/mcp/src/lib/topology.generated.ts` — is rendered again for the
551
+ topology and sign-in mode `.ailk-site-manifest.json` records, when its bytes
552
+ are still the render the record's `seams` entry names (the scaffold records
553
+ each one). Reported as **Regenerated**. A seam whose bytes differ from that
554
+ render was edited by hand: it is left as it is and listed under **Needs
555
+ review**. A site scaffolded before create-ailk recorded its seams has no
556
+ `seams` entry, so its seams are listed under **Needs review** too, unless
557
+ already current; delete one the site never edited and run `update` again to
558
+ take the render. `sync-routes --apply` regenerates a spoke's web seam and
559
+ gate the same way, so a synced route never imports a stale seam.
560
+
548
561
  A file outside the gated-off surfaces and spoke exclusions the site's scope
549
562
  no longer covers is **Skipped**, as is one that exists on disk but was never
550
563
  recorded (a module bundle's own file, say) when its bytes match no template
@@ -617,6 +630,16 @@ check by copying `tools/check-mdx-body.ts`, `tools/mdx-braces.ts` and
617
630
  `"mdx-body:check": "tsx tools/check-mdx-body.ts"` to its `package.json`
618
631
  scripts and `preflight`.
619
632
 
633
+ **An off-template site (#9559).** A site whose copied app code matches no
634
+ single create-ailk version can be declared off-template: its
635
+ `.ailk-template-files.json` carries an `offTemplate` string —
636
+ `"<decider>, <YYYY-MM-DD>, <reason>"` — and an empty `files`. Every file under
637
+ `apps/` is then site-owned and upgrades are hand-ported. `update`,
638
+ `sync-routes --apply`, `add-route`, `remove-module` and `add-module` each read
639
+ the record first and refuse such a site by name ("declares this site
640
+ off-template"), before any write. The template-guard hook finds no row for any
641
+ path in that record, so it passes every edit silently.
642
+
620
643
  ### Adopting an existing site
621
644
 
622
645
  A site that create-ailk did not scaffold, or that was scaffolded before
@@ -668,10 +691,9 @@ included). A second run is refused with exit 2 and the manifest untouched.
668
691
 
669
692
  `create-ailk update` (above) brings the copied `apps/web`, `apps/api` and
670
693
  `apps/mcp` code forward on its own. What it leaves alone still needs a
671
- per-version review: the generated seams, the declared-env check
672
- (`tools/declared-env.ts`, `tools/check-declared-env.ts`) and the one-line
673
- route re-exports are regenerated, not recorded, so `update` never touches
674
- them; everything else is content, or code that arrives through a
694
+ per-version review: the declared-env check (`tools/declared-env.ts`,
695
+ `tools/check-declared-env.ts`) and the one-line route re-exports are
696
+ regenerated, not recorded, so `update` never touches them; everything else is content, or code that arrives through a
675
697
  `@working-theory/*` package bump. Moving a spoke to a new create-ailk
676
698
  version still means:
677
699
 
@@ -72,7 +72,8 @@ export interface AddModuleResult {
72
72
  /**
73
73
  * Merge one module's bundle onto an existing site, sync its routes,
74
74
  * regenerate `architecture.yaml` and the nav, then append the module's pages
75
- * to the site's roster. Every refusal — an unreadable header or roster, a
75
+ * to the site's roster. Every refusal — an off-template or unreadable
76
+ * template record (#9559), an unreadable header or roster, a
76
77
  * module row no shipped manifest carries, a patch outside the allowlist, a
77
78
  * patch conflict, an unsafe bundle — throws before the first write (the header
78
79
  * and roster are read first; `extractModuleBundle` validates and computes
@@ -44,6 +44,7 @@ import { SITE_ROSTER_PATH, moduleRosterRows, planRosterAppend, readSiteRoster, s
44
44
  import { spokeCheckoutSite, spokeEnvRowOptions, writeSpokeCheckoutSlice, } from "./spoke-checkout.js";
45
45
  import { MODULE_SURFACES, NAV_CONFIG_PATH, isRemovedPublicRoutePath, isUnservedSurfaceContent, isUnservedSurfaceRoute, readNavConfigStamp, renderNavConfig, resolveSurfaces, } from "./surfaces.js";
46
46
  import { syncRoutes } from "./sync-routes.js";
47
+ import { TEMPLATE_RECORD_PATH, TemplateRecordError, parseTemplateRecord, } from "./template-record.js";
47
48
  import { TopologyError, isSpokeExcluded, readSiteTopology, readSpokeShape, spokeDestination, spokeModuleRefusal, } from "./topology.js";
48
49
  /**
49
50
  * The site's topology for add-module (#7426 D13): an unreadable manifest is a
@@ -112,7 +113,8 @@ export function checkPlusConfigPatches(patches) {
112
113
  /**
113
114
  * Merge one module's bundle onto an existing site, sync its routes,
114
115
  * regenerate `architecture.yaml` and the nav, then append the module's pages
115
- * to the site's roster. Every refusal — an unreadable header or roster, a
116
+ * to the site's roster. Every refusal — an off-template or unreadable
117
+ * template record (#9559), an unreadable header or roster, a
116
118
  * module row no shipped manifest carries, a patch outside the allowlist, a
117
119
  * patch conflict, an unsafe bundle — throws before the first write (the header
118
120
  * and roster are read first; `extractModuleBundle` validates and computes
@@ -121,6 +123,20 @@ export function checkPlusConfigPatches(patches) {
121
123
  export async function applyModuleToScaffold(opts) {
122
124
  const targetAbs = resolve(opts.targetDir);
123
125
  const archPath = join(targetAbs, "architecture.yaml");
126
+ // #9559 D2 — the record is parsed here, before the bundle lands, as
127
+ // `syncRoutes({ apply: true })` parses it after: an off-template (or any
128
+ // unreadable) record refuses with the tree untouched.
129
+ const recordPath = join(targetAbs, TEMPLATE_RECORD_PATH);
130
+ if (existsSync(recordPath)) {
131
+ try {
132
+ parseTemplateRecord(readFileSync(recordPath, "utf8"), { onUnrecordable: () => { } });
133
+ }
134
+ catch (err) {
135
+ if (err instanceof TemplateRecordError)
136
+ throw new AddModuleRefusedError(err.message);
137
+ throw err;
138
+ }
139
+ }
124
140
  // #7426 D13 — a spoke stays a spoke: a module it does not admit is refused
125
141
  // before the first write, and an admitted one lands through the spoke
126
142
  // filter. `mcp` follows whether the spoke still carries apps/mcp, and the
package/dist/cutover.d.ts CHANGED
@@ -11,8 +11,8 @@ export declare class CutoverRefusedError extends Error {
11
11
  readonly exitCode = 2;
12
12
  constructor(message: string);
13
13
  }
14
- /** A spawned command, no shell: its status and captured stdout. */
15
- export type Runner = (command: string, args: string[], options: {
14
+ /** A spawned command, no shell: its status and captured stdout. Only `vercel` and `git` are ever spawned. */
15
+ export type Runner = (command: "vercel" | "git", args: string[], options: {
16
16
  cwd: string;
17
17
  input?: string;
18
18
  }) => {
@@ -20,7 +20,11 @@ export type Runner = (command: string, args: string[], options: {
20
20
  stdout: string;
21
21
  error?: string;
22
22
  };
23
- /** The default runner: `spawnSync` with no shell, stdout piped, stderr shown. */
23
+ /**
24
+ * The default runner: `spawnSync` with no shell, stdout piped, stderr shown.
25
+ * Each binary is named literally at its spawn, never passed through a
26
+ * variable, so the spawn allowlist in `__tests__/security.test.ts` reads it.
27
+ */
24
28
  export declare const spawnRunner: Runner;
25
29
  /** Every step's collaborator; a test injects fakes, the CLI takes the defaults. */
26
30
  export interface CutoverDeps {
package/dist/cutover.js CHANGED
@@ -58,15 +58,20 @@ export class CutoverRefusedError extends Error {
58
58
  this.name = "CutoverRefusedError";
59
59
  }
60
60
  }
61
- /** The default runner: `spawnSync` with no shell, stdout piped, stderr shown. */
61
+ /**
62
+ * The default runner: `spawnSync` with no shell, stdout piped, stderr shown.
63
+ * Each binary is named literally at its spawn, never passed through a
64
+ * variable, so the spawn allowlist in `__tests__/security.test.ts` reads it.
65
+ */
62
66
  export const spawnRunner = (command, args, options) => {
63
- const result = spawnSync(command, args, {
67
+ const spawnOptions = {
64
68
  cwd: options.cwd,
65
69
  encoding: "utf8",
66
70
  shell: false,
67
71
  ...(options.input !== undefined && { input: options.input }),
68
72
  stdio: [options.input !== undefined ? "pipe" : "ignore", "pipe", "inherit"],
69
- });
73
+ };
74
+ const result = command === "git" ? spawnSync("git", args, spawnOptions) : spawnSync("vercel", args, spawnOptions);
70
75
  return {
71
76
  status: result.status,
72
77
  stdout: result.stdout ?? "",
@@ -1,4 +1,8 @@
1
- /** Names the platform sets, which need no row (D4). Fixed: a site cannot extend it. */
1
+ /**
2
+ * Names the platform sets, which need no row (D4). Fixed: a site cannot extend it.
3
+ * `__NEXT_RELATIVE_DIST_DIR` is Next's own: it sets it for the build it runs, and
4
+ * `apps/web/lib/served-pages.ts` reads it to find the build's routes manifest.
5
+ */
2
6
  export declare const PLATFORM_ENV_NAMES: readonly string[];
3
7
  /** Every name with one of these prefixes is a platform name too (D4). */
4
8
  export declare const PLATFORM_ENV_PREFIXES: readonly string[];
@@ -26,11 +26,16 @@
26
26
  */
27
27
  import { existsSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
28
28
  import { join } from "node:path";
29
- /** Names the platform sets, which need no row (D4). Fixed: a site cannot extend it. */
29
+ /**
30
+ * Names the platform sets, which need no row (D4). Fixed: a site cannot extend it.
31
+ * `__NEXT_RELATIVE_DIST_DIR` is Next's own: it sets it for the build it runs, and
32
+ * `apps/web/lib/served-pages.ts` reads it to find the build's routes manifest.
33
+ */
30
34
  export const PLATFORM_ENV_NAMES = [
31
35
  "NODE_ENV",
32
36
  "NEXT_RUNTIME",
33
37
  "NEXT_PHASE",
38
+ "__NEXT_RELATIVE_DIST_DIR",
34
39
  "CI",
35
40
  "PORT",
36
41
  "VERCEL",
@@ -6,8 +6,9 @@
6
6
  *
7
7
  * One plain sentence per name, drawn from the `.env.example` comments
8
8
  * (`apps/web`, `apps/mcp`, the repo root) where they exist. The keys are
9
- * exactly the non-platform names this monorepo's `apps/web` and `apps/mcp`
10
- * read: `__tests__/check-declared-env.test.ts` scans both with the same
9
+ * exactly the non-platform names this monorepo's spoke-carried trees read
10
+ * (`apps/web`, `apps/mcp`, and the packages a spoke carries by npm that the
11
+ * test lists): `__tests__/check-declared-env.test.ts` scans them with the same
11
12
  * scanner and fails on a name with no entry or an entry nothing reads, so a
12
13
  * new env read in a spoke-carried app cannot ship undescribed. A
13
14
  * `NEXT_PUBLIC_*` name is inlined into the browser bundle, so it is never a
@@ -1,4 +1,8 @@
1
1
  export const ENV_CATALOG = {
2
+ AILK_ADMIN_URL: {
3
+ description: "Optional. The hub Admin's absolute https URL, where team invitations are accepted; unset uses admin.<this site's host>.",
4
+ secret: false,
5
+ },
2
6
  AILK_API_URL: {
3
7
  description: "The hub API origin this site's server calls (forms, flows, listings). Server-only; never NEXT_PUBLIC_.",
4
8
  secret: false,
@@ -171,10 +175,6 @@ export const ENV_CATALOG = {
171
175
  description: 'Set to "true" or "1" for an MCP HTTP transport with no sessions, which any instance can answer; "false" or "0" keeps sessions in one process. Unset means stateless on Vercel (src/app.ts) and stateful on a port (src/index.ts).',
172
176
  secret: false,
173
177
  },
174
- MCP_OAUTH_ISSUER: {
175
- description: 'Which MCP authorization server\'s OAuth tokens the API honours: unset for the site\'s own apps/web, "admin" on a hub whose MCP server names the Admin (#10912). A malformed value refuses every OAuth token.',
176
- secret: false,
177
- },
178
178
  MCP_PUBLIC_HTTP_URL: {
179
179
  description: "The public URL of the MCP HTTP transport (apps/mcp's `/mcp`), advertised by /.well-known/mcp.json; with BETTER_AUTH_URL it turns on the OAuth metadata. Set by create-ailk provision-env.",
180
180
  secret: false,
@@ -227,10 +227,6 @@ export const ENV_CATALOG = {
227
227
  description: "The site name shown where the site's content files cannot be read (the OG image, the admin pages).",
228
228
  secret: false,
229
229
  },
230
- NEXT_PUBLIC_SITE_WORDMARK: {
231
- description: "The wordmark the generated OG image shows.",
232
- secret: false,
233
- },
234
230
  NEXT_PUBLIC_THEME_COOKIE_NAME: {
235
231
  description: "The cookie the colour-mode choice is stored in; defaults to ailk-theme.",
236
232
  secret: false,
@@ -1877,7 +1877,6 @@ export const EXCLUDE_TEMPLATE_DIRS = [
1877
1877
  "apps/web/app/[locale]/(authed)/account/artifacts/__tests__",
1878
1878
  "apps/web/app/[locale]/(authed)/account/billing/__tests__",
1879
1879
  "apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__",
1880
- "apps/web/app/[locale]/(authed)/account/invitations/[invitationId]/__tests__",
1881
1880
  "apps/web/app/[locale]/(authed)/account/privacy/__tests__",
1882
1881
  "apps/web/app/[locale]/(authed)/account/security/__tests__",
1883
1882
  // #11251 (ADR 0040 phase 3) — the flows pages ship in
@@ -40,17 +40,18 @@ import { normalizeModules } from "./module-architecture.js";
40
40
  import { writePaidSections } from "./paid-sections.js";
41
41
  import { RECOGNIZED_SHAPES, RESERVED_SHAPES, } from "./parse-args.js";
42
42
  import { RemoveModuleRefusedError, removeModuleFromScaffold, } from "./remove-module.js";
43
+ import { scaffoldSeamRows } from "./seam-refresh.js";
43
44
  import { writeSpokeFlowsReadme } from "./seed-flows.js";
44
45
  import { SITE_CHROME_PATH, renderSiteChrome, resolveSiteChrome, } from "./site-chrome.js";
45
46
  import { SITE_FONTS_PATH, renderSiteFonts } from "./site-fonts.js";
46
47
  import { planSiteManifest } from "./site-manifest.js";
47
48
  import { SITE_ROSTER_PATH, planHomeRecord, planSiteManifestDesign, readSiteRoster, withMeetPlaceholderSeeds, } from "./site-roster.js";
48
- import { dropSpokeCheckoutDependency, spokeCheckoutSite, spokeEnvRowOptions, writeSpokeCheckoutSlice, } from "./spoke-checkout.js";
49
+ import { LEAD_SITE_ENV_VAR, dropSpokeCheckoutDependency, spokeCheckoutSite, spokeEnvRowOptions, writeSpokeCheckoutSlice, } from "./spoke-checkout.js";
49
50
  import { GATEABLE_SURFACES, NAV_CONFIG_PATH, excludedRoutePaths, isUnservedSurfaceContent, isUnservedSurfaceRoute, renderNavConfig, resolveSurfaces, surfacesNamedByRoutes, } from "./surfaces.js";
50
51
  import { syncRoutes } from "./sync-routes.js";
51
52
  import { BASE_LAYER_DIR, SHAPE_STARTERS, isOwnTree, shippedManifestPath, TEMPLATE_MANIFESTS, TemplateError, mergeRoster, resolveTemplate, resolveTemplateLineage, rosterDeclares, templateDelivery, templateTreeDir, } from "./template-manifest.js";
52
53
  import { TEMPLATE_RECORD_PATH, isRecordable, planTemplateRecord, serializeTemplateRecord, sha256Hex, } from "./template-record.js";
53
- import { SPOKE_ONLY_FILES, TopologyError, applySpokeTransforms, isSpokeExcluded, normalizeHubSignInUrl, normalizeHubUrl, readSiteTopology, spokeExclusions, spokeDestination, spokeModuleRefusal, spokeModules, writeHubOriginEnv, writeHubSignInEnv, } from "./topology.js";
54
+ import { SPOKE_ONLY_FILES, TopologyError, applySpokeTransforms, isSpokeExcluded, normalizeHubSignInUrl, normalizeHubUrl, readSiteTopology, spokeExclusions, spokeDestination, spokeModuleRefusal, spokeModules, writeHubOriginEnv, writeHubSignInEnv, writeWebEnv, } from "./topology.js";
54
55
  import { validateTarget } from "./validate.js";
55
56
  const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
56
57
  const TEMPLATES_DIR = resolve(PKG_ROOT, "templates");
@@ -862,12 +863,16 @@ export async function scaffold(opts) {
862
863
  // path only when its final bytes still hash to the copy — a later
863
864
  // layer (a module bundle's patch, a generator) that rewrote the file
864
865
  // is absent here too.
865
- writeFileSync(join(result.targetDir, TEMPLATE_RECORD_PATH), serializeTemplateRecord(planTemplateRecord({
866
- targetDir: result.targetDir,
867
- copied,
868
- version: markers["CREATE_AILK_VERSION"] ?? "",
869
- projectName,
870
- })));
866
+ // #11148 — and the seams as rendered, so `update` can regenerate them.
867
+ writeFileSync(join(result.targetDir, TEMPLATE_RECORD_PATH), serializeTemplateRecord({
868
+ ...planTemplateRecord({
869
+ targetDir: result.targetDir,
870
+ copied,
871
+ version: markers["CREATE_AILK_VERSION"] ?? "",
872
+ projectName,
873
+ }),
874
+ seams: scaffoldSeamRows(result.targetDir, markers["CREATE_AILK_VERSION"] ?? ""),
875
+ }));
871
876
  }
872
877
  }
873
878
  // #7536 D3 — the registry follows `apps/web/package.json`, which a module
@@ -905,8 +910,12 @@ export async function scaffold(opts) {
905
910
  // (D2) — never the spoke key, which the hub issues.
906
911
  // #7894 D11 — a spoke signing in through its hub also gets the hub's web
907
912
  // origin and its own session secret; never the client secret.
908
- if (spoke !== undefined)
913
+ // #11148 (from #8487) — and its slug as the lead-site marker its /contact
914
+ // leads carry, so the hub tells its sites apart with no site edit.
915
+ if (spoke !== undefined) {
909
916
  writeHubOriginEnv(result.targetDir, spoke.hubOrigin);
917
+ writeWebEnv(result.targetDir, LEAD_SITE_ENV_VAR, () => spokeCheckoutSite(projectName));
918
+ }
910
919
  else
911
920
  writeAuthSecretFile(result.targetDir);
912
921
  if (spoke?.hubSignInOrigin !== undefined) {
@@ -466,7 +466,7 @@ export function removeModuleFromScaffold(opts) {
466
466
  files[p] = { sha256: sha256Hex(copy), version: opts.version };
467
467
  retired.push(p);
468
468
  }
469
- writeFileSync(recordPath, serializeTemplateRecord({ schema: 1, projectName: record.projectName, files }));
469
+ writeFileSync(recordPath, serializeTemplateRecord({ ...record, files }));
470
470
  }
471
471
  // ── The module set, the surfaces, architecture.yaml ─────────────────────
472
472
  const modules = normalizeModules(current.modules.filter((m) => m !== moduleName));
@@ -0,0 +1,60 @@
1
+ import { type TemplateFileRow } from "./template-record.js";
2
+ /** What a site's seam renders are keyed on, parsed from its manifest and `apps/web/package.json`. */
3
+ export interface SeamInputs {
4
+ topology: "hub" | "spoke";
5
+ signIn: "off" | "hub";
6
+ spokeBilling: boolean;
7
+ }
8
+ /**
9
+ * The topology, sign-in mode and spoke-billing flag the site at `targetDir`
10
+ * records — every input of `siteSeamRenders` that can refuse. A caller that
11
+ * writes before it plans (`sync-routes --apply`) reads these first, so a
12
+ * refusal lands before its first write (#11148).
13
+ * @throws TopologyError when the manifest records an unknown topology or mode,
14
+ * or `apps/web/package.json` is not JSON.
15
+ */
16
+ export declare function readSeamInputs(targetDir: string): SeamInputs;
17
+ /**
18
+ * Path → this create-ailk's render of every seam the site at `targetDir`
19
+ * carries, for the topology and sign-in mode `.ailk-site-manifest.json`
20
+ * records — the renders `applySpokeTransforms` and the spoke checkout write
21
+ * on a spoke, and the template's own copies on a hub. The gate only where the
22
+ * site keeps its `(authed)` group (a hub, or a spoke signing in through its
23
+ * hub); the MCP seam only where it keeps `apps/mcp`. `inputs` defaults to
24
+ * `readSeamInputs(targetDir)`.
25
+ * @throws TopologyError when `inputs` is not given and `readSeamInputs` refuses.
26
+ */
27
+ export declare function siteSeamRenders(targetDir: string, inputs?: SeamInputs): Map<string, string>;
28
+ /** The record row for a seam written with `render` by create-ailk `version`. */
29
+ export declare function seamRow(render: string, version: string): TemplateFileRow;
30
+ /**
31
+ * The `seams` rows a fresh scaffold records: one per seam whose bytes on
32
+ * disk are this version's render, after every layer landed.
33
+ */
34
+ export declare function scaffoldSeamRows(targetDir: string, version: string): Record<string, TemplateFileRow>;
35
+ export interface SeamRefreshPlan {
36
+ /**
37
+ * Path → the render to write: a seam that is absent, or still its recorded
38
+ * render, whose render exports every name a site file imports from it.
39
+ */
40
+ writes: Map<string, string>;
41
+ /** The seams left as the site keeps them, with why. Sorted by path. */
42
+ held: Array<{
43
+ path: string;
44
+ reason: string;
45
+ }>;
46
+ /**
47
+ * The `seams` rows once the plan lands, less the rows of `writes` — the
48
+ * caller adds `seamRow(render, version)` for each write it makes. A seam
49
+ * already this version's render gets its row here; a held seam keeps its
50
+ * own; a seam the site no longer carries drops its row.
51
+ */
52
+ rows: Record<string, TemplateFileRow>;
53
+ }
54
+ /**
55
+ * Which of the site's seams to regenerate (#11148). `recorded` is the
56
+ * record's `seams` rows; `only` narrows the seams considered (`sync-routes`
57
+ * passes the two its routes import); `inputs`, when given, is the
58
+ * `readSeamInputs` result the caller already read before its first write.
59
+ */
60
+ export declare function planSeamRefresh(targetDir: string, recorded: Readonly<Record<string, TemplateFileRow>>, version: string, only?: readonly string[], inputs?: SeamInputs): SeamRefreshPlan;
@@ -0,0 +1,214 @@
1
+ /**
2
+ * The topology seams a site carries, rendered for its recorded topology and
3
+ * sign-in mode, and the plan that regenerates them (#11148).
4
+ *
5
+ * A seam (`SPOKE_SEAM_FILES`) is generated output: `scaffold()` writes it,
6
+ * and nothing else may. `update` holds every template file a site edited,
7
+ * but a seam is never a template file (`isRecordable` is false for it), so
8
+ * before #11148 no consumer command rewrote one and a spoke stayed on the
9
+ * seam its scaffold rendered. Now `scaffold()` records the sha256 of each
10
+ * seam it rendered in `.ailk-template-files.json` `seams`, and `update` and
11
+ * `sync-routes --apply` rewrite a seam whose bytes are still that render.
12
+ * A seam whose bytes differ from it was edited by hand and is held; one with
13
+ * no recorded render (a site scaffolded before #11148) is held too, since
14
+ * nothing tells its edit from a stale render — deleting it takes the render.
15
+ * A render that drops a name a site file still imports from the seam is held
16
+ * as well, so a regeneration never breaks code the run leaves as it is.
17
+ *
18
+ * Reads the site; never writes. Every write goes through the caller.
19
+ */
20
+ import { existsSync, lstatSync, readFileSync } from "node:fs";
21
+ import { join } from "node:path";
22
+ import { exportsName, listFilesUnder, namedImportsOf } from "./lib/import-graph.js";
23
+ import { SPOKE_CHECKOUT_PACKAGE } from "./spoke-checkout.js";
24
+ import { TEMPLATE_RECORD_PATH, sha256Hex } from "./template-record.js";
25
+ import { API_ORIGIN_SEAM_PATH, AUTHED_GATE_SEAM_PATH, MCP_SEAM_PATH, WEB_SEAM_PATH, TopologyError, readSpokeShape, renderApiOriginSeam, renderAuthedGateSeam, renderMcpSeam, renderWebSeam, } from "./topology.js";
26
+ /** The `(authed)` group the gate seam sits in. */
27
+ const AUTHED_GROUP = "apps/web/app/[locale]/(authed)";
28
+ function onDisk(targetDir, rel) {
29
+ return existsSync(join(targetDir, ...rel.split("/")));
30
+ }
31
+ /**
32
+ * Whether `apps/web/package.json` declares the spoke checkout package (#8217 D7).
33
+ * @throws TopologyError when the file is not JSON — guessing would pick the wrong render.
34
+ */
35
+ function declaresSpokeCheckout(targetDir) {
36
+ const path = join(targetDir, "apps", "web", "package.json");
37
+ if (!existsSync(path))
38
+ return false;
39
+ let pkg;
40
+ try {
41
+ pkg = JSON.parse(readFileSync(path, "utf8"));
42
+ }
43
+ catch (err) {
44
+ throw new TopologyError(`apps/web/package.json is not valid JSON, so the web seam's render is unknown: ${err.message}`);
45
+ }
46
+ return Object.hasOwn(pkg.dependencies ?? {}, SPOKE_CHECKOUT_PACKAGE);
47
+ }
48
+ /** `path` less its source extension: what an import specifier of it resolves to. */
49
+ function moduleStem(path) {
50
+ return path.replace(/\.(?:[cm]?[jt]sx?)$/, "");
51
+ }
52
+ /**
53
+ * The module a local `specifier` in `fromPath` names, less its extension —
54
+ * relative, or `@/` from an apps/web file (its tsconfig `paths`); `undefined`
55
+ * for a package import.
56
+ */
57
+ function importedStem(fromPath, specifier) {
58
+ const alias = specifier.startsWith("@/") && fromPath.startsWith("apps/web/");
59
+ if (!alias && !specifier.startsWith("."))
60
+ return undefined;
61
+ const parts = alias ? ["apps", "web"] : fromPath.split("/").slice(0, -1);
62
+ for (const segment of (alias ? specifier.slice(2) : specifier).split("/")) {
63
+ if (segment === "" || segment === ".")
64
+ continue;
65
+ if (segment === "..")
66
+ parts.pop();
67
+ else
68
+ parts.push(segment);
69
+ }
70
+ return moduleStem(parts.join("/"));
71
+ }
72
+ /**
73
+ * Per seam stem, every `{ file, name }` a site source file under apps/web or
74
+ * apps/mcp imports from it by name — read from disk, so a file the run will
75
+ * rewrite is read as its current copy (conservative: it can only hold more).
76
+ */
77
+ function seamImports(targetDir, seams) {
78
+ const stems = new Map(seams.map((path) => [moduleStem(path), path]));
79
+ const out = new Map();
80
+ for (const file of [...listFilesUnder(targetDir, ["apps/web", "apps/mcp"])].sort()) {
81
+ if (stems.has(moduleStem(file)))
82
+ continue;
83
+ const text = readFileSync(join(targetDir, ...file.split("/")), "utf8");
84
+ if (!text.includes(".generated"))
85
+ continue;
86
+ for (const { specifier, names } of namedImportsOf(text)) {
87
+ const seam = stems.get(importedStem(file, specifier) ?? "");
88
+ if (seam === undefined)
89
+ continue;
90
+ const list = out.get(seam) ?? [];
91
+ list.push(...names.map((name) => ({ file, name })));
92
+ out.set(seam, list);
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+ /**
98
+ * The topology, sign-in mode and spoke-billing flag the site at `targetDir`
99
+ * records — every input of `siteSeamRenders` that can refuse. A caller that
100
+ * writes before it plans (`sync-routes --apply`) reads these first, so a
101
+ * refusal lands before its first write (#11148).
102
+ * @throws TopologyError when the manifest records an unknown topology or mode,
103
+ * or `apps/web/package.json` is not JSON.
104
+ */
105
+ export function readSeamInputs(targetDir) {
106
+ const spoke = readSpokeShape(targetDir);
107
+ const signIn = spoke?.signIn ?? "off";
108
+ return {
109
+ topology: spoke === undefined ? "hub" : "spoke",
110
+ signIn,
111
+ spokeBilling: signIn === "hub" && onDisk(targetDir, "apps/web") && declaresSpokeCheckout(targetDir),
112
+ };
113
+ }
114
+ /**
115
+ * Path → this create-ailk's render of every seam the site at `targetDir`
116
+ * carries, for the topology and sign-in mode `.ailk-site-manifest.json`
117
+ * records — the renders `applySpokeTransforms` and the spoke checkout write
118
+ * on a spoke, and the template's own copies on a hub. The gate only where the
119
+ * site keeps its `(authed)` group (a hub, or a spoke signing in through its
120
+ * hub); the MCP seam only where it keeps `apps/mcp`. `inputs` defaults to
121
+ * `readSeamInputs(targetDir)`.
122
+ * @throws TopologyError when `inputs` is not given and `readSeamInputs` refuses.
123
+ */
124
+ export function siteSeamRenders(targetDir, inputs = readSeamInputs(targetDir)) {
125
+ const { topology, signIn, spokeBilling } = inputs;
126
+ const renders = new Map();
127
+ if (!onDisk(targetDir, "apps/web"))
128
+ return renders;
129
+ renders.set(WEB_SEAM_PATH, renderWebSeam(topology, signIn, { spokeBilling }));
130
+ if ((topology === "hub" || signIn === "hub") && onDisk(targetDir, AUTHED_GROUP)) {
131
+ renders.set(AUTHED_GATE_SEAM_PATH, renderAuthedGateSeam(topology, signIn));
132
+ }
133
+ renders.set(API_ORIGIN_SEAM_PATH, renderApiOriginSeam(topology));
134
+ if (onDisk(targetDir, "apps/mcp"))
135
+ renders.set(MCP_SEAM_PATH, renderMcpSeam(topology));
136
+ return renders;
137
+ }
138
+ /** The record row for a seam written with `render` by create-ailk `version`. */
139
+ export function seamRow(render, version) {
140
+ return { sha256: sha256Hex(Buffer.from(render)), version };
141
+ }
142
+ /**
143
+ * The `seams` rows a fresh scaffold records: one per seam whose bytes on
144
+ * disk are this version's render, after every layer landed.
145
+ */
146
+ export function scaffoldSeamRows(targetDir, version) {
147
+ const rows = {};
148
+ for (const [path, render] of siteSeamRenders(targetDir)) {
149
+ const abs = join(targetDir, ...path.split("/"));
150
+ if (existsSync(abs) && readFileSync(abs, "utf8") === render)
151
+ rows[path] = seamRow(render, version);
152
+ }
153
+ return rows;
154
+ }
155
+ /**
156
+ * Which of the site's seams to regenerate (#11148). `recorded` is the
157
+ * record's `seams` rows; `only` narrows the seams considered (`sync-routes`
158
+ * passes the two its routes import); `inputs`, when given, is the
159
+ * `readSeamInputs` result the caller already read before its first write.
160
+ */
161
+ export function planSeamRefresh(targetDir, recorded, version, only, inputs) {
162
+ const writes = new Map();
163
+ const held = [];
164
+ const rows = {};
165
+ const renders = siteSeamRenders(targetDir, inputs);
166
+ const considered = [...renders.keys()].filter((path) => only === undefined || only.includes(path));
167
+ const imports = seamImports(targetDir, considered);
168
+ for (const path of considered) {
169
+ const render = renders.get(path);
170
+ const abs = join(targetDir, ...path.split("/"));
171
+ const row = recorded[path];
172
+ const keep = (reason) => {
173
+ if (row !== undefined)
174
+ rows[path] = row;
175
+ held.push({ path, reason });
176
+ };
177
+ // lstat, never stat: a symlink — dangling or not — is never written through.
178
+ let stat;
179
+ try {
180
+ stat = lstatSync(abs);
181
+ }
182
+ catch {
183
+ stat = undefined; // absent: written below
184
+ }
185
+ if (stat !== undefined && !stat.isFile()) {
186
+ keep("seam not regenerated: the path is not a regular file (a symlink or a directory) — replace it with a file, or delete it, and run the command again");
187
+ continue;
188
+ }
189
+ const current = stat !== undefined ? readFileSync(abs) : undefined;
190
+ if (current !== undefined && current.toString("utf8") === render) {
191
+ rows[path] = row?.sha256 === sha256Hex(current) ? row : seamRow(render, version);
192
+ continue;
193
+ }
194
+ if (current !== undefined && row?.sha256 !== sha256Hex(current)) {
195
+ keep(row !== undefined
196
+ ? `seam edited by hand: its bytes differ from the create-ailk ${row.version} render, so the ${version} render was not written — move the edit into the site's own code, delete the file and run the command again`
197
+ : `seam not regenerated: no recorded render to tell a hand edit from (none in ${TEMPLATE_RECORD_PATH}) — if the site never edited it, delete the file and run the command again to take the ${version} render`);
198
+ continue;
199
+ }
200
+ const dropped = (imports.get(path) ?? []).filter(({ name }) => !exportsName(render, name));
201
+ if (dropped.length > 0) {
202
+ const named = [...new Set(dropped.map(({ file, name }) => `${name} (${file})`))].join(", ");
203
+ keep(`seam not regenerated: the ${version} render does not export ${named}, which the site still imports — update the importer, then run the command again`);
204
+ continue;
205
+ }
206
+ writes.set(path, render);
207
+ }
208
+ // A row for a seam outside `only` is carried as it is.
209
+ for (const [path, row] of Object.entries(recorded)) {
210
+ if (only !== undefined && !only.includes(path) && renders.has(path))
211
+ rows[path] = row;
212
+ }
213
+ return { writes, held: held.sort((a, b) => a.path.localeCompare(b.path)), rows };
214
+ }
@@ -18,9 +18,18 @@ export declare const SPOKE_CHECKOUT_ENV_CATALOG: Readonly<Record<string, EnvCata
18
18
  /** The names a commerce spoke declares although only the package reads them (D9). */
19
19
  export declare const SPOKE_CHECKOUT_DECLARED_ENV: readonly string[];
20
20
  /**
21
- * The catalog (and declared names) a spoke's `appendEnvRows` call passes: a
22
- * commerce spoke adds the package's two rows (D9). `ENV_CATALOG` itself is
23
- * unchanged — its test fails on an entry the monorepo's apps never read.
21
+ * The lead-site marker (#11148, from #8487): the `/contact` action
22
+ * `@working-theory/site-pages` ships writes it as `payload.site`. The action
23
+ * reads it from an installed package, out of the declared-env scan's reach,
24
+ * so every spoke declares it, and the scaffold sets it to the site's slug in
25
+ * `apps/web/.env.local`.
26
+ */
27
+ export declare const LEAD_SITE_ENV_VAR = "AILK_LEAD_SITE";
28
+ /**
29
+ * The catalog (and declared names) a spoke's `appendEnvRows` call passes:
30
+ * every spoke declares `LEAD_SITE_ENV_VAR`, and a commerce spoke adds the
31
+ * package's two rows (D9). `ENV_CATALOG` itself is unchanged — its test
32
+ * fails on an entry the monorepo's apps never read.
24
33
  */
25
34
  export declare function spokeEnvRowOptions(commerce: boolean): Pick<PlanEnvRowsOptions, "catalog" | "declare">;
26
35
  /**
@@ -68,17 +68,26 @@ export const SPOKE_CHECKOUT_DECLARED_ENV = Object.freeze([
68
68
  "STRIPE_MODE",
69
69
  ]);
70
70
  /**
71
- * The catalog (and declared names) a spoke's `appendEnvRows` call passes: a
72
- * commerce spoke adds the package's two rows (D9). `ENV_CATALOG` itself is
73
- * unchanged — its test fails on an entry the monorepo's apps never read.
71
+ * The lead-site marker (#11148, from #8487): the `/contact` action
72
+ * `@working-theory/site-pages` ships writes it as `payload.site`. The action
73
+ * reads it from an installed package, out of the declared-env scan's reach,
74
+ * so every spoke declares it, and the scaffold sets it to the site's slug in
75
+ * `apps/web/.env.local`.
76
+ */
77
+ export const LEAD_SITE_ENV_VAR = "AILK_LEAD_SITE";
78
+ /**
79
+ * The catalog (and declared names) a spoke's `appendEnvRows` call passes:
80
+ * every spoke declares `LEAD_SITE_ENV_VAR`, and a commerce spoke adds the
81
+ * package's two rows (D9). `ENV_CATALOG` itself is unchanged — its test
82
+ * fails on an entry the monorepo's apps never read.
74
83
  */
75
84
  export function spokeEnvRowOptions(commerce) {
76
85
  return commerce
77
86
  ? {
78
87
  catalog: { ...ENV_CATALOG, ...SPOKE_CHECKOUT_ENV_CATALOG },
79
- declare: SPOKE_CHECKOUT_DECLARED_ENV,
88
+ declare: [LEAD_SITE_ENV_VAR, ...SPOKE_CHECKOUT_DECLARED_ENV],
80
89
  }
81
- : { catalog: ENV_CATALOG };
90
+ : { catalog: ENV_CATALOG, declare: [LEAD_SITE_ENV_VAR] };
82
91
  }
83
92
  /** `metadata.site` — the package's own pattern. */
84
93
  const SITE_PATTERN = /^[a-z0-9][a-z0-9-]{0,39}$/;