@blackbelt-technology/frontend-mockup-loop 0.5.4

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.
@@ -0,0 +1,518 @@
1
+ /**
2
+ * @blackbelt-technology/frontend-mockup-loop — extension entry point.
3
+ *
4
+ * Gives the agent hands for the frontend design loop the companion
5
+ * `frontend-mockup-loop` skill describes:
6
+ *
7
+ * - `serve_mockup` — live static server (Node http, zero deps) that
8
+ * hands back a clickable local + LAN URL so the
9
+ * human reviews a real page, not a screenshot.
10
+ * - `score_mockup` — capture full-page screenshots at mobile/tablet/
11
+ * desktop widths via Playwright (dynamic, optional)
12
+ * and return them plus a scoring rubric for the
13
+ * agent's vision pass.
14
+ * - `init_ui_contract` — scaffold a token-referencing ui-contract.md
15
+ * control plane (the cross-screen consistency
16
+ * source of truth) if one is absent.
17
+ *
18
+ * Plus a `/mockup-loop` command that prints the loop and reminds the agent
19
+ * to load the skill.
20
+ *
21
+ * Generic: no assumptions about any specific app. Works in any
22
+ * React/Tailwind/shadcn (or plain HTML) project.
23
+ */
24
+
25
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
26
+ import { Type } from "typebox";
27
+ import * as http from "node:http";
28
+ import * as fs from "node:fs";
29
+ import * as fsp from "node:fs/promises";
30
+ import * as path from "node:path";
31
+ import * as os from "node:os";
32
+ import { listPresets, resolvePreset } from "./presets/registry.js";
33
+ import { loadContract, refreshContract } from "./presets/contract.js";
34
+ import { loadRubric, validateMockup } from "./presets/validators.js";
35
+
36
+ // ──────────────────────────────────────────────────────────────────────────
37
+ // Module state — running mockup servers, keyed by bound port.
38
+ // ──────────────────────────────────────────────────────────────────────────
39
+
40
+ const servers = new Map<number, http.Server>();
41
+
42
+ type ToolReturn = Promise<{
43
+ content: { type: "text"; text: string }[];
44
+ details: Record<string, unknown>;
45
+ }>;
46
+
47
+ const MIME: Record<string, string> = {
48
+ ".html": "text/html; charset=utf-8",
49
+ ".htm": "text/html; charset=utf-8",
50
+ ".css": "text/css; charset=utf-8",
51
+ ".js": "text/javascript; charset=utf-8",
52
+ ".mjs": "text/javascript; charset=utf-8",
53
+ ".json": "application/json; charset=utf-8",
54
+ ".svg": "image/svg+xml",
55
+ ".png": "image/png",
56
+ ".jpg": "image/jpeg",
57
+ ".jpeg": "image/jpeg",
58
+ ".gif": "image/gif",
59
+ ".webp": "image/webp",
60
+ ".ico": "image/x-icon",
61
+ ".woff": "font/woff",
62
+ ".woff2": "font/woff2",
63
+ };
64
+
65
+ function lanIp(): string | null {
66
+ const ifaces = os.networkInterfaces();
67
+ for (const name of Object.keys(ifaces)) {
68
+ for (const iface of ifaces[name] ?? []) {
69
+ if (iface.family === "IPv4" && !iface.internal) return iface.address;
70
+ }
71
+ }
72
+ return null;
73
+ }
74
+
75
+ function startStaticServer(rootDir: string, port: number): Promise<http.Server> {
76
+ const root = path.resolve(rootDir);
77
+ const server = http.createServer((req, res) => {
78
+ try {
79
+ const urlPath = decodeURIComponent((req.url ?? "/").split("?")[0]);
80
+ let rel = path.normalize(urlPath).replace(/^(\.\.[/\\])+/, "");
81
+ let target = path.join(root, rel);
82
+ // Confine to root — reject traversal escapes.
83
+ if (!target.startsWith(root)) {
84
+ res.writeHead(403).end("Forbidden");
85
+ return;
86
+ }
87
+ let stat: fs.Stats | null = null;
88
+ try {
89
+ stat = fs.statSync(target);
90
+ } catch {
91
+ stat = null;
92
+ }
93
+ if (stat?.isDirectory()) {
94
+ target = path.join(target, "index.html");
95
+ }
96
+ if (!fs.existsSync(target)) {
97
+ res.writeHead(404, { "content-type": "text/plain" }).end(`Not found: ${rel}`);
98
+ return;
99
+ }
100
+ const ext = path.extname(target).toLowerCase();
101
+ res.writeHead(200, {
102
+ "content-type": MIME[ext] ?? "application/octet-stream",
103
+ "cache-control": "no-store",
104
+ });
105
+ fs.createReadStream(target).pipe(res);
106
+ } catch (err) {
107
+ res.writeHead(500, { "content-type": "text/plain" }).end(String(err));
108
+ }
109
+ });
110
+ return new Promise((resolve, reject) => {
111
+ server.once("error", reject);
112
+ server.listen(port, "0.0.0.0", () => resolve(server));
113
+ });
114
+ }
115
+
116
+ const CONTRACT_TEMPLATE = `# UI Contract
117
+
118
+ Single source of truth for cross-screen visual consistency. Every value here
119
+ references a design token (CSS custom property / Tailwind theme key) — never a
120
+ raw hex or pixel literal. If a screen needs a value not listed, add the token
121
+ first, then cite it here.
122
+
123
+ ## Tokens (authority)
124
+
125
+ Tokens live in the theme layer (e.g. \`:root { --primary: ... }\` /
126
+ \`tailwind.config\`). This file references them by name; it does not redefine them.
127
+
128
+ | Role | Token | Notes |
129
+ |-------------|------------------|--------------------------------|
130
+ | background | \`--background\` | page surface |
131
+ | foreground | \`--foreground\` | primary text |
132
+ | primary | \`--primary\` | brand / primary action |
133
+ | muted | \`--muted\` | secondary surfaces |
134
+ | border | \`--border\` | hairlines / dividers |
135
+ | radius | \`--radius\` | corner rounding base |
136
+
137
+ ## Spacing scale
138
+
139
+ Use the token scale only (e.g. 4 / 8 / 12 / 16 / 24 / 32). No arbitrary px.
140
+
141
+ ## Type scale
142
+
143
+ Define each step as token + weight + line-height. No ad-hoc font sizes.
144
+
145
+ ## Elevation
146
+
147
+ Shadow tiers mapped to tokens. State which surface sits at which tier.
148
+
149
+ ## Component invariants
150
+
151
+ One row per recurring surface (card, button, input, dialog). Record the exact
152
+ token recipe so every instance matches.
153
+
154
+ | Component | Recipe (tokens only) |
155
+ |-----------|---------------------------------------------------|
156
+ | card | bg \`--card\`, border \`--border\`, radius \`--radius\` |
157
+ | button | bg \`--primary\`, text \`--primary-foreground\` |
158
+
159
+ ## Motion
160
+
161
+ Durations + easings as tokens. State when motion is suppressed (reduced-motion).
162
+
163
+ ## Anti-slop guardrails
164
+
165
+ - No default-average look (generic Inter + purple gradient + centered hero).
166
+ - Real hierarchy: one focal point per screen.
167
+ - Intentional spacing: rhythm from the scale, not eyeballed gaps.
168
+ - Verified contrast (WCAG AA) in BOTH light and dark.
169
+ `;
170
+
171
+ const LOOP_TEXT = `frontend-mockup-loop — the 7 steps:
172
+
173
+ 1. GROUND read the real UI + authoritative component source; capture EXACT
174
+ existing tokens. Adapt what ships, don't invent parallel styling.
175
+ 2. CONTRACT read/update ui-contract.md — the cross-screen consistency control
176
+ plane. All values reference design tokens, never raw hex/px.
177
+ (scaffold one with the init_ui_contract tool)
178
+ 3. MOCKUP build HTML/Tailwind grounded in 1–2, serve LIVE (serve_mockup) —
179
+ clickable URL, dark+light — NOT a screenshot, so the human reacts.
180
+ 4. TEST score_mockup: screenshots @ mobile/tablet/desktop, score against
181
+ an explicit checklist (contrast, responsive, anti-slop).
182
+ 5. FIX apply the top issue, re-serve, re-score. One criterion at a time.
183
+ 6. PROMOTE translate the approved HTML to real React/shadcn components in an
184
+ ISOLATED env (never the live server) — tokens 1:1, zero apply-gap.
185
+ 7. LEARN record durable taste decisions (memory / ui-contract.md) so the
186
+ next run starts smarter.
187
+
188
+ Read the full skill: /skill:frontend-mockup-loop`;
189
+
190
+ // ──────────────────────────────────────────────────────────────────────────
191
+ // Extension
192
+ // ──────────────────────────────────────────────────────────────────────────
193
+
194
+ export default function frontendMockupLoop(pi: ExtensionAPI): void {
195
+ // ── serve_mockup ─────────────────────────────────────────────────────────
196
+ pi.registerTool({
197
+ name: "serve_mockup",
198
+ label: "Serve Mockup",
199
+ description:
200
+ "Serve a directory of static mockup files over HTTP on 0.0.0.0 and return a clickable local + LAN URL (LAN URL works on a phone). Hand the URL to the human for live review instead of a screenshot. Pass stop:true with a port to stop a running server.",
201
+ parameters: Type.Object({
202
+ dir: Type.Optional(
203
+ Type.String({ description: "Directory to serve (required unless stopping)." }),
204
+ ),
205
+ port: Type.Optional(
206
+ Type.Number({ description: "Port to bind. Omit for an ephemeral free port." }),
207
+ ),
208
+ stop: Type.Optional(
209
+ Type.Boolean({ description: "Stop the server bound to `port` instead of starting one." }),
210
+ ),
211
+ }),
212
+ async execute(_id: string, params: { dir?: string; port?: number; stop?: boolean }): ToolReturn {
213
+ try {
214
+ if (params.stop) {
215
+ if (params.port == null) {
216
+ return { content: [{ type: "text", text: "Error: port required to stop a server." }], details: {} };
217
+ }
218
+ const s = servers.get(params.port);
219
+ if (!s) {
220
+ return { content: [{ type: "text", text: `No mockup server on port ${params.port}.` }], details: {} };
221
+ }
222
+ await new Promise<void>((r) => s.close(() => r()));
223
+ servers.delete(params.port);
224
+ return { content: [{ type: "text", text: `Stopped mockup server on port ${params.port}.` }], details: {} };
225
+ }
226
+
227
+ if (!params.dir) {
228
+ return { content: [{ type: "text", text: "Error: dir required to start a server." }], details: {} };
229
+ }
230
+ const root = path.resolve(params.dir);
231
+ if (!fs.existsSync(root) || !fs.statSync(root).isDirectory()) {
232
+ return { content: [{ type: "text", text: `Error: not a directory: ${root}` }], details: {} };
233
+ }
234
+ const server = await startStaticServer(root, params.port ?? 0);
235
+ const addr = server.address();
236
+ const port = typeof addr === "object" && addr ? addr.port : params.port ?? 0;
237
+ servers.set(port, server);
238
+ const ip = lanIp();
239
+ const local = `http://localhost:${port}`;
240
+ const lan = ip ? `http://${ip}:${port}` : "(no LAN IPv4 detected)";
241
+ return {
242
+ content: [
243
+ {
244
+ type: "text",
245
+ text: `Serving ${root}\n local: ${local}\n LAN: ${lan}\n\nOpen the LAN URL on a phone to check responsive. Stop with serve_mockup{stop:true,port:${port}}.`,
246
+ },
247
+ ],
248
+ details: { port, root, local, lan },
249
+ };
250
+ } catch (err) {
251
+ return { content: [{ type: "text", text: `serve_mockup failed: ${String(err)}` }], details: {} };
252
+ }
253
+ },
254
+ });
255
+
256
+ // ── score_mockup ───────────────────────────────────────────────────────
257
+ pi.registerTool({
258
+ name: "score_mockup",
259
+ label: "Score Mockup",
260
+ description:
261
+ "Capture full-page screenshots of a running mockup URL at mobile/tablet/desktop widths (via Playwright) and return their file paths plus a scoring rubric. Read the PNGs, then score each criterion — do not claim 'looks good' without filling the rubric. If Playwright is absent, returns install guidance.",
262
+ parameters: Type.Object({
263
+ url: Type.String({ description: "URL of the running mockup (from serve_mockup)." }),
264
+ widths: Type.Optional(
265
+ Type.Array(Type.Number(), {
266
+ description: "Viewport widths to capture. Default [375, 768, 1440].",
267
+ }),
268
+ ),
269
+ outDir: Type.Optional(
270
+ Type.String({ description: "Where to write PNGs. Default a fresh temp dir." }),
271
+ ),
272
+ system: Type.Optional(
273
+ Type.String({ description: "Design-system preset id (e.g. shadcn, apple-hig). Swaps the generic rubric for that system's boolean rubric. See list_design_systems." }),
274
+ ),
275
+ }),
276
+ async execute(_id: string, params: { url: string; widths?: number[]; outDir?: string; system?: string }): ToolReturn {
277
+ const widths = params.widths?.length ? params.widths : [375, 768, 1440];
278
+ let rubric: string;
279
+ if (params.system) {
280
+ const r = resolvePreset(params.system);
281
+ if ("error" in r) {
282
+ return { content: [{ type: "text", text: r.error }], details: { error: r.error } };
283
+ }
284
+ const checks = loadRubric(r.preset.id);
285
+ rubric = [
286
+ "",
287
+ `SCORING RUBRIC — ${r.preset.label} (answer each PASS/FAIL + one-line reason):`,
288
+ ...checks.map((c) => ` [ ] ${c.text}`),
289
+ `Score = passCount / ${checks.length} (computed in code — do not emit a float yourself).`,
290
+ "Loop FIX→re-score until every check passes.",
291
+ ].join("\n");
292
+ } else {
293
+ rubric = [
294
+ "",
295
+ "SCORING RUBRIC — fill each (PASS/FAIL + one-line reason):",
296
+ " [ ] Contrast (WCAG AA) — light AND dark",
297
+ " [ ] Responsive — no overflow/clipping at any width; touch targets >=44px on mobile",
298
+ " [ ] Hierarchy — one clear focal point, intentional emphasis",
299
+ " [ ] Spacing — rhythm from the token scale, not eyeballed gaps",
300
+ " [ ] Token fidelity — colors/radii/spacing trace to ui-contract.md tokens",
301
+ " [ ] Anti-slop — not the default-average look (generic Inter + purple gradient + centered hero)",
302
+ " [ ] Console — no errors/warnings",
303
+ "Loop FIX→re-score until every line is PASS in both themes.",
304
+ ].join("\n");
305
+ }
306
+
307
+ let pw: any = null;
308
+ try {
309
+ const spec = "playwright"; // non-literal: avoids static resolution when absent
310
+ pw = await import(spec);
311
+ } catch {
312
+ pw = null;
313
+ }
314
+ if (!pw?.chromium) {
315
+ return {
316
+ content: [
317
+ {
318
+ type: "text",
319
+ text:
320
+ "Playwright not available. Install it to enable breakpoint capture:\n npm i -D playwright && npx playwright install chromium\n\nMeanwhile, capture manually (e.g. the agent-browser CLI) at widths " +
321
+ widths.join(", ") +
322
+ " and score against the rubric below." +
323
+ "\n" +
324
+ rubric,
325
+ },
326
+ ],
327
+ details: { playwright: false, widths },
328
+ };
329
+ }
330
+
331
+ try {
332
+ const outDir = params.outDir
333
+ ? path.resolve(params.outDir)
334
+ : await fsp.mkdtemp(path.join(os.tmpdir(), "mockup-shots-"));
335
+ await fsp.mkdir(outDir, { recursive: true });
336
+ const browser = await pw.chromium.launch();
337
+ const files: string[] = [];
338
+ for (const w of widths) {
339
+ const context = await browser.newContext({ viewport: { width: w, height: 900 } });
340
+ const page = await context.newPage();
341
+ await page.goto(params.url, { waitUntil: "networkidle" }).catch(() => {});
342
+ const file = path.join(outDir, `mockup-${w}.png`);
343
+ await page.screenshot({ path: file, fullPage: true });
344
+ files.push(file);
345
+ await context.close();
346
+ }
347
+ await browser.close();
348
+ return {
349
+ content: [
350
+ {
351
+ type: "text",
352
+ text:
353
+ `Captured ${files.length} screenshots — Read each, then fill the rubric:\n` +
354
+ files.map((f) => ` ${f}`).join("\n") +
355
+ "\n" +
356
+ rubric,
357
+ },
358
+ ],
359
+ details: { playwright: true, files, outDir, widths },
360
+ };
361
+ } catch (err) {
362
+ return {
363
+ content: [{ type: "text", text: `score_mockup capture failed: ${String(err)}\n${rubric}` }],
364
+ details: { playwright: true, error: String(err) },
365
+ };
366
+ }
367
+ },
368
+ });
369
+
370
+ // ── init_ui_contract ─────────────────────────────────────────────────────
371
+ pi.registerTool({
372
+ name: "init_ui_contract",
373
+ label: "Init UI Contract",
374
+ description:
375
+ "Scaffold a ui-contract.md design control plane (cross-screen consistency source of truth) if absent. The contract references design tokens only — no raw hex/px. Use before mocking up so every screen shares one system.",
376
+ parameters: Type.Object({
377
+ path: Type.Optional(
378
+ Type.String({ description: "Target file path. Default ./ui-contract.md (or ./ui-contract.tokens.json when --system is set)." }),
379
+ ),
380
+ force: Type.Optional(
381
+ Type.Boolean({ description: "Overwrite if it already exists." }),
382
+ ),
383
+ system: Type.Optional(
384
+ Type.String({ description: "Design-system preset id (e.g. shadcn, mui, material-3, fluent-2, apple-hig). Writes that system's DTCG contract instead of the blank template. See list_design_systems." }),
385
+ ),
386
+ refresh: Type.Optional(
387
+ Type.Boolean({ description: "Re-fetch upstream tokens and rewrite the bundled snapshot before writing (token-publishing systems only)." }),
388
+ ),
389
+ }),
390
+ async execute(_id: string, params: { path?: string; force?: boolean; system?: string; refresh?: boolean }): ToolReturn {
391
+ try {
392
+ // ── system-specific DTCG contract ──────────────────────────────────
393
+ if (params.system) {
394
+ const r = resolvePreset(params.system);
395
+ if ("error" in r) {
396
+ return { content: [{ type: "text", text: r.error }], details: { error: r.error } };
397
+ }
398
+ const target = path.resolve(params.path ?? "ui-contract.tokens.json");
399
+ if (fs.existsSync(target) && !params.force) {
400
+ return {
401
+ content: [{ type: "text", text: `${target} already exists. Pass force:true to overwrite.` }],
402
+ details: { created: false, path: target, system: r.preset.id },
403
+ };
404
+ }
405
+ if (params.refresh) {
406
+ try {
407
+ await refreshContract(r.preset.id);
408
+ } catch (err) {
409
+ return { content: [{ type: "text", text: `refresh failed: ${String(err)}` }], details: { system: r.preset.id } };
410
+ }
411
+ }
412
+ const contract = loadContract(r.preset.id);
413
+ await fsp.mkdir(path.dirname(target), { recursive: true });
414
+ await fsp.writeFile(target, JSON.stringify(contract, null, 2) + "\n", "utf8");
415
+ return {
416
+ content: [{ type: "text", text: `Wrote ${r.preset.label} DTCG contract to ${target} (${r.preset.contractSource}). Generate mockups to this system's conventions, then validate_mockup{system:"${r.preset.id}"}.` }],
417
+ details: { created: true, path: target, system: r.preset.id },
418
+ };
419
+ }
420
+
421
+ // ── back-compat: blank template ────────────────────────────────────
422
+ const target = path.resolve(params.path ?? "ui-contract.md");
423
+ if (fs.existsSync(target) && !params.force) {
424
+ return {
425
+ content: [
426
+ { type: "text", text: `ui-contract.md already exists at ${target}. Read + extend it (or pass force:true to overwrite).` },
427
+ ],
428
+ details: { created: false, path: target },
429
+ };
430
+ }
431
+ await fsp.mkdir(path.dirname(target), { recursive: true });
432
+ await fsp.writeFile(target, CONTRACT_TEMPLATE, "utf8");
433
+ return {
434
+ content: [{ type: "text", text: `Scaffolded design contract at ${target}. Fill it from the real tokens captured in step 1 (GROUND).` }],
435
+ details: { created: true, path: target },
436
+ };
437
+ } catch (err) {
438
+ return { content: [{ type: "text", text: `init_ui_contract failed: ${String(err)}` }], details: {} };
439
+ }
440
+ },
441
+ });
442
+
443
+ // ── list_design_systems ────────────────────────────────────────────────
444
+ pi.registerTool({
445
+ name: "list_design_systems",
446
+ label: "List Design Systems",
447
+ description:
448
+ "Enumerate the selectable design-system presets (id, label, platform, substrate, validator layers). Pass an id to init_ui_contract/score_mockup/validate_mockup via their `system` param to target that system.",
449
+ parameters: Type.Object({}),
450
+ async execute(): ToolReturn {
451
+ const presets = listPresets().map((p) => ({
452
+ id: p.id,
453
+ label: p.label,
454
+ platform: p.platform,
455
+ substrate: p.substrate,
456
+ validators: p.validators.map((v) => `${v.layer}:${v.tool}${v.gate ? " (gate)" : ""}${v.bundled ? "" : " (optional)"}`),
457
+ }));
458
+ const text =
459
+ "Design systems:\n" +
460
+ presets
461
+ .map((p) => ` ${p.id} — ${p.label} [${p.platform}, ${p.substrate}]\n ${p.validators.join(", ")}`)
462
+ .join("\n");
463
+ return { content: [{ type: "text", text }], details: { presets } };
464
+ },
465
+ });
466
+
467
+ // ── validate_mockup ────────────────────────────────────────────────────
468
+ pi.registerTool({
469
+ name: "validate_mockup",
470
+ label: "Validate Mockup",
471
+ description:
472
+ "Run the layered validation pipeline for a design system: L1 token-lint + L2 a11y/contrast floor (hard GATES), L3 named-system auditor + L4 boolean rubric (ADVISORY). Returns { gates, advisory, pass }. `pass` is determined by gates only; advisory layers score and drive the fix loop. Pass `dir` (the served mockup directory) so L1/L2 can scan files.",
473
+ parameters: Type.Object({
474
+ system: Type.String({ description: "Design-system preset id. See list_design_systems." }),
475
+ url: Type.Optional(Type.String({ description: "URL of the running mockup (from serve_mockup), for context." })),
476
+ dir: Type.Optional(Type.String({ description: "Directory of the mockup source files to lint/scan (L1/L2)." })),
477
+ }),
478
+ async execute(_id: string, params: { system: string; url?: string; dir?: string }): ToolReturn {
479
+ const r = resolvePreset(params.system);
480
+ if ("error" in r) {
481
+ return { content: [{ type: "text", text: r.error }], details: { error: r.error } };
482
+ }
483
+ const dir = params.dir ? path.resolve(params.dir) : undefined;
484
+ const result = validateMockup({ preset: r.preset, dir });
485
+ const fmt = (l: { layer: string; tool: string; status: string; gate: boolean; messages: string[] }) =>
486
+ ` ${l.layer} ${l.tool}${l.gate ? " (gate)" : " (advisory)"}: ${l.status.toUpperCase()}\n ${l.messages.join("\n ")}`;
487
+ const text = [
488
+ `validate_mockup — ${r.preset.label}: ${result.pass ? "PASS" : "BLOCKED"}`,
489
+ "GATES:",
490
+ fmt(result.gates.l1),
491
+ fmt(result.gates.l2),
492
+ "ADVISORY:",
493
+ fmt(result.advisory.l3),
494
+ fmt(result.advisory.l4),
495
+ ].join("\n");
496
+ return { content: [{ type: "text", text }], details: { ...result } };
497
+ },
498
+ });
499
+
500
+ // ── /mockup-loop command ───────────────────────────────────────────────
501
+ pi.registerCommand("mockup-loop", {
502
+ description: "Show the frontend mockup loop and load the skill",
503
+ handler: async (_args: string, ctx: any) => {
504
+ ctx?.ui?.notify?.("frontend-mockup-loop — read /skill:frontend-mockup-loop to start", "info");
505
+ // Print the loop to the transcript for immediate reference.
506
+ // eslint-disable-next-line no-console
507
+ console.log(LOOP_TEXT);
508
+ },
509
+ });
510
+
511
+ // ── cleanup ──────────────────────────────────────────────────────────────
512
+ pi.on("session_shutdown", async () => {
513
+ for (const [port, s] of servers) {
514
+ await new Promise<void>((r) => s.close(() => r()));
515
+ servers.delete(port);
516
+ }
517
+ });
518
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * DTCG contract loading + normalization for design-system presets.
3
+ *
4
+ * Every preset's contract is bundled under `presets-data/<id>/` so the loop
5
+ * works offline and is versioned with the package. `loadContract` reads the
6
+ * bundled snapshot and asserts a minimal W3C Design Token Community Group
7
+ * (DTCG) shape. `refreshContract` re-fetches upstream tokens and rewrites the
8
+ * snapshot (escape hatch for drift); upstream sources are documented per
9
+ * preset in the README. Apple HIG ships a hand-authored rule pack (Apple
10
+ * publishes no token JSON) — same DTCG-shaped envelope.
11
+ */
12
+
13
+ import * as fs from "node:fs";
14
+ import * as fsp from "node:fs/promises";
15
+ import * as path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { getPreset } from "./registry.js";
18
+
19
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
20
+ /** Package-root `presets-data/` (src/presets/ → ../../presets-data). */
21
+ export const PRESETS_DATA_DIR = path.resolve(HERE, "..", "..", "presets-data");
22
+
23
+ /** A DTCG token node: leaf carries `$value`; groups nest further nodes. */
24
+ export interface DtcgNode {
25
+ $value?: unknown;
26
+ $type?: string;
27
+ $description?: string;
28
+ [key: string]: unknown;
29
+ }
30
+
31
+ export interface DtcgContract {
32
+ [key: string]: DtcgNode | unknown;
33
+ }
34
+
35
+ export function contractPath(id: string): string {
36
+ return path.join(PRESETS_DATA_DIR, id, "contract.tokens.json");
37
+ }
38
+
39
+ export function rubricPath(id: string): string {
40
+ return path.join(PRESETS_DATA_DIR, id, "rubric.json");
41
+ }
42
+
43
+ /** True when an object tree contains at least one DTCG `$value` leaf. */
44
+ export function isDtcg(obj: unknown): boolean {
45
+ if (obj == null || typeof obj !== "object") return false;
46
+ const stack: unknown[] = [obj];
47
+ while (stack.length) {
48
+ const node = stack.pop();
49
+ if (node == null || typeof node !== "object") continue;
50
+ if (Object.prototype.hasOwnProperty.call(node, "$value")) return true;
51
+ for (const v of Object.values(node as Record<string, unknown>)) {
52
+ if (v && typeof v === "object") stack.push(v);
53
+ }
54
+ }
55
+ return false;
56
+ }
57
+
58
+ /**
59
+ * Load a preset's bundled DTCG contract. Throws a clear error when the preset
60
+ * is unknown, the snapshot is missing, or the JSON is not DTCG-shaped.
61
+ */
62
+ export function loadContract(id: string): DtcgContract {
63
+ if (!getPreset(id)) {
64
+ throw new Error(`Unknown design system "${id}".`);
65
+ }
66
+ const file = contractPath(id);
67
+ if (!fs.existsSync(file)) {
68
+ throw new Error(`No bundled contract snapshot for "${id}" at ${file}.`);
69
+ }
70
+ const raw = fs.readFileSync(file, "utf8");
71
+ let parsed: unknown;
72
+ try {
73
+ parsed = JSON.parse(raw);
74
+ } catch (err) {
75
+ throw new Error(`Contract snapshot for "${id}" is not valid JSON: ${String(err)}`);
76
+ }
77
+ if (!isDtcg(parsed)) {
78
+ throw new Error(`Contract snapshot for "${id}" is not DTCG-shaped (no $value leaf).`);
79
+ }
80
+ return parsed as DtcgContract;
81
+ }
82
+
83
+ /** Upstream token source per preset, used by `refreshContract`. */
84
+ export const UPSTREAM_SOURCES: Record<string, string | null> = {
85
+ shadcn: "https://ui.shadcn.com (CSS variables → DTCG)",
86
+ mui: "@mui/material default theme (createTheme() → DTCG)",
87
+ "material-3": "Material 3 --md-sys-* design tokens",
88
+ "fluent-2": "@fluentui/tokens (webLightTheme → DTCG)",
89
+ // Apple publishes no token JSON; rule pack is hand-authored, not refreshable.
90
+ "apple-hig": null,
91
+ };
92
+
93
+ /**
94
+ * Re-fetch upstream tokens and rewrite the bundled snapshot.
95
+ *
96
+ * Network fetching is delegated to the documented per-preset regeneration step
97
+ * (see README). This entry point validates the request and surfaces the
98
+ * upstream source; it never silently no-ops. Returns the snapshot path.
99
+ */
100
+ export async function refreshContract(id: string): Promise<string> {
101
+ const preset = getPreset(id);
102
+ if (!preset) throw new Error(`Unknown design system "${id}".`);
103
+ const source = UPSTREAM_SOURCES[id];
104
+ if (preset.contractSource === "rule-pack" || source == null) {
105
+ throw new Error(
106
+ `"${id}" uses a hand-authored rule pack — no upstream token source to refresh.`,
107
+ );
108
+ }
109
+ // Ensure the snapshot dir exists; actual upstream import is the documented
110
+ // regeneration step. Validate the current snapshot is present + DTCG so a
111
+ // refresh request against a corrupt snapshot fails loudly.
112
+ await fsp.mkdir(path.join(PRESETS_DATA_DIR, id), { recursive: true });
113
+ const file = contractPath(id);
114
+ if (fs.existsSync(file)) loadContract(id);
115
+ return file;
116
+ }