@blackbelt-technology/pi-dashboard-deck3d 0.8.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 (106) 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/harvest/harness.js +4 -4
  14. package/dist/runtime.js +5916 -4007
  15. package/fixtures/business-2031/assets/stub-chrome.png +0 -0
  16. package/fixtures/business-2031/assets/stub-icon.json +59 -0
  17. package/fixtures/business-2031/assets/stub-layout.json +195 -0
  18. package/fixtures/business-2031/assets/stub-outline.json +48 -0
  19. package/fixtures/business-2031/build-overrides.mjs +58 -13
  20. package/fixtures/business-2031/deck.agent.md +60 -0
  21. package/fixtures/business-2031/deck.json +133 -8
  22. package/fixtures/business-2031/overrides.json +133 -8
  23. package/package.json +8 -4
  24. package/scripts/gen-stub-assets.ts +31 -0
  25. package/src/art/cutout.ts +97 -0
  26. package/src/art/decode.ts +169 -0
  27. package/src/art/icon.ts +380 -0
  28. package/src/art/png.ts +232 -0
  29. package/src/art/trace.ts +288 -0
  30. package/src/check/rules.ts +13 -8
  31. package/src/cli.ts +313 -51
  32. package/src/compare/index.ts +131 -0
  33. package/src/compare/ssim.ts +91 -0
  34. package/src/fx/art-geometry.ts +137 -0
  35. package/src/fx/art3d.meta.json +30 -0
  36. package/src/fx/art3d.ts +131 -0
  37. package/src/fx/bank.meta.json +26 -0
  38. package/src/fx/bank.ts +8 -0
  39. package/src/fx/compose.ts +5 -4
  40. package/src/fx/crane.meta.json +26 -0
  41. package/src/fx/crane.ts +8 -0
  42. package/src/fx/dolly.ts +5 -1
  43. package/src/fx/fade.ts +5 -1
  44. package/src/fx/flythrough.ts +5 -1
  45. package/src/fx/frame-chrome.meta.json +17 -0
  46. package/src/fx/frame-chrome.ts +134 -0
  47. package/src/fx/haze.meta.json +19 -0
  48. package/src/fx/haze.ts +91 -0
  49. package/src/fx/icon3d.meta.json +21 -0
  50. package/src/fx/icon3d.ts +167 -0
  51. package/src/fx/index.ts +96 -66
  52. package/src/fx/iris.ts +5 -1
  53. package/src/fx/meta.schema.json +10 -2
  54. package/src/fx/path.meta.json +25 -0
  55. package/src/fx/path.ts +8 -0
  56. package/src/fx/persistent.ts +11 -0
  57. package/src/fx/revolve.meta.json +26 -0
  58. package/src/fx/revolve.ts +8 -0
  59. package/src/fx/slide-layer.meta.json +26 -0
  60. package/src/fx/slide-layer.ts +557 -0
  61. package/src/fx/slide-space.ts +142 -0
  62. package/src/fx/stub-assets.ts +117 -0
  63. package/src/fx/swing.meta.json +26 -0
  64. package/src/fx/swing.ts +8 -0
  65. package/src/fx/types.ts +63 -2
  66. package/src/ir/merge.ts +5 -2
  67. package/src/ir/schema.json +140 -3
  68. package/src/ir/types.ts +54 -0
  69. package/src/ir/validate.ts +91 -3
  70. package/src/parse/harvest/index.ts +4 -1
  71. package/src/parse/markdown.ts +38 -7
  72. package/src/pptx/baseline.ts +183 -0
  73. package/src/pptx/extract.ts +161 -0
  74. package/src/pptx/fallback.ts +70 -0
  75. package/src/pptx/import.ts +256 -0
  76. package/src/pptx/master.ts +135 -0
  77. package/src/pptx/media.ts +81 -0
  78. package/src/pptx/package.ts +109 -0
  79. package/src/pptx/ref.ts +100 -0
  80. package/src/pptx/shapes.ts +276 -0
  81. package/src/pptx/stage.ts +82 -0
  82. package/src/pptx/text.ts +202 -0
  83. package/src/pptx/theme.ts +194 -0
  84. package/src/pptx/types.ts +159 -0
  85. package/src/pptx/xfrm.ts +93 -0
  86. package/src/pptx/xml.ts +106 -0
  87. package/src/pptx/zip.ts +239 -0
  88. package/src/render/assets.ts +57 -0
  89. package/src/render/build.ts +75 -0
  90. package/src/render/index.ts +7 -2
  91. package/src/render/template.html +1 -1
  92. package/src/runtime/assets.ts +75 -0
  93. package/src/runtime/fade.ts +110 -0
  94. package/src/runtime/hud.ts +37 -9
  95. package/src/runtime/index.ts +431 -67
  96. package/src/runtime/post.ts +11 -5
  97. package/src/runtime/scene.ts +25 -2
  98. package/src/runtime/transition.ts +222 -0
  99. package/src/runtime/types.ts +13 -2
  100. package/src/serve/index.ts +199 -16
  101. package/src/util/cleanup.ts +13 -0
  102. package/src/util/confine.ts +15 -0
  103. package/src/variants/pick.ts +282 -0
  104. package/src/variants/render.ts +179 -0
  105. package/src/variants/schema.json +48 -0
  106. package/src/variants/style.ts +318 -0
@@ -7,10 +7,13 @@
7
7
  * 3. Overrides referencing a vanished target is a WARNING (kept, inert).
8
8
  * 4. `meta.derivedHash` mismatch is a WARNING (edited outside `overrides`).
9
9
  */
10
- import { readFileSync } from "node:fs";
11
- import { join } from "node:path";
10
+ import { createHash } from "node:crypto";
11
+ import { existsSync, readFileSync, statSync } from "node:fs";
12
+ import { isAbsolute, join, relative, resolve } from "node:path";
12
13
  import Ajv, { type ErrorObject } from "ajv";
13
14
  import { localRefs, resolveLocalEffect } from "../fx/local.js";
15
+ import { isPersistentFx } from "../fx/persistent.js";
16
+ import { realInside } from "../util/confine.js";
14
17
  import { pkgRoot } from "../util/paths.js";
15
18
  import { computeDerivedHash } from "./hash.js";
16
19
  import { findOrphanOverrides, orphanOverridePath } from "./merge.js";
@@ -133,6 +136,56 @@ function validateLocalEffects(deck: DeckIR, deckDir: string): ValidationIssue[]
133
136
  return errors;
134
137
  }
135
138
 
139
+ /**
140
+ * Resolve every `overrides.assets` entry against the deck directory (spec
141
+ * deck3d-slide-layers "Deck asset bundle"): unique id, `font-` prefix iff
142
+ * a font, path inside the deck directory, file present, sha256 pinned.
143
+ */
144
+ export function validateAssets(deck: DeckIR, deckDir: string): ValidationIssue[] {
145
+ const errors: ValidationIssue[] = [];
146
+ const seen = new Set<string>();
147
+ const root = resolve(deckDir);
148
+ (deck.overrides.assets ?? []).forEach((a, i) => {
149
+ const at = `overrides.assets[${i}]`;
150
+ if (seen.has(a.id)) errors.push({ path: `${at}.id`, message: `duplicate asset id '${a.id}'` });
151
+ seen.add(a.id);
152
+ const font = a.mime === "font/ttf" || a.mime === "font/otf";
153
+ if (font && !a.id.startsWith("font-")) errors.push({ path: `${at}.id`, message: `font asset id '${a.id}' must start with 'font-'` });
154
+ if (!font && a.id.startsWith("font-")) errors.push({ path: `${at}.id`, message: `'font-' ids are reserved for font assets (mime is ${a.mime})` });
155
+ const file = resolve(root, a.path);
156
+ const rel = relative(root, file);
157
+ if (isAbsolute(a.path) || rel.startsWith("..") || isAbsolute(rel)) {
158
+ errors.push({ path: `${at}.path`, message: `'${a.path}' is outside the deck directory` });
159
+ return;
160
+ }
161
+ if (!existsSync(file) || !statSync(file).isFile()) {
162
+ errors.push({ path: `${at}.path`, message: `missing file ${a.path}` });
163
+ return;
164
+ }
165
+ // The spelling is inside; the REAL path (symlinks followed) must be too.
166
+ if (!realInside(root, file)) {
167
+ errors.push({ path: `${at}.path`, message: `'${a.path}' resolves outside the deck directory (symlink)` });
168
+ return;
169
+ }
170
+ const sha = createHash("sha256").update(readFileSync(file)).digest("hex");
171
+ if (sha !== a.sha256) errors.push({ path: `${at}.sha256`, message: `${a.path} has sha256 ${sha}, pinned ${a.sha256} (re-pin after editing the file)` });
172
+ });
173
+ return errors;
174
+ }
175
+
176
+ /** A persistent card anywhere but deck-scope `overrides.effects` is an error. */
177
+ function validatePersistentScope(deck: DeckIR): ValidationIssue[] {
178
+ const errors: ValidationIssue[] = [];
179
+ for (const [id, slide] of Object.entries(deck.overrides.slides ?? {})) {
180
+ (slide.effects ?? []).forEach((ref, i) => {
181
+ if (isPersistentFx(ref.id)) {
182
+ errors.push({ path: `overrides.slides["${id}"].effects[${i}]`, message: `'${ref.id}' is persistent: deck-scope only (list it in overrides.effects)` });
183
+ }
184
+ });
185
+ }
186
+ return errors;
187
+ }
188
+
136
189
  const PROP_COUNT_BUDGET = 5;
137
190
  const PROP_BYTES_BUDGET = 10 * 1024 * 1024;
138
191
 
@@ -159,6 +212,36 @@ function validateProps(deck: DeckIR, opts: ValidateOptions): ValidationIssue[] {
159
212
  return warnings;
160
213
  }
161
214
 
215
+ /**
216
+ * Camera-path coherence the schema cannot express: keys strictly ordered, and
217
+ * `cameraPath` ⇔ the slide's RESOLVED transition is `path` (own > cycle > default).
218
+ */
219
+ function validateCameraPaths(deck: DeckIR): ValidationIssue[] {
220
+ const errors: ValidationIssue[] = [];
221
+ const fallback = deck.overrides.deck?.transition ?? deck.defaults.transition;
222
+ const cycle = deck.overrides.deck?.transitionCycle ?? deck.defaults.transitionCycle;
223
+ deck.slides.forEach((slide, i) => {
224
+ const ov = deck.overrides.slides?.[slide.id];
225
+ const at = `overrides.slides["${slide.id}"]`;
226
+ const kind = ov?.transition ?? (cycle?.length ? cycle[i % cycle.length] : (fallback ?? "dolly"));
227
+ const keys = ov?.cameraPath?.keys ?? [];
228
+ for (let k = 1; k < keys.length; k++) {
229
+ if (!(keys[k].t > keys[k - 1].t)) errors.push({ path: `${at}.cameraPath.keys[${k}].t`, message: `must be greater than keys[${k - 1}].t (${keys[k - 1].t})` });
230
+ }
231
+ if (ov?.cameraPath && kind !== "path") errors.push({ path: `${at}.cameraPath`, message: `ignored unless the slide's transition is "path" (resolved: "${kind}")` });
232
+ if (!ov?.cameraPath && kind === "path") errors.push({ path: `${at}.transition`, message: `"path" needs overrides.slides["${slide.id}"].cameraPath` });
233
+ });
234
+ return errors;
235
+ }
236
+
237
+ /** Validates an overrides-grammar fragment (a `style.json` variant) against the IR schema. */
238
+ const validateFragmentSchema = ajv.compile({ definitions: (loadSchema() as { definitions: object }).definitions, $ref: "#/definitions/overrides" });
239
+
240
+ export function validateOverridesFragment(fragment: unknown): ValidationIssue[] {
241
+ if (validateFragmentSchema(fragment)) return [];
242
+ return (validateFragmentSchema.errors ?? []).map((e) => ({ path: formatPath(e.instancePath), message: humanMessage(e) }));
243
+ }
244
+
162
245
  export function validate(ir: unknown, opts: ValidateOptions = {}): ValidationResult {
163
246
  const errors: ValidationIssue[] = [];
164
247
  const warnings: ValidationIssue[] = [];
@@ -173,7 +256,12 @@ export function validate(ir: unknown, opts: ValidateOptions = {}): ValidationRes
173
256
 
174
257
  const deck = ir as DeckIR;
175
258
  errors.push(...validateDerived(deck));
176
- if (opts.deckDir !== undefined) errors.push(...validateLocalEffects(deck, opts.deckDir));
259
+ errors.push(...validateCameraPaths(deck));
260
+ errors.push(...validatePersistentScope(deck));
261
+ if (opts.deckDir !== undefined) {
262
+ errors.push(...validateLocalEffects(deck, opts.deckDir));
263
+ errors.push(...validateAssets(deck, opts.deckDir));
264
+ }
177
265
  warnings.push(...validateProps(deck, opts));
178
266
 
179
267
  for (const orphan of findOrphanOverrides(deck)) {
@@ -15,11 +15,14 @@ export const DEFAULT_HARVEST_TIMEOUT_MS = 60_000;
15
15
 
16
16
  /** Raised for every harvest failure; the message is the one-line CLI reason. */
17
17
  export class HarvestError extends Error {
18
+ readonly slideId?: string;
19
+
18
20
  constructor(
19
21
  message: string,
20
- readonly slideId?: string,
22
+ slideId?: string,
21
23
  ) {
22
24
  super(message);
25
+ this.slideId = slideId;
23
26
  this.name = "HarvestError";
24
27
  }
25
28
  }
@@ -28,16 +28,21 @@ export interface ParsedDeck {
28
28
  }
29
29
 
30
30
  export class MarkdownParseError extends Error {
31
+ readonly slideId: string;
32
+
31
33
  constructor(
32
34
  message: string,
33
- readonly slideId: string,
35
+ slideId: string,
34
36
  ) {
35
37
  super(message);
38
+ this.slideId = slideId;
36
39
  this.name = "MarkdownParseError";
37
40
  }
38
41
  }
39
42
 
40
43
  const OVERRIDE_RE = /^<!--\s*deck3d:\s*([\s\S]*?)\s*-->\s*$/;
44
+ /** Start of an override comment, optionally in bullet form (`- <!-- deck3d:`). */
45
+ const OVERRIDE_OPEN_RE = /^(?:[-*]\s+)?<!--\s*deck3d:/;
41
46
  const BULLET_RE = /^\s*[-*]\s+(.*)$/;
42
47
 
43
48
  interface RawSlide {
@@ -142,10 +147,11 @@ export function parseMarkdown(source: string): ParsedDeck {
142
147
  const slides: ParsedSlide[] = raws.map((raw, i) => {
143
148
  const heading = parseHeading(raw.heading);
144
149
  const id = ids[i];
145
- const content = stripNonContent(raw.body);
150
+ const { lines: body, overrides } = collapseOverrideSpans(raw.body);
151
+ const content = stripNonContent(body);
146
152
  const subtitle = extractSubtitle(content);
147
153
  const bullets = extractBullets(content);
148
- const inlineOverrides = extractInlineOverride(content, id);
154
+ const inlineOverrides = extractInlineOverride(overrides, id);
149
155
  const mermaid = extractMermaid(raw.body);
150
156
  const slide: ParsedSlide = { index: i + 1, id, title: heading.title, bullets };
151
157
  if (heading.pin) slide.pin = heading.pin;
@@ -158,6 +164,31 @@ export function parseMarkdown(source: string): ParsedDeck {
158
164
  return { defaults, slides };
159
165
  }
160
166
 
167
+ /**
168
+ * Lift every `<!-- deck3d: … -->` span (single-line, multi-line, or bullet
169
+ * form `- <!-- deck3d: … -->`) out of the slide body into an override record,
170
+ * so an override can never be read as subtitle or bullet text. Fenced code is
171
+ * left untouched. An unterminated span runs to the end of the body.
172
+ */
173
+ function collapseOverrideSpans(body: string[]): { lines: string[]; overrides: string[] } {
174
+ const lines: string[] = [];
175
+ const overrides: string[] = [];
176
+ let inFence = false;
177
+ for (let i = 0; i < body.length; i++) {
178
+ const line = body[i];
179
+ const t = line.trim();
180
+ if (t.startsWith("```")) inFence = !inFence;
181
+ if (inFence || !OVERRIDE_OPEN_RE.test(t)) {
182
+ lines.push(line);
183
+ continue;
184
+ }
185
+ const span = [t.replace(/^[-*]\s+/, "")];
186
+ while (!span[span.length - 1].includes("-->") && i + 1 < body.length) span.push(body[++i]);
187
+ overrides.push(span.join("\n"));
188
+ }
189
+ return { lines, overrides };
190
+ }
191
+
161
192
  /** Lines that contribute to subtitle/bullets (drops fences and comments). */
162
193
  function stripNonContent(body: string[]): string[] {
163
194
  const out: string[] = [];
@@ -168,7 +199,7 @@ function stripNonContent(body: string[]): string[] {
168
199
  continue;
169
200
  }
170
201
  if (inFence) continue;
171
- if (line.trim().startsWith("<!--") && !OVERRIDE_RE.test(line.trim())) continue;
202
+ if (line.trim().startsWith("<!--")) continue;
172
203
  out.push(line);
173
204
  }
174
205
  return out;
@@ -198,9 +229,9 @@ function extractBullets(content: string[]): string[] {
198
229
  return bullets;
199
230
  }
200
231
 
201
- function extractInlineOverride(content: string[], slideId: string): SlideOverride | undefined {
202
- for (const line of content) {
203
- const m = OVERRIDE_RE.exec(line.trim());
232
+ function extractInlineOverride(spans: string[], slideId: string): SlideOverride | undefined {
233
+ for (const span of spans) {
234
+ const m = OVERRIDE_RE.exec(span.trim());
204
235
  if (!m) continue;
205
236
  try {
206
237
  return JSON.parse(m[1]) as SlideOverride;
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Baseline deck (spec "Baseline deck") and the re-import rules (spec
3
+ * "Re-import keeps tuning"): slide id matching by fingerprint, then by title
4
+ * at the nearest position; baseline overrides added only where absent; and
5
+ * reconciliation of imported (`pptx-`) assets by id.
6
+ */
7
+ import type { Draft } from "./shapes.js";
8
+ import { luminance } from "./theme.js";
9
+ import type { Layout, LayoutSlide, MediaFile, ThemeInfo } from "./types.js";
10
+
11
+ export interface AssetEntry {
12
+ id: string;
13
+ path: string;
14
+ sha256: string;
15
+ mime: string;
16
+ }
17
+
18
+ export const LAYOUT_ASSET_ID = "pptx-layout";
19
+
20
+ /** One markdown line safe for the deck grammar (no heading/bullet/fence/comment/pin). */
21
+ export function mdLine(s: string): string {
22
+ return s
23
+ .replace(/\s+/g, " ")
24
+ .trim()
25
+ .replace(/```/g, "'''")
26
+ .replace(/<!--/g, "<!-")
27
+ .replace(/\{#/g, "{ #")
28
+ .replace(/^[#>*\-+\s]+/, "")
29
+ .replace(/^(\d+)\.\s/, "$1 ");
30
+ }
31
+
32
+ const SKIP_PLACEHOLDERS = new Set(["dt", "ftr", "sldNum"]);
33
+
34
+ /** Subtitle + bullets: paragraphs of the slide's own non-title text items. */
35
+ export function slideBody(drafts: Draft[]): { subtitle?: string; bullets: string[] } {
36
+ const paras: string[] = [];
37
+ for (const d of drafts) {
38
+ if (d.isTitle || d.item.origin || d.item.kind !== "text") continue;
39
+ if (d.placeholder && SKIP_PLACEHOLDERS.has(d.placeholder)) continue;
40
+ for (const p of d.text.split("\n")) {
41
+ const line = mdLine(p);
42
+ if (line) paras.push(line);
43
+ }
44
+ }
45
+ const [subtitle, ...bullets] = paras;
46
+ return subtitle ? { subtitle, bullets } : { bullets: [] };
47
+ }
48
+
49
+ export function baselineMarkdown(slides: Array<{ id: string; title: string; drafts: Draft[] }>): string {
50
+ const out: string[] = [];
51
+ for (const s of slides) {
52
+ const title = mdLine(s.title);
53
+ out.push(`# ${title ? `${title} ` : ""}{#${s.id}}`, "");
54
+ const body = slideBody(s.drafts);
55
+ if (body.subtitle) out.push(body.subtitle, "");
56
+ for (const b of body.bullets) out.push(`- ${b}`);
57
+ if (body.bullets.length) out.push("");
58
+ }
59
+ return `${out.join("\n").trimEnd()}\n`;
60
+ }
61
+
62
+ /** `light` when the dominant background luminance is above 0.5. */
63
+ export function baselineMode(layout: Layout): "light" | "dark" {
64
+ const colors = layout.slides.map((s) => s.background?.color).filter((c): c is string => !!c);
65
+ const counts = new Map<string, number>();
66
+ for (const c of colors) counts.set(c, (counts.get(c) ?? 0) + 1);
67
+ const dominant = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0]?.[0] ?? layout.theme.colors.lt1;
68
+ return luminance(dominant) > 0.5 ? "light" : "dark";
69
+ }
70
+
71
+ export function baselineDeckOverrides(theme: ThemeInfo, mode: "light" | "dark"): Record<string, unknown> {
72
+ return {
73
+ palette: "custom",
74
+ mode,
75
+ colors: { accent: theme.colors.accent1, secondary: theme.colors.accent2, card: mode === "light" ? theme.colors.lt2 : theme.colors.dk2 },
76
+ };
77
+ }
78
+
79
+ export function importedAssets(media: MediaFile[], layoutSha: string): AssetEntry[] {
80
+ const out: AssetEntry[] = [{ id: LAYOUT_ASSET_ID, path: "pptx/layout.json", sha256: layoutSha, mime: "application/json" }];
81
+ for (const m of media) out.push({ id: m.asset, path: `pptx/media/${m.name}`, sha256: m.sha256, mime: m.mime });
82
+ return out.sort((a, b) => a.id.localeCompare(b.id));
83
+ }
84
+
85
+ // ── re-import ────────────────────────────────────────────────────────────────
86
+
87
+ export interface IdMatch {
88
+ ids: string[];
89
+ warnings: string[];
90
+ }
91
+
92
+ /**
93
+ * Give each new slide the id of the previous slide with an equal fingerprint,
94
+ * else of the previous slide with the same title at the nearest position,
95
+ * else the next unused `sNN`. Every new, moved or vanished id is reported.
96
+ */
97
+ export function matchSlideIds(next: Array<{ title: string; fingerprint: string }>, previous: LayoutSlide[] | undefined): IdMatch {
98
+ const pad = (n: number) => `s${String(n).padStart(2, "0")}`;
99
+ if (!previous?.length) return { ids: next.map((_, i) => pad(i + 1)), warnings: [] };
100
+ const used = new Set<string>();
101
+ const ids: Array<string | undefined> = next.map(() => undefined);
102
+ next.forEach((s, i) => {
103
+ const hit = previous.find((p) => !used.has(p.id) && p.fingerprint === s.fingerprint);
104
+ if (hit) {
105
+ ids[i] = hit.id;
106
+ used.add(hit.id);
107
+ }
108
+ });
109
+ next.forEach((s, i) => {
110
+ if (ids[i] || !s.title) return;
111
+ const candidates = previous.filter((p) => !used.has(p.id) && p.title === s.title);
112
+ candidates.sort((a, b) => Math.abs(a.index - (i + 1)) - Math.abs(b.index - (i + 1)) || a.index - b.index);
113
+ const hit = candidates[0];
114
+ if (hit) {
115
+ ids[i] = hit.id;
116
+ used.add(hit.id);
117
+ }
118
+ });
119
+ let n = Math.max(0, ...previous.map((p) => Number(/^s(\d+)$/.exec(p.id)?.[1] ?? 0)));
120
+ const warnings: string[] = [];
121
+ const final = ids.map((id, i) => {
122
+ if (id) return id;
123
+ let fresh: string;
124
+ do fresh = pad(++n);
125
+ while (used.has(fresh));
126
+ used.add(fresh);
127
+ warnings.push(`warning slide ${fresh} is new (position ${i + 1}${next[i].title ? `: "${next[i].title}"` : ""})`);
128
+ return fresh;
129
+ });
130
+ final.forEach((id, i) => {
131
+ const prev = previous.find((p) => p.id === id);
132
+ if (prev && prev.index !== i + 1) warnings.push(`warning slide ${id} moved from position ${prev.index} to ${i + 1}`);
133
+ });
134
+ for (const p of previous) if (!final.includes(p.id)) warnings.push(`warning slide ${p.id} vanished (was position ${p.index}${p.title ? `: "${p.title}"` : ""})`);
135
+ return { ids: final, warnings };
136
+ }
137
+
138
+ /** `overrides` paths of effect params whose string value equals `id`. */
139
+ export function effectParamRefs(overrides: Record<string, unknown>, id: string): string[] {
140
+ const refs: string[] = [];
141
+ const scan = (v: unknown, at: string): void => {
142
+ if (v === id) refs.push(at);
143
+ else if (Array.isArray(v)) v.forEach((x, i) => scan(x, `${at}[${i}]`));
144
+ else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) scan(x, `${at}.${k}`);
145
+ };
146
+ const lists: Array<[unknown, string]> = [[overrides.effects, "overrides.effects"]];
147
+ for (const [sid, s] of Object.entries((overrides.slides ?? {}) as Record<string, { effects?: unknown }>)) {
148
+ lists.push([s.effects, `overrides.slides["${sid}"].effects`]);
149
+ }
150
+ for (const [list, at] of lists) {
151
+ if (!Array.isArray(list)) continue;
152
+ list.forEach((ref, i) => scan((ref as { params?: unknown }).params, `${at}[${i}].params`));
153
+ }
154
+ return refs;
155
+ }
156
+
157
+ export interface Reconciled {
158
+ assets: AssetEntry[];
159
+ warnings: string[];
160
+ /** Non-empty ⇒ the import must fail without writing. */
161
+ dangling: string[];
162
+ }
163
+
164
+ /**
165
+ * Keep user assets (no `pptx-` prefix) untouched; replace imported ones by
166
+ * id; drop imported ids whose part vanished — failing when an effect param
167
+ * still references one.
168
+ */
169
+ export function reconcileAssets(previous: AssetEntry[] | undefined, imported: AssetEntry[], overrides: Record<string, unknown>): Reconciled {
170
+ const user = (previous ?? []).filter((a) => !a.id.startsWith("pptx-"));
171
+ const nextIds = new Set(imported.map((a) => a.id));
172
+ const warnings: string[] = [];
173
+ const dangling: string[] = [];
174
+ for (const a of previous ?? []) {
175
+ if (!a.id.startsWith("pptx-") || nextIds.has(a.id)) continue;
176
+ const refs = effectParamRefs(overrides, a.id);
177
+ if (refs.length) dangling.push(...refs.map((r) => `${r} references dropped asset '${a.id}'`));
178
+ else warnings.push(`warning asset ${a.id} dropped (its pptx part vanished)`);
179
+ }
180
+ const userIds = new Set(user.map((a) => a.id));
181
+ const merged = [...user, ...imported.filter((a) => !userIds.has(a.id))];
182
+ return { assets: merged.sort((a, b) => a.id.localeCompare(b.id)), warnings, dangling };
183
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * pptx package → per-slide drafts (design D1). Ids are assigned afterwards by
3
+ * `finalizeLayout`, so a `--force` re-import can reuse previous slide ids.
4
+ */
5
+ import { backgroundOf, hidesMasterShapes, MasterChain } from "./master.js";
6
+ import { MediaRegistry, sha256Hex } from "./media.js";
7
+ import { Package, readPresentation } from "./package.js";
8
+ import { type Draft, walkTree } from "./shapes.js";
9
+ import { type ColorEnv, parseClrMap, parseTheme, resolveColor } from "./theme.js";
10
+ import type { FallbackItem, Layout, LayoutItem, LayoutSlide, ThemeInfo } from "./types.js";
11
+ import { IDENTITY } from "./xfrm.js";
12
+ import { child, kids, path, type XNode } from "./xml.js";
13
+
14
+ export const SLIDE_WIDTH = 1920;
15
+
16
+ export interface ExtractedSlide {
17
+ title: string;
18
+ fingerprint: string;
19
+ background?: LayoutSlide["background"];
20
+ drafts: Draft[];
21
+ /** Plain text of the slide part's own items (baseline deck). */
22
+ part: string;
23
+ }
24
+
25
+ export interface Extracted {
26
+ size: { w: number; h: number };
27
+ theme: ThemeInfo;
28
+ slides: ExtractedSlide[];
29
+ media: MediaRegistry;
30
+ }
31
+
32
+ const normalise = (s: string) => s.replace(/\s+/g, " ").trim();
33
+
34
+ function readBackground(bg: XNode | undefined, env: ColorEnv, pkg: Package, part: string, media: MediaRegistry): LayoutSlide["background"] | undefined {
35
+ if (!bg) return undefined;
36
+ const pr = child(bg, "p:bgPr");
37
+ if (pr) {
38
+ const solid = child(pr, "a:solidFill");
39
+ if (solid) {
40
+ const c = resolveColor(solid, env);
41
+ return c ? { color: c.hex } : undefined;
42
+ }
43
+ const grad = child(pr, "a:gradFill");
44
+ if (grad) {
45
+ const stop = kids(child(grad, "a:gsLst"), "a:gs")[0];
46
+ const c = resolveColor(stop, env);
47
+ return c ? { color: c.hex } : undefined;
48
+ }
49
+ const blip = path(pr, "a:blipFill", "a:blip");
50
+ const rel = pkg.rels(part)[blip?.attrs["r:embed"] ?? ""];
51
+ if (rel && !rel.external && pkg.has(rel.part)) {
52
+ const file = media.addPart(rel.part, pkg.bytes(rel.part) as Uint8Array);
53
+ return { media: file.name, asset: file.asset };
54
+ }
55
+ return undefined;
56
+ }
57
+ const ref = child(bg, "p:bgRef");
58
+ const c = resolveColor(ref, env);
59
+ return c ? { color: c.hex } : undefined;
60
+ }
61
+
62
+ export function extractPptx(files: Map<string, Uint8Array>): Extracted {
63
+ const pkg = new Package(files);
64
+ const pres = readPresentation(pkg);
65
+ const scale = SLIDE_WIDTH / pres.width;
66
+ const size = { w: SLIDE_WIDTH, h: Math.round((SLIDE_WIDTH * pres.height) / pres.width) };
67
+ const media = new MediaRegistry();
68
+ const firstTheme = pres.slides.find((s) => s.theme)?.theme;
69
+ const deckTheme = parseTheme(firstTheme ? pkg.xml(firstTheme) : undefined);
70
+
71
+ const slides: ExtractedSlide[] = pres.slides.map((chain) => {
72
+ const theme = chain.theme ? parseTheme(pkg.xml(chain.theme)) : deckTheme;
73
+ const masterXml = chain.master ? pkg.xml(chain.master) : undefined;
74
+ const layoutXml = chain.layout ? pkg.xml(chain.layout) : undefined;
75
+ const slideXml = pkg.xml(chain.slide);
76
+ const env: ColorEnv = { theme, clrMap: parseClrMap(child(masterXml, "p:clrMap")) };
77
+ const mc = new MasterChain(pkg, chain.layout, chain.master, pres.defaultTextStyle);
78
+ const ctxBase = { pkg, scale, color: env, theme, chain: mc, media };
79
+
80
+ const drafts: Draft[] = [];
81
+ const hideAll = hidesMasterShapes(slideXml);
82
+ if (!hideAll && !hidesMasterShapes(layoutXml) && chain.master) {
83
+ drafts.push(...walkTree(mc.masterTree, { ...ctxBase, part: chain.master, origin: "master", skipPlaceholders: true }, IDENTITY));
84
+ }
85
+ if (!hideAll && chain.layout) {
86
+ drafts.push(...walkTree(mc.layoutTree, { ...ctxBase, part: chain.layout, origin: "master", skipPlaceholders: true }, IDENTITY));
87
+ }
88
+ drafts.push(...walkTree(path(slideXml, "p:cSld", "p:spTree"), { ...ctxBase, part: chain.slide, skipPlaceholders: false }, IDENTITY));
89
+
90
+ const bgSource: Array<[XNode | undefined, string | undefined]> = [
91
+ [slideXml, chain.slide],
92
+ [layoutXml, chain.layout],
93
+ [masterXml, chain.master],
94
+ ];
95
+ let background: LayoutSlide["background"] | undefined;
96
+ for (const [root, part] of bgSource) {
97
+ const bg = backgroundOf(root);
98
+ if (bg && part) {
99
+ background = readBackground(bg, env, pkg, part, media);
100
+ if (background) break;
101
+ }
102
+ }
103
+ // A picture covering the whole slide at the bottom of the z-order IS the
104
+ // background, whatever part it came from.
105
+ const first = drafts[0]?.item;
106
+ if (
107
+ first?.kind === "img" &&
108
+ first.rotation === 0 &&
109
+ Math.abs(first.rect.x) <= 1 &&
110
+ Math.abs(first.rect.y) <= 1 &&
111
+ first.rect.w >= size.w - 2 &&
112
+ first.rect.h >= size.h - 2
113
+ ) {
114
+ background = { ...(background?.color ? { color: background.color } : {}), media: first.media, asset: first.asset };
115
+ drafts.shift();
116
+ }
117
+
118
+ const titleDraft = drafts.find((d) => d.isTitle && !d.item.origin);
119
+ const title = normalise(titleDraft?.text ?? "");
120
+ const others = drafts.filter((d) => d !== titleDraft && !d.item.origin && d.text.trim()).map((d) => normalise(d.text));
121
+ const fingerprint = sha256Hex([title, ...others].join("\n"));
122
+ return { title, fingerprint, ...(background ? { background } : {}), drafts, part: chain.slide };
123
+ });
124
+
125
+ return { size, theme: deckTheme, slides, media };
126
+ }
127
+
128
+ export interface FallbackRecord {
129
+ slide: string;
130
+ item: FallbackItem;
131
+ }
132
+
133
+ /** Assign `sNN` / `sNN-iMMM` ids and build `layout.json`. */
134
+ export function finalizeLayout(ex: Extracted, ids: string[]): { layout: Layout; fallbacks: FallbackRecord[] } {
135
+ const fallbacks: FallbackRecord[] = [];
136
+ const slides: LayoutSlide[] = ex.slides.map((s, i) => {
137
+ const id = ids[i];
138
+ const items: LayoutItem[] = s.drafts.map((d, k) => {
139
+ const item = { id: `${id}-i${String(k + 1).padStart(3, "0")}`, ...d.item } as LayoutItem;
140
+ if (d.coversPrev && item.kind === "text" && k > 0) item.coveredBy = `${id}-i${String(k).padStart(3, "0")}`;
141
+ if (item.kind === "fallback") fallbacks.push({ slide: id, item });
142
+ return item;
143
+ });
144
+ return { id, index: i + 1, title: s.title, fingerprint: s.fingerprint, ...(s.background ? { background: s.background } : {}), items };
145
+ });
146
+ return { layout: { version: 1, size: ex.size, theme: ex.theme, slides }, fallbacks };
147
+ }
148
+
149
+ /** Recursively key-sorted JSON (byte-stable `layout.json`). */
150
+ export function stableStringify(value: unknown): string {
151
+ const sort = (v: unknown): unknown => {
152
+ if (Array.isArray(v)) return v.map(sort);
153
+ if (v && typeof v === "object") {
154
+ const out: Record<string, unknown> = {};
155
+ for (const k of Object.keys(v as Record<string, unknown>).sort()) out[k] = sort((v as Record<string, unknown>)[k]);
156
+ return out;
157
+ }
158
+ return v;
159
+ };
160
+ return `${JSON.stringify(sort(value), null, 2)}\n`;
161
+ }
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Visible fallbacks for constructs outside the supported matrix (design D5):
3
+ * a crop of the slide's reference render at the item's rotated bounding
4
+ * rect, or — without a reference — an outlined placeholder. One warning each.
5
+ */
6
+ import { cropRgba, decodePng, encodePng, PngLimitError, type RgbaImage } from "../art/png.js";
7
+ import type { FallbackRecord } from "./extract.js";
8
+ import type { MediaRegistry } from "./media.js";
9
+ import type { Rect } from "./types.js";
10
+
11
+ /** Axis-aligned bounding rect of `r` rotated `deg` about its centre. */
12
+ export function rotatedBounds(r: Rect, deg: number): Rect {
13
+ const a = (deg * Math.PI) / 180;
14
+ const w = Math.abs(r.w * Math.cos(a)) + Math.abs(r.h * Math.sin(a));
15
+ const h = Math.abs(r.w * Math.sin(a)) + Math.abs(r.h * Math.cos(a));
16
+ const cx = r.x + r.w / 2;
17
+ const cy = r.y + r.h / 2;
18
+ return { x: cx - w / 2, y: cy - h / 2, w, h };
19
+ }
20
+
21
+ export type DecodeAny = (png: Uint8Array) => Promise<RgbaImage>;
22
+
23
+ /** Pure PNG decode, falling back to `sandbox` for PNGs the TS decoder does not read. */
24
+ export function pngDecoder(sandbox?: (bytes: Uint8Array) => Promise<RgbaImage>): DecodeAny {
25
+ return async (png) => {
26
+ try {
27
+ return decodePng(png);
28
+ } catch (err) {
29
+ // A size-limit refusal is final: handing the PNG to the sandbox would only re-reject it
30
+ // (and, without chromium, replace this precise message with "needs chromium").
31
+ if (err instanceof PngLimitError || !sandbox) throw err;
32
+ return sandbox(png);
33
+ }
34
+ };
35
+ }
36
+
37
+ /**
38
+ * Fill `media`/`asset` on every fallback whose slide has a reference render
39
+ * (slide id → PNG bytes) and return the warning lines.
40
+ */
41
+ export async function applyFallbacks(
42
+ fallbacks: FallbackRecord[],
43
+ refs: Map<string, Uint8Array>,
44
+ slideWidth: number,
45
+ media: MediaRegistry,
46
+ decode: DecodeAny,
47
+ ): Promise<string[]> {
48
+ const warnings: string[] = [];
49
+ const decoded = new Map<string, RgbaImage>();
50
+ for (const { slide, item } of fallbacks) {
51
+ const ref = refs.get(slide);
52
+ if (!ref) {
53
+ warnings.push(`warning ${item.id} ${item.construct}: placeholder (no reference render)`);
54
+ continue;
55
+ }
56
+ let img = decoded.get(slide);
57
+ if (!img) {
58
+ img = await decode(ref);
59
+ decoded.set(slide, img);
60
+ }
61
+ const k = img.width / slideWidth;
62
+ const b = rotatedBounds(item.rect, item.rotation);
63
+ const crop = cropRgba(img, b.x * k, b.y * k, b.w * k, b.h * k);
64
+ const file = media.add(encodePng(crop), "png", `pptx-fallback-${item.id}`);
65
+ item.media = file.name;
66
+ item.asset = file.asset;
67
+ warnings.push(`warning ${item.id} ${item.construct}: raster fallback`);
68
+ }
69
+ return warnings;
70
+ }