@blackbelt-technology/pi-dashboard-deck3d 0.9.0 → 0.11.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/deck3d/SKILL.agent.md +78 -0
- package/.pi/skills/deck3d/SKILL.md +68 -0
- package/.pi/skills/deck3d/reference/effects.md +185 -2
- package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
- package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
- package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
- package/README.md +30 -2
- package/assets/preview/stub-chrome.png +0 -0
- package/assets/preview/stub-icon.json +59 -0
- package/assets/preview/stub-layout.json +195 -0
- package/assets/preview/stub-outline.json +48 -0
- package/dist/cli.js +11780 -5934
- package/dist/runtime.js +5916 -4007
- package/fixtures/business-2031/assets/stub-chrome.png +0 -0
- package/fixtures/business-2031/assets/stub-icon.json +59 -0
- package/fixtures/business-2031/assets/stub-layout.json +195 -0
- package/fixtures/business-2031/assets/stub-outline.json +48 -0
- package/fixtures/business-2031/build-overrides.mjs +58 -13
- package/fixtures/business-2031/deck.agent.md +60 -0
- package/fixtures/business-2031/deck.json +133 -8
- package/fixtures/business-2031/overrides.json +133 -8
- package/package.json +8 -4
- package/scripts/gen-stub-assets.ts +31 -0
- package/src/art/cutout.ts +97 -0
- package/src/art/decode.ts +169 -0
- package/src/art/icon.ts +380 -0
- package/src/art/png.ts +232 -0
- package/src/art/trace.ts +288 -0
- package/src/check/rules.ts +13 -8
- package/src/cli.ts +313 -51
- package/src/compare/index.ts +131 -0
- package/src/compare/ssim.ts +91 -0
- package/src/fx/art-geometry.ts +137 -0
- package/src/fx/art3d.meta.json +30 -0
- package/src/fx/art3d.ts +131 -0
- package/src/fx/bank.meta.json +26 -0
- package/src/fx/bank.ts +8 -0
- package/src/fx/compose.ts +5 -4
- package/src/fx/crane.meta.json +26 -0
- package/src/fx/crane.ts +8 -0
- package/src/fx/dolly.ts +5 -1
- package/src/fx/fade.ts +5 -1
- package/src/fx/flythrough.ts +5 -1
- package/src/fx/frame-chrome.meta.json +17 -0
- package/src/fx/frame-chrome.ts +134 -0
- package/src/fx/haze.meta.json +19 -0
- package/src/fx/haze.ts +91 -0
- package/src/fx/icon3d.meta.json +21 -0
- package/src/fx/icon3d.ts +167 -0
- package/src/fx/index.ts +96 -66
- package/src/fx/iris.ts +5 -1
- package/src/fx/meta.schema.json +10 -2
- package/src/fx/path.meta.json +25 -0
- package/src/fx/path.ts +8 -0
- package/src/fx/persistent.ts +11 -0
- package/src/fx/revolve.meta.json +26 -0
- package/src/fx/revolve.ts +8 -0
- package/src/fx/slide-layer.meta.json +26 -0
- package/src/fx/slide-layer.ts +557 -0
- package/src/fx/slide-space.ts +142 -0
- package/src/fx/stub-assets.ts +117 -0
- package/src/fx/swing.meta.json +26 -0
- package/src/fx/swing.ts +8 -0
- package/src/fx/types.ts +63 -2
- package/src/ir/merge.ts +5 -2
- package/src/ir/schema.json +140 -3
- package/src/ir/types.ts +54 -0
- package/src/ir/validate.ts +91 -3
- package/src/parse/harvest/index.ts +4 -1
- package/src/parse/markdown.ts +38 -7
- package/src/pptx/baseline.ts +183 -0
- package/src/pptx/extract.ts +161 -0
- package/src/pptx/fallback.ts +70 -0
- package/src/pptx/import.ts +256 -0
- package/src/pptx/master.ts +135 -0
- package/src/pptx/media.ts +81 -0
- package/src/pptx/package.ts +109 -0
- package/src/pptx/ref.ts +100 -0
- package/src/pptx/shapes.ts +276 -0
- package/src/pptx/stage.ts +82 -0
- package/src/pptx/text.ts +202 -0
- package/src/pptx/theme.ts +194 -0
- package/src/pptx/types.ts +159 -0
- package/src/pptx/xfrm.ts +93 -0
- package/src/pptx/xml.ts +106 -0
- package/src/pptx/zip.ts +239 -0
- package/src/render/assets.ts +57 -0
- package/src/render/build.ts +75 -0
- package/src/render/index.ts +7 -2
- package/src/render/template.html +1 -1
- package/src/runtime/assets.ts +75 -0
- package/src/runtime/fade.ts +110 -0
- package/src/runtime/hud.ts +37 -9
- package/src/runtime/index.ts +431 -67
- package/src/runtime/post.ts +11 -5
- package/src/runtime/scene.ts +25 -2
- package/src/runtime/transition.ts +222 -0
- package/src/runtime/types.ts +13 -2
- package/src/serve/index.ts +199 -16
- package/src/util/cleanup.ts +13 -0
- package/src/util/confine.ts +15 -0
- package/src/variants/pick.ts +282 -0
- package/src/variants/render.ts +179 -0
- package/src/variants/schema.json +48 -0
- package/src/variants/style.ts +318 -0
package/src/serve/index.ts
CHANGED
|
@@ -16,11 +16,13 @@
|
|
|
16
16
|
* `build` produces.
|
|
17
17
|
*/
|
|
18
18
|
import { createHash } from "node:crypto";
|
|
19
|
-
import { existsSync, type FSWatcher, mkdtempSync, readFileSync, watch, writeFileSync } from "node:fs";
|
|
19
|
+
import { existsSync, type FSWatcher, mkdtempSync, readFileSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
|
|
20
20
|
import { createServer, type Server, type ServerResponse } from "node:http";
|
|
21
21
|
import { tmpdir } from "node:os";
|
|
22
22
|
import { basename, dirname, extname, join, resolve, sep } from "node:path";
|
|
23
23
|
import type { CliIO, CliRun } from "../cli-io.js";
|
|
24
|
+
import { realInside } from "../util/confine.js";
|
|
25
|
+
import { LockError, withStyleLockAsync } from "../variants/style.js";
|
|
24
26
|
|
|
25
27
|
/** Media extensions the asset route will serve. */
|
|
26
28
|
const ASSET_TYPES: Record<string, string> = {
|
|
@@ -83,6 +85,8 @@ export interface ServeHandle {
|
|
|
83
85
|
htmlPath: string;
|
|
84
86
|
/** Resolves once any in-flight rebuild has settled. */
|
|
85
87
|
settled: () => Promise<void>;
|
|
88
|
+
/** Number of rebuilds run so far (the initial build counts as 1). */
|
|
89
|
+
rebuilds: () => number;
|
|
86
90
|
/** Last rebuild error, or null when the last rebuild succeeded. */
|
|
87
91
|
lastError: () => string | null;
|
|
88
92
|
/** Findings from the last `--check` pass, by slide id. */
|
|
@@ -115,6 +119,28 @@ const CLIENT = `<script>
|
|
|
115
119
|
box.textContent = JSON.parse(e.data).message;
|
|
116
120
|
});
|
|
117
121
|
es.addEventListener("ok", () => document.getElementById("deck3d-serve-error")?.remove());
|
|
122
|
+
// \`?variant=<step>:<name>\` previews a candidate in memory. \`V\` steps to the
|
|
123
|
+
// next variant of that step; it does nothing without the param, and never
|
|
124
|
+
// while a text field has focus.
|
|
125
|
+
const variant = window.__DECK3D_VARIANT;
|
|
126
|
+
if (variant) {
|
|
127
|
+
window.addEventListener("keydown", (e) => {
|
|
128
|
+
if ((e.key !== "v" && e.key !== "V") || e.metaKey || e.ctrlKey || e.altKey) return;
|
|
129
|
+
const t = document.activeElement;
|
|
130
|
+
if (t && (/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName) || t.isContentEditable)) return;
|
|
131
|
+
const next = variant.names[(variant.names.indexOf(variant.name) + 1) % variant.names.length];
|
|
132
|
+
const u = new URL(location.href);
|
|
133
|
+
u.searchParams.set("variant", variant.step + ":" + next);
|
|
134
|
+
location.href = u.toString();
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (window.__DECK3D_VARIANT_NOTICE) {
|
|
138
|
+
const n = document.createElement("div");
|
|
139
|
+
n.id = "deck3d-variant-notice";
|
|
140
|
+
n.style.cssText = "position:fixed;left:50%;top:12px;transform:translateX(-50%);z-index:9998;padding:8px 14px;border-radius:8px;background:#3b2d0d;color:#fde68a;font:12px/1.4 system-ui,sans-serif";
|
|
141
|
+
n.textContent = window.__DECK3D_VARIANT_NOTICE;
|
|
142
|
+
document.body.appendChild(n);
|
|
143
|
+
}
|
|
118
144
|
es.addEventListener("findings", (e) => {
|
|
119
145
|
window.__deck3dFindings = JSON.parse(e.data);
|
|
120
146
|
window.dispatchEvent(new CustomEvent("deck3d-findings"));
|
|
@@ -134,6 +160,12 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
134
160
|
const debounceMs = opts.debounceMs ?? 120;
|
|
135
161
|
|
|
136
162
|
let html: string | null = null;
|
|
163
|
+
let rebuildCount = 0;
|
|
164
|
+
/** A change arrived while a pick (or another writer) held the deck lock; rebuild once it is free. */
|
|
165
|
+
let deferred = false;
|
|
166
|
+
/** Last seen signature of style.json + asset files (see `sideSignature`). */
|
|
167
|
+
let sideSig = "";
|
|
168
|
+
const stylePath = join(deckDir, "style.json");
|
|
137
169
|
let lastError: string | null = null;
|
|
138
170
|
let findings: Record<string, string[]> = {};
|
|
139
171
|
let building: Promise<void> = Promise.resolve();
|
|
@@ -174,6 +206,56 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
174
206
|
if (touched) writeFileSync(jsonPath, `${JSON.stringify(ir, null, 2)}\n`);
|
|
175
207
|
}
|
|
176
208
|
|
|
209
|
+
/**
|
|
210
|
+
* Same for deck assets: serving is an authoring context, so replacing an
|
|
211
|
+
* asset file re-pins its `sha256` instead of failing the render on a stale one.
|
|
212
|
+
*/
|
|
213
|
+
function repinAssets(): void {
|
|
214
|
+
if (!existsSync(jsonPath)) return;
|
|
215
|
+
let ir: { overrides?: { assets?: Array<{ path: string; sha256: string }> } };
|
|
216
|
+
try {
|
|
217
|
+
ir = JSON.parse(readFileSync(jsonPath, "utf8")) as typeof ir;
|
|
218
|
+
} catch {
|
|
219
|
+
return;
|
|
220
|
+
}
|
|
221
|
+
let touched = false;
|
|
222
|
+
for (const a of ir.overrides?.assets ?? []) {
|
|
223
|
+
const file = resolve(deckDir, a.path);
|
|
224
|
+
if (!realInside(deckDir, file)) continue;
|
|
225
|
+
const sha = createHash("sha256").update(readFileSync(file)).digest("hex");
|
|
226
|
+
if (a.sha256 !== sha) {
|
|
227
|
+
a.sha256 = sha;
|
|
228
|
+
touched = true;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
if (touched) writeFileSync(jsonPath, `${JSON.stringify(ir, null, 2)}\n`);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** True while `style.json` records a half-written pick. */
|
|
235
|
+
function stylePending(): boolean {
|
|
236
|
+
try {
|
|
237
|
+
const st = JSON.parse(readFileSync(stylePath, "utf8")) as { steps?: Array<{ pending?: boolean }> };
|
|
238
|
+
return (st.steps ?? []).some((x) => x.pending === true);
|
|
239
|
+
} catch {
|
|
240
|
+
return false;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Signature of everything outside deck.md/deck.json whose change must rebuild: style.json + asset files. */
|
|
245
|
+
function sideSignature(): string {
|
|
246
|
+
const parts: string[] = [existsSync(stylePath) ? createHash("sha256").update(readFileSync(stylePath)).digest("hex") : "-"];
|
|
247
|
+
try {
|
|
248
|
+
const ir = JSON.parse(readFileSync(jsonPath, "utf8")) as { overrides?: { assets?: Array<{ path: string }> } };
|
|
249
|
+
for (const a of ir.overrides?.assets ?? []) {
|
|
250
|
+
const file = resolve(deckDir, a.path);
|
|
251
|
+
parts.push(existsSync(file) ? `${a.path}:${statSync(file).size}:${statSync(file).mtimeMs}` : `${a.path}:-`);
|
|
252
|
+
}
|
|
253
|
+
} catch {
|
|
254
|
+
// A broken deck.json is the parse step's problem.
|
|
255
|
+
}
|
|
256
|
+
return parts.join("|");
|
|
257
|
+
}
|
|
258
|
+
|
|
177
259
|
/**
|
|
178
260
|
* Digest of `deck.json` as the last rebuild left it. Every rebuild rewrites
|
|
179
261
|
* that file (`parse -o`), so a bare watcher on it would re-trigger itself
|
|
@@ -182,17 +264,48 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
182
264
|
let jsonDigest = "";
|
|
183
265
|
const digestJson = (): string => (existsSync(jsonPath) ? createHash("sha256").update(readFileSync(jsonPath)).digest("hex") : "");
|
|
184
266
|
|
|
267
|
+
/**
|
|
268
|
+
* True while a rebuild is running. Its own `parse` rewrites deck.json before
|
|
269
|
+
* `jsonDigest` is refreshed, so the poll must not read that mid-flight write
|
|
270
|
+
* as a foreign edit (it queued a spurious second rebuild).
|
|
271
|
+
*/
|
|
272
|
+
let rebuilding = false;
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* A rebuild rewrites deck.json (parse, re-pins), so it runs under the same
|
|
276
|
+
* lock as `variants pick|note|replay`. While another process holds it the
|
|
277
|
+
* rebuild is deferred (not failed): the poll retries once the lock is free.
|
|
278
|
+
*/
|
|
185
279
|
async function rebuild(): Promise<void> {
|
|
280
|
+
try {
|
|
281
|
+
await withStyleLockAsync(deckDir, runRebuild, { waitMs: 0 });
|
|
282
|
+
} catch (err) {
|
|
283
|
+
if (!(err instanceof LockError)) throw err;
|
|
284
|
+
deferred = true;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function runRebuild(): Promise<void> {
|
|
289
|
+
rebuilding = true;
|
|
290
|
+
rebuildCount++;
|
|
186
291
|
const errors: string[] = [];
|
|
187
292
|
const collect: CliIO = { stdout: () => {}, stderr: (m) => errors.push(m) };
|
|
188
293
|
try {
|
|
189
294
|
if ((await run(["parse", md, "-o", jsonPath], collect)) !== 0) throw new Error(errors.join("\n") || "parse failed");
|
|
190
295
|
repinLocalFx();
|
|
296
|
+
repinAssets();
|
|
191
297
|
// Render to a scratch file: the served copy carries the reload client,
|
|
192
298
|
// and the deck-dir artifact must not.
|
|
193
|
-
const
|
|
194
|
-
|
|
195
|
-
|
|
299
|
+
const scratchDir = mkdtempSync(join(tmpdir(), "deck3d-serve-out-"));
|
|
300
|
+
let built: string;
|
|
301
|
+
try {
|
|
302
|
+
const scratch = join(scratchDir, "deck.html");
|
|
303
|
+
if ((await run(["render", jsonPath, "-o", scratch], collect)) !== 0) throw new Error(errors.join("\n") || "render failed");
|
|
304
|
+
built = readFileSync(scratch, "utf8");
|
|
305
|
+
} finally {
|
|
306
|
+
// One scratch dir per rebuild: remove it on success AND on a failed render.
|
|
307
|
+
rmSync(scratchDir, { recursive: true, force: true });
|
|
308
|
+
}
|
|
196
309
|
writeFileSync(htmlPath, built);
|
|
197
310
|
html = built.replace("</body>", `${CLIENT}</body>`);
|
|
198
311
|
lastError = null;
|
|
@@ -207,6 +320,7 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
207
320
|
emit("error-report", { message: lastError });
|
|
208
321
|
} finally {
|
|
209
322
|
jsonDigest = digestJson();
|
|
323
|
+
rebuilding = false;
|
|
210
324
|
}
|
|
211
325
|
}
|
|
212
326
|
|
|
@@ -227,17 +341,30 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
227
341
|
}
|
|
228
342
|
|
|
229
343
|
function queue(): void {
|
|
344
|
+
// A rebuild reads the files as they are NOW, so the change it is about to
|
|
345
|
+
// absorb must not be reported again by the poll.
|
|
346
|
+
sideSig = sideSignature();
|
|
230
347
|
building = building.then(rebuild);
|
|
231
348
|
}
|
|
232
349
|
|
|
350
|
+
sideSig = sideSignature();
|
|
233
351
|
await (building = rebuild());
|
|
234
352
|
|
|
235
353
|
let timer: NodeJS.Timeout | null = null;
|
|
236
354
|
const watchers: FSWatcher[] = [];
|
|
355
|
+
const fire = (): void => {
|
|
356
|
+
if (stylePending()) {
|
|
357
|
+
deferred = true;
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
deferred = false;
|
|
361
|
+
queue();
|
|
362
|
+
};
|
|
237
363
|
const onChange = (): void => {
|
|
238
364
|
if (timer) clearTimeout(timer);
|
|
239
|
-
timer = setTimeout(
|
|
365
|
+
timer = setTimeout(fire, debounceMs);
|
|
240
366
|
};
|
|
367
|
+
|
|
241
368
|
const watchPath = (p: string, recursive = false, handler: () => void = onChange): void => {
|
|
242
369
|
if (!existsSync(p)) return;
|
|
243
370
|
try {
|
|
@@ -253,6 +380,19 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
253
380
|
// events for this file seconds late, and the rebuild rewrites it anyway, so
|
|
254
381
|
// a digest compare is both the change detector and the self-write filter.
|
|
255
382
|
const jsonPoll = setInterval(() => {
|
|
383
|
+
if (rebuilding) return;
|
|
384
|
+
// A rebuild deferred by a pending pick runs as soon as the marker clears.
|
|
385
|
+
if (deferred && !stylePending()) {
|
|
386
|
+
sideSig = sideSignature();
|
|
387
|
+
fire();
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
const side = sideSignature();
|
|
391
|
+
if (side !== sideSig) {
|
|
392
|
+
sideSig = side;
|
|
393
|
+
onChange();
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
256
396
|
if (digestJson() === jsonDigest) return;
|
|
257
397
|
onChange();
|
|
258
398
|
}, JSON_POLL_MS);
|
|
@@ -317,20 +457,44 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
317
457
|
res.end(JSON.stringify({ error: (e as Error).message }));
|
|
318
458
|
return;
|
|
319
459
|
}
|
|
320
|
-
// Validate BEFORE touching either file.
|
|
321
|
-
const invalid = await validPayload(patch);
|
|
322
|
-
if (invalid) {
|
|
323
|
-
res.writeHead(400, { "content-type": "application/json" });
|
|
324
|
-
res.end(JSON.stringify({ error: invalid }));
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
460
|
if (url.pathname === "/__apply") {
|
|
328
461
|
const { deepMerge } = await import("../ir/merge.js");
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
462
|
+
let invalid: string | null = null;
|
|
463
|
+
try {
|
|
464
|
+
// Validate, merge and write as ONE step under the deck lock: validating before
|
|
465
|
+
// waiting would check a deck a concurrent pick is about to change, and could
|
|
466
|
+
// persist a combination that was never validated.
|
|
467
|
+
await withStyleLockAsync(
|
|
468
|
+
deckDir,
|
|
469
|
+
async () => {
|
|
470
|
+
invalid = await validPayload(patch);
|
|
471
|
+
if (invalid) return;
|
|
472
|
+
const ir = JSON.parse(readFileSync(jsonPath, "utf8")) as Record<string, unknown>;
|
|
473
|
+
ir.overrides = deepMerge((ir.overrides ?? {}) as Record<string, unknown>, patch as Record<string, unknown>);
|
|
474
|
+
writeFileSync(target, `${JSON.stringify(ir, null, 2)}\n`);
|
|
475
|
+
},
|
|
476
|
+
{ waitMs: 3000 },
|
|
477
|
+
);
|
|
478
|
+
} catch (e) {
|
|
479
|
+
if (!(e instanceof LockError)) throw e;
|
|
480
|
+
res.writeHead(409, { "content-type": "application/json" });
|
|
481
|
+
res.end(JSON.stringify({ error: e.message }));
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
if (invalid) {
|
|
485
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
486
|
+
res.end(JSON.stringify({ error: invalid }));
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
332
489
|
await (building = building.then(rebuild));
|
|
333
490
|
} else {
|
|
491
|
+
// `/__overrides` only writes the standalone overrides file; it never touches deck.json.
|
|
492
|
+
const invalid = await validPayload(patch);
|
|
493
|
+
if (invalid) {
|
|
494
|
+
res.writeHead(400, { "content-type": "application/json" });
|
|
495
|
+
res.end(JSON.stringify({ error: invalid }));
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
334
498
|
writeFileSync(target, `${JSON.stringify(patch, null, 2)}\n`);
|
|
335
499
|
}
|
|
336
500
|
res.writeHead(200, { "content-type": "application/json" });
|
|
@@ -342,8 +506,26 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
342
506
|
res.end(lastError ?? "building");
|
|
343
507
|
return;
|
|
344
508
|
}
|
|
509
|
+
// `?variant=<step>:<name>`: the candidate rendered in memory — nothing is written.
|
|
510
|
+
const wanted = url.searchParams.get("variant");
|
|
511
|
+
let body = html;
|
|
512
|
+
if (wanted) {
|
|
513
|
+
const [stepId, name] = wanted.split(":");
|
|
514
|
+
const { readStyle } = await import("../variants/style.js");
|
|
515
|
+
const step = readStyle(stylePath)?.steps.find((x) => x.id === stepId);
|
|
516
|
+
const variant = step?.variants.find((v) => v.name === name);
|
|
517
|
+
if (step && variant) {
|
|
518
|
+
const { renderWithFragment } = await import("../variants/render.js");
|
|
519
|
+
const info = JSON.stringify({ step: step.id, name: variant.name, names: step.variants.map((v) => v.name) }).replace(/</g, "\\u003c");
|
|
520
|
+
const rendered = await renderWithFragment(jsonPath, variant.overrides);
|
|
521
|
+
body = rendered.replace("<body>", `<body><script>window.__DECK3D_VARIANT=${info};</script>`).replace("</body>", `${CLIENT}</body>`);
|
|
522
|
+
} else {
|
|
523
|
+
const notice = JSON.stringify(`Unknown variant '${wanted}': showing the deck without variants.`).replace(/</g, "\\u003c");
|
|
524
|
+
body = html.replace("<body>", `<body><script>window.__DECK3D_VARIANT_NOTICE=${notice};</script>`);
|
|
525
|
+
}
|
|
526
|
+
}
|
|
345
527
|
res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" });
|
|
346
|
-
res.end(
|
|
528
|
+
res.end(body);
|
|
347
529
|
})().catch((err: Error) => {
|
|
348
530
|
res.writeHead(500, { "content-type": "text/plain" });
|
|
349
531
|
res.end(err.message);
|
|
@@ -363,6 +545,7 @@ export async function startServe(mdPath: string, opts: ServeOptions): Promise<Se
|
|
|
363
545
|
await new Promise((r) => setTimeout(r, debounceMs + 60));
|
|
364
546
|
await building;
|
|
365
547
|
},
|
|
548
|
+
rebuilds: () => rebuildCount,
|
|
366
549
|
lastError: () => lastError,
|
|
367
550
|
findings: () => findings,
|
|
368
551
|
close: async () => {
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Release a browser, page or sandbox when its work is already done. Closing is
|
|
3
|
+
* cleanup, never part of the outcome: a rejecting `close()` must not turn a
|
|
4
|
+
* finished command into a failed one, nor replace the real error of an earlier
|
|
5
|
+
* failure. Used in `finally` blocks.
|
|
6
|
+
*/
|
|
7
|
+
export async function closeQuietly(target: { close(): Promise<unknown> } | undefined): Promise<void> {
|
|
8
|
+
try {
|
|
9
|
+
await target?.close();
|
|
10
|
+
} catch {
|
|
11
|
+
// Nothing useful to do: the work it served has already succeeded or failed on its own terms.
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path confinement that survives symlinks. `resolve()` normalises spelling
|
|
3
|
+
* only; `readFileSync` follows links, so a link inside the deck directory can
|
|
4
|
+
* point at a file outside it. Every read of a user-named file under a deck
|
|
5
|
+
* directory compares REAL paths.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
8
|
+
import { isAbsolute, relative, sep } from "node:path";
|
|
9
|
+
|
|
10
|
+
/** True when `file` exists and its real path lies inside the real path of `rootDir`. */
|
|
11
|
+
export function realInside(rootDir: string, file: string): boolean {
|
|
12
|
+
if (!existsSync(file) || !existsSync(rootDir)) return false;
|
|
13
|
+
const rel = relative(realpathSync(rootDir), realpathSync(file));
|
|
14
|
+
return rel === "" || (rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
|
|
15
|
+
}
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `variants pick | note | replay` (spec deck3d-variant-loop "Pick, ownership
|
|
3
|
+
* and replay"). A pick deep-merges a variant's fragment into `deck.json`
|
|
4
|
+
* overrides under the rules of `overrides apply`, behind two guards:
|
|
5
|
+
*
|
|
6
|
+
* - VALIDATION: the merged deck must validate and every effect param must be
|
|
7
|
+
* in range — otherwise neither file changes.
|
|
8
|
+
* - OWNERSHIP: arrays replace on merge, so a fragment that restates an
|
|
9
|
+
* `effects` / `props` list can silently drop entries other writers put
|
|
10
|
+
* there. Every id present in the live deck on a scope the fragment
|
|
11
|
+
* replaces must still be present, unless `--drop <id>` names it or
|
|
12
|
+
* `--replace-step <step>` names the earlier step that introduced it.
|
|
13
|
+
*
|
|
14
|
+
* Writes are three atomic renames: style.json `pending: true` → deck.json →
|
|
15
|
+
* style.json final. A crash in between leaves `pending: true`, which every
|
|
16
|
+
* variants command reports.
|
|
17
|
+
*/
|
|
18
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
19
|
+
import { dirname, join } from "node:path";
|
|
20
|
+
import { validateEffectParams } from "../fx/compose.js";
|
|
21
|
+
import { deepMerge } from "../ir/merge.js";
|
|
22
|
+
import type { DeckIR } from "../ir/types.js";
|
|
23
|
+
import { formatIssue, validate } from "../ir/validate.js";
|
|
24
|
+
import { interruptedMessage, LockError, pendingStep, readStyle, type Step, type Style, serialize, stylePath, withStyleLock, writeAtomic } from "./style.js";
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* A variants command waits this long for another deck3d process (e.g. a `serve`
|
|
28
|
+
* rebuild) to release the lock; `DECK3D_LOCK_WAIT_MS` overrides it.
|
|
29
|
+
*/
|
|
30
|
+
const lockWaitMs = (): number => Number(process.env.DECK3D_LOCK_WAIT_MS ?? 10_000);
|
|
31
|
+
|
|
32
|
+
export class PickError extends Error {
|
|
33
|
+
constructor(message: string) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "PickError";
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
type Json = Record<string, unknown>;
|
|
40
|
+
|
|
41
|
+
/** `scope path → ids` of every effect/prop list an overrides object carries. */
|
|
42
|
+
export function listScopes(overrides: unknown): Map<string, string[]> {
|
|
43
|
+
const out = new Map<string, string[]>();
|
|
44
|
+
const o = (overrides ?? {}) as Json;
|
|
45
|
+
const ids = (list: unknown, key: string): string[] | undefined =>
|
|
46
|
+
Array.isArray(list) ? list.map((e) => String((e as Json)[key] ?? "")).filter(Boolean) : undefined;
|
|
47
|
+
const eff = ids(o.effects, "id");
|
|
48
|
+
if (eff) out.set("overrides.effects", eff);
|
|
49
|
+
const props = ids(o.props, "id");
|
|
50
|
+
if (props) out.set("overrides.props", props);
|
|
51
|
+
for (const [slide, ov] of Object.entries((o.slides ?? {}) as Record<string, Json>)) {
|
|
52
|
+
const e = ids(ov?.effects, "id");
|
|
53
|
+
if (e) out.set(`overrides.slides["${slide}"].effects`, e);
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** True when a picked step AFTER `index` lists `id` on `scope` in its fragment. */
|
|
59
|
+
function laterPicksList(style: Style, index: number, scope: string, id: string): boolean {
|
|
60
|
+
return style.steps.slice(index + 1).some((s) => {
|
|
61
|
+
const picked = s.variants.find((v) => v.name === s.picked);
|
|
62
|
+
return !!picked && listScopes(picked.overrides).get(scope)?.includes(id) === true;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Who put `id` on `scope`: the earliest picked step (before `current`) whose fragment lists it. */
|
|
67
|
+
function introducedBy(style: Style, current: number, scope: string, id: string): string | undefined {
|
|
68
|
+
for (let i = 0; i < current; i++) {
|
|
69
|
+
const step = style.steps[i];
|
|
70
|
+
const picked = step.variants.find((v) => v.name === step.picked);
|
|
71
|
+
if (picked && listScopes(picked.overrides).get(scope)?.includes(id)) return step.id;
|
|
72
|
+
}
|
|
73
|
+
return undefined;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface GuardOptions {
|
|
77
|
+
drop: string[];
|
|
78
|
+
replaceStep?: string;
|
|
79
|
+
/**
|
|
80
|
+
* Replay only: true when a LATER picked step lists `id` on `scope`. Replay
|
|
81
|
+
* starts from the live deck, which already holds that later step's effect;
|
|
82
|
+
* an earlier fragment that omits it is not dropping it — the later step
|
|
83
|
+
* re-adds it when its turn comes.
|
|
84
|
+
*/
|
|
85
|
+
restoredLater?: (scope: string, id: string) => boolean;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Ownership conflicts of merging `fragment` into `overrides` as step `index` of `style`. */
|
|
89
|
+
export function ownershipConflicts(style: Style, index: number, overrides: unknown, fragment: unknown, opts: GuardOptions): string[] {
|
|
90
|
+
const live = listScopes(overrides);
|
|
91
|
+
const conflicts: string[] = [];
|
|
92
|
+
const self = style.steps[index]?.id;
|
|
93
|
+
for (const [scope, next] of listScopes(fragment)) {
|
|
94
|
+
for (const id of live.get(scope) ?? []) {
|
|
95
|
+
if (next.includes(id)) continue;
|
|
96
|
+
if (opts.drop.includes(id)) continue;
|
|
97
|
+
if (opts.restoredLater?.(scope, id)) continue;
|
|
98
|
+
const owner = introducedBy(style, index, scope, id);
|
|
99
|
+
// Re-picking the SAME step replaces its own earlier effects; `--replace-step` names another.
|
|
100
|
+
if (owner !== undefined && (owner === opts.replaceStep || owner === self)) continue;
|
|
101
|
+
const from = owner ? `step ${owner}` : "the configurator or a hand edit";
|
|
102
|
+
conflicts.push(`${scope}: would remove '${id}' (added by ${from}); carry it forward in the fragment, or pass --drop ${id}${owner ? ` / --replace-step ${owner}` : ""}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return conflicts;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function loadDeck(jsonPath: string): DeckIR {
|
|
109
|
+
return JSON.parse(readFileSync(jsonPath, "utf8")) as DeckIR;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Validation errors of a merged deck, one line each (empty when it is fine). */
|
|
113
|
+
export function mergedErrors(merged: DeckIR, deckDir: string): string[] {
|
|
114
|
+
const result = validate(merged, { deckDir });
|
|
115
|
+
const errors = result.errors.map((e) => formatIssue("error", e));
|
|
116
|
+
if (!errors.length) for (const v of validateEffectParams(merged)) errors.push(`error ${v.path}: ${v.message}`);
|
|
117
|
+
return errors;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface PickHooks {
|
|
121
|
+
/** Called after the pending marker and after deck.json are written (tests throw to simulate a crash). */
|
|
122
|
+
afterWrite?: (phase: "pending" | "deck") => void;
|
|
123
|
+
now?: () => Date;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface PickOptions {
|
|
127
|
+
deckJson: string;
|
|
128
|
+
step: string;
|
|
129
|
+
name: string;
|
|
130
|
+
note?: string;
|
|
131
|
+
drop?: string[];
|
|
132
|
+
replaceStep?: string;
|
|
133
|
+
hooks?: PickHooks;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function stepIndex(style: Style, id: string): number {
|
|
137
|
+
const i = style.steps.findIndex((s) => s.id === id);
|
|
138
|
+
if (i < 0) throw new PickError(`unknown step '${id}' (steps: ${style.steps.map((s) => s.id).join(", ") || "none"})`);
|
|
139
|
+
return i;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export function requireStyle(deckJson: string): { style: Style; path: string } {
|
|
143
|
+
const path = stylePath(dirname(deckJson));
|
|
144
|
+
const style = readStyle(path);
|
|
145
|
+
if (!style) throw new PickError(`no style.json beside ${deckJson}`);
|
|
146
|
+
const pending = pendingStep(style);
|
|
147
|
+
if (pending) throw new PickError(interruptedMessage(pending));
|
|
148
|
+
return { style, path };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function pickVariant(opts: PickOptions): void {
|
|
152
|
+
withStyleLock(dirname(opts.deckJson), () => pick(opts), { waitMs: lockWaitMs() });
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function pick(opts: PickOptions): void {
|
|
156
|
+
const deckDir = dirname(opts.deckJson);
|
|
157
|
+
const path = stylePath(deckDir);
|
|
158
|
+
const style = readStyle(path);
|
|
159
|
+
if (!style) throw new PickError(`no style.json beside ${opts.deckJson}`);
|
|
160
|
+
const idx = stepIndex(style, opts.step);
|
|
161
|
+
const step = style.steps[idx];
|
|
162
|
+
// A pending marker on THIS step is the re-run the message asks for; any other step's is not.
|
|
163
|
+
const other = style.steps.find((s) => s.pending && s.id !== step.id);
|
|
164
|
+
if (other) throw new PickError(interruptedMessage(other));
|
|
165
|
+
const variant = step.variants.find((v) => v.name === opts.name);
|
|
166
|
+
if (!variant) throw new PickError(`step '${step.id}' has no variant '${opts.name}' (one of ${step.variants.map((v) => v.name).join(", ")})`);
|
|
167
|
+
|
|
168
|
+
const deck = loadDeck(opts.deckJson);
|
|
169
|
+
const drop = opts.drop ?? [];
|
|
170
|
+
const conflicts = ownershipConflicts(style, idx, deck.overrides, variant.overrides, { drop, replaceStep: opts.replaceStep });
|
|
171
|
+
if (conflicts.length) throw new PickError(conflicts.join("\n"));
|
|
172
|
+
const merged: DeckIR = { ...deck, overrides: deepMerge(deck.overrides ?? {}, variant.overrides) as DeckIR["overrides"] };
|
|
173
|
+
const errors = mergedErrors(merged, deckDir);
|
|
174
|
+
if (errors.length) throw new PickError(errors.join("\n"));
|
|
175
|
+
|
|
176
|
+
const hooks = opts.hooks ?? {};
|
|
177
|
+
step.pending = true;
|
|
178
|
+
writeAtomic(path, serialize(style));
|
|
179
|
+
hooks.afterWrite?.("pending");
|
|
180
|
+
writeAtomic(opts.deckJson, serialize(merged));
|
|
181
|
+
hooks.afterWrite?.("deck");
|
|
182
|
+
step.picked = variant.name;
|
|
183
|
+
step.pickedAt = (hooks.now?.() ?? new Date()).toISOString();
|
|
184
|
+
step.pending = false;
|
|
185
|
+
if (opts.note !== undefined) step.note = opts.note;
|
|
186
|
+
if (drop.length) step.drop = drop;
|
|
187
|
+
else delete step.drop;
|
|
188
|
+
if (opts.replaceStep) step.replaceStep = opts.replaceStep;
|
|
189
|
+
else delete step.replaceStep;
|
|
190
|
+
writeAtomic(path, serialize(style));
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Record a free-text answer: `picked: null`, the note, and a new round. */
|
|
194
|
+
export function noteStep(deckJson: string, stepId: string, note: string): Step {
|
|
195
|
+
return withStyleLock(dirname(deckJson), () => note_(deckJson, stepId, note), { waitMs: lockWaitMs() });
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function note_(deckJson: string, stepId: string, note: string): Step {
|
|
199
|
+
const { style, path } = requireStyle(deckJson);
|
|
200
|
+
const step = style.steps[stepIndex(style, stepId)];
|
|
201
|
+
step.picked = null;
|
|
202
|
+
step.note = note;
|
|
203
|
+
step.round += 1;
|
|
204
|
+
delete step.pickedAt;
|
|
205
|
+
delete step.drop;
|
|
206
|
+
delete step.replaceStep;
|
|
207
|
+
writeAtomic(path, serialize(style));
|
|
208
|
+
return step;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export interface ReplayResult {
|
|
212
|
+
applied: string[];
|
|
213
|
+
/** Fragment keys that reference a slide or layout item no longer present. */
|
|
214
|
+
orphans: string[];
|
|
215
|
+
changed: boolean;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const ITEM_ID = /^s\d+-i\d+$/;
|
|
219
|
+
|
|
220
|
+
function layoutItemIds(deckDir: string): Set<string> | undefined {
|
|
221
|
+
const file = join(deckDir, "pptx", "layout.json");
|
|
222
|
+
if (!existsSync(file)) return undefined;
|
|
223
|
+
const layout = JSON.parse(readFileSync(file, "utf8")) as { slides?: Array<{ items?: Array<{ id: string }> }> };
|
|
224
|
+
return new Set((layout.slides ?? []).flatMap((s) => (s.items ?? []).map((i) => i.id)));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function collectItemRefs(v: unknown, out: Set<string>): void {
|
|
228
|
+
if (typeof v === "string") {
|
|
229
|
+
if (ITEM_ID.test(v)) out.add(v);
|
|
230
|
+
} else if (Array.isArray(v)) for (const x of v) collectItemRefs(x, out);
|
|
231
|
+
else if (v && typeof v === "object") {
|
|
232
|
+
for (const [k, x] of Object.entries(v)) {
|
|
233
|
+
if (ITEM_ID.test(k)) out.add(k);
|
|
234
|
+
collectItemRefs(x, out);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** Re-apply every picked fragment in step order; idempotent, writes only on change. */
|
|
240
|
+
export function replayPicks(deckJson: string): ReplayResult {
|
|
241
|
+
return withStyleLock(dirname(deckJson), () => replay(deckJson), { waitMs: lockWaitMs() });
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function replay(deckJson: string): ReplayResult {
|
|
245
|
+
const { style } = requireStyle(deckJson);
|
|
246
|
+
const deckDir = dirname(deckJson);
|
|
247
|
+
const before = readFileSync(deckJson, "utf8");
|
|
248
|
+
const deck = JSON.parse(before) as DeckIR;
|
|
249
|
+
const slideIds = new Set(deck.slides.map((s) => s.id));
|
|
250
|
+
const items = layoutItemIds(deckDir);
|
|
251
|
+
const orphans: string[] = [];
|
|
252
|
+
const applied: string[] = [];
|
|
253
|
+
let overrides: unknown = deck.overrides ?? {};
|
|
254
|
+
style.steps.forEach((step, idx) => {
|
|
255
|
+
if (typeof step.picked !== "string") return;
|
|
256
|
+
const variant = step.variants.find((v) => v.name === step.picked);
|
|
257
|
+
if (!variant) return;
|
|
258
|
+
const conflicts = ownershipConflicts(style, idx, overrides, variant.overrides, {
|
|
259
|
+
drop: step.drop ?? [],
|
|
260
|
+
replaceStep: step.replaceStep,
|
|
261
|
+
restoredLater: (scope, id) => laterPicksList(style, idx, scope, id),
|
|
262
|
+
});
|
|
263
|
+
if (conflicts.length) throw new PickError(`replay of step '${step.id}': ${conflicts.join("\n")}`);
|
|
264
|
+
overrides = deepMerge(overrides as Json, variant.overrides);
|
|
265
|
+
applied.push(step.id);
|
|
266
|
+
for (const sid of Object.keys(((variant.overrides as Json).slides ?? {}) as Json)) {
|
|
267
|
+
if (!slideIds.has(sid)) orphans.push(`step ${step.id}: overrides.slides["${sid}"] references a slide missing from the deck`);
|
|
268
|
+
}
|
|
269
|
+
if (items) {
|
|
270
|
+
const refs = new Set<string>();
|
|
271
|
+
collectItemRefs(variant.overrides, refs);
|
|
272
|
+
for (const id of [...refs].sort()) if (!items.has(id)) orphans.push(`step ${step.id}: item '${id}' is missing from the current layout`);
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
const merged: DeckIR = { ...deck, overrides: overrides as DeckIR["overrides"] };
|
|
276
|
+
const errors = mergedErrors(merged, deckDir);
|
|
277
|
+
if (errors.length) throw new PickError(errors.join("\n"));
|
|
278
|
+
const next = serialize(merged);
|
|
279
|
+
const changed = next !== before;
|
|
280
|
+
if (changed) writeAtomic(deckJson, next);
|
|
281
|
+
return { applied, orphans, changed };
|
|
282
|
+
}
|