create-ailk 0.47.0 → 0.48.1

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 (137) hide show
  1. package/README.md +192 -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 +1 -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 +807 -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 +42 -41
  59. package/dist/site-chrome.js +51 -70
  60. package/dist/site-fonts.d.ts +14 -14
  61. package/dist/site-fonts.js +9 -4
  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 +11 -4
  98. package/templates/apps/api/CLAUDE.md +6 -4
  99. package/templates/apps/api/src/lib/__mocks__/prisma.ts +15 -5
  100. package/templates/apps/mcp/CLAUDE.md +4 -2
  101. package/templates/apps/web/.env.example +10 -3
  102. package/templates/apps/web/CLAUDE.md +14 -3
  103. package/templates/apps/web/app/[locale]/layout.tsx +53 -50
  104. package/templates/apps/web/app/not-found.tsx +11 -11
  105. package/templates/apps/web/auth.ts +48 -35
  106. package/templates/apps/web/jest.config.cjs +5 -0
  107. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +179 -31
  108. package/templates/apps/web/lib/__tests__/library-fonts.test.ts +35 -0
  109. package/templates/apps/web/lib/__tests__/page-chrome-navigation.test.ts +71 -32
  110. package/templates/apps/web/lib/__tests__/page-chrome.test.ts +123 -26
  111. package/templates/apps/web/lib/__tests__/section-look.test.ts +150 -0
  112. package/templates/apps/web/lib/__tests__/site-theme.test.ts +81 -289
  113. package/templates/apps/web/lib/deck-page.ts +3 -10
  114. package/templates/apps/web/lib/deploy-fonts.ts +12 -0
  115. package/templates/apps/web/lib/hub-site-config.ts +97 -14
  116. package/templates/apps/web/lib/library-fonts.ts +41 -0
  117. package/templates/apps/web/lib/mcp-oauth.ts +11 -4
  118. package/templates/apps/web/lib/page-chrome.ts +52 -34
  119. package/templates/apps/web/lib/section-look.ts +28 -0
  120. package/templates/apps/web/lib/site-design.ts +205 -0
  121. package/templates/apps/web/lib/site-theme-head.ts +98 -13
  122. package/templates/apps/web/lib/site-theme.ts +40 -62
  123. package/templates/apps/web/messages/en.json +0 -6
  124. package/templates/apps/web/next.config.mjs +195 -6
  125. package/templates/apps/web/package.json +2 -0
  126. package/templates/apps/web/site-pages.config.tsx +4 -2
  127. package/templates/content/_site.mdx +0 -26
  128. package/templates/design.yaml +75 -0
  129. package/templates/project.yaml +14 -0
  130. package/versions.json +52 -51
  131. package/site-templates/marketing-site/DESIGN.md +0 -259
  132. package/site-templates/marketing-site-free/DESIGN.md +0 -259
  133. package/site-templates/saas-product/DESIGN.md +0 -259
  134. package/templates/apps/web/lib/__tests__/deck-page.test.ts +0 -288
  135. package/templates/apps/web/lib/__tests__/site-theme-head.test.ts +0 -70
  136. package/templates/apps/web/lib/site-chrome.ts +0 -46
  137. package/templates/apps/web/lib/site-fonts.ts +0 -15
@@ -0,0 +1,807 @@
1
+ /**
2
+ * `create-ailk look-settings` (#12476 D2, spec
3
+ * docs/specs/12476-import-each-live-site-s-spec.md): the design settings a
4
+ * live site's hub design record will hold, and the byte-for-byte proof that
5
+ * they are what the site's three generated look files were compiled from.
6
+ *
7
+ * It reads the site's `design.yaml`, its roster (`.ailk-site-manifest.json`,
8
+ * else the legacy `TEMPLATE-MANIFEST.json`), `content/_site.mdx`,
9
+ * `apps/web/lib/site-chrome.ts` and `apps/web/lib/site-fonts.ts` — each once,
10
+ * as text, never run. The settings are the design package with its layout
11
+ * replaced by the one `site-chrome.ts` declares (#12635); the run hands them
12
+ * over only when they compile, by create-ailk's own compile, to what each
13
+ * generated file holds: the `theme:` block byte for byte, and the values
14
+ * `site-chrome.ts` and `site-fonts.ts` declare — read as data, so a file an
15
+ * older create-ailk wrote, with an older type header, passes. It writes one file outside the
16
+ * checkout (`--out`, created mode 0600, never overwritten) binding the
17
+ * settings to the checkout by the digest of every file it read, and records
18
+ * the settings' own digest, which it also prints. The hub CLI
19
+ * `import-site-design` reads that file.
20
+ *
21
+ * Exit codes: 0 handed over · 1 a failure (a file missing, outside the site,
22
+ * not a regular file, over 1 MB, or refused by the reader — among them a
23
+ * `siteChrome` or `siteFonts` the reader cannot read as data) · 2 a bad flag,
24
+ * or an `--out` that exists or sits in the checkout · 3 a generated file that
25
+ * differs from what `design.yaml` compiles to.
26
+ *
27
+ * Pure module: no `import.meta.url`, so jest imports it directly.
28
+ */
29
+ import { createHash } from "node:crypto";
30
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync, unlinkSync, writeSync, } from "node:fs";
31
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
32
+ import { parseArgs } from "node:util";
33
+ import { compileDesignFonts, compileDesignTheme } from "./design-compile.js";
34
+ import { DESIGN_SETTINGS_FILE } from "./design-files.js";
35
+ import { DESIGN_COLOR_KEYS_LIGHT, DesignPackageError, readDesignPackageText, } from "./design-package.js";
36
+ import { spliceThemeBlock } from "./design-scaffold.js";
37
+ import { LAYOUT_OPTIONAL_KEYS, LAYOUT_REQUIRED_KEYS } from "./generated/design-settings.js";
38
+ import { SITE_MDX_PATH } from "./look-hub.js";
39
+ import { ParseError } from "./parse-args.js";
40
+ import { resolveSiteChrome, SITE_CHROME_PATH, TemplateLayoutError, validateTemplateLayout, } from "./site-chrome.js";
41
+ import { fontExportName, SITE_FONTS_PATH } from "./site-fonts.js";
42
+ import { LEGACY_SITE_ROSTER_PATH, parseSiteRoster, SITE_ROSTER_PATH } from "./site-roster.js";
43
+ const TAG = "[look:settings]";
44
+ /** A site file larger than this is refused (D2). */
45
+ export const LOOK_SITE_FILE_MAX_BYTES = 1_048_576;
46
+ /** The hand-off file's `kind` and `format` (D2). */
47
+ export const LOOK_SETTINGS_KIND = "ailk-look-settings";
48
+ export const LOOK_SETTINGS_FORMAT = 1;
49
+ /** The most characters a printed site or hub value keeps (D2's printing rule). */
50
+ const PRINTED_MAX = 120;
51
+ // ── Shared rules (D2) ────────────────────────────────────────────────────────
52
+ /**
53
+ * D2's printing rule: every character outside `[A-Za-z0-9._:/@ -]` becomes
54
+ * `\xNN`, one escape per UTF-8 byte, and the result is cut to 120 characters,
55
+ * so no site or hub value can carry a terminal escape or a forged line.
56
+ */
57
+ export function printable(value) {
58
+ let out = "";
59
+ for (const ch of value) {
60
+ out += /^[A-Za-z0-9._:/@ -]$/.test(ch)
61
+ ? ch
62
+ : [...Buffer.from(ch, "utf8")].map((byte) => `\\x${byte.toString(16).padStart(2, "0")}`).join("");
63
+ if (out.length >= PRINTED_MAX)
64
+ break;
65
+ }
66
+ return out.slice(0, PRINTED_MAX);
67
+ }
68
+ function sortKeys(value) {
69
+ if (Array.isArray(value))
70
+ return value.map(sortKeys);
71
+ if (typeof value !== "object" || value === null)
72
+ return value;
73
+ return Object.fromEntries(Object.keys(value)
74
+ .sort()
75
+ .map((key) => [key, sortKeys(value[key])]));
76
+ }
77
+ /** The canonical JSON of a value (D2): every object's keys sorted, no whitespace. */
78
+ export function canonicalJson(value) {
79
+ return JSON.stringify(sortKeys(value));
80
+ }
81
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
82
+ /** The settings digest (D2): the SHA-256 of the settings' canonical JSON, UTF-8. */
83
+ export function settingsDigest(settings) {
84
+ return sha256(Buffer.from(canonicalJson(settings), "utf8"));
85
+ }
86
+ // ── Reading the site ─────────────────────────────────────────────────────────
87
+ /** The run's refusal or failure: its exit code and the lines it prints. */
88
+ class Stop extends Error {
89
+ code;
90
+ lines;
91
+ constructor(code, lines) {
92
+ super(lines.join("\n"));
93
+ this.code = code;
94
+ this.lines = lines;
95
+ }
96
+ }
97
+ const fail = (line) => new Stop(1, [`${TAG} ${line}`]);
98
+ /** Whether `real` (a real path) sits under `root` (a real path), `root` itself excluded. */
99
+ function under(root, real) {
100
+ const rel = relative(root, real);
101
+ return rel !== "" && rel !== ".." && !rel.startsWith(`..${sep}`) && !rel.startsWith(sep);
102
+ }
103
+ /** Whether anything — a file, a directory, a link, a dangling link — is at `path`. */
104
+ function present(path) {
105
+ try {
106
+ lstatSync(path);
107
+ return true;
108
+ }
109
+ catch {
110
+ return false;
111
+ }
112
+ }
113
+ /**
114
+ * One site file, read once (D2): its real path must sit under the site's;
115
+ * it is opened there with `O_NOFOLLOW`, checked with `fstat` on that
116
+ * descriptor (a regular file, at most 1 MB) and read into one buffer — the
117
+ * buffer that is hashed, parsed and compared.
118
+ */
119
+ function readOnce(root, rel) {
120
+ let real;
121
+ try {
122
+ real = realpathSync(join(root, rel));
123
+ }
124
+ catch {
125
+ throw fail(`${rel}: not found`);
126
+ }
127
+ if (!under(root, real))
128
+ throw fail(`${rel}: resolves outside the site`);
129
+ let fd;
130
+ try {
131
+ fd = openSync(real, constants.O_RDONLY | constants.O_NOFOLLOW);
132
+ }
133
+ catch {
134
+ throw fail(`${rel}: is unreadable`);
135
+ }
136
+ try {
137
+ const stat = fstatSync(fd);
138
+ if (!stat.isFile())
139
+ throw fail(`${rel}: is not a regular file`);
140
+ if (stat.size > LOOK_SITE_FILE_MAX_BYTES)
141
+ throw fail(`${rel}: is over 1 MB`);
142
+ const buffer = readFileSync(fd);
143
+ if (buffer.length > LOOK_SITE_FILE_MAX_BYTES)
144
+ throw fail(`${rel}: is over 1 MB`);
145
+ return buffer;
146
+ }
147
+ finally {
148
+ closeSync(fd);
149
+ }
150
+ }
151
+ /** The 1-based number of the first line where `a` and `b` differ. */
152
+ function firstDifferingLine(a, b) {
153
+ const left = a.split("\n");
154
+ const right = b.split("\n");
155
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
156
+ if (left[i] !== right[i])
157
+ return i + 1;
158
+ }
159
+ return 1;
160
+ }
161
+ /** A generated file that differs; `what` names the declared value, never with the site's own text. */
162
+ const differs = (file, line, what) => `${TAG} ${file}: ${what === undefined ? "" : `${what} `}differs from what ${DESIGN_SETTINGS_FILE} compiles to at line ${line} — not imported`;
163
+ /** The roster name `readSiteRoster` would read: the current name when present, else the legacy one, else none. */
164
+ function rosterNameIn(root) {
165
+ return [SITE_ROSTER_PATH, LEGACY_SITE_ROSTER_PATH].find((name) => present(join(root, name)));
166
+ }
167
+ // ── Reading a declared value (#12635) ────────────────────────────────────────
168
+ /**
169
+ * A value the reader does not take as data — a name, a call, an operator. It
170
+ * is `{}` in canonical JSON, which no layout or face value equals. Only where
171
+ * it sits is read; it is never run.
172
+ */
173
+ const CODE = Object.freeze({});
174
+ /** How deep a declared value may nest: deeper is refused, so no file can exhaust the stack. */
175
+ const DECLARED_DEPTH_MAX = 8;
176
+ /**
177
+ * Read the object literal at `start` of a site file's `text` as data, never
178
+ * as code (#12635): strings in either quote, numbers, `true` / `false` /
179
+ * `null`, arrays and objects of them. A member value that is anything else —
180
+ * a name, a call, an array spread, or a literal followed by more code, such
181
+ * as `[…].join(" ")` — is `CODE`. Comments are skipped. Each object key's
182
+ * 1-based line goes into `lines`, and each member value's text span (start,
183
+ * end) into `spans`, by dotted path. Throws `refused` on what
184
+ * the reader does not read: an unclosed string, comment or bracket, an escape
185
+ * outside `\n \r \t \0 \\ \' \" \uXXXX`, a key that is not a plain name or
186
+ * string (a spread, a getter, a computed key), and a duplicate key.
187
+ */
188
+ function scanValue(text, start, lines, refused, spans = new Map()) {
189
+ let pos = start;
190
+ // Lines are counted once, as the scan moves forward, so a long file is never re-read per key.
191
+ let counted = 0;
192
+ let line = 1;
193
+ const lineAt = (at) => {
194
+ for (; counted < at; counted += 1)
195
+ if (text[counted] === "\n")
196
+ line += 1;
197
+ return line;
198
+ };
199
+ const skip = () => {
200
+ for (;;) {
201
+ const ws = /\s*/y;
202
+ ws.lastIndex = pos;
203
+ ws.exec(text);
204
+ pos = ws.lastIndex;
205
+ if (text.startsWith("//", pos)) {
206
+ const eol = text.indexOf("\n", pos);
207
+ pos = eol === -1 ? text.length : eol;
208
+ }
209
+ else if (text.startsWith("/*", pos)) {
210
+ const close = text.indexOf("*/", pos + 2);
211
+ if (close === -1)
212
+ throw refused();
213
+ pos = close + 2;
214
+ }
215
+ else {
216
+ return;
217
+ }
218
+ }
219
+ };
220
+ const ESCAPES = { n: "\n", r: "\r", t: "\t", "\\": "\\", "'": "'", '"': '"', "0": "\0" };
221
+ const readString = () => {
222
+ const quote = text[pos];
223
+ pos += 1;
224
+ let out = "";
225
+ for (;;) {
226
+ const ch = text[pos];
227
+ if (ch === undefined || ch === "\n")
228
+ throw refused();
229
+ pos += 1;
230
+ if (ch === quote)
231
+ return out;
232
+ if (ch !== "\\") {
233
+ out += ch;
234
+ continue;
235
+ }
236
+ const esc = text[pos] ?? "";
237
+ const hex = /^u([0-9a-fA-F]{4})/.exec(text.slice(pos, pos + 5));
238
+ if (hex !== null) {
239
+ out += String.fromCharCode(parseInt(hex[1], 16));
240
+ pos += 5;
241
+ }
242
+ else if (Object.hasOwn(ESCAPES, esc)) {
243
+ out += ESCAPES[esc];
244
+ pos += 1;
245
+ }
246
+ else {
247
+ throw refused();
248
+ }
249
+ }
250
+ };
251
+ /** Skip one value that is code, to the `,` `}` or `]` that ends it at its own depth. */
252
+ const skipCode = () => {
253
+ let depth = 0;
254
+ for (;;) {
255
+ skip();
256
+ const ch = text[pos];
257
+ if (ch === undefined)
258
+ throw refused();
259
+ if (depth === 0 && (ch === "," || ch === "}" || ch === "]"))
260
+ return;
261
+ if (ch === '"' || ch === "'" || ch === "`") {
262
+ const close = new RegExp(`(?:[^${ch}\\\\]|\\\\[\\s\\S])*${ch}`, "y");
263
+ close.lastIndex = pos + 1;
264
+ if (close.exec(text) === null)
265
+ throw refused();
266
+ pos = close.lastIndex;
267
+ continue;
268
+ }
269
+ if (ch === "(" || ch === "[" || ch === "{")
270
+ depth += 1;
271
+ if (ch === ")" || ch === "]" || ch === "}")
272
+ depth -= 1;
273
+ if (depth < 0)
274
+ throw refused();
275
+ pos += 1;
276
+ }
277
+ };
278
+ const NOT_LITERAL = Symbol("not a literal");
279
+ const readLiteral = (path, depth) => {
280
+ if (depth > DECLARED_DEPTH_MAX)
281
+ throw refused();
282
+ const ch = text[pos];
283
+ if (ch === '"' || ch === "'")
284
+ return readString();
285
+ const word = /(?:true|false|null|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)(?![\w$])/y;
286
+ word.lastIndex = pos;
287
+ const m = word.exec(text);
288
+ if (m !== null) {
289
+ pos = word.lastIndex;
290
+ return m[0] === "true" ? true : m[0] === "false" ? false : m[0] === "null" ? null : Number(m[0]);
291
+ }
292
+ if (ch === "[") {
293
+ pos += 1;
294
+ const items = [];
295
+ for (;;) {
296
+ skip();
297
+ if (text[pos] === "]")
298
+ break;
299
+ items.push(readValue(`${path}.${items.length}`, depth + 1));
300
+ if (text[pos] === ",")
301
+ pos += 1;
302
+ else if (text[pos] !== "]")
303
+ throw refused();
304
+ }
305
+ pos += 1;
306
+ return items;
307
+ }
308
+ if (ch === "{") {
309
+ pos += 1;
310
+ const obj = {};
311
+ for (;;) {
312
+ skip();
313
+ if (text[pos] === "}")
314
+ break;
315
+ const keyAt = pos;
316
+ let key;
317
+ if (text[pos] === '"' || text[pos] === "'") {
318
+ key = readString();
319
+ }
320
+ else {
321
+ const ident = /[A-Za-z_$][\w$]*/y;
322
+ ident.lastIndex = pos;
323
+ const id = ident.exec(text);
324
+ if (id === null)
325
+ throw refused();
326
+ key = id[0];
327
+ pos = ident.lastIndex;
328
+ }
329
+ if (key === "__proto__" || Object.hasOwn(obj, key))
330
+ throw refused();
331
+ skip();
332
+ if (text[pos] !== ":")
333
+ throw refused();
334
+ pos += 1;
335
+ const keyPath = path === "" ? key : `${path}.${key}`;
336
+ lines.set(keyPath, lineAt(keyAt));
337
+ obj[key] = readValue(keyPath, depth + 1);
338
+ if (text[pos] === ",")
339
+ pos += 1;
340
+ else if (text[pos] !== "}")
341
+ throw refused();
342
+ }
343
+ pos += 1;
344
+ return obj;
345
+ }
346
+ return NOT_LITERAL;
347
+ };
348
+ /** A member's value: its literal when it is all literal, else `CODE`; leaves `pos` on the `,` `}` or `]` after it. */
349
+ const readValue = (path, depth) => {
350
+ skip();
351
+ const at = pos;
352
+ const value = readLiteral(path, depth);
353
+ skip();
354
+ if (value !== NOT_LITERAL && [",", "}", "]"].includes(text[pos] ?? "")) {
355
+ spans.set(path, [at, pos]);
356
+ return value;
357
+ }
358
+ pos = at;
359
+ skipCode();
360
+ spans.set(path, [at, pos]);
361
+ return CODE;
362
+ };
363
+ skip();
364
+ if (text[pos] !== "{")
365
+ throw refused();
366
+ const value = readLiteral("", 0);
367
+ return { value, end: pos };
368
+ }
369
+ /** Whitespace and comments, as a regular-expression source. */
370
+ const TRIVIA = String.raw `(?:\s|//[^\n]*|/\*[\s\S]*?\*/)*`;
371
+ /**
372
+ * The offset after each `export const <name> … =` in `text`, found the way
373
+ * `readExportedData` finds one: by walking the file token by token, past
374
+ * comments and strings, so a declaration inside a template literal or a
375
+ * comment never counts. It refuses (throws `refused`) what would let the
376
+ * walk read the file differently from JavaScript, or let `<name>` be
377
+ * exported without being spelled: a `/` outside a comment (a regular
378
+ * expression can hold a quote), a `\` outside a string (`\u0073iteChrome`
379
+ * is a name), a template that computes a value (`${`), an
380
+ * unclosed string or comment, and `export *` or `export {`.
381
+ */
382
+ function declarationHeads(text, name, refused) {
383
+ const heads = [];
384
+ const head = new RegExp(`export\\s+(?:(const\\s+${name}(?![\\w$])[^=\\n]*=)|\\*|\\{)`, "y");
385
+ const token = /[A-Za-z_$][\w$]*|\s+/y;
386
+ let i = 0;
387
+ while (i < text.length) {
388
+ const ch = text[i];
389
+ if (text.startsWith("//", i)) {
390
+ const eol = text.indexOf("\n", i);
391
+ i = eol === -1 ? text.length : eol;
392
+ }
393
+ else if (text.startsWith("/*", i)) {
394
+ const close = text.indexOf("*/", i + 2);
395
+ if (close === -1)
396
+ throw refused();
397
+ i = close + 2;
398
+ }
399
+ else if (ch === "/" || ch === "\\") {
400
+ throw refused();
401
+ }
402
+ else if (ch === '"' || ch === "'" || ch === "`") {
403
+ const close = new RegExp(`(?:[^${ch}\\\\\\n]|\\\\[\\s\\S]${ch === "`" ? "|\\n" : ""})*${ch}`, "y");
404
+ close.lastIndex = i + 1;
405
+ const m = close.exec(text);
406
+ if (m === null || (ch === "`" && /(?<!\\)\$\{/.test(m[0])))
407
+ throw refused();
408
+ i = close.lastIndex;
409
+ }
410
+ else {
411
+ head.lastIndex = i;
412
+ const found = head.exec(text);
413
+ if (found !== null) {
414
+ if (found[1] === undefined)
415
+ throw refused();
416
+ heads.push(head.lastIndex);
417
+ i = head.lastIndex;
418
+ continue;
419
+ }
420
+ token.lastIndex = i;
421
+ i = token.exec(text) === null ? i + 1 : token.lastIndex;
422
+ }
423
+ }
424
+ return heads;
425
+ }
426
+ /**
427
+ * The one `export const <name>` a site file declares, read by `scanValue`
428
+ * (#12635). The declaration may carry a type (`: SiteChrome`) and end with
429
+ * `as const` or `satisfies <Type>`; anything else — none, two, or a value that
430
+ * is not an object literal — is refused by the reader (exit 1). So is a file
431
+ * that names `<name>` anywhere else, where code could change the value after
432
+ * it is declared (`siteChrome.nav = …`); what `declarationHeads` refuses, so
433
+ * a decoy in a string or comment never stands in for it; a declaration that does not end at a `;` or the end of the file,
434
+ * where the next line could continue it (`} && { … }`); and a line break
435
+ * other than `\n` or `\r\n`, which ends a `//` comment for JavaScript but not
436
+ * for the reader — the same refusal `readExportedData` makes in
437
+ * `packages-paid/api-workspace/src/bin/site-file-data.ts`.
438
+ */
439
+ function readDeclared(text, name, file) {
440
+ const refused = () => fail(`${file}: ${name} refused by the reader`);
441
+ if (/\r(?!\n)|\u2028|\u2029/.test(text))
442
+ throw refused();
443
+ const heads = declarationHeads(text, name, refused);
444
+ const head = heads[0];
445
+ const named = text.match(new RegExp(`(?<![\\w$])${name}(?![\\w$])`, "g"))?.length ?? 0;
446
+ if (heads.length !== 1 || named !== 1 || head === undefined)
447
+ throw refused();
448
+ const lines = new Map();
449
+ const spans = new Map();
450
+ const { value, end } = scanValue(text, head, lines, refused, spans);
451
+ const tail = new RegExp(`${TRIVIA}(?:(?:as\\s+const|satisfies\\s+[A-Za-z_$][\\w$.]*)${TRIVIA})?(?:;|$)`, "y");
452
+ tail.lastIndex = end;
453
+ if (tail.exec(text) === null)
454
+ throw refused();
455
+ return { value, lines, spans, line: text.slice(0, text.lastIndexOf("export", head)).split("\n").length };
456
+ }
457
+ /** Every key a layout carries — the generated lists, the same `design-package.ts` reads. */
458
+ const LAYOUT_KEYS = [...LAYOUT_REQUIRED_KEYS, ...LAYOUT_OPTIONAL_KEYS];
459
+ /**
460
+ * (#12635 c) The layout a `site-chrome.ts` declares: each layout key whose
461
+ * declared value the layout takes, so a site edited after its scaffold
462
+ * imports what it renders. A value it does not take is left out, and
463
+ * `chromeDifferences` names it.
464
+ */
465
+ function declaredLayout(chrome) {
466
+ const layout = {};
467
+ for (const key of LAYOUT_KEYS) {
468
+ if (!Object.hasOwn(chrome.value, key))
469
+ continue;
470
+ try {
471
+ Object.assign(layout, validateTemplateLayout({ [key]: chrome.value[key] }, SITE_CHROME_PATH));
472
+ }
473
+ catch (err) {
474
+ if (!(err instanceof TemplateLayoutError))
475
+ throw err;
476
+ }
477
+ }
478
+ return layout;
479
+ }
480
+ /**
481
+ * Whether a look is the same in both modes: every dark colour equals its
482
+ * light one — `design-package.ts`'s own test for a matching pair of sets,
483
+ * and the form `update` gives a site pinned light (#12500).
484
+ */
485
+ const sameInBothModes = (settings) => DESIGN_COLOR_KEYS_LIGHT.every((key) => settings.colors[key] === settings.colors[`${key}-dark`]);
486
+ /**
487
+ * (#12635 a) The `siteChrome` values that differ from `settings.layout`, in
488
+ * the file's order: a key the layout does not carry, a value it does not
489
+ * take or that the layout drops (a `deckGrounds` on a non-deck home), and a
490
+ * value left out. `colorMode: "light"` is equal when the settings are the
491
+ * same in both modes (#12500 retired the field).
492
+ */
493
+ function chromeDifferences(chrome, settings) {
494
+ const expected = { ...settings.layout };
495
+ const at = (key) => chrome.lines.get(key) ?? chrome.line;
496
+ const lines = [];
497
+ const keys = [...Object.keys(chrome.value), ...LAYOUT_KEYS.filter((key) => !Object.hasOwn(chrome.value, key))];
498
+ for (const key of keys) {
499
+ if (key === "colorMode") {
500
+ if (chrome.value[key] !== "light" || !sameInBothModes(settings)) {
501
+ lines.push(differs(SITE_CHROME_PATH, at(key), "siteChrome.colorMode"));
502
+ }
503
+ }
504
+ else if (!LAYOUT_KEYS.includes(key)) {
505
+ lines.push(`${TAG} ${SITE_CHROME_PATH}: siteChrome holds a key the layout does not carry at line ${at(key)} — not imported`);
506
+ }
507
+ else if (canonicalJson(chrome.value[key]) !== canonicalJson(expected[key])) {
508
+ // An absent key on either side is `undefined`, which equals only another absent key.
509
+ lines.push(differs(SITE_CHROME_PATH, at(key), `siteChrome.${key}`));
510
+ }
511
+ }
512
+ return lines;
513
+ }
514
+ /** The `className` the renderer writes, as its whole value: `[<slot>Face.variable, …].join(" ")`. */
515
+ const CLASS_NAME_VALUE = /^\[([^\]]*)\]\.join\(\s*(["'])\s\2\s*\)$/;
516
+ /**
517
+ * (#12635 b) The `siteFonts` values that differ from the faces the settings
518
+ * compile to. A role's face is read from what the file declares: its
519
+ * `families.<role>` (`var(--font-design-<slot>)` and the fallback after it)
520
+ * and the `<slot>Face` loader — a `next/font/google` export called with
521
+ * exactly `{ subsets: ["latin"], variable: "--font-design-<slot>" }`.
522
+ * `className` must name each loader the faces need (`<slot>Face.variable`),
523
+ * or the page never defines the face's variable.
524
+ */
525
+ function fontsDifferences(fonts, settings) {
526
+ const { text, declared } = fonts;
527
+ const refused = () => fail(`${SITE_FONTS_PATH}: siteFonts refused by the reader`);
528
+ const google = new Set();
529
+ for (const m of text.matchAll(/^import\s*\{([^}]*)\}\s*from\s*["']next\/font\/google["']/gm)) {
530
+ for (const name of m[1].split(","))
531
+ google.add(name.trim());
532
+ }
533
+ const loaders = new Map();
534
+ for (const m of text.matchAll(/^const\s+(display|body)Face\s*=\s*([A-Za-z_$][\w$]*)\s*\(/gm)) {
535
+ const slot = m[1];
536
+ let options = CODE;
537
+ try {
538
+ options = scanValue(text, m.index + m[0].length, new Map(), refused).value;
539
+ }
540
+ catch (err) {
541
+ if (!(err instanceof Stop))
542
+ throw err;
543
+ }
544
+ const loads = !loaders.has(slot) &&
545
+ google.has(m[2]) &&
546
+ canonicalJson(options) === canonicalJson({ subsets: ["latin"], variable: `--font-design-${slot}` });
547
+ loaders.set(slot, loads ? m[2] : CODE);
548
+ }
549
+ const at = (path) => declared.lines.get(path) ?? declared.line;
550
+ const lines = [];
551
+ for (const key of Object.keys(declared.value)) {
552
+ if (key !== "className" && key !== "families") {
553
+ lines.push(`${TAG} ${SITE_FONTS_PATH}: siteFonts holds a key the faces do not carry at line ${at(key)} — not imported`);
554
+ }
555
+ }
556
+ const faces = compileDesignFonts(settings);
557
+ // The loaders the faces need: one per distinct family, named for the first role using it (the renderer's rule).
558
+ const needed = new Map();
559
+ for (const role of ["display", "body"]) {
560
+ const face = faces?.[role];
561
+ if (face !== undefined && !needed.has(face.family))
562
+ needed.set(face.family, role);
563
+ }
564
+ const className = declared.value["className"];
565
+ const span = declared.spans.get("className");
566
+ const classValue = span === undefined ? null : CLASS_NAME_VALUE.exec(text.slice(span[0], span[1]).trim());
567
+ const classSlots = className === ""
568
+ ? []
569
+ : className === CODE && classValue !== null
570
+ ? classValue[1].split(",").map((item) => /^\s*(display|body)Face\.variable\s*$/.exec(item)?.[1] ?? CODE)
571
+ : [CODE];
572
+ if (canonicalJson([...classSlots].sort()) !== canonicalJson([...needed.values()].sort())) {
573
+ lines.push(differs(SITE_FONTS_PATH, at("className"), "siteFonts.className"));
574
+ }
575
+ const families = declared.value["families"];
576
+ if (typeof families !== "object" || families === null || Array.isArray(families) || families === CODE) {
577
+ return [...lines, differs(SITE_FONTS_PATH, at("families"), "siteFonts.families")];
578
+ }
579
+ const declaredFamilies = families;
580
+ for (const key of Object.keys(declaredFamilies)) {
581
+ if (key !== "display" && key !== "body") {
582
+ lines.push(`${TAG} ${SITE_FONTS_PATH}: siteFonts.families holds a key the faces do not carry at line ${at(`families.${key}`)} — not imported`);
583
+ }
584
+ }
585
+ for (const role of ["display", "body"]) {
586
+ const want = faces?.[role];
587
+ const value = declaredFamilies[role];
588
+ const ref = typeof value === "string" ? /^var\(--font-design-(display|body)\)(?:, (.+))?$/.exec(value) : null;
589
+ const got = value === undefined
590
+ ? undefined
591
+ : ref === null
592
+ ? CODE
593
+ : { source: "google", family: loaders.get(ref[1]) ?? CODE, fallback: ref[2] ?? "" };
594
+ const wanted = want === undefined ? undefined : { source: want.source, family: fontExportName(want.family), fallback: want.fallback };
595
+ // `CODE` is `{}` in canonical JSON, which no face and no family name equals; an absent side is `undefined`.
596
+ if (canonicalJson(got) !== canonicalJson(wanted)) {
597
+ lines.push(differs(SITE_FONTS_PATH, at(`families.${role}`), `siteFonts.families.${role}`));
598
+ }
599
+ }
600
+ return lines;
601
+ }
602
+ /** `--out`'s checks before anything is read (exit 2): it must not exist, and its directory must sit outside the site. */
603
+ function checkOut(root, out) {
604
+ const path = resolve(out);
605
+ if (present(path))
606
+ throw new Stop(2, [`${TAG} --out ${printable(out)} already exists`]);
607
+ let parent;
608
+ try {
609
+ parent = realpathSync(dirname(path));
610
+ }
611
+ catch {
612
+ throw new Stop(2, [`${TAG} --out ${printable(out)}: its directory does not exist`]);
613
+ }
614
+ if (parent === root || under(root, parent)) {
615
+ throw new Stop(2, [`${TAG} --out ${printable(out)} sits inside the site; write it outside the checkout`]);
616
+ }
617
+ // Opened inside the directory just checked, never through its unresolved path.
618
+ return join(parent, basename(path));
619
+ }
620
+ /** Every check in one pass (D2 steps 2–4); the lines of each generated file that differs. */
621
+ function differences(pkg, settings, siteMdx, chrome, fonts) {
622
+ const lines = [];
623
+ // Step 2 — the theme, compiled from the settings the record stores.
624
+ if (!/^---\r?\n[\s\S]*?\r?\n---/.test(siteMdx))
625
+ throw fail(`${SITE_MDX_PATH}: has no frontmatter`);
626
+ const spliced = (from) => spliceThemeBlock(siteMdx, compileDesignTheme(from), SITE_MDX_PATH);
627
+ const theme = spliced(settings);
628
+ if (theme !== siteMdx) {
629
+ lines.push(spliced(pkg) === siteMdx
630
+ ? `${TAG} ${SITE_MDX_PATH}: compiled with the design's own deck grounds, which a non-deck home drops — this piece cannot import it`
631
+ : differs(SITE_MDX_PATH, firstDifferingLine(siteMdx, theme)));
632
+ }
633
+ // Step 3 — the layout: the values `site-chrome.ts` declares (#12635).
634
+ lines.push(...chromeDifferences(chrome, settings));
635
+ // Step 4 — the faces `site-fonts.ts` declares; an absent file is equal only when the settings source none.
636
+ if (fonts === undefined) {
637
+ if (compileDesignFonts(settings) !== undefined) {
638
+ lines.push(`${TAG} ${SITE_FONTS_PATH}: missing, but ${DESIGN_SETTINGS_FILE} sources faces — not imported`);
639
+ }
640
+ }
641
+ else {
642
+ lines.push(...fontsDifferences(fonts, settings));
643
+ }
644
+ return lines;
645
+ }
646
+ /** Where the settings' layout came from, as the `layout:` line names it (#12635). */
647
+ function layoutSource(pkg, settings, template) {
648
+ const layout = canonicalJson(settings.layout);
649
+ if (layout === canonicalJson(resolveSiteChrome(undefined, pkg.layout)))
650
+ return DESIGN_SETTINGS_FILE;
651
+ if (layout === canonicalJson(resolveSiteChrome(template, pkg.layout)))
652
+ return `the template's layout over ${DESIGN_SETTINGS_FILE}`;
653
+ return `${basename(SITE_CHROME_PATH)}'s layout over ${DESIGN_SETTINGS_FILE}`;
654
+ }
655
+ /** The summary lines printed after the settings (D2 "On success"). */
656
+ function summary(settings, layout, digest, siteMdx) {
657
+ const faces = compileDesignFonts(settings);
658
+ const faceList = ["display", "body"].flatMap((role) => {
659
+ const face = faces?.[role];
660
+ return face === undefined ? [] : [`${role} ${printable(face.family)} (google)`];
661
+ });
662
+ const pageTypes = Object.keys(settings.sections).map(printable);
663
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(siteMdx)?.[1] ?? "";
664
+ return [
665
+ `settings sha256: ${digest}`,
666
+ `layout: ${layout}`,
667
+ `faces: ${faceList.length === 0 ? "none" : faceList.join(" ")}`,
668
+ `sections: ${pageTypes.length === 0 ? "none" : pageTypes.join(", ")}`,
669
+ ...(/^brand:/m.test(frontmatter) ? ["brand: set in _site.mdx — stays there"] : []),
670
+ ];
671
+ }
672
+ /** Reads, checks and hands over (D2); answers the exit code. */
673
+ export function lookSettings(o) {
674
+ const line = o.onLine ?? (() => { });
675
+ const error = o.onError ?? (() => { });
676
+ try {
677
+ let root;
678
+ try {
679
+ root = realpathSync(o.dir);
680
+ }
681
+ catch {
682
+ throw fail(`the site ${printable(o.dir)} was not found`);
683
+ }
684
+ const out = checkOut(root, o.out);
685
+ const files = {};
686
+ const read = (rel) => {
687
+ const buffer = readOnce(root, rel);
688
+ files[rel] = sha256(buffer);
689
+ return buffer.toString("utf8");
690
+ };
691
+ // The design package, parsed from exactly the bytes hashed.
692
+ const designText = read(DESIGN_SETTINGS_FILE);
693
+ let pkg;
694
+ try {
695
+ pkg = readDesignPackageText(designText, DESIGN_SETTINGS_FILE);
696
+ }
697
+ catch (err) {
698
+ // The field only, never the message: it can quote a value.
699
+ const field = err instanceof DesignPackageError ? `${printable(err.field)} ` : "";
700
+ throw fail(`${DESIGN_SETTINGS_FILE}: ${field}refused by the reader`);
701
+ }
702
+ // The roster `readSiteRoster` would read, and no other.
703
+ const rosterName = rosterNameIn(root);
704
+ let roster;
705
+ if (rosterName !== undefined) {
706
+ const rosterText = read(rosterName);
707
+ try {
708
+ roster = parseSiteRoster(rosterText, rosterName);
709
+ }
710
+ catch {
711
+ throw fail(`${rosterName}: refused by the reader`);
712
+ }
713
+ }
714
+ const siteMdx = read(SITE_MDX_PATH);
715
+ const chrome = readDeclared(read(SITE_CHROME_PATH), "siteChrome", SITE_CHROME_PATH);
716
+ const fontsText = present(join(root, SITE_FONTS_PATH)) ? read(SITE_FONTS_PATH) : undefined;
717
+ const fonts = fontsText === undefined ? undefined : { text: fontsText, declared: readDeclared(fontsText, "siteFonts", SITE_FONTS_PATH) };
718
+ // Step 1 — the settings: the package with the layout `site-chrome.ts` declares (#12635).
719
+ const settings = { ...pkg, layout: resolveSiteChrome(declaredLayout(chrome)) };
720
+ const refused = differences(pkg, settings, siteMdx, chrome, fonts);
721
+ if (refused.length > 0)
722
+ throw new Stop(3, refused);
723
+ const digest = settingsDigest(settings);
724
+ const handOff = {
725
+ kind: LOOK_SETTINGS_KIND,
726
+ format: LOOK_SETTINGS_FORMAT,
727
+ files,
728
+ settingsSha256: digest,
729
+ settings,
730
+ };
731
+ // Created exclusively, mode 0600: an existing file is never overwritten.
732
+ let fd;
733
+ try {
734
+ fd = openSync(out, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
735
+ }
736
+ catch {
737
+ throw new Stop(2, [`${TAG} --out ${printable(o.out)} could not be created`]);
738
+ }
739
+ try {
740
+ writeSync(fd, `${JSON.stringify(handOff, null, 2)}\n`);
741
+ }
742
+ catch {
743
+ // A partial hand-off is never left behind for the next run to refuse.
744
+ closeSync(fd);
745
+ unlinkSync(out);
746
+ throw fail(`--out ${printable(o.out)} could not be written`);
747
+ }
748
+ closeSync(fd);
749
+ line(JSON.stringify(settings, null, 2));
750
+ const templateLayoutOf = o.templateLayoutOf ?? ((r) => r.template.layout);
751
+ const layout = layoutSource(pkg, settings, roster === undefined ? undefined : templateLayoutOf(roster));
752
+ for (const entry of summary(settings, layout, digest, siteMdx))
753
+ line(entry);
754
+ return { exitCode: 0 };
755
+ }
756
+ catch (err) {
757
+ if (!(err instanceof Stop))
758
+ throw err;
759
+ for (const entry of err.lines)
760
+ error(entry);
761
+ return { exitCode: err.code };
762
+ }
763
+ }
764
+ export const LOOK_SETTINGS_HELP = `create-ailk look-settings — the design settings a site's hub design record will hold.
765
+
766
+ Usage:
767
+ create-ailk look-settings [<dir>] --out <file>
768
+
769
+ Arguments:
770
+ <dir> The site checkout. Defaults to the current dir.
771
+
772
+ Options:
773
+ --out <file> Where the settings are handed over: a new file outside the checkout.
774
+ -h, --help Show this help.
775
+
776
+ Reads design.yaml, the site roster, content/_site.mdx, apps/web/lib/site-chrome.ts and
777
+ apps/web/lib/site-fonts.ts as text. The settings take their layout from site-chrome.ts,
778
+ and are handed over only when they compile to the theme: block byte for byte and to the
779
+ values site-chrome.ts and site-fonts.ts declare. Runs no site code and needs no credential.
780
+ The runbook is docs/internal/runbooks/site-design-import.md.
781
+ Exit 0 handed over, 1 a failure, 2 a bad flag or --out, 3 a generated file that differs.
782
+ `;
783
+ export function parseLookSettingsArgs(argv) {
784
+ let parsed;
785
+ try {
786
+ parsed = parseArgs({
787
+ args: argv,
788
+ strict: true,
789
+ allowPositionals: true,
790
+ options: {
791
+ out: { type: "string" },
792
+ help: { type: "boolean", default: false, short: "h" },
793
+ },
794
+ });
795
+ }
796
+ catch (err) {
797
+ throw new ParseError(`look-settings: ${err.message}`);
798
+ }
799
+ const [target, ...rest] = parsed.positionals;
800
+ if (rest.length > 0) {
801
+ throw new ParseError(`look-settings takes at most one site directory, got ${parsed.positionals.length} arguments`);
802
+ }
803
+ const help = parsed.values.help === true;
804
+ if (!help && parsed.values.out === undefined)
805
+ throw new ParseError("look-settings: --out is required");
806
+ return { target, out: parsed.values.out, help };
807
+ }