@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,228 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Mock-site environment: resolve the project's launcher + app build config through a
|
|
3
|
+
// build-tool adapter, load the (optional) mock options, and generate the inheriting
|
|
4
|
+
// Vite config at `node_modules/.vite-mock-site/mock-site.config.mjs` on every start.
|
|
5
|
+
// No static `vite` import: the serve path loads the PROJECT's Vite lazily.
|
|
6
|
+
// See change: add-mock-site-exact-env (design D1, D2, D8, D9).
|
|
7
|
+
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import * as fs from "node:fs";
|
|
10
|
+
import { createRequire } from "node:module";
|
|
11
|
+
import * as path from "node:path";
|
|
12
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
|
+
import { validateOptions } from "./options.mjs";
|
|
14
|
+
import { mockSite } from "./plugin.mjs";
|
|
15
|
+
|
|
16
|
+
/** @typedef {import("./options.mjs").MockSiteUserOptions} MockSiteUserOptions */
|
|
17
|
+
|
|
18
|
+
const VITE_CONFIGS = ["vite.config.ts", "vite.config.mts", "vite.config.js", "vite.config.mjs", "vite.config.cts", "vite.config.cjs"];
|
|
19
|
+
const OPTION_FILES = ["mock-site.config.ts", "mock-site.config.mts", "mock-site.config.js", "mock-site.config.mjs"];
|
|
20
|
+
/** Build tools we can name in an "unsupported" error: marker file → tool. */
|
|
21
|
+
const OTHER_TOOLS = [
|
|
22
|
+
[/^webpack\.config\./, "webpack"], [/^rspack\.config\./, "rspack"], [/^next\.config\./, "next"],
|
|
23
|
+
[/^\.parcelrc$/, "parcel"], [/^angular\.json$/, "angular"], [/^rollup\.config\./, "rollup"],
|
|
24
|
+
];
|
|
25
|
+
const BUILD_ADAPTERS = ["vite"];
|
|
26
|
+
/** The launcher flag each adapter maps a base onto; an adapter without one cannot apply a base (D11 (8)). */
|
|
27
|
+
const BASE_FLAGS = /** @type {Record<string, string>} */ ({ vite: "--base" });
|
|
28
|
+
const NEXT_STEP = `declare it in package.json: "mockSite": { "launcher": "<script that starts the build tool>", "config": "<app build config>" }, or add a build-tool adapter`;
|
|
29
|
+
export const GENERATED_DIR = path.join("node_modules", ".vite-mock-site");
|
|
30
|
+
|
|
31
|
+
/** @param {string} file */
|
|
32
|
+
function readJson(file) {
|
|
33
|
+
try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return undefined; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* A declared project-relative path: must exist, and its real path (symlinks
|
|
38
|
+
* followed) must sit inside the project root.
|
|
39
|
+
* @param {string} root @param {string} rel @param {"launcher"|"config"} what
|
|
40
|
+
* @returns {{ ok: true, file: string } | { ok: false, error: string }}
|
|
41
|
+
*/
|
|
42
|
+
function declaredPath(root, rel, what) {
|
|
43
|
+
const abs = path.resolve(root, rel);
|
|
44
|
+
if (!fs.existsSync(abs)) return { ok: false, error: `declared ${what} not found: ${abs} (package.json "mockSite.${what}")` };
|
|
45
|
+
const real = fs.realpathSync(abs);
|
|
46
|
+
const realRoot = fs.realpathSync(root);
|
|
47
|
+
const inside = real === realRoot || real.startsWith(realRoot + path.sep);
|
|
48
|
+
if (!inside) return { ok: false, error: `refusing ${what} outside the project: ${real} (declared as ${rel}; project ${realRoot})` };
|
|
49
|
+
return { ok: true, file: real };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The project's Vite package dir, or null. @param {string} root */
|
|
53
|
+
function viteDir(root) {
|
|
54
|
+
try {
|
|
55
|
+
return path.dirname(createRequire(path.join(root, "package.json")).resolve("vite/package.json"));
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** @param {string} root @param {any} pkg */
|
|
62
|
+
function detectViteConfig(root, pkg) {
|
|
63
|
+
for (const f of VITE_CONFIGS) if (fs.existsSync(path.join(root, f))) return path.join(root, f);
|
|
64
|
+
const dev = typeof pkg?.scripts?.dev === "string" ? pkg.scripts.dev : "";
|
|
65
|
+
const m = /\bvite\b[^&|;]*?(?:--config|-c)[ =]+(\S+)/.exec(dev);
|
|
66
|
+
if (m && fs.existsSync(path.resolve(root, m[1]))) return path.resolve(root, m[1]);
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Resolve the launcher + app config. Order: package.json `mockSite`, then the mock
|
|
72
|
+
* options' `launcher`/`config`, then Vite adapter detection.
|
|
73
|
+
* @param {string} root
|
|
74
|
+
* @param {{ options?: MockSiteUserOptions }} [opts]
|
|
75
|
+
* @returns {{ ok: true, adapter: "vite", launcher: string, config: string, source: "declared"|"detected" } | { ok: false, error: string }}
|
|
76
|
+
*/
|
|
77
|
+
export function resolveLauncher(root, opts = {}) {
|
|
78
|
+
const pkg = readJson(path.join(root, "package.json")) ?? {};
|
|
79
|
+
const manifest = pkg.mockSite && typeof pkg.mockSite === "object" ? pkg.mockSite : {};
|
|
80
|
+
const launcherDecl = manifest.launcher ?? opts.options?.launcher;
|
|
81
|
+
const configDecl = manifest.config ?? opts.options?.config;
|
|
82
|
+
let config;
|
|
83
|
+
if (configDecl) {
|
|
84
|
+
const r = declaredPath(root, configDecl, "config");
|
|
85
|
+
if (!r.ok) return r;
|
|
86
|
+
config = r.file;
|
|
87
|
+
} else {
|
|
88
|
+
config = detectViteConfig(root, pkg);
|
|
89
|
+
if (!config) {
|
|
90
|
+
const names = fs.existsSync(root) ? fs.readdirSync(root) : [];
|
|
91
|
+
const other = OTHER_TOOLS.find(([re]) => names.some((n) => /** @type {RegExp} */ (re).test(n)));
|
|
92
|
+
if (other) return { ok: false, error: `build tool ${other[1]} has no mock-site adapter (supported adapters: ${BUILD_ADAPTERS.join(", ")}); ${NEXT_STEP}` };
|
|
93
|
+
return { ok: false, error: `no app build config found in ${root} (looked for ${VITE_CONFIGS.join(", ")} and a "--config" in scripts.dev; supported adapters: ${BUILD_ADAPTERS.join(", ")}); ${NEXT_STEP}` };
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
let launcher;
|
|
97
|
+
if (launcherDecl) {
|
|
98
|
+
const r = declaredPath(root, launcherDecl, "launcher");
|
|
99
|
+
if (!r.ok) return r;
|
|
100
|
+
launcher = r.file;
|
|
101
|
+
} else {
|
|
102
|
+
const dir = viteDir(root);
|
|
103
|
+
if (!dir || !fs.existsSync(path.join(dir, "bin", "vite.js"))) return { ok: false, error: `vite not found from ${root}; install vite in the project, or ${NEXT_STEP}` };
|
|
104
|
+
launcher = path.join(dir, "bin", "vite.js");
|
|
105
|
+
}
|
|
106
|
+
return { ok: true, adapter: "vite", launcher, config, source: launcherDecl || configDecl ? "declared" : "detected" };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Take the app's build shape: resolve root-relative settings against the app's
|
|
111
|
+
* source root, then drop dev-server runtime (`server`), output (`build`) and `root`.
|
|
112
|
+
* The app's root is relative to its config's directory (where its scripts run).
|
|
113
|
+
* @param {Record<string, any>} cfg @param {string} configFile
|
|
114
|
+
*/
|
|
115
|
+
export function inheritAppConfig(cfg, configFile) {
|
|
116
|
+
const appRoot = path.resolve(path.dirname(configFile), typeof cfg.root === "string" ? cfg.root : ".");
|
|
117
|
+
const out = { ...cfg };
|
|
118
|
+
out.publicDir = out.publicDir === false ? false : path.resolve(appRoot, typeof out.publicDir === "string" ? out.publicDir : "public");
|
|
119
|
+
out.envDir = out.envDir === false ? false : path.resolve(appRoot, typeof out.envDir === "string" ? out.envDir : ".");
|
|
120
|
+
if (typeof out.cacheDir === "string") out.cacheDir = path.resolve(appRoot, out.cacheDir);
|
|
121
|
+
delete out.server;
|
|
122
|
+
delete out.build;
|
|
123
|
+
delete out.root;
|
|
124
|
+
delete out.preview;
|
|
125
|
+
// The app's own `base` never leaks in: without `--base` the site serves at `/` (the mock site's base comes ONLY from the
|
|
126
|
+
// launcher's `--base`, never from this per-project generated config). See change: serve-live-previews-on-capability-origin (D11 (7)).
|
|
127
|
+
delete out.base;
|
|
128
|
+
return { config: out, appRoot };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Load the project's own Vite (ESM entry) lazily — the extension never imports it statically.
|
|
133
|
+
* @param {string} root
|
|
134
|
+
*/
|
|
135
|
+
export async function importProjectVite(root) {
|
|
136
|
+
const dir = viteDir(root);
|
|
137
|
+
if (!dir) throw new Error(`vite not found from ${root}; install vite in the project`);
|
|
138
|
+
const pkg = readJson(path.join(dir, "package.json")) ?? {};
|
|
139
|
+
const dot = pkg.exports?.["."];
|
|
140
|
+
const entry = (typeof dot?.import === "string" ? dot.import : dot?.import?.default) ?? pkg.module ?? "dist/node/index.js";
|
|
141
|
+
return import(pathToFileURL(path.join(dir, entry)).href);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** The options file under `mockups/`, or null. @param {string} root */
|
|
145
|
+
export function optionsFile(root) {
|
|
146
|
+
for (const f of OPTION_FILES) if (fs.existsSync(path.join(root, "mockups", f))) return path.join(root, "mockups", f);
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Load + validate the optional options file through the project's Vite config loader.
|
|
152
|
+
* @param {string} root @param {any} vite
|
|
153
|
+
* @returns {Promise<{ ok: true, options: MockSiteUserOptions, file: string|null } | { ok: false, error: string }>}
|
|
154
|
+
*/
|
|
155
|
+
export async function loadOptions(root, vite) {
|
|
156
|
+
const file = optionsFile(root);
|
|
157
|
+
if (!file) return { ok: true, options: {}, file: null };
|
|
158
|
+
try {
|
|
159
|
+
const loaded = await vite.loadConfigFromFile({ command: "serve", mode: "development" }, file, root, "silent");
|
|
160
|
+
return { ok: true, options: validateOptions(loaded?.config, file), file };
|
|
161
|
+
} catch (e) {
|
|
162
|
+
const msg = String(/** @type {Error} */ (e)?.message ?? e).split("\n")[0];
|
|
163
|
+
return { ok: false, error: msg.includes(file) ? msg : `mock options file failed to load: ${file}: ${msg}` };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Everything a start needs: options, launcher, app config, and the generated config
|
|
169
|
+
* (rewritten on every call).
|
|
170
|
+
* @param {string} root
|
|
171
|
+
* @returns {Promise<{ ok: true, launcher: string, config: string, generated: string, source: string, optionsFile: string|null, adapter: "vite", baseFlag: string|null } | { ok: false, error: string }>}
|
|
172
|
+
*/
|
|
173
|
+
export async function prepareMockSite(root) {
|
|
174
|
+
/** @type {MockSiteUserOptions} */
|
|
175
|
+
let options = {};
|
|
176
|
+
let file = null;
|
|
177
|
+
if (optionsFile(root)) {
|
|
178
|
+
let vite;
|
|
179
|
+
try { vite = await importProjectVite(root); } catch (e) { return { ok: false, error: String(/** @type {Error} */ (e).message) }; }
|
|
180
|
+
const o = await loadOptions(root, vite);
|
|
181
|
+
if (!o.ok) return o;
|
|
182
|
+
options = o.options;
|
|
183
|
+
file = o.file;
|
|
184
|
+
}
|
|
185
|
+
const l = resolveLauncher(root, { options });
|
|
186
|
+
if (!l.ok) return l;
|
|
187
|
+
const generated = writeGeneratedConfig(root, { config: l.config, options, optionsFile: file });
|
|
188
|
+
return { ok: true, launcher: l.launcher, config: l.config, generated, source: l.source, optionsFile: file, adapter: l.adapter, baseFlag: BASE_FLAGS[l.adapter] ?? null };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Write `<root>/node_modules/.vite-mock-site/mock-site.config.<hash>.mjs` (plain .mjs:
|
|
193
|
+
* no TS stripping under node_modules; `<hash>` of the root keeps projects that share
|
|
194
|
+
* a symlinked node_modules apart). It imports the project's Vite next to it.
|
|
195
|
+
* @param {string} root @param {{ config: string, options: MockSiteUserOptions, optionsFile: string|null }} p
|
|
196
|
+
*/
|
|
197
|
+
function writeGeneratedConfig(root, p) {
|
|
198
|
+
const dir = path.join(root, GENERATED_DIR);
|
|
199
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
200
|
+
const file = path.join(dir, `mock-site.config.${createHash("sha256").update(root).digest("hex").slice(0, 8)}.mjs`);
|
|
201
|
+
const envModule = fileURLToPath(import.meta.url);
|
|
202
|
+
const params = { projectRoot: root, config: p.config, options: p.options, optionsFile: p.optionsFile };
|
|
203
|
+
fs.writeFileSync(file, `// GENERATED by the mock site on every start — do not edit.
|
|
204
|
+
import * as vite from "vite";
|
|
205
|
+
import { createMockSiteConfig } from ${JSON.stringify(envModule)};
|
|
206
|
+
export default (env) => createMockSiteConfig(${JSON.stringify(params)}, env, vite);
|
|
207
|
+
`);
|
|
208
|
+
return file;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* @public Imported by the generated config (a file knip cannot see).
|
|
213
|
+
* Called by the generated config inside the launcher's process: load the app
|
|
214
|
+
* config, inherit its build shape, and layer the mock-site plugin on top.
|
|
215
|
+
* @param {{ projectRoot: string, config: string, options: MockSiteUserOptions, optionsFile: string|null }} p
|
|
216
|
+
* @param {{ mode?: string }} env
|
|
217
|
+
* @param {any} vite
|
|
218
|
+
*/
|
|
219
|
+
export async function createMockSiteConfig(p, env, vite) {
|
|
220
|
+
const loaded = await vite.loadConfigFromFile({ command: "serve", mode: env?.mode ?? "development", isSsrBuild: false, isPreview: false }, p.config, path.dirname(p.config));
|
|
221
|
+
if (!loaded) throw new Error(`mock-site: app config did not load: ${p.config}`);
|
|
222
|
+
const { config, appRoot } = inheritAppConfig(loaded.config, p.config);
|
|
223
|
+
const o = p.options ?? {};
|
|
224
|
+
console.log(`mock-site: app config ${p.config}${p.optionsFile ? `, options ${p.optionsFile}` : ""}`);
|
|
225
|
+
return vite.mergeConfig(config, {
|
|
226
|
+
plugins: [mockSite({ projectRoot: p.projectRoot, app: o.app, title: o.title, themes: o.themes, aliases: o.aliases, appRoot })],
|
|
227
|
+
});
|
|
228
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Types for frameworks.mjs (plain-JS module; see change: add-mock-site-exact-env).
|
|
2
|
+
export interface FrameworkAdapter { dedupe: string[]; include: string[] }
|
|
3
|
+
export declare const FRAMEWORK_ADAPTERS: Record<string, FrameworkAdapter>;
|
|
4
|
+
export declare const DEFAULT_FRAMEWORK: string;
|
|
5
|
+
export declare function frameworkProblem(framework: unknown): string | null;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Component-framework adapters for the mock site. Pure (no node imports): shared by
|
|
3
|
+
// the node plugin (dedupe + pre-bundling) and the browser shell (unknown-framework
|
|
4
|
+
// page error). Fixtures, scripts and the cursor overlay sit OUTSIDE the adapter.
|
|
5
|
+
// See change: add-mock-site-exact-env (design D8).
|
|
6
|
+
|
|
7
|
+
/** @typedef {{ dedupe: string[], include: string[] }} FrameworkAdapter */
|
|
8
|
+
|
|
9
|
+
/** @type {Record<string, FrameworkAdapter>} */
|
|
10
|
+
export const FRAMEWORK_ADAPTERS = {
|
|
11
|
+
react: {
|
|
12
|
+
dedupe: ["react", "react-dom"],
|
|
13
|
+
include: ["react", "react-dom", "react-dom/client", "react/jsx-runtime", "react/jsx-dev-runtime"],
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export const DEFAULT_FRAMEWORK = "react";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Page error for a mock whose `framework` has no adapter; null when supported.
|
|
21
|
+
* @param {unknown} framework
|
|
22
|
+
*/
|
|
23
|
+
export function frameworkProblem(framework) {
|
|
24
|
+
const name = framework === undefined ? DEFAULT_FRAMEWORK : String(framework);
|
|
25
|
+
if (Object.hasOwn(FRAMEWORK_ADAPTERS, name)) return null;
|
|
26
|
+
return `framework "${name}" has no mock-site adapter (supported: ${Object.keys(FRAMEWORK_ADAPTERS).join(", ")})`;
|
|
27
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
// Types for headless.mjs (plain-JS module; see change: add-mock-site-exact-env).
|
|
2
|
+
export interface Health { completed: number; failed: number; errors?: string[]; loopMs?: number[] }
|
|
3
|
+
type Open = (url: string) => Promise<{ health: Health; close: () => Promise<void> }>;
|
|
4
|
+
/** What the site shows for `#<id>` (shown section id, Locate problems, runnable pane specs). */
|
|
5
|
+
export interface MockPage { checked: string | null; problems: string[]; panes: string[] }
|
|
6
|
+
type Inspect = (url: string, id: string) => Promise<MockPage>;
|
|
7
|
+
export declare const DEFAULT_LOOPS: number;
|
|
8
|
+
export declare function videoPath(root: string, spec: string, out?: string): string;
|
|
9
|
+
export declare function main(kind: "check" | "video", argv: string[], cwd?: string, deps?: { open?: Open; inspect?: Inspect }): Promise<{ code: number; out: string }>;
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Headless runs of a scripted frame against a RUNNING mock site:
|
|
3
|
+
// mock-check <ref> [--loops N] [--url U] N loops (default 3), exit 1 on any failed loop
|
|
4
|
+
// mock-check <mock-id> [--loops N] Locate problems (exit 1), then the Locate pane(s) and every
|
|
5
|
+
// scripted frame, N loops each; unknown id -> exit 2
|
|
6
|
+
// mock-video <ref> [--out F] [--url U] record one loop to .webm (default: project build cache)
|
|
7
|
+
// The pane page (`?pane=<id>/<frame>/<side>&mkLoops=N`) runs the script and
|
|
8
|
+
// publishes `window.__mkHealth = { completed, failed, errors }`.
|
|
9
|
+
// See change: add-mock-site-exact-env (design D4, D7), add-mock-locate-frame (D8).
|
|
10
|
+
|
|
11
|
+
import * as fs from "node:fs";
|
|
12
|
+
import * as os from "node:os";
|
|
13
|
+
import * as path from "node:path";
|
|
14
|
+
import { joinUrl } from "./base.mjs";
|
|
15
|
+
import { launchChromium } from "./browser.mjs";
|
|
16
|
+
import { GENERATED_DIR } from "./env.mjs";
|
|
17
|
+
import { parseRef } from "./refs.mjs";
|
|
18
|
+
|
|
19
|
+
export const DEFAULT_LOOPS = 3;
|
|
20
|
+
const DEFAULT_URL = "http://localhost:5299";
|
|
21
|
+
const STEP_BUDGET_MS = 60_000;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* @param {string[]} argv
|
|
25
|
+
* @returns {{ ok: true, ref: string, loops: number, url: string, out?: string } | { ok: false, error: string }}
|
|
26
|
+
*/
|
|
27
|
+
function parseArgs(argv) {
|
|
28
|
+
/** @type {string[]} */
|
|
29
|
+
const pos = [];
|
|
30
|
+
let loops = DEFAULT_LOOPS, url = DEFAULT_URL, out;
|
|
31
|
+
for (let i = 0; i < argv.length; i++) {
|
|
32
|
+
const a = argv[i];
|
|
33
|
+
if (a === "--loops") { loops = Number(argv[++i]); if (!Number.isInteger(loops) || loops < 1) return { ok: false, error: "--loops must be a positive integer" }; }
|
|
34
|
+
else if (a === "--url") url = String(argv[++i] ?? "").replace(/\/+$/, "");
|
|
35
|
+
else if (a === "--out") out = argv[++i];
|
|
36
|
+
else pos.push(a);
|
|
37
|
+
}
|
|
38
|
+
if (!pos[0]) return { ok: false, error: "missing <ref> (#<id>[/<frame>[/<side>]])" };
|
|
39
|
+
return { ok: true, ref: pos[0], loops, url, ...(out ? { out } : {}) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** `<id>/<frame>/<side>` of a frame ref (side defaults to proposed). @param {string} ref */
|
|
43
|
+
function paneSpec(ref) {
|
|
44
|
+
const r = parseRef(ref);
|
|
45
|
+
if (!r.frame) throw new Error(`ref needs a frame: ${ref} (want #<id>/<frame>[/<side>])`);
|
|
46
|
+
return `${r.id}/${r.frame}/${r.side ?? "proposed"}`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** @param {{ completed: number, failed: number, errors?: string[], loopMs?: number[] }} h */
|
|
50
|
+
const summary = (h) => {
|
|
51
|
+
const mean = h.loopMs?.length ? `, mean ${Math.round(h.loopMs.reduce((a, b) => a + b, 0) / h.loopMs.length)} ms` : "";
|
|
52
|
+
return [`completed ${h.completed}, failed ${h.failed}${mean}`, ...(h.errors ?? []).map((e) => ` ${e}`)].join("\n");
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* @typedef {{ checked: string | null, problems: string[], panes: string[] }} MockPage
|
|
57
|
+
* What the site shows for `#<id>`: the shown mock section's id, its Locate problems, and its
|
|
58
|
+
* runnable pane specs (`data-mk-locate-checked`, `data-mk-locate-problems`, `data-mk-panes`).
|
|
59
|
+
* @param {string} url @param {string} id @returns {Promise<MockPage>}
|
|
60
|
+
*/
|
|
61
|
+
async function inspectMock(url, id) {
|
|
62
|
+
await assertSite(url);
|
|
63
|
+
const { browser } = await launchChromium(await chromium());
|
|
64
|
+
try {
|
|
65
|
+
const page = await browser.newPage();
|
|
66
|
+
await page.goto(joinUrl(url, `#${id}`));
|
|
67
|
+
const sec = await page.waitForSelector("section[data-mk-locate-checked]", { timeout: 30_000 }).catch(() => null);
|
|
68
|
+
if (!sec) return { checked: null, problems: [], panes: [] };
|
|
69
|
+
const attr = async (/** @type {string} */ n) => String((await sec.getAttribute(n)) ?? "");
|
|
70
|
+
const split = (/** @type {string} */ v, /** @type {RegExp} */ re) => v.split(re).filter(Boolean);
|
|
71
|
+
return { checked: await attr("data-mk-locate-checked"), problems: split(await attr("data-mk-locate-problems"), /,/), panes: split(await attr("data-mk-panes"), /\s+/) };
|
|
72
|
+
} finally {
|
|
73
|
+
await browser.close();
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Default video file: the project's build cache, never a mock dir. @param {string} root @param {string} spec @param {string} [out] */
|
|
78
|
+
export function videoPath(root, spec, out) {
|
|
79
|
+
if (out) return path.resolve(out);
|
|
80
|
+
return path.join(root, GENERATED_DIR, "videos", `${spec.replace(/\//g, "-")}.webm`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** @param {string} url */
|
|
84
|
+
async function assertSite(url) {
|
|
85
|
+
const r = await fetch(joinUrl(url, "__mock/decisions")).then((x) => x.json()).catch(() => null);
|
|
86
|
+
if (!r?.mockSite) throw new Error(`no mock site at ${url}; start it (serve_mock_site, or npm run mocks) or pass --url`);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** @param {any} page @param {number} loops */
|
|
90
|
+
async function waitHealth(page, loops) {
|
|
91
|
+
const deadline = Date.now() + STEP_BUDGET_MS * loops;
|
|
92
|
+
for (;;) {
|
|
93
|
+
const h = await page.evaluate(() => /** @type {any} */ (window).__mkHealth ?? null);
|
|
94
|
+
if (h?.error) return { completed: 0, failed: loops, errors: [h.error] };
|
|
95
|
+
if (h && h.completed + h.failed >= loops) return h;
|
|
96
|
+
if (Date.now() > deadline) return { completed: h?.completed ?? 0, failed: loops - (h?.completed ?? 0), errors: [...(h?.errors ?? []), "timed out"] };
|
|
97
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function chromium() {
|
|
102
|
+
const spec = "playwright";
|
|
103
|
+
const pw = await import(spec).catch(() => null);
|
|
104
|
+
if (!pw?.chromium) throw new Error("playwright not installed: npm i -D playwright && npx playwright install chromium");
|
|
105
|
+
return pw.chromium;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* @param {{ spec: string, loops: number, url: string }} o
|
|
110
|
+
* @param {{ open?: (url: string) => Promise<{ health: any, close: () => Promise<void> }> }} [deps]
|
|
111
|
+
*/
|
|
112
|
+
async function runCheck(o, deps = {}) {
|
|
113
|
+
const target = joinUrl(o.url, `?pane=${encodeURIComponent(o.spec)}&mkLoops=${o.loops}&mkFast=1`);
|
|
114
|
+
if (deps.open) { const r = await deps.open(target); await r.close(); return r.health; }
|
|
115
|
+
await assertSite(o.url);
|
|
116
|
+
const { browser } = await launchChromium(await chromium());
|
|
117
|
+
try {
|
|
118
|
+
const page = await browser.newPage();
|
|
119
|
+
await page.goto(target);
|
|
120
|
+
return await waitHealth(page, o.loops);
|
|
121
|
+
} finally {
|
|
122
|
+
await browser.close();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* `mock-check <mock-id>`: Locate problems first (exit 1, nothing run), then every pane N loops.
|
|
128
|
+
* @param {{ id: string, loops: number, url: string }} o
|
|
129
|
+
* @param {{ open?: (url: string) => Promise<{ health: any, close: () => Promise<void> }>, inspect?: (url: string, id: string) => Promise<MockPage> }} deps
|
|
130
|
+
* @returns {Promise<{ code: number, out: string }>}
|
|
131
|
+
*/
|
|
132
|
+
async function checkMock(o, deps) {
|
|
133
|
+
const page = await (deps.inspect ?? inspectMock)(o.url, o.id);
|
|
134
|
+
if (page.checked !== o.id) return { code: 2, out: `unknown mock ${o.id}` };
|
|
135
|
+
if (page.problems.length) return { code: 1, out: page.problems.map((p) => `${p} ${o.id}`).join("\n") };
|
|
136
|
+
const lines = [];
|
|
137
|
+
let failed = false;
|
|
138
|
+
for (const spec of page.panes) {
|
|
139
|
+
const h = await runCheck({ spec, loops: o.loops, url: o.url }, deps);
|
|
140
|
+
failed ||= h.failed > 0;
|
|
141
|
+
lines.push(`${spec}: ${summary(h)}`);
|
|
142
|
+
}
|
|
143
|
+
return { code: failed ? 1 : 0, out: lines.join("\n") || `${o.id}: no scripted panes` };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* `mock-check <mock-id>` path: null when the ref names a frame (the frame path runs instead).
|
|
148
|
+
* @param {{ ref: string, loops: number, url: string }} a @param {Parameters<typeof checkMock>[1]} deps
|
|
149
|
+
* @returns {Promise<{ code: number, out: string } | null>}
|
|
150
|
+
*/
|
|
151
|
+
async function checkBareId(a, deps) {
|
|
152
|
+
let r;
|
|
153
|
+
try { r = parseRef(a.ref); } catch (e) { return { code: 2, out: String(/** @type {Error} */ (e).message) }; }
|
|
154
|
+
if (r.frame !== undefined) return null;
|
|
155
|
+
try { return await checkMock({ id: r.id, loops: a.loops, url: a.url }, deps); }
|
|
156
|
+
catch (e) { return { code: 1, out: String(/** @type {Error} */ (e).message).split("\n")[0] }; }
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** @param {{ spec: string, url: string, out: string }} o */
|
|
160
|
+
async function runVideo(o) {
|
|
161
|
+
await assertSite(o.url);
|
|
162
|
+
const { browser } = await launchChromium(await chromium());
|
|
163
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "mock-video-"));
|
|
164
|
+
try {
|
|
165
|
+
const ctx = await browser.newContext({ recordVideo: { dir } });
|
|
166
|
+
const page = await ctx.newPage();
|
|
167
|
+
await page.goto(joinUrl(o.url, `?pane=${encodeURIComponent(o.spec)}&mkLoops=1`));
|
|
168
|
+
const h = await waitHealth(page, 1);
|
|
169
|
+
await page.close();
|
|
170
|
+
fs.mkdirSync(path.dirname(o.out), { recursive: true });
|
|
171
|
+
await page.video()?.saveAs(o.out);
|
|
172
|
+
await ctx.close();
|
|
173
|
+
return h;
|
|
174
|
+
} finally {
|
|
175
|
+
await browser.close();
|
|
176
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* @param {"check"|"video"} kind @param {string[]} argv @param {string} cwd
|
|
182
|
+
* @param {{ open?: (url: string) => Promise<{ health: any, close: () => Promise<void> }>, inspect?: (url: string, id: string) => Promise<MockPage> }} [deps]
|
|
183
|
+
* @returns {Promise<{ code: number, out: string }>}
|
|
184
|
+
*/
|
|
185
|
+
export async function main(kind, argv, cwd = process.cwd(), deps = {}) {
|
|
186
|
+
const a = parseArgs(argv);
|
|
187
|
+
const usage = kind === "check" ? "usage: mock-check <mock-id | ref> [--loops N] [--url U]" : "usage: mock-video <ref> [--out file.webm] [--url U]";
|
|
188
|
+
if (!a.ok) return { code: 2, out: `${a.error}\n${usage}` };
|
|
189
|
+
if (kind === "check") {
|
|
190
|
+
const byId = await checkBareId(a, deps);
|
|
191
|
+
if (byId) return byId;
|
|
192
|
+
}
|
|
193
|
+
let spec;
|
|
194
|
+
try { spec = paneSpec(a.ref); } catch (e) { return { code: 2, out: String(/** @type {Error} */ (e).message) }; }
|
|
195
|
+
try {
|
|
196
|
+
if (kind === "check") {
|
|
197
|
+
const h = await runCheck({ spec, loops: a.loops, url: a.url }, deps);
|
|
198
|
+
return { code: h.failed > 0 ? 1 : 0, out: `${spec}: ${summary(h)}` };
|
|
199
|
+
}
|
|
200
|
+
const { findProjectRoot } = await import("./cli.mjs");
|
|
201
|
+
const out = videoPath(findProjectRoot(cwd), spec, a.out && path.resolve(cwd, a.out));
|
|
202
|
+
const h = await runVideo({ spec, url: a.url, out });
|
|
203
|
+
return { code: h.failed > 0 ? 1 : 0, out: `${h.failed > 0 ? "loop failed" : "video"}: ${out}\n${summary(h)}` };
|
|
204
|
+
} catch (e) {
|
|
205
|
+
return { code: 1, out: String(/** @type {Error} */ (e).message).split("\n")[0] };
|
|
206
|
+
}
|
|
207
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Types for locate.mjs (plain-JS module; see change: add-mock-locate-frame).
|
|
2
|
+
/** Any mock shape: `frames[].phone`, `locate.script[]`, `locate.phone.script[]` are read. */
|
|
3
|
+
export declare function locateProblems(mock: { frames?: readonly object[]; locate?: object }): string[];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Locate problems of a mock (framework-free): shared by the site shell (problem list,
|
|
3
|
+
// sidebar / title markers) and `mock-check <mock-id>`. See change: add-mock-locate-frame (design D4).
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @typedef {{ act?: string, unless?: unknown }} Step
|
|
7
|
+
* @typedef {{ script?: Step[] }} Walk
|
|
8
|
+
* @typedef {{ frames?: { phone?: boolean }[], locate?: Walk & { phone?: Walk } }} LocateMock
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Problems of one Locate walk (desktop or phone). @param {Walk} w @returns {string[]} */
|
|
12
|
+
function walkProblems(w) {
|
|
13
|
+
const script = w.script ?? [];
|
|
14
|
+
const last = script[script.length - 1];
|
|
15
|
+
if (last?.act !== "spot") return ["LOCATE WITHOUT SPOT"];
|
|
16
|
+
return script.some((s) => s.act === "spot" && s.unless !== undefined) ? ["SPOT WITH UNLESS"] : [];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* `NO LOCATE`, `NO PHONE LOCATE`, `LOCATE WITHOUT SPOT`, `SPOT WITH UNLESS` (Locate scripts only).
|
|
21
|
+
* @param {LocateMock} mock @returns {string[]}
|
|
22
|
+
*/
|
|
23
|
+
export function locateProblems(mock) {
|
|
24
|
+
const l = mock.locate;
|
|
25
|
+
if (!l) return ["NO LOCATE"];
|
|
26
|
+
const out = walkProblems(l);
|
|
27
|
+
if (l.phone) out.push(...walkProblems(l.phone));
|
|
28
|
+
else if ((mock.frames ?? []).some((f) => f.phone)) out.push("NO PHONE LOCATE");
|
|
29
|
+
return [...new Set(out)];
|
|
30
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// Types for options.mjs (plain-JS module; see change: add-mock-site-exact-env).
|
|
2
|
+
import type { ThemeSpec } from "./plugin.mjs";
|
|
3
|
+
export interface MockSiteUserOptions {
|
|
4
|
+
title?: string;
|
|
5
|
+
/** First entry is the default; a `system` entry follows prefers-color-scheme. */
|
|
6
|
+
themes?: ThemeSpec[];
|
|
7
|
+
/** Project setup module, relative to `mockups/` (exports `setup`, `Providers`). */
|
|
8
|
+
app?: string;
|
|
9
|
+
/** Extra aliases the app config lacks (the app's own aliases are inherited). */
|
|
10
|
+
aliases?: Record<string, string>;
|
|
11
|
+
/** Launcher script (project-relative); package.json `mockSite.launcher` wins. */
|
|
12
|
+
launcher?: string;
|
|
13
|
+
/** App build config (project-relative); package.json `mockSite.config` wins. */
|
|
14
|
+
config?: string;
|
|
15
|
+
/** Extra keys `mock-capture` redacts. */
|
|
16
|
+
redact?: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare function defineMockSite(o: MockSiteUserOptions): MockSiteUserOptions;
|
|
19
|
+
export declare function validateOptions(o: unknown, file: string): MockSiteUserOptions;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// Mock options file (`mockups/mock-site.config.ts`): a plain options object, never
|
|
3
|
+
// a build config. Build plugins come only from the app's own config, so nothing
|
|
4
|
+
// can be registered twice. Optional. See change: add-mock-site-exact-env (D9).
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* @typedef {{ id: string, label: string, attrs?: Record<string, string|null>, system?: { dark: string, light: string } }} ThemeSpec
|
|
8
|
+
* @typedef {{
|
|
9
|
+
* title?: string,
|
|
10
|
+
* themes?: ThemeSpec[],
|
|
11
|
+
* app?: string,
|
|
12
|
+
* aliases?: Record<string, string>,
|
|
13
|
+
* launcher?: string,
|
|
14
|
+
* config?: string,
|
|
15
|
+
* redact?: string[],
|
|
16
|
+
* }} MockSiteUserOptions
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
const KEYS = new Set(["title", "themes", "app", "aliases", "launcher", "config", "redact"]);
|
|
20
|
+
/** Keys that only make sense in a build config: refused with the "not a build config" message. */
|
|
21
|
+
const BUILD_KEYS = new Set(["plugins", "resolve", "server", "build", "css", "define", "optimizeDeps", "root", "publicDir", "esbuild"]);
|
|
22
|
+
|
|
23
|
+
/** @public Identity helper for typed options files (consumer `mockups/mock-site.config.ts`). @param {MockSiteUserOptions} o */
|
|
24
|
+
export const defineMockSite = (o) => o;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Validate a loaded options object; throws naming the file and the offending key.
|
|
28
|
+
* @param {unknown} o @param {string} file
|
|
29
|
+
* @returns {MockSiteUserOptions}
|
|
30
|
+
*/
|
|
31
|
+
export function validateOptions(o, file) {
|
|
32
|
+
if (o === undefined || o === null) return {};
|
|
33
|
+
if (typeof o !== "object" || Array.isArray(o)) throw new Error(`mock options must be an object: ${file}`);
|
|
34
|
+
for (const k of Object.keys(o)) {
|
|
35
|
+
if (BUILD_KEYS.has(k)) throw new Error(`mock options are not a build config: ${file} sets "${k}"; build settings and plugins come from the app config (package.json "mockSite.config")`);
|
|
36
|
+
if (!KEYS.has(k)) throw new Error(`unknown mock option "${k}" in ${file} (allowed: ${[...KEYS].join(", ")})`);
|
|
37
|
+
}
|
|
38
|
+
const r = /** @type {Record<string, unknown>} */ (o);
|
|
39
|
+
for (const k of ["title", "app", "launcher", "config"]) if (r[k] !== undefined && typeof r[k] !== "string") throw new Error(`mock option "${k}" must be a string: ${file}`);
|
|
40
|
+
if (r.aliases !== undefined && (typeof r.aliases !== "object" || Array.isArray(r.aliases) || Object.values(/** @type {object} */ (r.aliases)).some((v) => typeof v !== "string")))
|
|
41
|
+
throw new Error(`mock option "aliases" must map strings to paths: ${file}`);
|
|
42
|
+
if (r.themes !== undefined && !Array.isArray(r.themes)) throw new Error(`mock option "themes" must be an array: ${file}`);
|
|
43
|
+
if (r.redact !== undefined && (!Array.isArray(r.redact) || r.redact.some((v) => typeof v !== "string"))) throw new Error(`mock option "redact" must be a string array: ${file}`);
|
|
44
|
+
return /** @type {MockSiteUserOptions} */ (o);
|
|
45
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Types for plugin.mjs (plain-JS module; see change: add-live-component-mock-site, add-mock-site-exact-env).
|
|
2
|
+
export interface ThemeSpec { id: string; label: string; attrs?: Record<string, string | null>; system?: { dark: string; light: string } }
|
|
3
|
+
export interface MockSiteOptions {
|
|
4
|
+
/** Project root holding `mockups/` (and optionally `openspec/changes/`). */
|
|
5
|
+
projectRoot: string;
|
|
6
|
+
/** Project adapter module, relative to `mockups/` (exports `setup`, `Providers`). Absent: no setup, pass-through Providers. */
|
|
7
|
+
app?: string;
|
|
8
|
+
title?: string;
|
|
9
|
+
/** First entry is the default; a `system` entry follows prefers-color-scheme. */
|
|
10
|
+
themes?: ThemeSpec[];
|
|
11
|
+
/** Extra dir the app's sources live in (added to `server.fs.allow`). */
|
|
12
|
+
appRoot?: string;
|
|
13
|
+
aliases?: Record<string, string>;
|
|
14
|
+
port?: number;
|
|
15
|
+
/** Bind 0.0.0.0 (LAN clients view only). Default from MOCK_SITE_LAN=1. */
|
|
16
|
+
lan?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/** False for Vite versions with a known `server.fs.deny` bypass (LAN mode refuses them). */
|
|
19
|
+
export declare function isLanSafeVite(version: string): boolean;
|
|
20
|
+
/** Vite plugin (typed loosely so the package needs no `vite` dependency). */
|
|
21
|
+
export declare function mockSite(options: MockSiteOptions): { name: string; [hook: string]: unknown };
|