@blackbelt-technology/frontend-mockup-loop 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.pi/skills/frontend-mockup-loop/SKILL.md +87 -8
- package/README.md +47 -2
- package/package.json +43 -4
- package/references/live-mock-site.md +332 -0
- package/site/Site.tsx +627 -0
- package/site/clock.ts +39 -0
- package/site/fixtures.ts +144 -0
- package/site/frame-env.ts +59 -0
- package/site/kit.tsx +175 -0
- package/site/main.tsx +11 -0
- package/site/pane-runtime.ts +230 -0
- package/site/pane-scroll-guard.ts +70 -0
- package/site/ring-line.ts +100 -0
- package/site/script.ts +201 -0
- package/site/site.css +179 -0
- package/site/step-gate.ts +138 -0
- package/site/tsconfig.json +16 -0
- package/site/virtual.d.ts +16 -0
- package/src/extension.ts +189 -58
- package/src/mock-site/base.d.mts +2 -0
- package/src/mock-site/base.mjs +28 -0
- package/src/mock-site/browser.d.mts +8 -0
- package/src/mock-site/browser.mjs +72 -0
- package/src/mock-site/capture.d.mts +8 -0
- package/src/mock-site/capture.mjs +221 -0
- package/src/mock-site/check.mjs +8 -0
- package/src/mock-site/cli.d.mts +3 -0
- package/src/mock-site/cli.mjs +96 -0
- package/src/mock-site/decisions.d.mts +6 -0
- package/src/mock-site/decisions.mjs +71 -0
- package/src/mock-site/discover.d.mts +7 -0
- package/src/mock-site/discover.mjs +137 -0
- package/src/mock-site/env.d.mts +15 -0
- package/src/mock-site/env.mjs +228 -0
- package/src/mock-site/frameworks.d.mts +5 -0
- package/src/mock-site/frameworks.mjs +27 -0
- package/src/mock-site/headless.d.mts +9 -0
- package/src/mock-site/headless.mjs +207 -0
- package/src/mock-site/locate.d.mts +3 -0
- package/src/mock-site/locate.mjs +30 -0
- package/src/mock-site/options.d.mts +19 -0
- package/src/mock-site/options.mjs +45 -0
- package/src/mock-site/plugin.d.mts +21 -0
- package/src/mock-site/plugin.mjs +191 -0
- package/src/mock-site/refs.d.mts +7 -0
- package/src/mock-site/refs.mjs +65 -0
- package/src/mock-site/serve-cli.mjs +43 -0
- package/src/mock-site/video.mjs +8 -0
- package/src/mock-site-serve.ts +186 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// `mockSite(options)` — Vite plugin that turns a project's `mockups/` into the
|
|
3
|
+
// live-component mock site. No runtime `vite` import (types only), so the pi
|
|
4
|
+
// extension loads without Vite. Read-only: decisions are written by the
|
|
5
|
+
// `mock-decide` CLI only. See change: add-live-component-mock-site (D1-D5),
|
|
6
|
+
// add-mock-site-exact-env (D2, D6, D8).
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import { createRequire } from "node:module";
|
|
9
|
+
import * as path from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import { readDecisions } from "./decisions.mjs";
|
|
12
|
+
import { discoverMocks, mockRoots } from "./discover.mjs";
|
|
13
|
+
import { DEFAULT_FRAMEWORK, FRAMEWORK_ADAPTERS } from "./frameworks.mjs";
|
|
14
|
+
|
|
15
|
+
const SITE_DIR = fileURLToPath(new URL("../../site/", import.meta.url));
|
|
16
|
+
const V_CONFIG = "virtual:mock-site/config";
|
|
17
|
+
const V_APP = "virtual:mock-site/app";
|
|
18
|
+
const V_MOCKS = "virtual:mock-site/mocks";
|
|
19
|
+
/** Optional peers of fixture / script panes: pre-bundled only when the project has them. */
|
|
20
|
+
const LAZY_PEERS = ["@mswjs/interceptors/fetch", "@mswjs/interceptors/XMLHttpRequest", "@mswjs/interceptors/WebSocket", "@testing-library/user-event"];
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @typedef {{ id: string, label: string, attrs?: Record<string, string|null>, system?: { dark: string, light: string } }} ThemeSpec
|
|
24
|
+
* @typedef {{
|
|
25
|
+
* projectRoot: string,
|
|
26
|
+
* app?: string,
|
|
27
|
+
* title?: string,
|
|
28
|
+
* themes?: ThemeSpec[],
|
|
29
|
+
* appRoot?: string,
|
|
30
|
+
* aliases?: Record<string, string>,
|
|
31
|
+
* port?: number,
|
|
32
|
+
* lan?: boolean,
|
|
33
|
+
* }} MockSiteOptions
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
/** @param {string} p */
|
|
37
|
+
const fsUrl = (p) => `/@fs/${p.replace(/\\/g, "/").replace(/^\/+/, "")}`;
|
|
38
|
+
|
|
39
|
+
/** @param {import("node:http").ServerResponse} res @param {number} code @param {unknown} body */
|
|
40
|
+
function send(res, code, body) {
|
|
41
|
+
res.statusCode = code;
|
|
42
|
+
res.setHeader("content-type", "application/json");
|
|
43
|
+
res.end(JSON.stringify(body));
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @param {MockSiteOptions} options
|
|
48
|
+
* @returns {any} Vite plugin
|
|
49
|
+
*/
|
|
50
|
+
/**
|
|
51
|
+
* LAN mode exposes the project over the network and relies on `server.fs.deny`.
|
|
52
|
+
* False for Vite releases with a known deny bypass: GHSA-8jhw-289h-jh2g (<5.2.6),
|
|
53
|
+
* GHSA-93m4-6634-74q7 (<5.4.21, 6.0–6.4.0, 7.0.0–7.0.7, 7.1.0–7.1.10) and
|
|
54
|
+
* GHSA-8g5g-mxqh-grgj (6.4.4).
|
|
55
|
+
* Mirrors the package's optional `vite` peer range.
|
|
56
|
+
* @param {string} version
|
|
57
|
+
*/
|
|
58
|
+
export function isLanSafeVite(version) {
|
|
59
|
+
const [maj, min, pat] = version.split(/[.-]/).map(Number);
|
|
60
|
+
const n = maj * 1e6 + min * 1e3 + pat;
|
|
61
|
+
if (maj === 5) return n >= 5_004_021;
|
|
62
|
+
if (maj === 6) return n >= 6_004_001 && n !== 6_004_004;
|
|
63
|
+
if (maj === 7) return min === 0 ? n >= 7_000_008 : min === 1 ? n >= 7_001_011 : true;
|
|
64
|
+
return maj > 7;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function mockSite(options) {
|
|
68
|
+
const projectRoot = path.resolve(options.projectRoot);
|
|
69
|
+
const mockupsDir = path.join(projectRoot, "mockups");
|
|
70
|
+
const appFile = options.app ? path.resolve(mockupsDir, options.app) : null;
|
|
71
|
+
const fw = FRAMEWORK_ADAPTERS[DEFAULT_FRAMEWORK];
|
|
72
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
73
|
+
const peers = LAZY_PEERS.filter((p) => { try { req.resolve(p); return true; } catch { return false; } });
|
|
74
|
+
const lan = options.lan ?? process.env.MOCK_SITE_LAN === "1";
|
|
75
|
+
const siteDir = fs.existsSync(SITE_DIR) ? SITE_DIR : path.join(path.dirname(fileURLToPath(import.meta.url)), "../../site/");
|
|
76
|
+
const themes = options.themes ?? [
|
|
77
|
+
{ id: "system", label: "System", system: { dark: "dark", light: "light" } },
|
|
78
|
+
{ id: "dark", label: "Dark", attrs: { "data-theme": "dark" } },
|
|
79
|
+
{ id: "light", label: "Light", attrs: { "data-theme": "light" } },
|
|
80
|
+
];
|
|
81
|
+
const current = () => discoverMocks(projectRoot);
|
|
82
|
+
/** The resolved Vite `base` (always ends with `/`). The plugin mounts BEFORE Vite's base middleware, so paths arrive unstripped. */
|
|
83
|
+
let base = "/";
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
name: "mock-site",
|
|
87
|
+
enforce: "pre",
|
|
88
|
+
/** @param {any} c */
|
|
89
|
+
configResolved(c) {
|
|
90
|
+
base = typeof c.base === "string" && c.base.startsWith("/") ? c.base.replace(/\/*$/, "/") : "/";
|
|
91
|
+
},
|
|
92
|
+
async config() {
|
|
93
|
+
if (lan) {
|
|
94
|
+
const { version } = await import("vite");
|
|
95
|
+
if (!isLanSafeVite(version)) throw new Error(`mock-site: LAN mode refused on vite ${version} (known server.fs.deny bypass); upgrade vite (>=5.4.21 <6, >=6.4.1 except 6.4.4, >=7.0.8, >=7.1.11)`);
|
|
96
|
+
}
|
|
97
|
+
const { mocks } = current();
|
|
98
|
+
return {
|
|
99
|
+
root: mockupsDir,
|
|
100
|
+
cacheDir: path.join(projectRoot, "node_modules", ".vite-mock-site"),
|
|
101
|
+
appType: "custom",
|
|
102
|
+
resolve: {
|
|
103
|
+
alias: [{ find: /^mock-site\/kit$/, replacement: path.join(siteDir, "kit.tsx") }, ...Object.entries(options.aliases ?? {}).map(([find, replacement]) => ({ find, replacement }))],
|
|
104
|
+
dedupe: fw.dedupe,
|
|
105
|
+
},
|
|
106
|
+
optimizeDeps: {
|
|
107
|
+
entries: [path.join(siteDir, "main.tsx"), ...mocks.map((m) => m.file)],
|
|
108
|
+
include: [...fw.include, ...peers],
|
|
109
|
+
},
|
|
110
|
+
server: {
|
|
111
|
+
host: lan ? "0.0.0.0" : "127.0.0.1",
|
|
112
|
+
...(options.port ? { port: options.port, strictPort: true } : {}),
|
|
113
|
+
fs: {
|
|
114
|
+
allow: [siteDir, projectRoot, ...(options.appRoot ? [path.resolve(options.appRoot)] : [])],
|
|
115
|
+
// LAN mode REPLACES Vite's deny list, so restate its defaults (and newer
|
|
116
|
+
// Vite ones) before adding ours.
|
|
117
|
+
...(lan ? { deny: [".env", ".env.*", "*.{crt,cer,der,pem,key,p12,pfx}", "**/.git/**", "**/.yarnrc.yml", "**/.npmrc", "**/.pi/**",
|
|
118
|
+
// secret DATA files by extension only — a bare *secret* glob would also block app modules (SecretsPanel.tsx)
|
|
119
|
+
"**/.secrets", "**/.secrets/**", "**/*.secret", "**/*secret*.{json,yaml,yml,env,txt,ini,toml}", "**/.secrets*.{json,yaml,yml,env,txt}"] } : {}),
|
|
120
|
+
},
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
},
|
|
124
|
+
/** @param {string} id */
|
|
125
|
+
resolveId(id) {
|
|
126
|
+
if (id === V_CONFIG || id === V_APP || id === V_MOCKS) return "\0" + id;
|
|
127
|
+
return null;
|
|
128
|
+
},
|
|
129
|
+
/** @param {string} id */
|
|
130
|
+
load(id) {
|
|
131
|
+
if (id === "\0" + V_CONFIG) return `export const MOCK_CONFIG = ${JSON.stringify({ title: options.title ?? "Mocks", themes })};`;
|
|
132
|
+
if (id === "\0" + V_APP) return appFile ? `export * from ${JSON.stringify(appFile)};` : "export const setup = undefined;\nexport const Providers = (p) => p.children;\n";
|
|
133
|
+
if (id === "\0" + V_MOCKS) {
|
|
134
|
+
const { mocks, errors } = current();
|
|
135
|
+
const imports = mocks.map((m, i) => `import m${i} from ${JSON.stringify(m.file)};`).join("\n");
|
|
136
|
+
const list = mocks.map((m, i) => `{ id: ${JSON.stringify(m.id)}, mock: m${i} }`).join(",\n ");
|
|
137
|
+
return `${imports}\nexport const MOCKS = [\n ${list}\n];\nexport const ERRORS = ${JSON.stringify(errors)};\n`;
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
},
|
|
141
|
+
/** @param {any} srv */
|
|
142
|
+
configureServer(srv) {
|
|
143
|
+
for (const r of [mockupsDir, path.join(projectRoot, "openspec", "changes"), ...mockRoots(projectRoot)]) if (fs.existsSync(r)) srv.watcher.add(r);
|
|
144
|
+
/** @param {string} f */
|
|
145
|
+
const onFs = (f) => {
|
|
146
|
+
const name = path.basename(f);
|
|
147
|
+
if (!f.startsWith(projectRoot) || f.includes(`${path.sep}archive${path.sep}`) || f.includes(`${path.sep}node_modules${path.sep}`)) return;
|
|
148
|
+
if (name === "decision.json") srv.ws.send({ type: "custom", event: "mock:decisions" });
|
|
149
|
+
if (name === "mock.tsx") {
|
|
150
|
+
const mod = srv.moduleGraph.getModuleById("\0" + V_MOCKS);
|
|
151
|
+
if (mod) srv.moduleGraph.invalidateModule(mod);
|
|
152
|
+
srv.ws.send({ type: "full-reload" });
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
srv.watcher.on("add", onFs);
|
|
156
|
+
srv.watcher.on("unlink", onFs);
|
|
157
|
+
srv.watcher.on("change", (/** @type {string} */ f) => { if (path.basename(f) === "decision.json") onFs(f); });
|
|
158
|
+
|
|
159
|
+
srv.middlewares.use(`${base}__mock/decisions`, (/** @type {any} */ _req, /** @type {any} */ res) => {
|
|
160
|
+
const { mocks, errors } = current();
|
|
161
|
+
const { decisions, warnings } = readDecisions(mocks);
|
|
162
|
+
send(res, 200, { mockSite: true, decisions, warnings, errors });
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
// HTML entry (the package ships no index.html): `/` and `/?pane=…`.
|
|
166
|
+
srv.middlewares.use(async (/** @type {any} */ req, /** @type {any} */ res, /** @type {any} */ next) => {
|
|
167
|
+
// Path only: `new URL("//…", base)` reads `//` as an authority and throws, killing the site.
|
|
168
|
+
const pathname = (req.url ?? "/").split(/[?#]/, 1)[0];
|
|
169
|
+
// `<base minus the slash>` redirects to the base (Vite only does so for some `Accept` headers).
|
|
170
|
+
if (req.method === "GET" && base !== "/" && pathname === base.slice(0, -1)) {
|
|
171
|
+
res.statusCode = 302;
|
|
172
|
+
res.setHeader("location", base + (req.url ?? "").slice(pathname.length));
|
|
173
|
+
return res.end();
|
|
174
|
+
}
|
|
175
|
+
if (req.method !== "GET" || (pathname !== base && pathname !== `${base}index.html`)) return next();
|
|
176
|
+
const html = `<!doctype html>
|
|
177
|
+
<html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>${(options.title ?? "Mocks").replace(/[<&]/g, "")}</title></head>
|
|
178
|
+
<body><div id="root"></div><script type="module" src="${fsUrl(path.join(siteDir, "main.tsx"))}"></script></body></html>`;
|
|
179
|
+
try {
|
|
180
|
+
const out = await srv.transformIndexHtml(req.url, html);
|
|
181
|
+
res.statusCode = 200;
|
|
182
|
+
res.setHeader("content-type", "text/html");
|
|
183
|
+
res.end(out);
|
|
184
|
+
} catch (e) {
|
|
185
|
+
next(e);
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Types for refs.mjs (plain-JS module; see change: add-live-component-mock-site).
|
|
2
|
+
export declare const MOCK_ID_RE: RegExp;
|
|
3
|
+
export declare const RING_RE: RegExp;
|
|
4
|
+
export declare function isRingN(n: unknown): boolean;
|
|
5
|
+
export interface Ref { id: string; frame?: number | "locate" | "locate-phone"; side?: "current" | "proposed"; ring?: string; step?: number }
|
|
6
|
+
export declare function parseRef(input: string): Ref;
|
|
7
|
+
export declare function refId(ref: string): string;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Reference grammar for the live-component mock site. Pure: shared by the node
|
|
3
|
+
// plugin, the `mock-decide` CLI, and the browser shell (no node imports).
|
|
4
|
+
// <id> | <id>/<frame> | <id>/<frame>/<side> | <id>/<frame>/<side>/<ring|step-<k>>
|
|
5
|
+
// <frame> = 1-based number, `locate` or `locate-phone` (Locate side: proposed only).
|
|
6
|
+
// See change: add-live-component-mock-site (design D7), add-mock-site-exact-env (D5),
|
|
7
|
+
// add-mock-locate-frame (D2).
|
|
8
|
+
|
|
9
|
+
/** Mock id = directory name: `<yyyy-mm-dd>-<slug>`. */
|
|
10
|
+
export const MOCK_ID_RE = /^\d{4}-\d{2}-\d{2}-[a-z0-9-]+$/;
|
|
11
|
+
/** Ring number segment (a ref segment, so no `/`). */
|
|
12
|
+
export const RING_RE = /^[A-Za-z0-9-]+$/;
|
|
13
|
+
/** Step segment: `step-<k>`, k 1-based. Reserved: a ring `n` never starts with `step-`. */
|
|
14
|
+
const STEP_RE = /^step-[1-9]\d*$/;
|
|
15
|
+
/** Locate frame segments (not counted as frames). */
|
|
16
|
+
const LOCATE_FRAMES = ["locate", "locate-phone"];
|
|
17
|
+
|
|
18
|
+
/** A valid ring `n`: ref-safe and not in the reserved `step-` space. @param {unknown} n */
|
|
19
|
+
export const isRingN = (n) => RING_RE.test(String(n)) && !String(n).startsWith("step-");
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {{ id: string, frame?: number | "locate" | "locate-phone", side?: "current"|"proposed", ring?: string, step?: number }} Ref
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Parse a mock id, a `#ref`, or a full site URL (its hash) into a Ref.
|
|
27
|
+
* Throws `Error("bad ref …")` naming the offending segment.
|
|
28
|
+
* @param {string} input
|
|
29
|
+
* @returns {Ref}
|
|
30
|
+
*/
|
|
31
|
+
export function parseRef(input) {
|
|
32
|
+
let s = String(input ?? "").trim();
|
|
33
|
+
if (/^[a-z]+:\/\//i.test(s)) {
|
|
34
|
+
const i = s.indexOf("#");
|
|
35
|
+
if (i < 0) throw new Error(`bad ref: URL has no #<id> hash: ${input}`);
|
|
36
|
+
s = s.slice(i + 1);
|
|
37
|
+
} else if (s.startsWith("#")) s = s.slice(1);
|
|
38
|
+
if (!s) throw new Error("bad ref: empty");
|
|
39
|
+
const parts = s.split("/");
|
|
40
|
+
if (parts.length > 4) throw new Error(`bad ref: too many segments in ${s}`);
|
|
41
|
+
const [id, frame, side, ring] = parts;
|
|
42
|
+
if (!MOCK_ID_RE.test(id)) throw new Error(`bad ref: id "${id}" must match yyyy-mm-dd-slug`);
|
|
43
|
+
/** @type {Ref} */
|
|
44
|
+
const out = { id };
|
|
45
|
+
if (frame === undefined) return out;
|
|
46
|
+
const locate = LOCATE_FRAMES.includes(frame);
|
|
47
|
+
if (!locate && !/^[1-9]\d*$/.test(frame)) throw new Error(`bad ref: frame "${frame}" must be 1-based`);
|
|
48
|
+
out.frame = locate ? /** @type {"locate"|"locate-phone"} */ (frame) : Number(frame);
|
|
49
|
+
if (side === undefined) return out;
|
|
50
|
+
if (side !== "current" && side !== "proposed") throw new Error(`bad ref: side "${side}" must be current|proposed`);
|
|
51
|
+
if (locate && side === "current") throw new Error(`bad ref: Locate frame has no side "current"`);
|
|
52
|
+
out.side = side;
|
|
53
|
+
if (ring === undefined) return out;
|
|
54
|
+
if (ring.startsWith("step-")) {
|
|
55
|
+
if (!STEP_RE.test(ring)) throw new Error(`bad ref: step "${ring}" must be step-<k>, k 1-based`);
|
|
56
|
+
out.step = Number(ring.slice(5));
|
|
57
|
+
return out;
|
|
58
|
+
}
|
|
59
|
+
if (!RING_RE.test(ring)) throw new Error(`bad ref: ring "${ring}" must match [A-Za-z0-9-]+`);
|
|
60
|
+
out.ring = ring;
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** DOM id for a ref string. @param {string} ref */
|
|
65
|
+
export const refId = (ref) => `r-${ref}`;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
// Foreground mock site for humans (`npm run mocks`): same launcher + generated
|
|
4
|
+
// inheriting config as `serve_mock_site`, stdio inherited, Ctrl-C stops it.
|
|
5
|
+
// node <pkg>/src/mock-site/serve-cli.mjs [--port 5299] [--lan] [--base /some/prefix/]
|
|
6
|
+
// See change: add-mock-site-exact-env (design D1, D12).
|
|
7
|
+
import { spawn } from "node:child_process";
|
|
8
|
+
import { validateBase } from "./base.mjs";
|
|
9
|
+
import { findProjectRoot } from "./cli.mjs";
|
|
10
|
+
import { prepareMockSite } from "./env.mjs";
|
|
11
|
+
|
|
12
|
+
const argv = process.argv.slice(2);
|
|
13
|
+
const i = argv.indexOf("--port");
|
|
14
|
+
const port = i >= 0 ? Number(argv[i + 1]) : 5299;
|
|
15
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || port === 8000) {
|
|
16
|
+
process.stderr.write(`mock-site: --port must be an integer 1-65535 other than the reserved 8000 (got ${argv[i + 1]})\n`);
|
|
17
|
+
process.exit(2);
|
|
18
|
+
}
|
|
19
|
+
const lan = argv.includes("--lan");
|
|
20
|
+
const bi = argv.indexOf("--base");
|
|
21
|
+
const baseArg = bi >= 0 ? validateBase(argv[bi + 1]) : { ok: true, base: null };
|
|
22
|
+
if (!baseArg.ok) {
|
|
23
|
+
process.stderr.write(`mock-site: ${baseArg.error}\n`);
|
|
24
|
+
process.exit(2);
|
|
25
|
+
}
|
|
26
|
+
const root = findProjectRoot(process.cwd());
|
|
27
|
+
const prep = await prepareMockSite(root);
|
|
28
|
+
if (!prep.ok) {
|
|
29
|
+
process.stderr.write(`mock-site: ${prep.error}\n`);
|
|
30
|
+
process.exit(1);
|
|
31
|
+
}
|
|
32
|
+
process.stdout.write(`mock-site: launcher ${prep.launcher} (${prep.source}), app config ${prep.config}\n`);
|
|
33
|
+
if (baseArg.base && !prep.baseFlag) {
|
|
34
|
+
process.stderr.write(`mock-site: the ${prep.adapter} adapter cannot apply a base; start without --base\n`);
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
const child = spawn(process.execPath, [prep.launcher, "--config", prep.generated, "--port", String(port), "--strictPort", ...(baseArg.base && prep.baseFlag ? [prep.baseFlag, baseArg.base] : [])], {
|
|
38
|
+
cwd: root,
|
|
39
|
+
env: { ...process.env, MOCK_SITE_LAN: lan ? "1" : "0" },
|
|
40
|
+
stdio: "inherit",
|
|
41
|
+
});
|
|
42
|
+
for (const s of /** @type {const} */ (["SIGINT", "SIGTERM"])) process.on(s, () => child.kill(s));
|
|
43
|
+
child.on("exit", (code) => process.exit(code ?? 0));
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
// mock-video bin — see headless.mjs. See change: add-mock-site-exact-env.
|
|
4
|
+
import { main } from "./headless.mjs";
|
|
5
|
+
|
|
6
|
+
const { code, out } = await main("video", process.argv.slice(2));
|
|
7
|
+
(code ? process.stderr : process.stdout).write(out + "\n");
|
|
8
|
+
process.exit(code);
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `serve_mock_site` process management: start the project's OWN launcher on the
|
|
3
|
+
* generated inheriting config (`prepareMockSite`), wait until the mock-site marker
|
|
4
|
+
* answers, stop it, and kill every child on shutdown. Erasable-only TypeScript
|
|
5
|
+
* (jiti gate). See change: add-live-component-mock-site (design D11),
|
|
6
|
+
* add-mock-site-exact-env (D1, D10).
|
|
7
|
+
*/
|
|
8
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import * as http from "node:http";
|
|
11
|
+
import * as os from "node:os";
|
|
12
|
+
import * as path from "node:path";
|
|
13
|
+
import { validateBase } from "./mock-site/base.mjs";
|
|
14
|
+
import { prepareMockSite } from "./mock-site/env.mjs";
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_MOCK_SITE_PORT = 5299;
|
|
17
|
+
const READY_TIMEOUT_MS = 30_000;
|
|
18
|
+
const KILL_GRACE_MS = 3_000;
|
|
19
|
+
/** How long the emitter waits for a host to answer `mock-site:base-reservation` (canonical, D9). */
|
|
20
|
+
export const RESERVATION_WAIT_MS = 2_000;
|
|
21
|
+
/** The neutral probe name; no host-specific event name appears in this package. */
|
|
22
|
+
const RESERVATION_EVENT = "mock-site:base-reservation";
|
|
23
|
+
|
|
24
|
+
export const children = new Map<number, ChildProcess>();
|
|
25
|
+
|
|
26
|
+
export type ServeResult =
|
|
27
|
+
| { ok: true; port: number; local: string; lan: string | null; root: string; launcher: string; config: string; base: string | null; note?: string }
|
|
28
|
+
| { ok: false; error: string };
|
|
29
|
+
|
|
30
|
+
/** Ports the mock site must never take: 8000, PI_DASHBOARD_PORT, ~/.pi/dashboard/config.json port + the tier-3 preview pool. */
|
|
31
|
+
function forbiddenPorts(env: NodeJS.ProcessEnv = process.env, home: string = os.homedir()): Set<number> {
|
|
32
|
+
const out = new Set<number>([8000]);
|
|
33
|
+
const p = Number(env.PI_DASHBOARD_PORT);
|
|
34
|
+
if (Number.isInteger(p) && p > 0) out.add(p);
|
|
35
|
+
try {
|
|
36
|
+
const cfg = JSON.parse(fs.readFileSync(path.join(home, ".pi", "dashboard", "config.json"), "utf8"));
|
|
37
|
+
const c = Number(cfg?.port);
|
|
38
|
+
if (Number.isInteger(c) && c > 0) out.add(c);
|
|
39
|
+
// Tier-3 pool ports belong to the dashboard's preview listeners (`liveServer.previewOrigins.portPool`, "a-b", ≤ 100 ports).
|
|
40
|
+
const m = /^(\d{1,5})-(\d{1,5})$/.exec(String(cfg?.liveServer?.previewOrigins?.portPool ?? ""));
|
|
41
|
+
if (m && Number(m[2]) >= Number(m[1]) && Number(m[2]) - Number(m[1]) < 100) for (let p2 = Number(m[1]); p2 <= Number(m[2]); p2++) out.add(p2);
|
|
42
|
+
} catch {
|
|
43
|
+
/* no config */
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function lanIp(): string | null {
|
|
49
|
+
for (const list of Object.values(os.networkInterfaces())) for (const a of list ?? []) if (a.family === "IPv4" && !a.internal) return a.address;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function probe(port: number, base = "/"): Promise<boolean> {
|
|
54
|
+
return new Promise((resolve) => {
|
|
55
|
+
const req = http.get({ host: "127.0.0.1", port, path: `${base}__mock/decisions`, agent: false, timeout: 2000 }, (res) => {
|
|
56
|
+
let b = "";
|
|
57
|
+
res.on("data", (c) => (b += c));
|
|
58
|
+
res.on("end", () => {
|
|
59
|
+
try { resolve(JSON.parse(b)?.mockSite === true); } catch { resolve(false); }
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
req.on("error", () => resolve(false));
|
|
63
|
+
req.on("timeout", () => { req.destroy(); resolve(false); });
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function portInUse(port: number): Promise<boolean> {
|
|
68
|
+
return new Promise((resolve) => {
|
|
69
|
+
const s = http.createServer();
|
|
70
|
+
s.once("error", () => resolve(true));
|
|
71
|
+
s.listen(port, "127.0.0.1", () => s.close(() => resolve(false)));
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function killChild(child: ChildProcess): Promise<void> {
|
|
76
|
+
return new Promise((resolve) => {
|
|
77
|
+
if (child.exitCode !== null || child.signalCode !== null) return resolve();
|
|
78
|
+
const t = setTimeout(() => child.kill("SIGKILL"), KILL_GRACE_MS);
|
|
79
|
+
child.once("exit", () => { clearTimeout(t); resolve(); });
|
|
80
|
+
child.kill("SIGTERM");
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The slice of `pi.events` the emitter needs. */
|
|
85
|
+
export interface ReservationEvents {
|
|
86
|
+
emit(channel: string, data: unknown): void;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Ask the host for a base (D9/D11): emit the neutral probe, then wait up to {@link RESERVATION_WAIT_MS} for `probe.pending`.
|
|
91
|
+
* No listener / a listener that never sets `pending` / a throwing emit = no reservation WITHOUT waiting. A timeout, a
|
|
92
|
+
* rejection or a malformed answer aborts `signal` (so a late reservation is released by the host) and means "root".
|
|
93
|
+
*/
|
|
94
|
+
async function reserveBase(events: ReservationEvents, port: number): Promise<{ base: string | null; why?: string; abort: () => void }> {
|
|
95
|
+
const ac = new AbortController();
|
|
96
|
+
const probeData: { port: number; pending?: Promise<unknown>; signal: AbortSignal } = { port, signal: ac.signal };
|
|
97
|
+
try {
|
|
98
|
+
events.emit(RESERVATION_EVENT, probeData);
|
|
99
|
+
} catch {
|
|
100
|
+
return { base: null, abort: () => ac.abort() };
|
|
101
|
+
}
|
|
102
|
+
if (probeData.pending === undefined) return { base: null, abort: () => ac.abort() };
|
|
103
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
104
|
+
const timeout = new Promise<"timeout">((r) => { timer = setTimeout(() => r("timeout"), RESERVATION_WAIT_MS); });
|
|
105
|
+
try {
|
|
106
|
+
const got = await Promise.race([Promise.resolve(probeData.pending), timeout]);
|
|
107
|
+
if (got === "timeout") { ac.abort(); return { base: null, why: "no answer within 2 s", abort: () => ac.abort() }; }
|
|
108
|
+
if (got === null || got === undefined) return { base: null, abort: () => ac.abort() };
|
|
109
|
+
const v = validateBase((got as { base?: unknown })?.base);
|
|
110
|
+
if (!v.ok || v.base === null) { ac.abort(); return { base: null, why: "the host answered with an unusable base", abort: () => ac.abort() }; }
|
|
111
|
+
return { base: v.base, abort: () => ac.abort() };
|
|
112
|
+
} catch (e) {
|
|
113
|
+
ac.abort();
|
|
114
|
+
const msg = String((e as Error)?.message ?? e).replace(/^base reservation unavailable:\s*/, "").slice(0, 120);
|
|
115
|
+
return { base: null, why: msg || "the host refused", abort: () => ac.abort() };
|
|
116
|
+
} finally {
|
|
117
|
+
clearTimeout(timer);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function startMockSite(opts: { dir?: string; port?: number; lan?: boolean; base?: unknown; events?: ReservationEvents }): Promise<ServeResult> {
|
|
122
|
+
const root = path.resolve(opts.dir ?? process.cwd());
|
|
123
|
+
const port = opts.port ?? DEFAULT_MOCK_SITE_PORT;
|
|
124
|
+
if (forbiddenPorts().has(port)) return { ok: false, error: `port ${port} is reserved; pick another port` };
|
|
125
|
+
if (children.has(port)) return { ok: false, error: `a mock site is already running on port ${port}` };
|
|
126
|
+
// An explicit base is validated BEFORE anything starts; `/` means "no base" and emits no probe.
|
|
127
|
+
const explicit = opts.base === undefined ? undefined : validateBase(opts.base);
|
|
128
|
+
if (explicit && !explicit.ok) return { ok: false, error: explicit.error };
|
|
129
|
+
const prep = await prepareMockSite(root);
|
|
130
|
+
if (!prep.ok) return { ok: false, error: prep.error };
|
|
131
|
+
if (explicit?.ok && explicit.base && !prep.baseFlag) {
|
|
132
|
+
return { ok: false, error: `the ${prep.adapter} launcher adapter cannot apply a base path; start without \`base\` (the site is served at the root)` };
|
|
133
|
+
}
|
|
134
|
+
// The port is checked free BEFORE the probe is emitted, so a busy port never reserves a base.
|
|
135
|
+
if (await portInUse(port)) return { ok: false, error: `port ${port} is busy; stop that process or pass another port` };
|
|
136
|
+
|
|
137
|
+
let base: string | null = explicit?.ok ? explicit.base : null;
|
|
138
|
+
let note: string | undefined;
|
|
139
|
+
let abortReservation: () => void = () => {};
|
|
140
|
+
if (explicit === undefined && prep.baseFlag && opts.events) {
|
|
141
|
+
const r = await reserveBase(opts.events, port);
|
|
142
|
+
base = r.base;
|
|
143
|
+
abortReservation = r.abort;
|
|
144
|
+
if (r.why) note = `base reservation unavailable: ${r.why}; the site starts at the root`;
|
|
145
|
+
}
|
|
146
|
+
const fail = (error: string): ServeResult => { abortReservation(); return { ok: false, error }; };
|
|
147
|
+
|
|
148
|
+
const child = spawn(process.execPath, [prep.launcher, "--config", prep.generated, "--port", String(port), "--strictPort", ...(base && prep.baseFlag ? [prep.baseFlag, base] : [])], {
|
|
149
|
+
cwd: root,
|
|
150
|
+
env: { ...process.env, MOCK_SITE_LAN: opts.lan ? "1" : "0", FORCE_COLOR: "0" },
|
|
151
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
152
|
+
});
|
|
153
|
+
let tail = "";
|
|
154
|
+
const keep = (c: Buffer) => { tail = (tail + c.toString()).slice(-2000); };
|
|
155
|
+
child.stdout?.on("data", keep);
|
|
156
|
+
child.stderr?.on("data", keep);
|
|
157
|
+
let exited = false;
|
|
158
|
+
child.once("exit", () => { exited = true; children.delete(port); });
|
|
159
|
+
child.once("error", () => { exited = true; });
|
|
160
|
+
|
|
161
|
+
const t0 = Date.now();
|
|
162
|
+
while (Date.now() - t0 < READY_TIMEOUT_MS) {
|
|
163
|
+
if (exited) return fail(`mock site exited during start (port ${port}):\n${tail.trim()}`);
|
|
164
|
+
if (await probe(port, base ?? "/")) {
|
|
165
|
+
children.set(port, child);
|
|
166
|
+
const ip = opts.lan ? lanIp() : null;
|
|
167
|
+
const at = base ?? "";
|
|
168
|
+
return { ok: true, port, root, local: `http://localhost:${port}${at}`, lan: ip ? `http://${ip}:${port}${at}` : null, launcher: prep.launcher, config: prep.config, base, ...(note ? { note } : {}) };
|
|
169
|
+
}
|
|
170
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
171
|
+
}
|
|
172
|
+
await killChild(child);
|
|
173
|
+
return fail(`mock site not ready within ${READY_TIMEOUT_MS / 1000}s on port ${port}${base ? ` (probed ${base}__mock/decisions)` : ""}:\n${tail.trim()}`);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function stopMockSite(port: number): Promise<boolean> {
|
|
177
|
+
const c = children.get(port);
|
|
178
|
+
if (!c) return false;
|
|
179
|
+
await killChild(c);
|
|
180
|
+
children.delete(port);
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function stopAllMockSites(): Promise<void> {
|
|
185
|
+
await Promise.all([...children.keys()].map((p) => stopMockSite(p)));
|
|
186
|
+
}
|