@blackbelt-technology/frontend-mockup-loop 0.11.0 → 0.12.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 (49) hide show
  1. package/.pi/skills/frontend-mockup-loop/SKILL.md +87 -8
  2. package/README.md +47 -2
  3. package/package.json +43 -4
  4. package/references/live-mock-site.md +332 -0
  5. package/site/Site.tsx +627 -0
  6. package/site/clock.ts +39 -0
  7. package/site/fixtures.ts +144 -0
  8. package/site/frame-env.ts +59 -0
  9. package/site/kit.tsx +175 -0
  10. package/site/main.tsx +11 -0
  11. package/site/pane-runtime.ts +230 -0
  12. package/site/pane-scroll-guard.ts +70 -0
  13. package/site/ring-line.ts +100 -0
  14. package/site/script.ts +201 -0
  15. package/site/site.css +179 -0
  16. package/site/step-gate.ts +138 -0
  17. package/site/tsconfig.json +16 -0
  18. package/site/virtual.d.ts +16 -0
  19. package/src/extension.ts +189 -58
  20. package/src/mock-site/base.d.mts +2 -0
  21. package/src/mock-site/base.mjs +28 -0
  22. package/src/mock-site/browser.d.mts +8 -0
  23. package/src/mock-site/browser.mjs +72 -0
  24. package/src/mock-site/capture.d.mts +8 -0
  25. package/src/mock-site/capture.mjs +221 -0
  26. package/src/mock-site/check.mjs +8 -0
  27. package/src/mock-site/cli.d.mts +3 -0
  28. package/src/mock-site/cli.mjs +96 -0
  29. package/src/mock-site/decisions.d.mts +6 -0
  30. package/src/mock-site/decisions.mjs +71 -0
  31. package/src/mock-site/discover.d.mts +7 -0
  32. package/src/mock-site/discover.mjs +137 -0
  33. package/src/mock-site/env.d.mts +15 -0
  34. package/src/mock-site/env.mjs +228 -0
  35. package/src/mock-site/frameworks.d.mts +5 -0
  36. package/src/mock-site/frameworks.mjs +27 -0
  37. package/src/mock-site/headless.d.mts +9 -0
  38. package/src/mock-site/headless.mjs +207 -0
  39. package/src/mock-site/locate.d.mts +3 -0
  40. package/src/mock-site/locate.mjs +30 -0
  41. package/src/mock-site/options.d.mts +19 -0
  42. package/src/mock-site/options.mjs +45 -0
  43. package/src/mock-site/plugin.d.mts +21 -0
  44. package/src/mock-site/plugin.mjs +191 -0
  45. package/src/mock-site/refs.d.mts +7 -0
  46. package/src/mock-site/refs.mjs +65 -0
  47. package/src/mock-site/serve-cli.mjs +43 -0
  48. package/src/mock-site/video.mjs +8 -0
  49. package/src/mock-site-serve.ts +186 -0
@@ -0,0 +1,221 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // mock-capture — record a running app's HTTP traffic for a URL (Playwright HAR),
4
+ // redact credential-bearing headers / cookies / query params / JSON body keys,
5
+ // REFUSE to write when a secret pattern survives, and write `fixtures.har.json`
6
+ // into the mock dir. HTTP only: WebSocket fixtures are written by hand.
7
+ // mock-capture <url> <mockDir> [--redact <key>]... [--out <file>]
8
+ // See change: add-mock-site-exact-env (design D3, "Secret patterns").
9
+ import * as fs from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { pathToFileURL } from "node:url";
13
+
14
+ export const REDACTED = "[REDACTED]";
15
+ /** Built-in redaction list: authorization, cookies, password, secret, token, api-key-like, session keys. */
16
+ const DEFAULT_KEY_RE = /authorization|cookie|passw(or)?d|secret|token|api[-_]?key|session/i;
17
+ /** @type {[string, RegExp][]} */
18
+ export const SECRET_PATTERNS = [
19
+ ["bearer token", /\bBearer\s+[A-Za-z0-9._~+/-]{6,}=*/],
20
+ ["JWT", /\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}/],
21
+ ["sk- key", /\bsk-[A-Za-z0-9_-]{12,}/],
22
+ ["GitHub token", /\bgh[po]_[A-Za-z0-9]{20,}/],
23
+ ["GitHub PAT", /\bgithub_pat_[A-Za-z0-9_]{20,}/],
24
+ ["Slack token", /\bxox[abprs]-[A-Za-z0-9-]{10,}/],
25
+ ["AWS access key", /\bAKIA[0-9A-Z]{16}\b/],
26
+ ["Google API key", /\bAIza[0-9A-Za-z_-]{35}/],
27
+ ];
28
+
29
+ /** @param {string[]} extra */
30
+ const keyMatcher = (extra) => {
31
+ const set = new Set(extra.map((k) => k.toLowerCase()));
32
+ return (/** @type {string} */ k) => DEFAULT_KEY_RE.test(k) || set.has(k.toLowerCase());
33
+ };
34
+
35
+ /** Deep-redact JSON values under matching keys. @param {unknown} v @param {(k: string) => boolean} hit @returns {unknown} */
36
+ function redactJson(v, hit) {
37
+ if (Array.isArray(v)) return v.map((x) => redactJson(x, hit));
38
+ if (v && typeof v === "object") return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, hit(k) ? REDACTED : redactJson(x, hit)]));
39
+ return v;
40
+ }
41
+
42
+ /** @param {string|undefined} text @param {(k: string) => boolean} hit */
43
+ function redactBody(text, hit) {
44
+ if (typeof text !== "string" || !text) return text;
45
+ try { return JSON.stringify(redactJson(JSON.parse(text), hit)); } catch { return text; }
46
+ }
47
+
48
+ /** @param {{ name: string, value: string }[]|undefined} list @param {(k: string) => boolean} hit */
49
+ const redactPairs = (list, hit) => (list ?? []).map((p) => (hit(p.name) ? { ...p, value: REDACTED } : p));
50
+
51
+ /**
52
+ * Redact a HAR in place-safe copy: headers, cookies, query (and the URL), JSON bodies.
53
+ * @param {any} har @param {string[]} [extra] additional key names
54
+ */
55
+ export function redactHar(har, extra = []) {
56
+ const hit = keyMatcher(extra);
57
+ const out = structuredClone(har);
58
+ for (const e of out.log?.entries ?? []) {
59
+ const rq = e.request ?? {}, rs = e.response ?? {};
60
+ rq.headers = redactPairs(rq.headers, hit);
61
+ rs.headers = redactPairs(rs.headers, hit);
62
+ rq.cookies = redactPairs(rq.cookies, hit);
63
+ rs.cookies = redactPairs(rs.cookies, hit);
64
+ rq.queryString = redactPairs(rq.queryString, hit);
65
+ if (typeof rq.url === "string") {
66
+ try {
67
+ const u = new URL(rq.url);
68
+ for (const k of [...u.searchParams.keys()]) if (hit(k)) u.searchParams.set(k, REDACTED);
69
+ rq.url = u.toString();
70
+ } catch { /* keep */ }
71
+ }
72
+ if (rq.postData?.text) rq.postData.text = redactBody(rq.postData.text, hit);
73
+ if (rs.content?.text) rs.content.text = redactBody(rs.content.text, hit);
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** @param {string} s */
79
+ const matchSecret = (s) => SECRET_PATTERNS.find(([, re]) => re.test(s))?.[0];
80
+
81
+ /** @param {unknown} v @param {string} at @returns {{ at: string, kind: string } | null} */
82
+ function scanJson(v, at) {
83
+ if (typeof v === "string") { const k = matchSecret(v); return k ? { at, kind: k } : null; }
84
+ if (Array.isArray(v)) { for (let i = 0; i < v.length; i++) { const r = scanJson(v[i], `${at}[${i}]`); if (r) return r; } return null; }
85
+ if (v && typeof v === "object") { for (const [k, x] of Object.entries(v)) { const r = scanJson(x, `${at}.${k}`); if (r) return r; } }
86
+ return null;
87
+ }
88
+
89
+ /** @param {string|undefined} text @param {string} where */
90
+ function scanBody(text, where) {
91
+ if (typeof text !== "string" || !text) return null;
92
+ try {
93
+ const r = scanJson(JSON.parse(text), "$");
94
+ return r ? { location: `${where} ${r.at}`, kind: r.kind } : null;
95
+ } catch {
96
+ const k = matchSecret(text);
97
+ return k ? { location: where, kind: k } : null;
98
+ }
99
+ }
100
+
101
+ /**
102
+ * First secret left in a (redacted) HAR, naming the entry and JSON path; null when clean.
103
+ * @param {any} har
104
+ * @returns {{ location: string, kind: string } | null}
105
+ */
106
+ export function scanSecrets(har) {
107
+ const entries = har.log?.entries ?? [];
108
+ for (let i = 0; i < entries.length; i++) {
109
+ const { request: rq = {}, response: rs = {} } = entries[i];
110
+ const label = `entry ${i} (${rq.method ?? "?"} ${rq.url ?? "?"})`;
111
+ // Every field redactHar touches is scanned: a value under a key the list misses must still refuse.
112
+ const urlKind = matchSecret(String(rq.url ?? ""));
113
+ if (urlKind) return { location: `${label} url`, kind: urlKind };
114
+ for (const [side, list] of /** @type {const} */ ([["request header", rq.headers], ["response header", rs.headers], ["request cookie", rq.cookies], ["response cookie", rs.cookies], ["query", rq.queryString]])) {
115
+ for (const p of list ?? []) { const k = matchSecret(String(p.value)); if (k) return { location: `${label} ${side} ${p.name}`, kind: k }; }
116
+ }
117
+ const r = scanBody(rq.postData?.text, `${label} request body`) ?? scanBody(rs.content?.text, `${label} response body`);
118
+ if (r) return r;
119
+ }
120
+ return null;
121
+ }
122
+
123
+ /**
124
+ * Keep the app's data requests (fetch / XHR, or JSON responses) as replayable entries.
125
+ * @param {any} har @param {string} source
126
+ */
127
+ export function harToFixtures(har, source) {
128
+ const entries = (har.log?.entries ?? []).filter((/** @type {any} */ e) => {
129
+ const t = e._resourceType;
130
+ const mime = String(e.response?.content?.mimeType ?? "");
131
+ return t === "fetch" || t === "xhr" || (!t && mime.includes("json"));
132
+ }).map((/** @type {any} */ e) => {
133
+ const u = new URL(e.request.url);
134
+ return {
135
+ method: String(e.request.method).toUpperCase(),
136
+ path: u.pathname,
137
+ query: u.search,
138
+ status: e.response.status,
139
+ contentType: String(e.response.content?.mimeType ?? "application/json"),
140
+ body: e.response.content?.encoding === "base64" ? "" : (e.response.content?.text ?? ""),
141
+ };
142
+ });
143
+ return { version: 1, source, entries };
144
+ }
145
+
146
+ /**
147
+ * Redact, refuse on secrets, convert, write. Writes nothing on refusal.
148
+ * @param {any} har @param {{ out: string, source: string, redact?: string[] }} o
149
+ * @returns {{ ok: true, file: string, count: number } | { ok: false, error: string }}
150
+ */
151
+ export function writeFixtures(har, o) {
152
+ const clean = redactHar(har, o.redact ?? []);
153
+ const hit = scanSecrets(clean);
154
+ if (hit) return { ok: false, error: `refusing to write ${o.out}: ${hit.kind} at ${hit.location}. Add its key with --redact <key> (or "redact" in the mock options), or strip it from the app's data` };
155
+ let fx;
156
+ try { fx = harToFixtures(clean, o.source); } catch (e) { return { ok: false, error: `malformed HAR: ${String(/** @type {Error} */ (e).message).split("\n")[0]}` }; }
157
+ fs.mkdirSync(path.dirname(o.out), { recursive: true });
158
+ fs.writeFileSync(o.out, JSON.stringify(fx, null, 2) + "\n");
159
+ return { ok: true, file: o.out, count: fx.entries.length };
160
+ }
161
+
162
+ /** Record a HAR of one page load with Playwright. @param {string} url @returns {Promise<any>} */
163
+ async function recordHar(url) {
164
+ const spec = "playwright";
165
+ const pw = await import(spec).catch(() => null);
166
+ if (!pw?.chromium) throw new Error("playwright not installed: npm i -D playwright");
167
+ const { launchChromium } = await import("./browser.mjs");
168
+ const { browser } = await launchChromium(pw.chromium);
169
+ const tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "mock-capture-")), "capture.har");
170
+ try {
171
+ const ctx = await browser.newContext({ recordHar: { path: tmp, content: "embed" } });
172
+ const page = await ctx.newPage();
173
+ await page.goto(url, { waitUntil: "networkidle" });
174
+ await ctx.close();
175
+ return JSON.parse(fs.readFileSync(tmp, "utf8"));
176
+ } finally {
177
+ await browser.close();
178
+ fs.rmSync(path.dirname(tmp), { recursive: true, force: true });
179
+ }
180
+ }
181
+
182
+ /**
183
+ * @param {string[]} argv @param {{ cwd?: string, record?: (url: string) => Promise<any>, redact?: string[] }} [deps]
184
+ * @returns {Promise<{ code: number, out: string }>}
185
+ */
186
+ export async function run(argv, deps = {}) {
187
+ const usage = "usage: mock-capture <url> <mockDir> [--redact <key>]... [--out <file>]";
188
+ /** @type {string[]} */
189
+ const pos = [], redact = [...(deps.redact ?? [])];
190
+ let out;
191
+ for (let i = 0; i < argv.length; i++) {
192
+ if (argv[i] === "--redact" && argv[i + 1]) redact.push(argv[++i]);
193
+ else if (argv[i] === "--out" && argv[i + 1]) out = argv[++i];
194
+ else pos.push(argv[i]);
195
+ }
196
+ const [url, mockDir] = pos;
197
+ if (!url || !mockDir || !/^https?:\/\//.test(url)) return { code: 2, out: usage };
198
+ const cwd = deps.cwd ?? process.cwd();
199
+ const file = path.resolve(cwd, out ?? path.join(mockDir, "fixtures.har.json"));
200
+ let har;
201
+ try { har = await (deps.record ?? recordHar)(url); } catch (e) { return { code: 1, out: `capture failed: ${String(/** @type {Error} */ (e).message).split("\n")[0]}` }; }
202
+ const r = writeFixtures(har, { out: file, source: url, redact });
203
+ if (!r.ok) return { code: 1, out: r.error };
204
+ return { code: 0, out: `wrote ${r.count} HTTP fixtures to ${r.file} (WebSocket traffic is not captured; write WS fixtures by hand)` };
205
+ }
206
+
207
+ if (process.argv[1] && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href) {
208
+ const { findProjectRoot } = await import("./cli.mjs");
209
+ const { importProjectVite, loadOptions, optionsFile } = await import("./env.mjs");
210
+ const root = findProjectRoot(process.cwd());
211
+ /** @type {string[]} */
212
+ let redact = [];
213
+ if (optionsFile(root)) {
214
+ const o = await loadOptions(root, await importProjectVite(root));
215
+ if (!o.ok) { process.stderr.write(o.error + "\n"); process.exit(1); }
216
+ redact = o.options.redact ?? [];
217
+ }
218
+ const { code, out } = await run(process.argv.slice(2), { redact });
219
+ (code ? process.stderr : process.stdout).write(out + "\n");
220
+ process.exit(code);
221
+ }
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // mock-check bin — see headless.mjs. See change: add-mock-site-exact-env.
4
+ import { main } from "./headless.mjs";
5
+
6
+ const { code, out } = await main("check", process.argv.slice(2));
7
+ (code ? process.stderr : process.stdout).write(out + "\n");
8
+ process.exit(code);
@@ -0,0 +1,3 @@
1
+ // Types for cli.mjs (plain-JS module; see change: add-mock-site-exact-env).
2
+ export declare function findProjectRoot(cwd: string): string;
3
+ export declare function run(argv: string[], cwd?: string): { code: number; out: string };
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ // @ts-check
3
+ // mock-decide — the agent's accept/reject for live-component mocks: the ONLY
4
+ // writer of `decision.json` (`by: "agent"`; the site shows it read-only). Works
5
+ // without the site running. See change: add-live-component-mock-site (D4),
6
+ // add-mock-site-exact-env (D6).
7
+ // mock-decide list
8
+ // mock-decide accept <ref> [note]
9
+ // mock-decide reject <ref> <note> (a reason is required)
10
+ // mock-decide reopen <ref>
11
+ // mock-decide adoptable (JSON offer for rules.proposal / Step 1b)
12
+ // mock-decide move <mockDir> <changeDir> (adoption: move a live mock dir as one unit)
13
+ // <ref> = mock id, any #ref, or a full site URL.
14
+ import * as fs from "node:fs";
15
+ import * as path from "node:path";
16
+ import { execFileSync } from "node:child_process";
17
+ import { pathToFileURL } from "node:url";
18
+ import { parseRef } from "./refs.mjs";
19
+ import { discoverMocks, listAdoptable, moveMockDir } from "./discover.mjs";
20
+ import { NOTE_MAX, readDecisions, writeDecision } from "./decisions.mjs";
21
+
22
+ /** @param {string} d */
23
+ const hasManifestKey = (d) => {
24
+ try { return !!JSON.parse(fs.readFileSync(path.join(d, "package.json"), "utf8"))?.mockSite; } catch { return false; }
25
+ };
26
+ /** A change dir's own `mockups/` is a mock root, never a project root. @param {string} d */
27
+ const isChangeDir = (d) => path.basename(path.dirname(path.dirname(d))) === "openspec" && path.basename(path.dirname(d)) === "changes";
28
+
29
+ /**
30
+ * Project root: nearest ancestor whose `package.json` declares `mockSite`, else the
31
+ * nearest ancestor with a `mockups/` dir, else the git toplevel, else cwd.
32
+ * @param {string} cwd
33
+ */
34
+ export function findProjectRoot(cwd) {
35
+ const chain = [];
36
+ for (let d = path.resolve(cwd); ; d = path.dirname(d)) {
37
+ chain.push(d);
38
+ if (path.dirname(d) === d) break;
39
+ }
40
+ const declared = chain.find(hasManifestKey);
41
+ if (declared) return declared;
42
+ const withMocks = chain.find((d) => !isChangeDir(d) && !!fs.statSync(path.join(d, "mockups"), { throwIfNoEntry: false })?.isDirectory());
43
+ if (withMocks) return withMocks;
44
+ try {
45
+ return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
46
+ } catch {
47
+ return path.resolve(cwd);
48
+ }
49
+ }
50
+
51
+ /**
52
+ * @param {string[]} argv @param {string} cwd
53
+ * @returns {{ code: number, out: string }}
54
+ */
55
+ export function run(argv, cwd = process.cwd()) {
56
+ const [cmd, rawRef, ...rest] = argv;
57
+ const root = findProjectRoot(cwd);
58
+ const usage = "usage: mock-decide list | accept <ref> [note] | reject <ref> <note> | reopen <ref> | adoptable | move <mockDir> <changeDir>";
59
+ if (cmd === "adoptable") return { code: 0, out: JSON.stringify(listAdoptable(root), null, 2) };
60
+ if (cmd === "move") {
61
+ if (!rawRef || !rest[0]) return { code: 2, out: usage };
62
+ const r = moveMockDir(path.resolve(cwd, rawRef), path.resolve(cwd, rest[0]));
63
+ return r.ok ? { code: 0, out: `moved to ${r.dest}` } : { code: 1, out: String(r.error) };
64
+ }
65
+ const { mocks, errors } = discoverMocks(root);
66
+ if (cmd === "list") {
67
+ const { decisions, warnings } = readDecisions(mocks);
68
+ const lines = mocks.map((m) => {
69
+ const d = decisions[m.id];
70
+ return `${(d?.status ?? "open").padEnd(9)}${m.id}${d ? ` by ${d.by}${d.note ? `: ${d.note}` : ""}` : ""} ${path.relative(root, m.dir)}`;
71
+ });
72
+ return { code: 0, out: [...lines, ...warnings.map((w) => `warning: ${w}`), ...errors.map((e) => `error: ${e}`)].join("\n") || "(no mocks)" };
73
+ }
74
+ if (!["accept", "reject", "reopen"].includes(cmd)) return { code: 2, out: usage };
75
+ if (!rawRef) return { code: 2, out: usage };
76
+ let id;
77
+ try { id = parseRef(rawRef).id; } catch (e) { return { code: 2, out: String(/** @type {Error} */ (e).message) }; }
78
+ const mock = mocks.find((m) => m.id === id);
79
+ if (!mock) return { code: 1, out: `unknown mock id: ${id} (run: mock-decide list)` };
80
+ const note = rest.join(" ").trim();
81
+ if (cmd === "reject" && !note) return { code: 2, out: "reject needs a reason: mock-decide reject <ref> \"why\"" };
82
+ if ([...note].length > NOTE_MAX) return { code: 2, out: `note over ${NOTE_MAX} characters (${[...note].length}); shorten it` };
83
+ const status = cmd === "accept" ? "accepted" : cmd === "reject" ? "rejected" : "open";
84
+ try {
85
+ writeDecision(mock, { status, by: "agent", ...(note ? { note } : {}) });
86
+ } catch (e) {
87
+ return { code: 1, out: `cannot write decision for ${id}: ${String(/** @type {Error} */ (e).message).split("\n")[0]}` };
88
+ }
89
+ return { code: 0, out: `${status} ${id}` };
90
+ }
91
+
92
+ if (process.argv[1] && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href) {
93
+ const { code, out } = run(process.argv.slice(2));
94
+ (code ? process.stderr : process.stdout).write(out + "\n");
95
+ process.exit(code);
96
+ }
@@ -0,0 +1,6 @@
1
+ // Types for decisions.mjs (plain-JS module; see change: add-live-component-mock-site).
2
+ export interface Decision { status: "accepted" | "rejected"; by: "user" | "agent"; note?: string; at: string }
3
+ export declare function readDecisionFile(file: string): { decision?: Decision; warning?: string };
4
+ export declare function readDecisions(mocks: { id: string; dir: string }[]): { decisions: Record<string, Decision>; warnings: string[] };
5
+ export declare function writeDecision(mock: { dir: string }, d: { status: "accepted" | "rejected" | "open"; by: "user" | "agent"; note?: string }): void;
6
+ export declare const NOTE_MAX: number;
@@ -0,0 +1,71 @@
1
+ // @ts-check
2
+ // Page-level decisions: `<mockDir>/decision.json` = { status, by, note?, at };
3
+ // open = file absent. Atomic writes, never through a symlink, malformed = open.
4
+ // Written only by the `mock-decide` CLI; legacy `by: "user"` files (removed site
5
+ // buttons) are still read. See change: add-live-component-mock-site (design D4,
6
+ // D5), add-mock-site-exact-env (D6).
7
+ import * as fs from "node:fs";
8
+ import * as path from "node:path";
9
+ /** Max note length in code points. */
10
+ export const NOTE_MAX = 500;
11
+
12
+ /** @typedef {{ status: "accepted"|"rejected", by: "user"|"agent", note?: string, at: string }} Decision */
13
+
14
+ /**
15
+ * @param {string} file
16
+ * @returns {{ decision?: Decision, warning?: string }}
17
+ */
18
+ export function readDecisionFile(file) {
19
+ if (!fs.existsSync(file)) return {};
20
+ try {
21
+ const d = JSON.parse(fs.readFileSync(file, "utf8"));
22
+ const bad = !d || typeof d !== "object" || Array.isArray(d) || (d.status !== "accepted" && d.status !== "rejected")
23
+ || (d.by !== "user" && d.by !== "agent") || (d.note !== undefined && typeof d.note !== "string")
24
+ || typeof d.at !== "string" || Number.isNaN(Date.parse(d.at));
25
+ if (bad) {
26
+ return { warning: `invalid decision (treated as open): ${file}` };
27
+ }
28
+ return { decision: d };
29
+ } catch {
30
+ return { warning: `unreadable decision (treated as open): ${file}` };
31
+ }
32
+ }
33
+
34
+ /**
35
+ * @param {{ id: string, dir: string }[]} mocks
36
+ * @returns {{ decisions: Record<string, Decision>, warnings: string[] }}
37
+ */
38
+ export function readDecisions(mocks) {
39
+ /** @type {Record<string, Decision>} */
40
+ const decisions = {};
41
+ /** @type {string[]} */
42
+ const warnings = [];
43
+ for (const m of mocks) {
44
+ const r = readDecisionFile(path.join(m.dir, "decision.json"));
45
+ if (r.decision) decisions[m.id] = r.decision;
46
+ if (r.warning) warnings.push(r.warning);
47
+ }
48
+ return { decisions, warnings };
49
+ }
50
+
51
+ let seq = 0;
52
+ /**
53
+ * @param {{ dir: string }} mock
54
+ * @param {{ status: "accepted"|"rejected"|"open", by: "user"|"agent", note?: string }} d
55
+ */
56
+ export function writeDecision(mock, d) {
57
+ const file = path.join(mock.dir, "decision.json");
58
+ for (const p of [mock.dir, file]) {
59
+ if (fs.existsSync(p) && fs.lstatSync(p).isSymbolicLink()) throw new Error(`refusing symlink: ${p}`);
60
+ }
61
+ if (d.status === "open") { fs.rmSync(file, { force: true }); return; }
62
+ /** @type {Decision} */
63
+ const out = { status: d.status, by: d.by, ...(d.note ? { note: d.note } : {}), at: new Date().toISOString() };
64
+ const tmp = path.join(mock.dir, `.decision.json.tmp-${process.pid}-${++seq}`);
65
+ try {
66
+ fs.writeFileSync(tmp, JSON.stringify(out, null, 2) + "\n", { flag: "wx" });
67
+ fs.renameSync(tmp, file);
68
+ } finally {
69
+ fs.rmSync(tmp, { force: true });
70
+ }
71
+ }
@@ -0,0 +1,7 @@
1
+ // Types for discover.mjs (plain-JS module; see change: add-live-component-mock-site).
2
+ export interface MockEntry { id: string; dir: string; file: string; root: string }
3
+ export declare function mockRoots(projectRoot: string): string[];
4
+ export declare function discoverMocks(projectRoot: string): { mocks: MockEntry[]; errors: string[] };
5
+ export interface AdoptOption { entry: string; label: string; status?: string }
6
+ export declare function listAdoptable(projectRoot: string): { options: AdoptOption[]; skipped: { entry: string; reason: string }[]; warnings: string[] };
7
+ export declare function moveMockDir(src: string, changeDir: string): { ok: boolean; dest: string; error?: string };
@@ -0,0 +1,137 @@
1
+ // @ts-check
2
+ // Mock discovery + adoption helpers. One mock = `<root>/<id>/mock.tsx` (+ optional
3
+ // `decision.json`), roots = `mockups/` and `openspec/changes/*/mockups/`
4
+ // (archive and node_modules excluded). See change: add-live-component-mock-site
5
+ // (design D3, D12), add-mock-site-exact-env (D2).
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import { execFileSync } from "node:child_process";
9
+ import { MOCK_ID_RE } from "./refs.mjs";
10
+ import { readDecisionFile } from "./decisions.mjs";
11
+
12
+ /** @typedef {{ id: string, dir: string, file: string, root: string }} MockEntry */
13
+
14
+ /** Mock roots of a project (existing dirs only). @param {string} projectRoot */
15
+ export function mockRoots(projectRoot) {
16
+ const roots = [path.join(projectRoot, "mockups")];
17
+ const changes = path.join(projectRoot, "openspec", "changes");
18
+ if (fs.existsSync(changes)) {
19
+ for (const d of fs.readdirSync(changes, { withFileTypes: true })) {
20
+ if (!d.isDirectory() || d.name === "archive") continue;
21
+ roots.push(path.join(changes, d.name, "mockups"));
22
+ }
23
+ }
24
+ // Never a dependency dir (Vite does not watch it, and it is not the project's).
25
+ return roots.filter((r) => fs.existsSync(r) && !path.resolve(r).split(path.sep).includes("node_modules"));
26
+ }
27
+
28
+ /**
29
+ * @param {string} projectRoot
30
+ * @returns {{ mocks: MockEntry[], errors: string[] }}
31
+ */
32
+ export function discoverMocks(projectRoot) {
33
+ /** @type {Map<string, MockEntry[]>} */
34
+ const byId = new Map();
35
+ /** @type {string[]} */
36
+ const errors = [];
37
+ for (const root of mockRoots(projectRoot)) {
38
+ for (const d of fs.readdirSync(root, { withFileTypes: true })) {
39
+ if (!d.isDirectory()) continue;
40
+ const dir = path.join(root, d.name);
41
+ const file = path.join(dir, "mock.tsx");
42
+ if (!fs.existsSync(file)) continue;
43
+ if (!MOCK_ID_RE.test(d.name)) {
44
+ errors.push(`invalid mock id (want yyyy-mm-dd-slug): ${path.relative(projectRoot, dir)}`);
45
+ continue;
46
+ }
47
+ const list = byId.get(d.name) ?? [];
48
+ list.push({ id: d.name, dir, file, root });
49
+ byId.set(d.name, list);
50
+ }
51
+ }
52
+ /** @type {MockEntry[]} */
53
+ const mocks = [];
54
+ for (const [id, list] of byId) {
55
+ if (list.length > 1) errors.push(`duplicate mock id ${id}: ${list.map((m) => path.relative(projectRoot, m.dir)).join(" and ")}`);
56
+ else mocks.push(list[0]);
57
+ }
58
+ mocks.sort((a, b) => (a.id < b.id ? 1 : a.id > b.id ? -1 : 0));
59
+ return { mocks, errors };
60
+ }
61
+
62
+ const MARKER_RE = /Pending change: ([^|]+?)\s*\|\s*$/;
63
+
64
+ /**
65
+ * Adoption offer for `rules.proposal` / plan-proposal Step 1b: marked rows of
66
+ * `mockups/AGENTS.md`, live mocks filtered + labelled by their decision.
67
+ * Accepted first `(accepted)`, open / malformed `(open)`, rejected skipped.
68
+ * @param {string} projectRoot
69
+ */
70
+ export function listAdoptable(projectRoot) {
71
+ const agents = path.join(projectRoot, "mockups", "AGENTS.md");
72
+ /** @type {{ entry: string, label: string, status?: string }[]} */
73
+ const accepted = [], rest = [];
74
+ /** @type {{ entry: string, reason: string }[]} */
75
+ const skipped = [];
76
+ /** @type {string[]} */
77
+ const warnings = [];
78
+ const text = fs.existsSync(agents) ? fs.readFileSync(agents, "utf8") : "";
79
+ for (const line of text.split("\n")) {
80
+ const marker = MARKER_RE.exec(line);
81
+ if (!line.startsWith("|") || !marker || line.includes("See change:")) continue;
82
+ const m = /^\|\s*`([^`]+)`/.exec(line);
83
+ if (!m) continue;
84
+ const entry = m[1];
85
+ const intent = marker[1].trim();
86
+ const abs = path.join(projectRoot, "mockups", entry.replace(/\/$/, ""));
87
+ if (!fs.existsSync(abs) || path.dirname(abs) !== path.join(projectRoot, "mockups")) {
88
+ skipped.push({ entry, reason: "missing or not directly under mockups/" });
89
+ continue;
90
+ }
91
+ if (!fs.existsSync(path.join(abs, "mock.tsx"))) { rest.push({ entry, label: `${entry} — ${intent}` }); continue; }
92
+ const d = readDecisionFile(path.join(abs, "decision.json"));
93
+ if (d.warning) warnings.push(d.warning);
94
+ const status = d.decision?.status ?? "open";
95
+ if (status === "rejected") skipped.push({ entry, reason: "rejected" });
96
+ else (status === "accepted" ? accepted : rest).push({ entry, label: `${entry} — ${intent} (${status})`, status });
97
+ }
98
+ return { options: [...accepted, ...rest], skipped, warnings };
99
+ }
100
+
101
+ /** @param {string} cwd @param {string[]} args */
102
+ function git(cwd, args) {
103
+ try { execFileSync("git", args, { cwd, stdio: "pipe" }); return true; } catch { return false; }
104
+ }
105
+
106
+ /**
107
+ * Move one live mock dir into `<changeDir>/mockups/` as a unit: `git mv`, then
108
+ * `mv` + `git add -A` for anything left (untracked files). Ignores `.*.tmp-*`.
109
+ * Verdict: ok only when the source dir no longer exists.
110
+ * @param {string} src @param {string} changeDir
111
+ * @returns {{ ok: boolean, dest: string, error?: string }}
112
+ */
113
+ export function moveMockDir(src, changeDir) {
114
+ const dest = path.join(changeDir, "mockups", path.basename(src));
115
+ if (fs.existsSync(dest)) return { ok: false, dest, error: `destination exists: ${dest}` };
116
+ if (!fs.existsSync(src)) return { ok: false, dest, error: `source missing: ${src}` };
117
+ for (const f of fs.readdirSync(src)) if (/^\..*\.tmp-/.test(f)) fs.rmSync(path.join(src, f), { force: true });
118
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
119
+ const repo = git(src, ["rev-parse", "--show-toplevel"]);
120
+ // git mv renames the whole dir (untracked files too) but stages only tracked ones.
121
+ if (repo && git(src, ["mv", src, dest]) && !fs.existsSync(src)) {
122
+ git(changeDir, ["add", "-A", "--", dest]);
123
+ return { ok: true, dest };
124
+ }
125
+ try {
126
+ if (fs.existsSync(dest)) {
127
+ for (const f of fs.readdirSync(src)) fs.renameSync(path.join(src, f), path.join(dest, f));
128
+ fs.rmdirSync(src);
129
+ } else fs.renameSync(src, dest);
130
+ } catch (e) {
131
+ return { ok: false, dest, error: String(e) };
132
+ }
133
+ // Stage each side on its own: a pathspec that matches nothing (an untracked,
134
+ // now-vanished source) makes `git add` fail and stage nothing at all.
135
+ if (repo) { git(changeDir, ["add", "-A", "--", dest]); git(changeDir, ["add", "-A", "--", src]); }
136
+ return fs.existsSync(src) ? { ok: false, dest, error: `source still exists: ${src}` } : { ok: true, dest };
137
+ }
@@ -0,0 +1,15 @@
1
+ // Types for env.mjs (plain-JS module; see change: add-mock-site-exact-env).
2
+ import type { MockSiteUserOptions } from "./options.mjs";
3
+ export declare const GENERATED_DIR: string;
4
+ export declare function resolveLauncher(root: string, opts?: { options?: MockSiteUserOptions }):
5
+ | { ok: true; adapter: "vite"; launcher: string; config: string; source: "declared" | "detected" }
6
+ | { ok: false; error: string };
7
+ export declare function inheritAppConfig(cfg: Record<string, any>, configFile: string): { config: Record<string, any>; appRoot: string };
8
+ export declare function importProjectVite(root: string): Promise<any>;
9
+ export declare function optionsFile(root: string): string | null;
10
+ export declare function loadOptions(root: string, vite: any): Promise<{ ok: true; options: MockSiteUserOptions; file: string | null } | { ok: false; error: string }>;
11
+ export declare function prepareMockSite(root: string): Promise<
12
+ | { ok: true; launcher: string; config: string; generated: string; source: string; optionsFile: string | null; adapter: "vite"; baseFlag: string | null }
13
+ | { ok: false; error: string }
14
+ >;
15
+ export declare function createMockSiteConfig(p: { projectRoot: string; config: string; options: MockSiteUserOptions; optionsFile: string | null }, env: { mode?: string }, vite: any): Promise<any>;