@blackbelt-technology/pi-dashboard-deck3d 0.9.0 → 0.10.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.
Files changed (105) hide show
  1. package/.pi/skills/deck3d/SKILL.agent.md +78 -0
  2. package/.pi/skills/deck3d/SKILL.md +68 -0
  3. package/.pi/skills/deck3d/reference/effects.md +185 -2
  4. package/.pi/skills/deck3d/reference/ir-fields.md +26 -3
  5. package/.pi/skills/deck3d-from-pptx/SKILL.md +134 -0
  6. package/.pi/skills/deck3d-from-pptx/reference/steps.md +72 -0
  7. package/README.md +30 -2
  8. package/assets/preview/stub-chrome.png +0 -0
  9. package/assets/preview/stub-icon.json +59 -0
  10. package/assets/preview/stub-layout.json +195 -0
  11. package/assets/preview/stub-outline.json +48 -0
  12. package/dist/cli.js +11780 -5934
  13. package/dist/runtime.js +5916 -4007
  14. package/fixtures/business-2031/assets/stub-chrome.png +0 -0
  15. package/fixtures/business-2031/assets/stub-icon.json +59 -0
  16. package/fixtures/business-2031/assets/stub-layout.json +195 -0
  17. package/fixtures/business-2031/assets/stub-outline.json +48 -0
  18. package/fixtures/business-2031/build-overrides.mjs +58 -13
  19. package/fixtures/business-2031/deck.agent.md +60 -0
  20. package/fixtures/business-2031/deck.json +133 -8
  21. package/fixtures/business-2031/overrides.json +133 -8
  22. package/package.json +8 -4
  23. package/scripts/gen-stub-assets.ts +31 -0
  24. package/src/art/cutout.ts +97 -0
  25. package/src/art/decode.ts +169 -0
  26. package/src/art/icon.ts +380 -0
  27. package/src/art/png.ts +232 -0
  28. package/src/art/trace.ts +288 -0
  29. package/src/check/rules.ts +13 -8
  30. package/src/cli.ts +313 -51
  31. package/src/compare/index.ts +131 -0
  32. package/src/compare/ssim.ts +91 -0
  33. package/src/fx/art-geometry.ts +137 -0
  34. package/src/fx/art3d.meta.json +30 -0
  35. package/src/fx/art3d.ts +131 -0
  36. package/src/fx/bank.meta.json +26 -0
  37. package/src/fx/bank.ts +8 -0
  38. package/src/fx/compose.ts +5 -4
  39. package/src/fx/crane.meta.json +26 -0
  40. package/src/fx/crane.ts +8 -0
  41. package/src/fx/dolly.ts +5 -1
  42. package/src/fx/fade.ts +5 -1
  43. package/src/fx/flythrough.ts +5 -1
  44. package/src/fx/frame-chrome.meta.json +17 -0
  45. package/src/fx/frame-chrome.ts +134 -0
  46. package/src/fx/haze.meta.json +19 -0
  47. package/src/fx/haze.ts +91 -0
  48. package/src/fx/icon3d.meta.json +21 -0
  49. package/src/fx/icon3d.ts +167 -0
  50. package/src/fx/index.ts +96 -66
  51. package/src/fx/iris.ts +5 -1
  52. package/src/fx/meta.schema.json +10 -2
  53. package/src/fx/path.meta.json +25 -0
  54. package/src/fx/path.ts +8 -0
  55. package/src/fx/persistent.ts +11 -0
  56. package/src/fx/revolve.meta.json +26 -0
  57. package/src/fx/revolve.ts +8 -0
  58. package/src/fx/slide-layer.meta.json +26 -0
  59. package/src/fx/slide-layer.ts +557 -0
  60. package/src/fx/slide-space.ts +142 -0
  61. package/src/fx/stub-assets.ts +117 -0
  62. package/src/fx/swing.meta.json +26 -0
  63. package/src/fx/swing.ts +8 -0
  64. package/src/fx/types.ts +63 -2
  65. package/src/ir/merge.ts +5 -2
  66. package/src/ir/schema.json +140 -3
  67. package/src/ir/types.ts +54 -0
  68. package/src/ir/validate.ts +91 -3
  69. package/src/parse/harvest/index.ts +4 -1
  70. package/src/parse/markdown.ts +38 -7
  71. package/src/pptx/baseline.ts +183 -0
  72. package/src/pptx/extract.ts +161 -0
  73. package/src/pptx/fallback.ts +70 -0
  74. package/src/pptx/import.ts +256 -0
  75. package/src/pptx/master.ts +135 -0
  76. package/src/pptx/media.ts +81 -0
  77. package/src/pptx/package.ts +109 -0
  78. package/src/pptx/ref.ts +100 -0
  79. package/src/pptx/shapes.ts +276 -0
  80. package/src/pptx/stage.ts +82 -0
  81. package/src/pptx/text.ts +202 -0
  82. package/src/pptx/theme.ts +194 -0
  83. package/src/pptx/types.ts +159 -0
  84. package/src/pptx/xfrm.ts +93 -0
  85. package/src/pptx/xml.ts +106 -0
  86. package/src/pptx/zip.ts +239 -0
  87. package/src/render/assets.ts +57 -0
  88. package/src/render/build.ts +75 -0
  89. package/src/render/index.ts +7 -2
  90. package/src/render/template.html +1 -1
  91. package/src/runtime/assets.ts +75 -0
  92. package/src/runtime/fade.ts +110 -0
  93. package/src/runtime/hud.ts +37 -9
  94. package/src/runtime/index.ts +431 -67
  95. package/src/runtime/post.ts +11 -5
  96. package/src/runtime/scene.ts +25 -2
  97. package/src/runtime/transition.ts +222 -0
  98. package/src/runtime/types.ts +13 -2
  99. package/src/serve/index.ts +199 -16
  100. package/src/util/cleanup.ts +13 -0
  101. package/src/util/confine.ts +15 -0
  102. package/src/variants/pick.ts +282 -0
  103. package/src/variants/render.ts +179 -0
  104. package/src/variants/schema.json +48 -0
  105. package/src/variants/style.ts +318 -0
@@ -0,0 +1,256 @@
1
+ /**
2
+ * `deck3d pptx import` orchestrator (spec deck3d-pptx-import): guarded zip →
3
+ * extraction → slide ids (re-import matching) → reference renders → visible
4
+ * fallbacks → `layout.json` + media + baseline `deck.md`/`deck.json`, all
5
+ * staged and committed atomically.
6
+ */
7
+ import { existsSync, readFileSync } from "node:fs";
8
+ import { basename, dirname, extname, join, posix, resolve } from "node:path";
9
+ import type { Sandbox } from "../art/decode.js";
10
+ import { encodePng } from "../art/png.js";
11
+ import type { DeckIR } from "../ir/types.js";
12
+ import { formatIssue, type ValidationIssue, validate, validateAssets } from "../ir/validate.js";
13
+ import { withStyleLockAsync } from "../variants/style.js";
14
+ import {
15
+ type AssetEntry,
16
+ baselineDeckOverrides,
17
+ baselineMarkdown,
18
+ baselineMode,
19
+ importedAssets,
20
+ matchSlideIds,
21
+ reconcileAssets,
22
+ } from "./baseline.js";
23
+ import { extractPptx, finalizeLayout, stableStringify } from "./extract.js";
24
+ import { applyFallbacks, pngDecoder } from "./fallback.js";
25
+ import { sha256Hex } from "./media.js";
26
+ import { refFromDir, refFromLibreOffice } from "./ref.js";
27
+ import { defaultWrite, type RenameFn, Stage, type WriteFn } from "./stage.js";
28
+ import { type Layout, PptxImportError } from "./types.js";
29
+ import { readPptxZip } from "./zip.js";
30
+
31
+ export interface ImportOptions {
32
+ input: string;
33
+ out?: string;
34
+ ref?: string;
35
+ force?: boolean;
36
+ /** Environment used to find `soffice`/`pdftoppm` (tests strip PATH). */
37
+ env?: NodeJS.ProcessEnv;
38
+ /** Write hook (fault injection in tests). */
39
+ write?: WriteFn;
40
+ /** Rename hook used by the commit (fault injection in tests). */
41
+ rename?: RenameFn;
42
+ /** Sandbox factory; resolves undefined when chromium is unavailable. */
43
+ sandbox?: () => Promise<Sandbox | undefined>;
44
+ }
45
+
46
+ export interface ImportResult {
47
+ dir: string;
48
+ slides: string[];
49
+ warnings: string[];
50
+ }
51
+
52
+ /** Top-level entries a commit replaces wholesale (see `Stage.commit`). */
53
+ const REPLACED = new Set(["pptx", "deck.md", "deck.json", "deck.json.bak"]);
54
+ /** Top-level files (not directories) the import regenerates on every run. */
55
+ const GENERATED = new Set(["deck.md", "deck.json", "deck.json.bak"]);
56
+
57
+ /**
58
+ * Carry user-owned asset files that live INSIDE a replaced entry (e.g.
59
+ * `pptx/custom/logo.png`) into the staged tree, so the directory swap does
60
+ * not delete them. A user file whose path an imported file also claims, with
61
+ * different content, is a conflict: refuse rather than overwrite either.
62
+ */
63
+ function preserveUserFiles(assets: AssetEntry[] | undefined, existingDir: string, stage: Stage): void {
64
+ for (const a of assets ?? []) {
65
+ if (a.id.startsWith("pptx-")) continue;
66
+ const rel = posix.normalize(a.path.replace(/\\/g, "/"));
67
+ if (rel.startsWith("..") || posix.isAbsolute(rel) || !REPLACED.has(rel.split("/")[0])) continue;
68
+ // Files the import itself WRITES are not the user's to claim: the new deck.json would pin
69
+ // bytes the import then overwrites.
70
+ if (GENERATED.has(rel)) throw new PptxImportError(`user asset '${a.id}' at '${a.path}' claims a generated file the import writes; use another path`);
71
+ const src = join(existingDir, rel);
72
+ if (!existsSync(src)) continue; // `validate` reports a missing file
73
+ const staged = join(stage.dir, rel);
74
+ const bytes = readFileSync(src);
75
+ if (existsSync(staged)) {
76
+ if (!readFileSync(staged).equals(bytes)) {
77
+ throw new PptxImportError(`user asset '${a.id}' at '${a.path}' collides with an imported file; move it outside pptx/`);
78
+ }
79
+ continue;
80
+ }
81
+ stage.file(rel, bytes);
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Validate the generated deck. User-owned references (assets without the
87
+ * `pptx-` prefix, `local:` effects) live in the EXISTING deck directory and
88
+ * survive the import untouched, so they resolve there; the imported `pptx-`
89
+ * assets exist only in staging and are checked against it. A fresh import has
90
+ * no existing directory, so staging resolves everything.
91
+ */
92
+ export function validateGenerated(ir: DeckIR, stageDir: string, targetDir: string): ValidationIssue[] {
93
+ if (!existsSync(targetDir)) return validate(ir, { deckDir: stageDir }).errors;
94
+ const assets = ir.overrides.assets ?? [];
95
+ const imported = assets.map((a, i) => ({ a, i })).filter(({ a }) => a.id.startsWith("pptx-"));
96
+ const importedIdx = new Set(imported.map(({ i }) => i));
97
+ const errors = validate(ir, { deckDir: targetDir }).errors.filter((e) => {
98
+ const m = /^overrides\.assets\[(\d+)\]/.exec(e.path);
99
+ return !(m && importedIdx.has(Number(m[1])));
100
+ });
101
+ const own = validateAssets({ ...ir, overrides: { ...ir.overrides, assets: imported.map(({ a }) => a) } }, stageDir);
102
+ for (const e of own) {
103
+ const k = Number(/^overrides\.assets\[(\d+)\]/.exec(e.path)?.[1]);
104
+ errors.push({ ...e, path: e.path.replace(/^overrides\.assets\[\d+\]/, `overrides.assets[${imported[k]?.i ?? k}]`) });
105
+ }
106
+ return errors;
107
+ }
108
+
109
+ async function defaultSandbox(): Promise<Sandbox | undefined> {
110
+ try {
111
+ const { openSandbox } = await import("../art/decode.js");
112
+ return await openSandbox();
113
+ } catch {
114
+ return undefined;
115
+ }
116
+ }
117
+
118
+ function readJson<T>(path: string): T | undefined {
119
+ if (!existsSync(path)) return undefined;
120
+ try {
121
+ return JSON.parse(readFileSync(path, "utf8")) as T;
122
+ } catch {
123
+ return undefined;
124
+ }
125
+ }
126
+
127
+ export async function importPptx(opts: ImportOptions): Promise<ImportResult> {
128
+ const input = resolve(opts.input);
129
+ const dir = resolve(opts.out ?? join(dirname(input), basename(input, extname(input))));
130
+ // A re-import READS the previous deck.json (to keep its overrides) and later
131
+ // replaces it, so it holds the same deck lock as `variants pick|note|replay` and
132
+ // `serve` from that read to the commit: a pick landing in between would be lost.
133
+ if (opts.force && existsSync(dir)) {
134
+ return withStyleLockAsync(dir, () => runImport(opts, input, dir), { waitMs: Number(process.env.DECK3D_LOCK_WAIT_MS ?? 10_000) });
135
+ }
136
+ return runImport(opts, input, dir);
137
+ }
138
+
139
+ async function runImport(opts: ImportOptions, input: string, dir: string): Promise<ImportResult> {
140
+ if (!opts.force) {
141
+ for (const name of ["deck.md", "deck.json"]) {
142
+ const p = join(dir, name);
143
+ if (existsSync(p)) throw new PptxImportError(`${p} already exists (pass --force to re-import and keep its overrides)`);
144
+ }
145
+ }
146
+ if (!existsSync(input)) throw new PptxImportError(`missing input ${input}`);
147
+
148
+ const files = readPptxZip(new Uint8Array(readFileSync(input)));
149
+ const ex = extractPptx(files);
150
+ if (!ex.slides.length) throw new PptxImportError("the presentation has no slides");
151
+
152
+ const warnings: string[] = [];
153
+ const prevLayout = opts.force ? readJson<Layout>(join(dir, "pptx", "layout.json")) : undefined;
154
+ const prevDeckRaw = opts.force && existsSync(join(dir, "deck.json")) ? readFileSync(join(dir, "deck.json"), "utf8") : undefined;
155
+ const prevDeck = prevDeckRaw ? (JSON.parse(prevDeckRaw) as DeckIR) : undefined;
156
+
157
+ const match = matchSlideIds(ex.slides, prevLayout?.slides);
158
+ warnings.push(...match.warnings);
159
+ const { layout, fallbacks } = finalizeLayout(ex, match.ids);
160
+
161
+ // The sandbox is opened lazily: only JPEG exports and exotic PNGs need it.
162
+ let sandbox: Sandbox | undefined;
163
+ let sandboxTried = false;
164
+ const getSandbox = async (): Promise<Sandbox | undefined> => {
165
+ if (!sandboxTried) {
166
+ sandboxTried = true;
167
+ sandbox = await (opts.sandbox ?? defaultSandbox)();
168
+ }
169
+ return sandbox;
170
+ };
171
+ /**
172
+ * Close the browser exactly once. This is cleanup, never part of the outcome:
173
+ * a failing close is a warning (it must not turn a finished import into a
174
+ * failed one, nor mask the real error of an earlier failure).
175
+ */
176
+ let closed = false;
177
+ const closeSandbox = async (): Promise<string | undefined> => {
178
+ if (closed || !sandbox) return undefined;
179
+ closed = true;
180
+ try {
181
+ await sandbox.close();
182
+ } catch (err) {
183
+ return `warning sandbox close failed: ${(err as Error).message}`;
184
+ }
185
+ return undefined;
186
+ };
187
+ const stage = new Stage(dir, opts.write ?? defaultWrite, opts.rename);
188
+ try {
189
+ const refs = opts.ref
190
+ ? await refFromDir(opts.ref, ex.slides.length, async (bytes) => {
191
+ const sb = await getSandbox();
192
+ if (!sb) return undefined;
193
+ const { sniffMime } = await import("../art/decode.js");
194
+ return encodePng(await sb.decode(bytes, sniffMime(bytes)));
195
+ })
196
+ : refFromLibreOffice(input, ex.slides.length, opts.env);
197
+ warnings.push(...refs.warnings);
198
+ const refById = new Map<string, Uint8Array>();
199
+ for (const [n, png] of refs.images) refById.set(match.ids[n - 1], png);
200
+
201
+ const decode = pngDecoder(async (bytes) => {
202
+ const sb = await getSandbox();
203
+ if (!sb) throw new PptxImportError("a reference render needs chromium to decode (npx playwright install chromium)");
204
+ return sb.decode(bytes, "image/png");
205
+ });
206
+ warnings.push(...(await applyFallbacks(fallbacks, refById, layout.size.w, ex.media, decode)));
207
+
208
+ const layoutJson = stableStringify(layout);
209
+ stage.file("pptx/layout.json", layoutJson);
210
+ const media = ex.media.files();
211
+ for (const m of media) stage.file(`pptx/media/${m.name}`, m.bytes);
212
+ for (const [id, png] of [...refById.entries()].sort()) stage.file(`pptx/ref/${id}.png`, png);
213
+
214
+ const md = baselineMarkdown(ex.slides.map((s, i) => ({ id: match.ids[i], title: s.title, drafts: s.drafts })));
215
+ stage.file("deck.md", md);
216
+
217
+ const { parseDeck } = await import("../parse/derive.js");
218
+ const { defaultEffectsFor, defaultSceneFor } = await import("../fx/defaults.js");
219
+ const { ir, warnings: parseWarnings } = await parseDeck(md, {
220
+ source: "deck.md",
221
+ ...(prevDeck ? { previous: prevDeck } : {}),
222
+ effectsForSlide: (slide, autoStyle) => defaultEffectsFor(slide, autoStyle),
223
+ sceneForSlide: (slide, autoStyle) => defaultSceneFor(slide, autoStyle),
224
+ });
225
+ warnings.push(...parseWarnings.map((w) => (w.startsWith("warn") ? w : `warning ${w}`)));
226
+
227
+ const overrides = ir.overrides as Record<string, unknown> & { deck?: Record<string, unknown>; assets?: AssetEntry[] };
228
+ const deckOv: Record<string, unknown> = { ...(overrides.deck ?? {}) };
229
+ for (const [k, v] of Object.entries(baselineDeckOverrides(layout.theme, baselineMode(layout)))) {
230
+ if (deckOv[k] === undefined) deckOv[k] = v;
231
+ }
232
+ overrides.deck = deckOv;
233
+ const rec = reconcileAssets(prevDeck?.overrides.assets as AssetEntry[] | undefined, importedAssets(ex.media.assetEntries(), sha256Hex(layoutJson)), overrides);
234
+ if (rec.dangling.length) throw new PptxImportError(`re-import would drop referenced assets: ${rec.dangling.join("; ")}`);
235
+ warnings.push(...rec.warnings);
236
+ overrides.assets = rec.assets;
237
+
238
+ preserveUserFiles(overrides.assets, dir, stage);
239
+ // A bad import never lands: the deck must validate before anything is committed.
240
+ const problems = validateGenerated(ir, stage.dir, dir);
241
+ if (problems.length) throw new PptxImportError(`generated deck failed validation: ${problems.map((e) => formatIssue("error", e)).join("; ")}`);
242
+ stage.file("deck.json", `${JSON.stringify(ir, null, 2)}\n`);
243
+ if (prevDeckRaw !== undefined) stage.file("deck.json.bak", prevDeckRaw);
244
+ // Everything that can fail is done; release the browser BEFORE the commit changes the target.
245
+ const closeWarning = await closeSandbox();
246
+ if (closeWarning) warnings.push(closeWarning);
247
+ stage.commit(["pptx", "deck.md", "deck.json", "deck.json.bak"]);
248
+ } catch (err) {
249
+ stage.discard();
250
+ throw err;
251
+ } finally {
252
+ // Earlier failures still release the browser; the outcome is already decided.
253
+ await closeSandbox();
254
+ }
255
+ return { dir, slides: match.ids, warnings };
256
+ }
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Slide layout / master inheritance (design D1 `master.ts`): placeholder
3
+ * geometry and text styles, and the master's text style families.
4
+ */
5
+ import type { Package } from "./package.js";
6
+ import { child, path, type XNode } from "./xml.js";
7
+
8
+ export interface PhInfo {
9
+ type: string;
10
+ idx?: string;
11
+ }
12
+
13
+ interface PhEntry extends PhInfo {
14
+ sp: XNode;
15
+ }
16
+
17
+ /** `p:ph` of a shape (`p:sp`, `p:pic`, `p:graphicFrame`), when it is a placeholder. */
18
+ export function placeholderOf(shape: XNode): PhInfo | undefined {
19
+ const nv = shape.children.find((c) => c.name.startsWith("p:nv"));
20
+ const ph = path(nv, "p:nvPr", "p:ph");
21
+ if (!ph) return undefined;
22
+ return { type: ph.attrs.type ?? "body", idx: ph.attrs.idx };
23
+ }
24
+
25
+ export function isTitleType(type: string | undefined): boolean {
26
+ return type === "title" || type === "ctrTitle";
27
+ }
28
+
29
+ /** Master placeholder family a slide/layout placeholder type falls back to. */
30
+ function masterType(type: string): string {
31
+ if (isTitleType(type)) return "title";
32
+ if (type === "dt" || type === "ftr" || type === "sldNum") return type;
33
+ return "body";
34
+ }
35
+
36
+ function indexPlaceholders(spTree: XNode | undefined): PhEntry[] {
37
+ const out: PhEntry[] = [];
38
+ const walk = (n: XNode | undefined): void => {
39
+ for (const c of n?.children ?? []) {
40
+ if (c.name === "p:grpSp") walk(c);
41
+ const ph = placeholderOf(c);
42
+ if (ph) out.push({ ...ph, sp: c });
43
+ }
44
+ };
45
+ walk(spTree);
46
+ return out;
47
+ }
48
+
49
+ export interface Inheritance {
50
+ /** Text list styles, highest priority first (layout ph, master ph, family, default). */
51
+ lists: XNode[];
52
+ /** `a:bodyPr` chain (layout ph, master ph). */
53
+ bodyPrs: XNode[];
54
+ /** First inherited `a:xfrm` when the shape has none of its own. */
55
+ xfrm?: XNode;
56
+ }
57
+
58
+ /** Per-slide resolver for placeholder and text-style inheritance. */
59
+ export class MasterChain {
60
+ private readonly defaultTextStyle: XNode | undefined;
61
+ readonly layoutTree?: XNode;
62
+ readonly masterTree?: XNode;
63
+ private layoutPh: PhEntry[];
64
+ private masterPh: PhEntry[];
65
+ private txStyles?: XNode;
66
+
67
+ constructor(
68
+ pkg: Package,
69
+ layoutPart: string | undefined,
70
+ masterPart: string | undefined,
71
+ defaultTextStyle: XNode | undefined,
72
+ ) {
73
+ this.defaultTextStyle = defaultTextStyle;
74
+ const layout = layoutPart ? pkg.xml(layoutPart) : undefined;
75
+ const master = masterPart ? pkg.xml(masterPart) : undefined;
76
+ this.layoutTree = path(layout, "p:cSld", "p:spTree");
77
+ this.masterTree = path(master, "p:cSld", "p:spTree");
78
+ this.layoutPh = indexPlaceholders(this.layoutTree);
79
+ this.masterPh = indexPlaceholders(this.masterTree);
80
+ this.txStyles = child(master, "p:txStyles");
81
+ }
82
+
83
+ private matchLayout(ph: PhInfo): PhEntry | undefined {
84
+ if (ph.idx !== undefined) {
85
+ const byIdx = this.layoutPh.find((e) => e.idx === ph.idx);
86
+ if (byIdx) return byIdx;
87
+ }
88
+ return (
89
+ this.layoutPh.find((e) => e.type === ph.type) ??
90
+ (isTitleType(ph.type) ? this.layoutPh.find((e) => isTitleType(e.type)) : undefined)
91
+ );
92
+ }
93
+
94
+ private matchMaster(ph: PhInfo): PhEntry | undefined {
95
+ const want = masterType(ph.type);
96
+ return this.masterPh.find((e) => masterType(e.type) === want);
97
+ }
98
+
99
+ /** Inheritance for a placeholder (`ph`) or a plain shape (`undefined`). */
100
+ resolve(ph: PhInfo | undefined): Inheritance {
101
+ const family = ph
102
+ ? child(this.txStyles, isTitleType(ph.type) ? "p:titleStyle" : masterType(ph.type) === "body" ? "p:bodyStyle" : "p:otherStyle")
103
+ : child(this.txStyles, "p:otherStyle");
104
+ if (!ph) {
105
+ return { lists: [this.defaultTextStyle, family].filter((n): n is XNode => !!n), bodyPrs: [] };
106
+ }
107
+ const chain = [this.matchLayout(ph), this.matchMaster(ph)].filter((e): e is PhEntry => !!e);
108
+ const lists: XNode[] = [];
109
+ const bodyPrs: XNode[] = [];
110
+ let xfrm: XNode | undefined;
111
+ for (const e of chain) {
112
+ const tx = child(e.sp, "p:txBody");
113
+ const ls = child(tx, "a:lstStyle");
114
+ if (ls) lists.push(ls);
115
+ const bp = child(tx, "a:bodyPr");
116
+ if (bp) bodyPrs.push(bp);
117
+ xfrm ??= path(e.sp, "p:spPr", "a:xfrm") ?? child(e.sp, "p:xfrm");
118
+ }
119
+ if (family) lists.push(family);
120
+ if (this.defaultTextStyle) lists.push(this.defaultTextStyle);
121
+ return { lists, bodyPrs, xfrm };
122
+ }
123
+ }
124
+
125
+ /** True when a `p:sld`/`p:sldLayout` hides master shapes (`showMasterSp="0"`). */
126
+ export function hidesMasterShapes(root: XNode | undefined): boolean {
127
+ const v = root?.attrs.showMasterSp;
128
+ return v === "0" || v === "false";
129
+ }
130
+
131
+ /** Background node (`p:bg`) of a slide/layout/master part. */
132
+ export function backgroundOf(root: XNode | undefined): XNode | undefined {
133
+ return path(root, "p:cSld", "p:bg");
134
+ }
135
+
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Media registry: package parts → content-hash named files
3
+ * (`m-<first 12 hex of sha256>.<ext>`), identical bytes stored once, while
4
+ * EACH part keeps its own stable deck asset id (`pptx-` + slugified part
5
+ * path) so a re-import updates the asset in place whatever else changed.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import type { MediaFile } from "./types.js";
9
+
10
+ export const MIME_BY_EXT: Record<string, string> = {
11
+ png: "image/png",
12
+ jpg: "image/jpeg",
13
+ jpeg: "image/jpeg",
14
+ gif: "image/gif",
15
+ webp: "image/webp",
16
+ svg: "image/svg+xml",
17
+ json: "application/json",
18
+ txt: "text/plain",
19
+ ttf: "font/ttf",
20
+ otf: "font/otf",
21
+ };
22
+
23
+ export function sha256Hex(bytes: Uint8Array | string): string {
24
+ return createHash("sha256").update(bytes).digest("hex");
25
+ }
26
+
27
+ /** `ppt/media/image7.png` → `pptx-ppt-media-image7-png`. */
28
+ export function assetIdForPart(part: string): string {
29
+ const slug = part
30
+ .toLowerCase()
31
+ .replace(/[^a-z0-9]+/g, "-")
32
+ .replace(/^-+|-+$/g, "");
33
+ return `pptx-${slug}`.slice(0, 128);
34
+ }
35
+
36
+ export function extOf(name: string): string {
37
+ const i = name.lastIndexOf(".");
38
+ return i < 0 ? "" : name.slice(i + 1).toLowerCase();
39
+ }
40
+
41
+ export class MediaRegistry {
42
+ /** Stored files, one per distinct content. */
43
+ private byHash = new Map<string, MediaFile>();
44
+ /** One entry per asset id: identical bytes share a FILE but never an id. */
45
+ private byId = new Map<string, MediaFile>();
46
+
47
+ /**
48
+ * Register bytes under the asset id `id`. Identical content is stored once
49
+ * (same `m-<sha>.<ext>` file), but every part keeps its own stable id, so a
50
+ * re-import that drops the first of two identical parts leaves the second's
51
+ * id — and every reference to it — intact.
52
+ */
53
+ add(bytes: Uint8Array, ext: string, id: string): MediaFile {
54
+ const existing = this.byId.get(id);
55
+ if (existing) return existing;
56
+ const sha = sha256Hex(bytes);
57
+ let stored = this.byHash.get(sha);
58
+ if (!stored) {
59
+ const e = ext.toLowerCase() === "jpeg" ? "jpg" : ext.toLowerCase();
60
+ stored = { name: `m-${sha.slice(0, 12)}.${e}`, asset: id, mime: MIME_BY_EXT[e] ?? "application/octet-stream", bytes, sha256: sha };
61
+ this.byHash.set(sha, stored);
62
+ }
63
+ const entry: MediaFile = { ...stored, asset: id };
64
+ this.byId.set(id, entry);
65
+ return entry;
66
+ }
67
+
68
+ addPart(part: string, bytes: Uint8Array): MediaFile {
69
+ return this.add(bytes, extOf(part), assetIdForPart(part));
70
+ }
71
+
72
+ /** Distinct stored files, sorted by name (deterministic write order). */
73
+ files(): MediaFile[] {
74
+ return [...this.byHash.values()].sort((a, b) => a.name.localeCompare(b.name));
75
+ }
76
+
77
+ /** Every asset id with the file it points at, sorted by id. */
78
+ assetEntries(): MediaFile[] {
79
+ return [...this.byId.values()].sort((a, b) => a.asset.localeCompare(b.asset));
80
+ }
81
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * OPC package navigation: relationships, the presentation's slide list and
3
+ * size, and each slide's layout → master → theme chain.
4
+ */
5
+ import { posix } from "node:path";
6
+ import { PptxImportError } from "./types.js";
7
+ import { child, kids, num, parseXml, path, type XNode } from "./xml.js";
8
+
9
+ export interface Rel {
10
+ type: string;
11
+ target: string;
12
+ /** Resolved package part name (no leading `/`), or the raw target when external. */
13
+ part: string;
14
+ external: boolean;
15
+ }
16
+
17
+ export type Rels = Record<string, Rel>;
18
+
19
+ export class Package {
20
+ readonly files: Map<string, Uint8Array>;
21
+ private xmlCache = new Map<string, XNode>();
22
+ private relCache = new Map<string, Rels>();
23
+
24
+ constructor(files: Map<string, Uint8Array>) {
25
+ this.files = files;
26
+ }
27
+
28
+ has(part: string): boolean {
29
+ return this.files.has(part);
30
+ }
31
+
32
+ bytes(part: string): Uint8Array | undefined {
33
+ return this.files.get(part);
34
+ }
35
+
36
+ xml(part: string): XNode | undefined {
37
+ const cached = this.xmlCache.get(part);
38
+ if (cached) return cached;
39
+ const data = this.files.get(part);
40
+ if (!data) return undefined;
41
+ let node: XNode;
42
+ try {
43
+ node = parseXml(data);
44
+ } catch (err) {
45
+ throw new PptxImportError(`malformed XML in '${part}': ${(err as Error).message}`);
46
+ }
47
+ this.xmlCache.set(part, node);
48
+ return node;
49
+ }
50
+
51
+ rels(part: string): Rels {
52
+ const cached = this.relCache.get(part);
53
+ if (cached) return cached;
54
+ const dir = posix.dirname(part);
55
+ const relsPart = posix.join(dir, "_rels", `${posix.basename(part)}.rels`);
56
+ const out: Rels = {};
57
+ const root = this.xml(relsPart);
58
+ for (const r of kids(root, "Relationship")) {
59
+ const id = r.attrs.Id;
60
+ const target = r.attrs.Target ?? "";
61
+ if (!id) continue;
62
+ const external = r.attrs.TargetMode === "External";
63
+ const resolved = target.startsWith("/") ? target.slice(1) : posix.normalize(posix.join(dir, target));
64
+ out[id] = { type: r.attrs.Type ?? "", target, part: external ? target : resolved, external };
65
+ }
66
+ this.relCache.set(part, out);
67
+ return out;
68
+ }
69
+
70
+ /** First relationship of `part` whose type ends with `/<suffix>`. */
71
+ relOfType(part: string, suffix: string): Rel | undefined {
72
+ return Object.values(this.rels(part)).find((r) => r.type.endsWith(`/${suffix}`));
73
+ }
74
+ }
75
+
76
+ export interface SlideChain {
77
+ slide: string;
78
+ layout?: string;
79
+ master?: string;
80
+ theme?: string;
81
+ }
82
+
83
+ export interface PresentationInfo {
84
+ /** Slide size in EMU. */
85
+ width: number;
86
+ height: number;
87
+ slides: SlideChain[];
88
+ defaultTextStyle?: XNode;
89
+ }
90
+
91
+ export function readPresentation(pkg: Package): PresentationInfo {
92
+ const presPart = "ppt/presentation.xml";
93
+ const pres = pkg.xml(presPart);
94
+ if (!pres) throw new PptxImportError("not a .pptx (OOXML) file");
95
+ const size = child(pres, "p:sldSz");
96
+ const width = num(size?.attrs.cx, 12192000);
97
+ const height = num(size?.attrs.cy, 6858000);
98
+ const rels = pkg.rels(presPart);
99
+ const slides: SlideChain[] = [];
100
+ for (const id of kids(path(pres, "p:sldIdLst"), "p:sldId")) {
101
+ const rel = rels[id.attrs["r:id"] ?? ""];
102
+ if (!rel || rel.external || !pkg.has(rel.part)) continue;
103
+ const layout = pkg.relOfType(rel.part, "slideLayout")?.part;
104
+ const master = layout ? pkg.relOfType(layout, "slideMaster")?.part : undefined;
105
+ const theme = master ? pkg.relOfType(master, "theme")?.part : undefined;
106
+ slides.push({ slide: rel.part, layout, master, theme });
107
+ }
108
+ return { width, height, slides, defaultTextStyle: child(pres, "p:defaultTextStyle") };
109
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Reference renders (design D6, spec "Reference renders"): `--ref <dir>` user
3
+ * exports first (PowerPoint / Keynote naming accepted), else LibreOffice +
4
+ * `pdftoppm` when both are on PATH, else one warning. Output is always
5
+ * `pptx/ref/sNN.png`; renders are authoring inputs, never embedded.
6
+ */
7
+ import { spawnSync } from "node:child_process";
8
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { delimiter, join } from "node:path";
11
+ import { isPng } from "../art/png.js";
12
+
13
+ /** Slide number a `--ref` file name refers to, or undefined. */
14
+ export function refSlideNumber(fileName: string): number | undefined {
15
+ const m = /^(.+)\.(png|jpe?g)$/i.exec(fileName);
16
+ if (!m) return undefined;
17
+ const base = m[1].toLowerCase();
18
+ const hit = /^(?:.*[ _-])?(?:s(\d+)|slide[ _-]?(\d+)|(\d+))$/.exec(base);
19
+ const n = hit ? Number(hit[1] ?? hit[2] ?? hit[3]) : Number.NaN;
20
+ return Number.isInteger(n) && n > 0 ? n : undefined;
21
+ }
22
+
23
+ export function onPath(cmd: string, env: NodeJS.ProcessEnv = process.env): boolean {
24
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
25
+ if (dir && existsSync(join(dir, cmd))) return true;
26
+ }
27
+ return false;
28
+ }
29
+
30
+ export interface RefResult {
31
+ /** Slide number (1-based) → PNG bytes. */
32
+ images: Map<number, Uint8Array>;
33
+ warnings: string[];
34
+ }
35
+
36
+ /** Convert non-PNG exports through `toPng` (the sandboxed decoder); undefined ⇒ skipped. */
37
+ export type ToPng = (bytes: Uint8Array) => Promise<Uint8Array | undefined>;
38
+
39
+ export async function refFromDir(dir: string, slideCount: number, toPng: ToPng): Promise<RefResult> {
40
+ const images = new Map<number, Uint8Array>();
41
+ const warnings: string[] = [];
42
+ const unmatched: string[] = [];
43
+ for (const name of readdirSync(dir).sort()) {
44
+ if (!/\.(png|jpe?g)$/i.test(name)) continue;
45
+ const n = refSlideNumber(name);
46
+ if (n === undefined || n > slideCount || images.has(n)) {
47
+ unmatched.push(name);
48
+ continue;
49
+ }
50
+ const bytes = new Uint8Array(readFileSync(join(dir, name)));
51
+ const png = isPng(bytes) ? bytes : await toPng(bytes);
52
+ if (!png) {
53
+ warnings.push(`warning --ref ${name}: cannot convert to PNG without chromium (npx playwright install chromium); skipped`);
54
+ continue;
55
+ }
56
+ images.set(n, png);
57
+ }
58
+ const missing: number[] = [];
59
+ for (let n = 1; n <= slideCount; n++) if (!images.has(n)) missing.push(n);
60
+ if (unmatched.length || missing.length) {
61
+ const parts: string[] = [];
62
+ if (unmatched.length) parts.push(`unmatched files: ${unmatched.join(", ")}`);
63
+ if (missing.length) parts.push(`slides without a reference: ${missing.join(", ")}`);
64
+ warnings.push(`warning --ref ${dir}: ${parts.join("; ")}`);
65
+ }
66
+ return { images, warnings };
67
+ }
68
+
69
+ export const NO_RENDERER_WARNING =
70
+ "warning no reference renders: pass --ref <dir> or install LibreOffice (soffice) + poppler (pdftoppm); compare and raster fallbacks are unavailable";
71
+
72
+ /** LibreOffice → PDF → pdftoppm PNGs at 1920 px wide. */
73
+ export function refFromLibreOffice(pptxPath: string, slideCount: number, env: NodeJS.ProcessEnv = process.env): RefResult {
74
+ const images = new Map<number, Uint8Array>();
75
+ if (!onPath("soffice", env) || !onPath("pdftoppm", env)) return { images, warnings: [NO_RENDERER_WARNING] };
76
+ const work = mkdtempSync(join(tmpdir(), "deck3d-ref-"));
77
+ try {
78
+ const conv = spawnSync("soffice", ["--headless", "--convert-to", "pdf", "--outdir", work, pptxPath], { env, encoding: "utf8", timeout: 300_000 });
79
+ if (conv.status !== 0) {
80
+ return { images, warnings: [`warning soffice exited with status ${conv.status ?? "signal"}; continuing without reference renders`] };
81
+ }
82
+ const pdf = readdirSync(work).find((f) => f.toLowerCase().endsWith(".pdf"));
83
+ if (!pdf) return { images, warnings: ["warning soffice produced no PDF; continuing without reference renders"] };
84
+ const ppm = spawnSync("pdftoppm", ["-png", "-scale-to-x", "1920", "-scale-to-y", "-1", join(work, pdf), join(work, "p")], {
85
+ env,
86
+ encoding: "utf8",
87
+ timeout: 300_000,
88
+ });
89
+ if (ppm.status !== 0) {
90
+ return { images, warnings: [`warning pdftoppm exited with status ${ppm.status ?? "signal"}; continuing without reference renders`] };
91
+ }
92
+ for (const f of readdirSync(work)) {
93
+ const m = /^p-0*(\d+)\.png$/.exec(f);
94
+ if (m && Number(m[1]) <= slideCount) images.set(Number(m[1]), new Uint8Array(readFileSync(join(work, f))));
95
+ }
96
+ return { images, warnings: [] };
97
+ } finally {
98
+ rmSync(work, { recursive: true, force: true });
99
+ }
100
+ }