pptx-ts 0.0.1

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 (78) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +319 -0
  3. package/dist/autopage-DkjYZUFD.js +423 -0
  4. package/dist/autopage-DkjYZUFD.js.map +1 -0
  5. package/dist/browser.d.ts +31 -0
  6. package/dist/browser.d.ts.map +1 -0
  7. package/dist/browser.js +110 -0
  8. package/dist/browser.js.map +1 -0
  9. package/dist/diagnostics-Du_s75MT.d.ts +829 -0
  10. package/dist/diagnostics-Du_s75MT.d.ts.map +1 -0
  11. package/dist/enums-CvRYniUA.d.ts +463 -0
  12. package/dist/enums-CvRYniUA.d.ts.map +1 -0
  13. package/dist/errors-Bvln0H-7.js +112 -0
  14. package/dist/errors-Bvln0H-7.js.map +1 -0
  15. package/dist/errors-PflMPWBn.d.ts +182 -0
  16. package/dist/errors-PflMPWBn.d.ts.map +1 -0
  17. package/dist/fit-BKs0zxMI.js +1356 -0
  18. package/dist/fit-BKs0zxMI.js.map +1 -0
  19. package/dist/html-dom-B0I0QSbU.js +679 -0
  20. package/dist/html-dom-B0I0QSbU.js.map +1 -0
  21. package/dist/html.d.ts +26 -0
  22. package/dist/html.d.ts.map +1 -0
  23. package/dist/html.js +63 -0
  24. package/dist/html.js.map +1 -0
  25. package/dist/index.d.ts +24 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +57 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/inspect.d.ts +197 -0
  30. package/dist/inspect.d.ts.map +1 -0
  31. package/dist/inspect.js +317 -0
  32. package/dist/inspect.js.map +1 -0
  33. package/dist/math.d.ts +37 -0
  34. package/dist/math.d.ts.map +1 -0
  35. package/dist/math.js +203 -0
  36. package/dist/math.js.map +1 -0
  37. package/dist/measure.d.ts +313 -0
  38. package/dist/measure.d.ts.map +1 -0
  39. package/dist/measure.js +3 -0
  40. package/dist/namespaces-BVnNu7sg.js +666 -0
  41. package/dist/namespaces-BVnNu7sg.js.map +1 -0
  42. package/dist/node.d.ts +20 -0
  43. package/dist/node.d.ts.map +1 -0
  44. package/dist/node.js +55 -0
  45. package/dist/node.js.map +1 -0
  46. package/dist/notes-RLCwdlTE.js +1703 -0
  47. package/dist/notes-RLCwdlTE.js.map +1 -0
  48. package/dist/package-CaOLXSNi.d.ts +193 -0
  49. package/dist/package-CaOLXSNi.d.ts.map +1 -0
  50. package/dist/pres-C5__xkDh.d.ts +202 -0
  51. package/dist/pres-C5__xkDh.d.ts.map +1 -0
  52. package/dist/presentation-Cp7vzlAw.js +5427 -0
  53. package/dist/presentation-Cp7vzlAw.js.map +1 -0
  54. package/dist/presentation-types-DP_8jog7.d.ts +4872 -0
  55. package/dist/presentation-types-DP_8jog7.d.ts.map +1 -0
  56. package/dist/read.d.ts +55 -0
  57. package/dist/read.d.ts.map +1 -0
  58. package/dist/read.js +4 -0
  59. package/dist/script.d.ts +581 -0
  60. package/dist/script.d.ts.map +1 -0
  61. package/dist/script.js +3741 -0
  62. package/dist/script.js.map +1 -0
  63. package/dist/shapes-BemroU-z.js +6951 -0
  64. package/dist/shapes-BemroU-z.js.map +1 -0
  65. package/dist/slide-js0QpRV-.d.ts +3873 -0
  66. package/dist/slide-js0QpRV-.d.ts.map +1 -0
  67. package/dist/text-CyetbF6p.js +11278 -0
  68. package/dist/text-CyetbF6p.js.map +1 -0
  69. package/dist/units-1kRzYShk.js +231 -0
  70. package/dist/units-1kRzYShk.js.map +1 -0
  71. package/dist/units-internal-Dg95w_YD.js +753 -0
  72. package/dist/units-internal-Dg95w_YD.js.map +1 -0
  73. package/dist/zip.d.ts +68 -0
  74. package/dist/zip.d.ts.map +1 -0
  75. package/dist/zip.js +163 -0
  76. package/dist/zip.js.map +1 -0
  77. package/package.json +152 -0
  78. package/skills/ts-pptx-upstream/SKILL.md +340 -0
@@ -0,0 +1,317 @@
1
+ import { d as emuToInches, l as STANDARD_LAYOUTS, x as warn } from "./units-1kRzYShk.js";
2
+ import { a as TsPptxError, i as PackageReadError, n as InvalidOptionError, o as UnsupportedFeatureError, r as MediaError, t as InternalError } from "./errors-Bvln0H-7.js";
3
+ import { t as OOXML_NS } from "./namespaces-BVnNu7sg.js";
4
+ import { Nt as attr, Wt as intValue, zt as firstChild } from "./shapes-BemroU-z.js";
5
+ import { f as OpcPackage, t as Presentation } from "./presentation-Cp7vzlAw.js";
6
+ //#region src/inspect.ts
7
+ /**
8
+ * A cheap, flat snapshot of what a `.pptx` contains: every element on every
9
+ * slide, with its slide-absolute box and the handful of text/fill properties a
10
+ * layout audit asks about.
11
+ *
12
+ * It is a **projection over `ts-pptx/read`**, not a second reader. `read` gives a
13
+ * navigable, mutable model of a package and answers questions in the shape of the
14
+ * OOXML tree; this answers one flat question — "what is on the slides, and where"
15
+ * — in the shape a linter, an overlap check, or a diffing tool wants. The two used
16
+ * to be independent implementations over two different XML parsers, which meant
17
+ * every read-side fix had to be made twice and a divergence between them was
18
+ * invisible to every test. Now the model below is the only reader, and this file
19
+ * is the flattening.
20
+ *
21
+ * What it deliberately does NOT do, and why the projection is not just
22
+ * `Presentation` re-exported:
23
+ * - **Only geometry a shape carries itself.** A placeholder that inherits its box
24
+ * from the layout is omitted rather than resolved (`absoluteFrame`, not
25
+ * `resolvedFrame`) — the snapshot reports what the slide states.
26
+ * - **A `p:graphicFrame` is a box, not its contents.** A table, chart or SmartArt
27
+ * graphic is reported as one element with its box, its kind, and the text a
28
+ * reader sees on the slide, but its structure is not flattened: no per-run
29
+ * formatting, no cells, no series. Walk `ts-pptx/read` for what is inside one.
30
+ */
31
+ const DEFAULT_INSPECT_SLIDE_SIZE = Object.freeze({
32
+ widthIn: round(STANDARD_LAYOUTS.LAYOUT_WIDE.widthIn, 3),
33
+ heightIn: STANDARD_LAYOUTS.LAYOUT_WIDE.heightIn
34
+ });
35
+ /**
36
+ * Load a `.pptx` as an {@link OpcPackage} — the same package model `ts-pptx/read`
37
+ * uses, so a caller that starts here can hand the result straight to
38
+ * `Presentation.fromPackage()` without re-reading the bytes.
39
+ *
40
+ * The input must be a real OPC package: a zip that merely contains some slide XML
41
+ * but no `[Content_Types].xml` is rejected with a `PackageReadError`.
42
+ */
43
+ async function loadPptxPackage(input) {
44
+ return OpcPackage.load(await input);
45
+ }
46
+ /** Every part in the package, as zip paths (`ppt/slides/slide1.xml`), sorted. */
47
+ function listPptxParts(pptxPackage) {
48
+ return [...pptxPackage.parts.keys()].map(zipPathOf).sort();
49
+ }
50
+ /** Read a package part as UTF-8 text, or `null` when the part is absent. */
51
+ async function readPptxTextPart(pptxPackage, path) {
52
+ const bytes = await readPptxBinaryPart(pptxPackage, path);
53
+ return bytes ? textDecoder.decode(bytes) : null;
54
+ }
55
+ /**
56
+ * Read a package part as raw bytes — the binary sibling of {@link readPptxTextPart}
57
+ * for embedded media (SVG/PNG/EMF blobs, fonts, …) that must not be UTF-8 decoded.
58
+ * Returns `null` when the part is absent. The `Uint8Array` is browser-isomorphic;
59
+ * Node consumers can wrap it with `Buffer.from(...)` if they need Buffer methods.
60
+ */
61
+ async function readPptxBinaryPart(pptxPackage, path) {
62
+ return pptxPackage.part(partNameOf(path))?.bytes ?? null;
63
+ }
64
+ const textDecoder = new TextDecoder("utf-8");
65
+ /** OPC partnames are absolute (`/ppt/…`); this surface speaks zip paths (`ppt/…`). */
66
+ function zipPathOf(partName) {
67
+ return partName.startsWith("/") ? partName.slice(1) : partName;
68
+ }
69
+ function partNameOf(zipPath) {
70
+ return zipPath.startsWith("/") ? zipPath : `/${zipPath}`;
71
+ }
72
+ async function inspectPptx(input) {
73
+ const pptxPackage = await loadPptxPackage(input);
74
+ const slideSize = await readPresentationSize(pptxPackage);
75
+ return {
76
+ slideSize,
77
+ slides: await extractSlides(pptxPackage, slideSize)
78
+ };
79
+ }
80
+ async function readPresentationSize(pptxPackage, fallback = DEFAULT_INSPECT_SLIDE_SIZE) {
81
+ const size = presentationOf(pptxPackage)?.slideSize;
82
+ if (!size) return fallback;
83
+ return {
84
+ widthIn: round(size.widthIn, 3),
85
+ heightIn: round(size.heightIn, 3)
86
+ };
87
+ }
88
+ /**
89
+ * Every slide in the deck, in **presentation order** (`p:sldIdLst`) — the order
90
+ * PowerPoint shows them in, which is not the order their parts are named once a
91
+ * deck has been reordered.
92
+ */
93
+ async function extractSlides(pptxPackage, size) {
94
+ const slideSize = size || await readPresentationSize(pptxPackage);
95
+ const presentation = presentationOf(pptxPackage);
96
+ if (!presentation) return [];
97
+ return presentation.slides.map((slide, index) => {
98
+ const path = zipPathOf(slide.partName);
99
+ const harvested = [];
100
+ harvest(slide.shapes, null, harvested);
101
+ const elements = flatten(harvested, path);
102
+ const text = elements.map((el) => el.text).filter(Boolean).join(" ");
103
+ return {
104
+ index,
105
+ name: slide.name || `Slide ${index + 1}`,
106
+ path,
107
+ size: slideSize,
108
+ elements,
109
+ text,
110
+ wordCount: countWords(text)
111
+ };
112
+ });
113
+ }
114
+ /**
115
+ * The deck's `Presentation`, or `null` when the package holds no readable
116
+ * `presentation.xml`. Callers here are auditing files they did not author, so a
117
+ * package that is a valid OPC container but not a presentation reports an empty
118
+ * deck rather than throwing. `presentationPart` is the throw site: it rejects a
119
+ * package with no — or more than one — office-document relationship.
120
+ */
121
+ function presentationOf(pptxPackage) {
122
+ const presentation = Presentation.fromPackage(pptxPackage);
123
+ try {
124
+ return presentation.presentationPart.isXmlPart ? presentation : null;
125
+ } catch {
126
+ return null;
127
+ }
128
+ }
129
+ function overlapArea(a, b) {
130
+ return Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y));
131
+ }
132
+ function boxAnchor(box, anchor, axis) {
133
+ if (axis === "x") {
134
+ if (anchor === "left") return box.x;
135
+ if (anchor === "right") return box.x + box.w;
136
+ return box.x + box.w / 2;
137
+ }
138
+ if (anchor === "top") return box.y;
139
+ if (anchor === "bottom") return box.y + box.h;
140
+ return box.y + box.h / 2;
141
+ }
142
+ /**
143
+ * Flatten a shape list depth-first in document order: each shape is followed by
144
+ * its descendants, which is both paint order and the order the
145
+ * {@link PptxSlideElement.zIndex} contract promises. Every entry's index in `out`
146
+ * is its zIndex. Returns the zIndices assigned at this level, which is what the
147
+ * enclosing group records as its {@link PptxSlideElement.childZIndices}.
148
+ */
149
+ function harvest(shapes, parentZIndex, out) {
150
+ const zIndices = [];
151
+ for (const shape of shapes) {
152
+ const entry = {
153
+ shape,
154
+ parentZIndex,
155
+ childZIndices: []
156
+ };
157
+ const zIndex = out.push(entry) - 1;
158
+ zIndices.push(zIndex);
159
+ if (shape.shapeType === "group") entry.childZIndices = harvest(shape.shapes, zIndex, out);
160
+ }
161
+ return zIndices;
162
+ }
163
+ /**
164
+ * Turn harvested shapes into elements, dropping the ones with no resolvable slide
165
+ * position. A dropped shape keeps its zIndex — the numbers are positions in the
166
+ * shape tree, and renumbering them would silently repoint every `parentZIndex`.
167
+ */
168
+ function flatten(harvested, slidePath) {
169
+ return harvested.map((entry, zIndex) => toElement(entry, zIndex, slidePath)).filter((element) => Boolean(element));
170
+ }
171
+ function toElement(entry, zIndex, slidePath) {
172
+ const { shape } = entry;
173
+ const frame = shape.absoluteFrame;
174
+ if (!frame) {
175
+ reportUnresolvable(shape, zIndex, slidePath);
176
+ return null;
177
+ }
178
+ const textFrame = shape.textFrame;
179
+ const paragraphs = textFrame ? textFrame.paragraphs.map((p) => ({ runs: p.runs.map(toRun) })) : [];
180
+ const textRuns = paragraphs.flatMap((paragraph) => paragraph.runs);
181
+ const runText = textRuns.map((run) => run.text).join("");
182
+ const text = (shape.shapeType === "graphicFrame" ? graphicFrameText(shape) : runText).replace(/\s+/g, " ").trim();
183
+ const kind = shape.shapeType === "group" ? "group" : shape.shapeType === "graphicFrame" ? "graphicFrame" : text ? "text" : shape.shapeType === "picture" ? "image" : "shape";
184
+ return {
185
+ id: shape.id ?? zIndex + 1,
186
+ name: shape.name || `${kind} ${zIndex + 1}`,
187
+ kind,
188
+ graphicKind: shape.shapeType === "graphicFrame" ? graphicKindOf(shape) : null,
189
+ zIndex,
190
+ box: {
191
+ x: emuToInches(frame.left),
192
+ y: emuToInches(frame.top),
193
+ w: emuToInches(frame.width),
194
+ h: emuToInches(frame.height)
195
+ },
196
+ rotation: frame.rotation,
197
+ flipH: frame.flipH,
198
+ flipV: frame.flipV,
199
+ parentZIndex: entry.parentZIndex,
200
+ childZIndices: entry.childZIndices,
201
+ text,
202
+ textWrap: textFrame?.bodyProperties?.wrap ?? null,
203
+ autofit: textFrame?.autofit ?? null,
204
+ autofitFontScale: textFrame?.autofitFontScale ?? null,
205
+ bodyInsets: readBodyInsets(textFrame),
206
+ textRuns,
207
+ paragraphs,
208
+ fontSizes: [...new Set(textRuns.map((run) => run.fontSizePt).filter((size) => size !== null))],
209
+ colors: [...new Set(textRuns.map((run) => run.color).filter((color) => Boolean(color)))],
210
+ fill: shape.fillColor,
211
+ line: shape.lineColor,
212
+ shapeType: shape.presetGeometry
213
+ };
214
+ }
215
+ /**
216
+ * What a graphic frame hosts, from the same `a:graphicData/@uri` the read model's
217
+ * `has*` predicates compare against. A frame that answers none of them is `'other'`
218
+ * rather than dropped: a box the deck's author placed is on the slide whether or not
219
+ * this library models its payload, and an overlap or coverage check that skipped it
220
+ * would report a gap where a 3D model or an OLE object sits.
221
+ */
222
+ function graphicKindOf(frame) {
223
+ if (frame.hasTable) return "table";
224
+ if (frame.hasChart) return "chart";
225
+ if (frame.hasChartEx) return "chartEx";
226
+ if (frame.hasDiagram) return "diagram";
227
+ return "other";
228
+ }
229
+ /**
230
+ * The text a graphic frame puts on the slide: table cells in row order, or SmartArt
231
+ * node text. Charts contribute nothing, matching `Slide.text` on the read model — a
232
+ * chart's strings are data labels and axis titles that PowerPoint itself does not
233
+ * treat as slide body text.
234
+ *
235
+ * Separators are single spaces rather than the read model's ` `/`
236
+ `, because the
237
+ * caller collapses whitespace anyway; the point here is only that cells do not run
238
+ * together into one word.
239
+ */
240
+ function graphicFrameText(frame) {
241
+ const table = frame.table;
242
+ if (table) return table.rows.map((row) => row.cells.map((cell) => cell.text).join(" ")).join(" ");
243
+ return frame.diagram?.text ?? "";
244
+ }
245
+ /** Project one read-model {@link Run} onto the flat run shape. */
246
+ function toRun(run) {
247
+ return {
248
+ text: run.text,
249
+ fontSizePt: run.fontSizePt,
250
+ color: run.color,
251
+ fontFace: run.fontName,
252
+ bold: run.bold ?? false,
253
+ italic: run.italic ?? false,
254
+ strike: run.strike,
255
+ highlight: run.highlight?.hex ?? null,
256
+ charSpacingPt: run.charSpacingPt
257
+ };
258
+ }
259
+ const DEFAULT_INSET_LR_IN = .1;
260
+ const DEFAULT_INSET_TB_IN = .05;
261
+ const POINTS_PER_INCH = 72;
262
+ function readBodyInsets(textFrame) {
263
+ const insets = textFrame?.bodyProperties?.insetsPt;
264
+ if (!insets) return null;
265
+ const inches = (pt, fallback) => pt === void 0 ? fallback : pt / POINTS_PER_INCH;
266
+ return {
267
+ left: inches(insets.left, DEFAULT_INSET_LR_IN),
268
+ top: inches(insets.top, DEFAULT_INSET_TB_IN),
269
+ right: inches(insets.right, DEFAULT_INSET_LR_IN),
270
+ bottom: inches(insets.bottom, DEFAULT_INSET_TB_IN)
271
+ };
272
+ }
273
+ /** Warn about a shape whose slide position cannot be resolved, unless it never claimed one. */
274
+ function reportUnresolvable(shape, zIndex, slidePath) {
275
+ const element = shape.element_;
276
+ if (!hasBox(ownTransform(element), "a:off", "a:ext")) return;
277
+ const who = shape.name ? `"${shape.name}"` : `the element at zIndex ${zIndex}`;
278
+ if (enclosingGroupLacksTransform(element)) {
279
+ warn("inspect/group-transform-missing", `inspect: skipped ${who} on ${slidePath} — an enclosing group has no usable a:xfrm, so its slide position cannot be resolved.`);
280
+ return;
281
+ }
282
+ warn("inspect/group-transform-degenerate", `inspect: skipped ${who} on ${slidePath} — an enclosing group has a degenerate transform (zero a:chExt), so its slide position cannot be resolved.`);
283
+ }
284
+ /** The element's own `a:xfrm` — on `p:grpSpPr` for a group, `p:spPr` for every other kind. */
285
+ function ownTransform(element) {
286
+ const props = firstChild(element, element.localName === "grpSp" ? "p:grpSpPr" : "p:spPr");
287
+ return props && firstChild(props, "a:xfrm");
288
+ }
289
+ /** Whether any enclosing `p:grpSp` fails to state a complete child-space mapping. */
290
+ function enclosingGroupLacksTransform(element) {
291
+ for (let node = element.parentNode; node && node.nodeType === 1; node = node.parentNode) {
292
+ const parent = node;
293
+ if (parent.namespaceURI !== OOXML_NS.p || parent.localName !== "grpSp") return false;
294
+ const xfrm = ownTransform(parent);
295
+ if (!hasBox(xfrm, "a:off", "a:ext") || !hasBox(xfrm, "a:chOff", "a:chExt")) return true;
296
+ }
297
+ return false;
298
+ }
299
+ /** Whether a transform states a complete position + extent pair. */
300
+ function hasBox(xfrm, offName, extName) {
301
+ if (!xfrm) return false;
302
+ const off = firstChild(xfrm, offName);
303
+ const ext = firstChild(xfrm, extName);
304
+ if (!off || !ext) return false;
305
+ return intValue(attr(off, "x")) !== null && intValue(attr(off, "y")) !== null && intValue(attr(ext, "cx")) !== null && intValue(attr(ext, "cy")) !== null;
306
+ }
307
+ function countWords(text) {
308
+ return text.split(/\s+/).filter(Boolean).length;
309
+ }
310
+ function round(value, digits) {
311
+ const factor = 10 ** digits;
312
+ return Math.round(value * factor) / factor;
313
+ }
314
+ //#endregion
315
+ export { DEFAULT_INSPECT_SLIDE_SIZE, InternalError, InvalidOptionError, MediaError, PackageReadError, TsPptxError, UnsupportedFeatureError, boxAnchor, extractSlides, inspectPptx, listPptxParts, loadPptxPackage, overlapArea, readPptxBinaryPart, readPptxTextPart, readPresentationSize };
316
+
317
+ //# sourceMappingURL=inspect.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"inspect.js","names":[],"sources":["../src/inspect.ts"],"sourcesContent":["/**\n * A cheap, flat snapshot of what a `.pptx` contains: every element on every\n * slide, with its slide-absolute box and the handful of text/fill properties a\n * layout audit asks about.\n *\n * It is a **projection over `ts-pptx/read`**, not a second reader. `read` gives a\n * navigable, mutable model of a package and answers questions in the shape of the\n * OOXML tree; this answers one flat question — \"what is on the slides, and where\"\n * — in the shape a linter, an overlap check, or a diffing tool wants. The two used\n * to be independent implementations over two different XML parsers, which meant\n * every read-side fix had to be made twice and a divergence between them was\n * invisible to every test. Now the model below is the only reader, and this file\n * is the flattening.\n *\n * What it deliberately does NOT do, and why the projection is not just\n * `Presentation` re-exported:\n * - **Only geometry a shape carries itself.** A placeholder that inherits its box\n * from the layout is omitted rather than resolved (`absoluteFrame`, not\n * `resolvedFrame`) — the snapshot reports what the slide states.\n * - **A `p:graphicFrame` is a box, not its contents.** A table, chart or SmartArt\n * graphic is reported as one element with its box, its kind, and the text a\n * reader sees on the slide, but its structure is not flattened: no per-run\n * formatting, no cells, no series. Walk `ts-pptx/read` for what is inside one.\n */\nimport { warn } from './diagnostics.js'\nimport { OpcPackage } from './read/opc/package.js'\nimport { Presentation } from './read/api/presentation.js'\nimport type { AnyShape } from './read/api/shapes.js'\nimport type { GraphicFrame } from './read/api/shapes/graphic-frame.js'\nimport type { Run, TextFrame } from './read/api/text.js'\nimport { ELEMENT_NODE, OOXML_NS, attr, firstChild, intValue, type Element } from './read/oxml/dom.js'\nimport { STANDARD_LAYOUTS, emuToInches } from './units.js'\n\n/**\n * Input to the inspect surface. A `string` is a **filesystem path** (Node) read\n * from disk; pass `Uint8Array`/`ArrayBuffer`/`Blob`/`number[]` for an in-memory\n * archive. (A string is a path, not JSZip's latin1 binary content — see\n * {@link ZipInput}.)\n */\ntype PptxInspectInputValue = string | number[] | Uint8Array | ArrayBuffer | Blob\n\nexport type PptxInspectInput = PptxInspectInputValue | Promise<PptxInspectInputValue>\n\nexport interface PptxSlideSize {\n\twidthIn: number\n\theightIn: number\n}\n\nexport interface PptxBox {\n\tx: number\n\ty: number\n\tw: number\n\th: number\n}\n\nexport interface PptxTextRun {\n\ttext: string\n\tfontSizePt: number | null\n\tcolor: string | null\n\t/** Run font face (`a:rPr > a:latin@typeface`), or null when it inherits from the theme/placeholder. */\n\tfontFace: string | null\n\t/** Bold (`a:rPr@b`). */\n\tbold: boolean\n\t/** Italic (`a:rPr@i`). */\n\titalic: boolean\n\t/** Strikethrough token (`a:rPr@strike`: `noStrike`/`sngStrike`/`dblStrike`), or null when unset. */\n\tstrike: string | null\n\t/** Highlight colour hex (`a:rPr > a:highlight`), or null when unset. A theme token is resolved against the slide's theme. */\n\thighlight: string | null\n\t/** Character spacing in points (`a:rPr@spc`, authored in hundredths of a point), or null when unset. */\n\tcharSpacingPt: number | null\n}\n\n/**\n * One paragraph (`a:p`): its runs in document order. Preserves the paragraph/line\n * boundaries that the flat {@link PptxSlideElement.textRuns} list discards — needed\n * to measure a `wrap=\"none\"` frame line-by-line (each paragraph is one unwrapped line).\n */\nexport interface PptxParagraph {\n\truns: PptxTextRun[]\n}\n\n/**\n * What an element is. `'group'` is a `p:grpSp` container: it has its own identity,\n * box, and fill, but no text of its own — its content is the elements that name it\n * in {@link PptxSlideElement.parentZIndex}. `'graphicFrame'` is a `p:graphicFrame`\n * hosting a table, a chart or a SmartArt graphic; {@link PptxSlideElement.graphicKind}\n * says which, and it keeps that kind even when it carries text (a `'text'` element is\n * always a `p:sp`).\n */\nexport type PptxSlideElementKind = 'text' | 'image' | 'shape' | 'group' | 'graphicFrame'\n\n/**\n * What a `'graphicFrame'` element hosts, read from its `a:graphicData/@uri`:\n * a table (`a:tbl`), a classic chart (`c:chart`), a 2016-family chart\n * (`cx:chartSpace`: waterfall/funnel/treemap/…), or a SmartArt diagram. `'other'`\n * is a frame whose URI matches none of those — an OLE object, an ink part, a 3D\n * model — reported as a box so it is not silently missing from the slide.\n */\nexport type PptxGraphicKind = 'table' | 'chart' | 'chartEx' | 'diagram' | 'other'\n\n/**\n * Vertical-autofit mode of a text frame, read from the `a:bodyPr` child element:\n * - `'none'`: no autofit (`a:noAutofit`, or no autofit child at all). The box has a\n * fixed height the text must fit inside — a genuine overflow candidate.\n * - `'normAutofit'`: shrink text to fit (`a:normAutofit`, ts-pptx `fit: 'shrink'`).\n * Text is downscaled rather than overflowing.\n * - `'spAutoFit'`: resize shape to fit text (`a:spAutoFit`, ts-pptx `fit: 'resize'`).\n * The authored height is an output, not a constraint, so the box cannot overflow.\n */\nexport type PptxAutofitMode = 'none' | 'normAutofit' | 'spAutoFit'\n\n/**\n * Text-frame body insets in inches (`a:bodyPr` `lIns`/`tIns`/`rIns`/`bIns`), with\n * PowerPoint defaults applied when an attribute is absent (0.1in left/right,\n * 0.05in top/bottom). Subtract these from {@link PptxBox} to get the inner text box.\n */\nexport interface PptxBodyInsets {\n\tleft: number\n\ttop: number\n\tright: number\n\tbottom: number\n}\n\nexport interface PptxSlideElement {\n\tid: string | number\n\tname: string\n\tkind: PptxSlideElementKind\n\t/**\n\t * What a `'graphicFrame'` element hosts, or `null` for every other kind. See\n\t * {@link PptxGraphicKind}.\n\t */\n\tgraphicKind: PptxGraphicKind | null\n\t/**\n\t * Paint order on the slide, `0`-based: the element's position in a depth-first\n\t * walk of `p:spTree` in document order. A group is immediately followed by its\n\t * own children, which is also the order PowerPoint paints them, so a higher\n\t * `zIndex` draws on top. Unique within a slide, which is what\n\t * {@link parentZIndex} / {@link childZIndices} key on.\n\t */\n\tzIndex: number\n\t/**\n\t * Position and size in **slide-absolute** inches, composing every enclosing\n\t * group transform — directly comparable across elements whether or not they are\n\t * grouped. For a rotated element this is the unrotated placement box (the box\n\t * PowerPoint writes after Ungroup); see {@link rotation}.\n\t */\n\tbox: PptxBox\n\t/**\n\t * Effective clockwise rotation in degrees, normalised to `[0, 360)`, after\n\t * composing the element's own `a:xfrm@rot` with every enclosing group rotation.\n\t */\n\trotation: number\n\t/** Effective horizontal flip, XOR-composing the element's own `@flipH` with enclosing group flips. */\n\tflipH: boolean\n\t/** Effective vertical flip, XOR-composing the element's own `@flipV` with enclosing group flips. */\n\tflipV: boolean\n\t/** {@link zIndex} of the enclosing `'group'` element, or `null` when the element sits at slide level. */\n\tparentZIndex: number | null\n\t/** {@link zIndex} of each direct child, in document order. Empty unless {@link kind} is `'group'`. */\n\tchildZIndices: number[]\n\t/**\n\t * The element's text, whitespace-collapsed to one line. For a `'graphicFrame'`\n\t * this is the text the structure puts on the slide (table cells in row order,\n\t * SmartArt node text), which is what {@link PptxSlideInspection.text} and\n\t * `wordCount` then count; a chart contributes nothing, matching `Slide.text` on\n\t * the read model. That text has no {@link textRuns} or {@link paragraphs} here —\n\t * per-run formatting inside a structure is what this surface does not flatten.\n\t */\n\ttext: string\n\ttextWrap: string | null\n\tautofit: PptxAutofitMode | null\n\t/**\n\t * Baked shrink scale from `<a:normAutofit@fontScale>` as a percent (62.5 = 62.5%),\n\t * or null when the frame has no `normAutofit` or bakes no scale (a bare\n\t * `<a:normAutofit/>`, which PowerPoint draws at 100% until edited).\n\t */\n\tautofitFontScale: number | null\n\tbodyInsets: PptxBodyInsets | null\n\ttextRuns: PptxTextRun[]\n\t/** Runs grouped by their source paragraph (`a:p`), in document order. */\n\tparagraphs: PptxParagraph[]\n\tfontSizes: number[]\n\tcolors: string[]\n\tfill: string | null\n\tline: string | null\n\tshapeType: string | null\n}\n\nexport interface PptxSlideInspection {\n\tindex: number\n\tname: string\n\tpath: string\n\tsize: PptxSlideSize\n\telements: PptxSlideElement[]\n\ttext: string\n\twordCount: number\n}\n\nexport interface PptxInspection {\n\tslideSize: PptxSlideSize\n\tslides: PptxSlideInspection[]\n}\n\nexport type PptxBoxAxis = 'x' | 'y'\nexport type PptxBoxAnchor = 'left' | 'center' | 'right' | 'top' | 'middle' | 'bottom'\n\nexport const DEFAULT_INSPECT_SLIDE_SIZE: PptxSlideSize = Object.freeze({\n\twidthIn: round(STANDARD_LAYOUTS.LAYOUT_WIDE.widthIn, 3),\n\theightIn: STANDARD_LAYOUTS.LAYOUT_WIDE.heightIn,\n})\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Package layer\n *\n * Thin conveniences over `OpcPackage`, kept because this surface speaks zip\n * paths (`ppt/slides/slide1.xml`) while OPC speaks partnames (`/ppt/...`), and\n * because reaching a part's bytes is the one thing a caller of a *flat* surface\n * still routinely needs.\n * ──────────────────────────────────────────────────────────────────────────── */\n\n/**\n * Load a `.pptx` as an {@link OpcPackage} — the same package model `ts-pptx/read`\n * uses, so a caller that starts here can hand the result straight to\n * `Presentation.fromPackage()` without re-reading the bytes.\n *\n * The input must be a real OPC package: a zip that merely contains some slide XML\n * but no `[Content_Types].xml` is rejected with a `PackageReadError`.\n */\nexport async function loadPptxPackage(input: PptxInspectInput): Promise<OpcPackage> {\n\treturn OpcPackage.load(await input)\n}\n\n/** Every part in the package, as zip paths (`ppt/slides/slide1.xml`), sorted. */\nexport function listPptxParts(pptxPackage: OpcPackage): string[] {\n\treturn [...pptxPackage.parts.keys()].map(zipPathOf).sort()\n}\n\n/** Read a package part as UTF-8 text, or `null` when the part is absent. */\nexport async function readPptxTextPart(pptxPackage: OpcPackage, path: string): Promise<string | null> {\n\tconst bytes = await readPptxBinaryPart(pptxPackage, path)\n\treturn bytes ? textDecoder.decode(bytes) : null\n}\n\n/**\n * Read a package part as raw bytes — the binary sibling of {@link readPptxTextPart}\n * for embedded media (SVG/PNG/EMF blobs, fonts, …) that must not be UTF-8 decoded.\n * Returns `null` when the part is absent. The `Uint8Array` is browser-isomorphic;\n * Node consumers can wrap it with `Buffer.from(...)` if they need Buffer methods.\n */\nexport async function readPptxBinaryPart(pptxPackage: OpcPackage, path: string): Promise<Uint8Array | null> {\n\treturn pptxPackage.part(partNameOf(path))?.bytes ?? null\n}\n\nconst textDecoder = new TextDecoder('utf-8')\n\n/** OPC partnames are absolute (`/ppt/…`); this surface speaks zip paths (`ppt/…`). */\nfunction zipPathOf(partName: string): string {\n\treturn partName.startsWith('/') ? partName.slice(1) : partName\n}\n\nfunction partNameOf(zipPath: string): string {\n\treturn zipPath.startsWith('/') ? zipPath : `/${zipPath}`\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * The surface\n * ──────────────────────────────────────────────────────────────────────────── */\n\nexport async function inspectPptx(input: PptxInspectInput): Promise<PptxInspection> {\n\tconst pptxPackage = await loadPptxPackage(input)\n\tconst slideSize = await readPresentationSize(pptxPackage)\n\tconst slides = await extractSlides(pptxPackage, slideSize)\n\treturn { slideSize, slides }\n}\n\nexport async function readPresentationSize(\n\tpptxPackage: OpcPackage,\n\tfallback: PptxSlideSize = DEFAULT_INSPECT_SLIDE_SIZE\n): Promise<PptxSlideSize> {\n\tconst size = presentationOf(pptxPackage)?.slideSize\n\tif (!size) return fallback\n\treturn { widthIn: round(size.widthIn, 3), heightIn: round(size.heightIn, 3) }\n}\n\n/**\n * Every slide in the deck, in **presentation order** (`p:sldIdLst`) — the order\n * PowerPoint shows them in, which is not the order their parts are named once a\n * deck has been reordered.\n */\nexport async function extractSlides(pptxPackage: OpcPackage, size?: PptxSlideSize): Promise<PptxSlideInspection[]> {\n\tconst slideSize = size || (await readPresentationSize(pptxPackage))\n\tconst presentation = presentationOf(pptxPackage)\n\tif (!presentation) return []\n\n\treturn presentation.slides.map((slide, index) => {\n\t\tconst path = zipPathOf(slide.partName)\n\t\tconst harvested: HarvestedShape[] = []\n\t\tharvest(slide.shapes, null, harvested) // slide level: no enclosing group\n\t\tconst elements = flatten(harvested, path)\n\t\tconst text = elements\n\t\t\t.map((el) => el.text)\n\t\t\t.filter(Boolean)\n\t\t\t.join(' ')\n\n\t\treturn {\n\t\t\tindex,\n\t\t\tname: slide.name || `Slide ${index + 1}`,\n\t\t\tpath,\n\t\t\tsize: slideSize,\n\t\t\telements,\n\t\t\ttext,\n\t\t\twordCount: countWords(text),\n\t\t}\n\t})\n}\n\n/**\n * The deck's `Presentation`, or `null` when the package holds no readable\n * `presentation.xml`. Callers here are auditing files they did not author, so a\n * package that is a valid OPC container but not a presentation reports an empty\n * deck rather than throwing. `presentationPart` is the throw site: it rejects a\n * package with no — or more than one — office-document relationship.\n */\nfunction presentationOf(pptxPackage: OpcPackage): Presentation | null {\n\tconst presentation = Presentation.fromPackage(pptxPackage)\n\ttry {\n\t\treturn presentation.presentationPart.isXmlPart ? presentation : null\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function overlapArea(a: PptxBox, b: PptxBox): number {\n\tconst x = Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x))\n\tconst y = Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y))\n\treturn x * y\n}\n\nexport function boxAnchor(box: PptxBox, anchor: PptxBoxAnchor, axis: PptxBoxAxis): number {\n\tif (axis === 'x') {\n\t\tif (anchor === 'left') return box.x\n\t\tif (anchor === 'right') return box.x + box.w\n\t\treturn box.x + box.w / 2\n\t}\n\tif (anchor === 'top') return box.y\n\tif (anchor === 'bottom') return box.y + box.h\n\treturn box.y + box.h / 2\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Shape-tree harvest\n * ──────────────────────────────────────────────────────────────────────────── */\n\n/** One harvested shape, before it is flattened into a {@link PptxSlideElement}. */\ninterface HarvestedShape {\n\tshape: AnyShape\n\tparentZIndex: number | null\n\tchildZIndices: number[]\n}\n\n/**\n * Flatten a shape list depth-first in document order: each shape is followed by\n * its descendants, which is both paint order and the order the\n * {@link PptxSlideElement.zIndex} contract promises. Every entry's index in `out`\n * is its zIndex. Returns the zIndices assigned at this level, which is what the\n * enclosing group records as its {@link PptxSlideElement.childZIndices}.\n */\nfunction harvest(shapes: AnyShape[], parentZIndex: number | null, out: HarvestedShape[]): number[] {\n\tconst zIndices: number[] = []\n\tfor (const shape of shapes) {\n\t\tconst entry: HarvestedShape = { shape, parentZIndex, childZIndices: [] }\n\t\tconst zIndex = out.push(entry) - 1\n\t\tzIndices.push(zIndex)\n\t\tif (shape.shapeType === 'group') entry.childZIndices = harvest(shape.shapes, zIndex, out)\n\t}\n\treturn zIndices\n}\n\n/**\n * Turn harvested shapes into elements, dropping the ones with no resolvable slide\n * position. A dropped shape keeps its zIndex — the numbers are positions in the\n * shape tree, and renumbering them would silently repoint every `parentZIndex`.\n */\nfunction flatten(harvested: HarvestedShape[], slidePath: string): PptxSlideElement[] {\n\treturn harvested\n\t\t.map((entry, zIndex) => toElement(entry, zIndex, slidePath))\n\t\t.filter((element): element is PptxSlideElement => Boolean(element))\n}\n\nfunction toElement(entry: HarvestedShape, zIndex: number, slidePath: string): PptxSlideElement | null {\n\tconst { shape } = entry\n\tconst frame = shape.absoluteFrame\n\tif (!frame) {\n\t\treportUnresolvable(shape, zIndex, slidePath)\n\t\treturn null\n\t}\n\n\t// Only `p:sp` holds a text body, so every other kind projects as an empty frame.\n\tconst textFrame = shape.textFrame\n\tconst paragraphs = textFrame ? textFrame.paragraphs.map((p) => ({ runs: p.runs.map(toRun) })) : []\n\tconst textRuns = paragraphs.flatMap((paragraph) => paragraph.runs)\n\t// A graphic frame has no text body of its own; its text comes from the structure\n\t// it hosts, and arrives as a plain string with no runs behind it.\n\tconst runText = textRuns.map((run) => run.text).join('')\n\tconst raw = shape.shapeType === 'graphicFrame' ? graphicFrameText(shape) : runText\n\t// Deliberately not `TextFrame.text`: this is one whitespace-collapsed line for\n\t// matching and word-counting, not the frame's text with its line structure.\n\tconst text = raw.replace(/\\s+/g, ' ').trim()\n\tconst kind: PptxSlideElementKind =\n\t\tshape.shapeType === 'group'\n\t\t\t? 'group'\n\t\t\t: shape.shapeType === 'graphicFrame'\n\t\t\t\t? 'graphicFrame'\n\t\t\t\t: text\n\t\t\t\t\t? 'text'\n\t\t\t\t\t: shape.shapeType === 'picture'\n\t\t\t\t\t\t? 'image'\n\t\t\t\t\t\t: 'shape'\n\n\treturn {\n\t\tid: shape.id ?? zIndex + 1,\n\t\tname: shape.name || `${kind} ${zIndex + 1}`,\n\t\tkind,\n\t\tgraphicKind: shape.shapeType === 'graphicFrame' ? graphicKindOf(shape) : null,\n\t\tzIndex,\n\t\tbox: {\n\t\t\tx: emuToInches(frame.left),\n\t\t\ty: emuToInches(frame.top),\n\t\t\tw: emuToInches(frame.width),\n\t\t\th: emuToInches(frame.height),\n\t\t},\n\t\trotation: frame.rotation,\n\t\tflipH: frame.flipH,\n\t\tflipV: frame.flipV,\n\t\tparentZIndex: entry.parentZIndex,\n\t\tchildZIndices: entry.childZIndices,\n\t\ttext,\n\t\ttextWrap: textFrame?.bodyProperties?.wrap ?? null,\n\t\tautofit: textFrame?.autofit ?? null,\n\t\tautofitFontScale: textFrame?.autofitFontScale ?? null,\n\t\tbodyInsets: readBodyInsets(textFrame),\n\t\ttextRuns,\n\t\tparagraphs,\n\t\tfontSizes: [...new Set(textRuns.map((run) => run.fontSizePt).filter((size): size is number => size !== null))],\n\t\tcolors: [...new Set(textRuns.map((run) => run.color).filter((color): color is string => Boolean(color)))],\n\t\tfill: shape.fillColor,\n\t\tline: shape.lineColor,\n\t\tshapeType: shape.presetGeometry,\n\t}\n}\n\n/**\n * What a graphic frame hosts, from the same `a:graphicData/@uri` the read model's\n * `has*` predicates compare against. A frame that answers none of them is `'other'`\n * rather than dropped: a box the deck's author placed is on the slide whether or not\n * this library models its payload, and an overlap or coverage check that skipped it\n * would report a gap where a 3D model or an OLE object sits.\n */\nfunction graphicKindOf(frame: GraphicFrame): PptxGraphicKind {\n\tif (frame.hasTable) return 'table'\n\tif (frame.hasChart) return 'chart'\n\tif (frame.hasChartEx) return 'chartEx'\n\tif (frame.hasDiagram) return 'diagram'\n\treturn 'other'\n}\n\n/**\n * The text a graphic frame puts on the slide: table cells in row order, or SmartArt\n * node text. Charts contribute nothing, matching `Slide.text` on the read model — a\n * chart's strings are data labels and axis titles that PowerPoint itself does not\n * treat as slide body text.\n *\n * Separators are single spaces rather than the read model's `\t`/`\n`, because the\n * caller collapses whitespace anyway; the point here is only that cells do not run\n * together into one word.\n */\nfunction graphicFrameText(frame: GraphicFrame): string {\n\tconst table = frame.table\n\tif (table) return table.rows.map((row) => row.cells.map((cell) => cell.text).join(' ')).join(' ')\n\treturn frame.diagram?.text ?? ''\n}\n\n/** Project one read-model {@link Run} onto the flat run shape. */\nfunction toRun(run: Run): PptxTextRun {\n\treturn {\n\t\ttext: run.text,\n\t\tfontSizePt: run.fontSizePt,\n\t\tcolor: run.color,\n\t\tfontFace: run.fontName,\n\t\t// The read model distinguishes \"explicitly not bold\" from \"unset, inherits\";\n\t\t// this surface reports what renders, so an unset flag is `false`.\n\t\tbold: run.bold ?? false,\n\t\titalic: run.italic ?? false,\n\t\tstrike: run.strike,\n\t\thighlight: run.highlight?.hex ?? null,\n\t\tcharSpacingPt: run.charSpacingPt,\n\t}\n}\n\n// PowerPoint body-inset defaults (ECMA-376 §21.1.2.1.1 prose; the XSD leaves\n// lIns/tIns/rIns/bIns optional with no schema default): 0.1in left/right,\n// 0.05in top/bottom. The read model reports only the explicitly-set sides.\nconst DEFAULT_INSET_LR_IN = 0.1\nconst DEFAULT_INSET_TB_IN = 0.05\nconst POINTS_PER_INCH = 72\n\nfunction readBodyInsets(textFrame: TextFrame | null): PptxBodyInsets | null {\n\tconst insets = textFrame?.bodyProperties?.insetsPt\n\tif (!insets) return null\n\tconst inches = (pt: number | undefined, fallback: number): number =>\n\t\tpt === undefined ? fallback : pt / POINTS_PER_INCH\n\treturn {\n\t\tleft: inches(insets.left, DEFAULT_INSET_LR_IN),\n\t\ttop: inches(insets.top, DEFAULT_INSET_TB_IN),\n\t\tright: inches(insets.right, DEFAULT_INSET_LR_IN),\n\t\tbottom: inches(insets.bottom, DEFAULT_INSET_TB_IN),\n\t}\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n * Unresolvable positions\n *\n * `absoluteFrame` reports `null` for three different situations, and only two of\n * them are worth telling the caller about. The distinction is not recoverable\n * from the `null`, so it is re-derived here from the same ancestry the read model\n * walks.\n * ──────────────────────────────────────────────────────────────────────────── */\n\n/** Warn about a shape whose slide position cannot be resolved, unless it never claimed one. */\nfunction reportUnresolvable(shape: AnyShape, zIndex: number, slidePath: string): void {\n\tconst element = shape.element_\n\t// No own `a:xfrm` at all: the shape inherits its geometry from a layout\n\t// placeholder, which this surface deliberately does not resolve. Nothing is\n\t// wrong with the deck, so nothing is reported.\n\tif (!hasBox(ownTransform(element), 'a:off', 'a:ext')) return\n\n\tconst who = shape.name ? `\"${shape.name}\"` : `the element at zIndex ${zIndex}`\n\tif (enclosingGroupLacksTransform(element)) {\n\t\twarn(\n\t\t\t'inspect/group-transform-missing',\n\t\t\t`inspect: skipped ${who} on ${slidePath} — an enclosing group has no usable a:xfrm, so its slide position cannot be resolved.`\n\t\t)\n\t\treturn\n\t}\n\twarn(\n\t\t'inspect/group-transform-degenerate',\n\t\t`inspect: skipped ${who} on ${slidePath} — an enclosing group has a degenerate transform (zero a:chExt), so its slide position cannot be resolved.`\n\t)\n}\n\n/** The element's own `a:xfrm` — on `p:grpSpPr` for a group, `p:spPr` for every other kind. */\nfunction ownTransform(element: Element): Element | null {\n\tconst props = firstChild(element, element.localName === 'grpSp' ? 'p:grpSpPr' : 'p:spPr')\n\treturn props && firstChild(props, 'a:xfrm')\n}\n\n/** Whether any enclosing `p:grpSp` fails to state a complete child-space mapping. */\nfunction enclosingGroupLacksTransform(element: Element): boolean {\n\tfor (let node = element.parentNode; node && node.nodeType === ELEMENT_NODE; node = node.parentNode) {\n\t\tconst parent = node as Element\n\t\tif (parent.namespaceURI !== OOXML_NS.p || parent.localName !== 'grpSp') return false // reached the shape tree\n\t\tconst xfrm = ownTransform(parent)\n\t\tif (!hasBox(xfrm, 'a:off', 'a:ext') || !hasBox(xfrm, 'a:chOff', 'a:chExt')) return true\n\t}\n\treturn false\n}\n\n/** Whether a transform states a complete position + extent pair. */\nfunction hasBox(xfrm: Element | null, offName: string, extName: string): boolean {\n\tif (!xfrm) return false\n\tconst off = firstChild(xfrm, offName)\n\tconst ext = firstChild(xfrm, extName)\n\tif (!off || !ext) return false\n\treturn (\n\t\tintValue(attr(off, 'x')) !== null &&\n\t\tintValue(attr(off, 'y')) !== null &&\n\t\tintValue(attr(ext, 'cx')) !== null &&\n\t\tintValue(attr(ext, 'cy')) !== null\n\t)\n}\n\nfunction countWords(text: string): number {\n\treturn text.split(/\\s+/).filter(Boolean).length\n}\n\nfunction round(value: number, digits: number): number {\n\tconst factor = 10 ** digits\n\treturn Math.round(value * factor) / factor\n}\n\n// Error taxonomy — see `entry-errors.ts`. Re-exported from every entry so `instanceof`\n// works whichever subpath a consumer imports.\nexport * from './entry-errors.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+MA,MAAa,6BAA4C,OAAO,OAAO;CACtE,SAAS,MAAM,iBAAiB,YAAY,SAAS,CAAC;CACtD,UAAU,iBAAiB,YAAY;AACxC,CAAC;;;;;;;;;AAmBD,eAAsB,gBAAgB,OAA8C;CACnF,OAAO,WAAW,KAAK,MAAM,KAAK;AACnC;;AAGA,SAAgB,cAAc,aAAmC;CAChE,OAAO,CAAC,GAAG,YAAY,MAAM,KAAK,CAAC,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,KAAK;AAC1D;;AAGA,eAAsB,iBAAiB,aAAyB,MAAsC;CACrG,MAAM,QAAQ,MAAM,mBAAmB,aAAa,IAAI;CACxD,OAAO,QAAQ,YAAY,OAAO,KAAK,IAAI;AAC5C;;;;;;;AAQA,eAAsB,mBAAmB,aAAyB,MAA0C;CAC3G,OAAO,YAAY,KAAK,WAAW,IAAI,CAAC,CAAC,EAAE,SAAS;AACrD;AAEA,MAAM,cAAc,IAAI,YAAY,OAAO;;AAG3C,SAAS,UAAU,UAA0B;CAC5C,OAAO,SAAS,WAAW,GAAG,IAAI,SAAS,MAAM,CAAC,IAAI;AACvD;AAEA,SAAS,WAAW,SAAyB;CAC5C,OAAO,QAAQ,WAAW,GAAG,IAAI,UAAU,IAAI;AAChD;AAMA,eAAsB,YAAY,OAAkD;CACnF,MAAM,cAAc,MAAM,gBAAgB,KAAK;CAC/C,MAAM,YAAY,MAAM,qBAAqB,WAAW;CAExD,OAAO;EAAE;EAAW,QAAA,MADC,cAAc,aAAa,SAAS;CAC9B;AAC5B;AAEA,eAAsB,qBACrB,aACA,WAA0B,4BACD;CACzB,MAAM,OAAO,eAAe,WAAW,CAAC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AC3C;;AAGA,SAAS,6BAA6B,SAA2B;CAChE,KAAK,IAAI,OAAO,QAAQ,YAAY,QAAQ,KAAK,aAAA,GAA2B,OAAO,KAAK,YAAY;EACnG,MAAM,SAAS;EACf,IAAI,OAAO,iBAAiB,SAAS,KAAK,OAAO,cAAc,SAAS,OAAO;EAC/E,MAAM,OAAO,aAAa,MAAM;EAChC,IAAI,CAAC,OAAO,MAAM,SAAS,OAAO,KAAK,CAAC,OAAO,MAAM,WAAW,SAAS,GAAG,OAAO;CACpF;CACA,OAAO;AACR;;AAGA,SAAS,OAAO,MAAsB,SAAiB,SAA0B;CAChF,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,MAAM,WAAW,MAAM,OAAO;CACpC,MAAM,MAAM,WAAW,MAAM,OAAO;CACpC,IAAI,CAAC,OAAO,CAAC,KAAK,OAAO;CACzB,OACC,SAAS,KAAK,KAAK,GAAG,CAAC,MAAM,QAC7B,SAAS,KAAK,KAAK,GAAG,CAAC,MAAM,QAC7B,SAAS,KAAK,KAAK,IAAI,CAAC,MAAM,QAC9B,SAAS,KAAK,KAAK,IAAI,CAAC,MAAM;AAEhC;AAEA,SAAS,WAAW,MAAsB;CACzC,OAAO,KAAK,MAAM,KAAK,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;AAC1C;AAEA,SAAS,MAAM,OAAe,QAAwB;CACrD,MAAM,SAAS,MAAM;CACrB,OAAO,KAAK,MAAM,QAAQ,MAAM,IAAI;AACrC"}
package/dist/math.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { a as TsPptxError, d as InvalidOptionErrorCode, f as MediaErrorCode, h as UnsupportedFeatureErrorCode, i as PackageReadError, l as ErrorCode, m as TsPptxCode, n as InvalidOptionError, o as TsPptxErrorOptions, p as PackageReadErrorCode, r as MediaError, s as UnsupportedFeatureError, t as InternalError, u as InternalErrorCode } from "./errors-PflMPWBn.js";
2
+ //#region src/math.d.ts
3
+ /**
4
+ * Convert a MathML string to OMML for the `math:` option on `addText`.
5
+ *
6
+ * Canonical output form: a bare `<m:oMath>…</m:oMath>` in the `m:` namespace, with no
7
+ * namespace declarations (the `math:` option's envelope supplies the `m` prefix).
8
+ *
9
+ * @param mathml - a MathML string (e.g. `<math>…</math>`)
10
+ * @returns OMML `<m:oMath>…</m:oMath>`
11
+ */
12
+ declare function mathmlToOmml(mathml: string): string;
13
+ interface LatexToOmmlOptions {
14
+ /**
15
+ * Display (block) math: render in `displayMode` and wrap the result in
16
+ * `<m:oMathPara>` (a centered display-math paragraph). Default `true`. When `false`,
17
+ * temml renders in inline mode and the result is a bare `<m:oMath>`.
18
+ */
19
+ display?: boolean;
20
+ }
21
+ /**
22
+ * Convert a LaTeX string to OMML for the `math:` option on `addText`.
23
+ *
24
+ * Display math (the default) is returned as a full `<m:oMathPara>` centered display
25
+ * paragraph; with `{ display: false }` a bare `<m:oMath>` is returned (both forms are
26
+ * accepted by the `math:` option). Throws on invalid LaTeX, surfacing temml's parse
27
+ * position.
28
+ *
29
+ * @param latex - a LaTeX math expression, e.g. `x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}`
30
+ * @param opts - see {@link LatexToOmmlOptions}
31
+ * @returns OMML `<m:oMathPara>…</m:oMathPara>` (display) or `<m:oMath>…</m:oMath>` (inline)
32
+ * @throws {Error} if the LaTeX cannot be parsed
33
+ */
34
+ declare function latexToOmml(latex: string, opts?: LatexToOmmlOptions): string;
35
+ //#endregion
36
+ export { type ErrorCode, InternalError, type InternalErrorCode, InvalidOptionError, type InvalidOptionErrorCode, LatexToOmmlOptions, MediaError, type MediaErrorCode, PackageReadError, type PackageReadErrorCode, type TsPptxCode, TsPptxError, type TsPptxErrorOptions, UnsupportedFeatureError, type UnsupportedFeatureErrorCode, latexToOmml, mathmlToOmml };
37
+ //# sourceMappingURL=math.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"math.d.ts","names":[],"sources":["../src/math.ts"],"mappings":";;;;;;;;;;;iBAwMgB,aAAa;UAKZ;;;;;;EAMhB;;;;;;;;;;;;;;;iBAgBe,YAAY,eAAe,OAAM"}
package/dist/math.js ADDED
@@ -0,0 +1,203 @@
1
+ import { a as TsPptxError, i as PackageReadError, n as InvalidOptionError, o as UnsupportedFeatureError, r as MediaError, t as InternalError } from "./errors-Bvln0H-7.js";
2
+ import { createRequire } from "node:module";
3
+ //#region src/math.ts
4
+ /**
5
+ * `@shbernal/ts-pptx/math` — author display equations in LaTeX or MathML and get
6
+ * OMML for the `math:` option on `addText` (see {@link TextProps.math}).
7
+ *
8
+ * Pipeline: LaTeX --temml--> MathML --mathml2omml--> OMML.
9
+ *
10
+ * Both converters are **optional peer dependencies** (temml is MIT, mathml2omml is
11
+ * LGPL-3.0-or-later); install them to use this subpath:
12
+ *
13
+ * ```sh
14
+ * npm install temml mathml2omml
15
+ * ```
16
+ *
17
+ * This subpath is **Node-only**: it loads the converters synchronously via
18
+ * `node:module`'s `createRequire`, so `latexToOmml()` / `mathmlToOmml()` stay
19
+ * synchronous. Both display and inline (in-sentence) equations are supported: a
20
+ * default `latexToOmml()` returns a centered display `<m:oMathPara>`, while
21
+ * `latexToOmml(tex, { display: false })` (and `mathmlToOmml()`) return the bare
22
+ * `<m:oMath>` form you pass to a text item with `inline: true` to flow it
23
+ * mid-paragraph (see {@link TextProps.inline}).
24
+ *
25
+ * @module
26
+ */
27
+ const nodeRequire = createRequire(import.meta.url);
28
+ const MISSING_DEPS_MESSAGE = "@shbernal/ts-pptx/math requires the optional peer dependencies 'temml' and 'mathml2omml'. Install them with: npm install temml mathml2omml";
29
+ /** Require an optional peer, remapping a not-found error to the install hint. */
30
+ function requirePeer(id) {
31
+ try {
32
+ return nodeRequire(id);
33
+ } catch (err) {
34
+ if (err?.code === "MODULE_NOT_FOUND") throw new UnsupportedFeatureError("math/missing-optional-peer", MISSING_DEPS_MESSAGE, { cause: err });
35
+ throw err;
36
+ }
37
+ }
38
+ let temmlModule;
39
+ let mml2ommlFn;
40
+ function loadTemml() {
41
+ if (!temmlModule) {
42
+ const mod = requirePeer("temml");
43
+ temmlModule = "renderToString" in mod ? mod : mod.default;
44
+ }
45
+ return temmlModule;
46
+ }
47
+ function loadMml2omml() {
48
+ if (!mml2ommlFn) mml2ommlFn = requirePeer("mathml2omml").mml2omml;
49
+ return mml2ommlFn;
50
+ }
51
+ /**
52
+ * mathml2omml puts namespace declarations on the `<m:oMath>` opening tag: `xmlns:m`
53
+ * (redundant — the `<a14:m>` envelope the `math:` option authors already declares it)
54
+ * and `xmlns:w` (unused in the output it produces). Strip them so the result is a bare
55
+ * `<m:oMath>` that drops into the `math:` option cleanly.
56
+ */
57
+ function stripOMathNamespaces(omml) {
58
+ return omml.replace(/^(\s*<m:oMath)\b[^>]*>/, "$1>");
59
+ }
60
+ /** Centered-display paragraph props, matching what the `math:` emitter/oracle author. */
61
+ const DISPLAY_PARA_PR = "<m:oMathParaPr><m:jc m:val=\"centerGroup\"/></m:oMathParaPr>";
62
+ /**
63
+ * The operator-dictionary subset this module has to carry, keyed by the character temml
64
+ * puts in the `<mo>` of an accent and valued by the combining mark OMML wants in `m:chr`.
65
+ *
66
+ * Two halves of one problem. **Which** `<mover>`s are accents: temml renders every accent
67
+ * command as a bare `<mover>` with no `accent="true"`, which is correct for a browser —
68
+ * MathML renderers derive accent positioning from the operator dictionary, so the attribute
69
+ * is redundant there — but mathml2omml has no dictionary and keys strictly off the
70
+ * attribute, mapping a bare `<mover>` to `<m:limUpp>` (an over-*limit*, with limit spacing)
71
+ * instead of `<m:acc>`. Membership in this table is the dictionary lookup that is otherwise
72
+ * missing. **Which character** to attach: mathml2omml passes the `<mo>` text straight
73
+ * through to `m:chr`, and temml emits the *spacing* modifiers (U+02C6 MODIFIER LETTER
74
+ * CIRCUMFLEX, U+2192 RIGHTWARDS ARROW) while ECMA-376 §22.1.2.20 says an `accPr` character
75
+ * "should be within the range of (U+0300–U+036F) or (U+20D0–U+20EF)" — the combining marks,
76
+ * which is also what Word itself writes. Left alone, `\vec{v}` would hang a full-size arrow
77
+ * over the base instead of an arrow accent.
78
+ *
79
+ * Keyed by character rather than by LaTeX command because that is all that survives into
80
+ * the MathML. Derived by rendering every accent command temml documents and reading back
81
+ * the `<mo>` it produced; the commands each entry serves are named in the comments.
82
+ */
83
+ const ACCENT_CHARS = /* @__PURE__ */ new Map([
84
+ ["ˆ", "̂"],
85
+ ["~", "̃"],
86
+ ["´", "́"],
87
+ ["ˊ", "́"],
88
+ ["`", "̀"],
89
+ ["ˋ", "̀"],
90
+ ["¨", "̈"],
91
+ ["˙", "̇"],
92
+ ["‾", "̄"],
93
+ ["ˉ", "̄"],
94
+ ["˘", "̆"],
95
+ ["ˇ", "̌"],
96
+ ["˚", "̊"],
97
+ ["˝", "̋"],
98
+ ["→", "⃗"],
99
+ ["…", "⃛"]
100
+ ]);
101
+ /** An `<mover>`'s last child, when that child is an `<mo>`: `[, attributes, text]`. */
102
+ const TRAILING_MO = /<mo\b([^>]*)>([^<]*)<\/mo>\s*$/;
103
+ /**
104
+ * Stamp `accent="true"` on the `<mover>`s that are accents, and swap their operator for the
105
+ * combining mark OMML wants. See {@link ACCENT_CHARS} for why both are needed.
106
+ *
107
+ * Scoped as narrowly as the defect. Only `<mo stretchy="false">` qualifies, which is how
108
+ * temml distinguishes a true accent from a *wide* one (`\widehat`, `\overrightarrow`) or a
109
+ * group character (`\overbrace`, `\overgroup`) — those already reach `m:groupChr`, which is
110
+ * a reasonable rendering, so they are left alone rather than churned. `\stackrel` is an
111
+ * over-relation whose character comes from the caller, so it stays `m:limUpp` unless the
112
+ * caller happened to stack a diacritic. An `<mover>` that already states `accent` is the
113
+ * author's call and is never rewritten.
114
+ *
115
+ * `<munder>` is deliberately **not** touched. The symmetric-looking fix — stamping
116
+ * `accentunder="true"` — makes mathml2omml emit `<m:acc>`, which is an *over*-accent: it
117
+ * would move `\utilde`'s tilde above the base. OMML has no under-accent object, so the
118
+ * `m:limLow` an under-accent already produces is the closest thing available.
119
+ *
120
+ * Implemented against the tag text rather than through a DOM. temml's output is
121
+ * machine-generated and well-formed, so pairing `<mover>` with `</mover>` on a stack is
122
+ * exact, and this subpath otherwise carries no XML parser — the read path's is a different
123
+ * dependency and pulling it in here would grow the module for one rewrite.
124
+ */
125
+ function markAccentedMovers(mathml) {
126
+ const edits = [];
127
+ const open = [];
128
+ const tags = /<(\/?)mover\b[^>]*>/g;
129
+ for (let tag = tags.exec(mathml); tag !== null; tag = tags.exec(mathml)) {
130
+ if (tag[1] === "") {
131
+ open.push(tag[0].includes("accent=") ? -1 : tag.index);
132
+ continue;
133
+ }
134
+ const openAt = open.pop();
135
+ if (openAt === void 0 || openAt === -1) continue;
136
+ const openEnd = mathml.indexOf(">", openAt) + 1;
137
+ const mo = TRAILING_MO.exec(mathml.slice(openEnd, tag.index));
138
+ if (!mo) continue;
139
+ const [whole, attrs = "", operator = ""] = mo;
140
+ if (!attrs.includes("stretchy=\"false\"")) continue;
141
+ const combining = ACCENT_CHARS.get(operator);
142
+ if (combining === void 0) continue;
143
+ edits.push({
144
+ at: openEnd + mo.index + whole.length - `${operator}</mo>`.length,
145
+ length: operator.length,
146
+ text: combining
147
+ });
148
+ edits.push({
149
+ at: openAt + 6,
150
+ length: 0,
151
+ text: " accent=\"true\""
152
+ });
153
+ }
154
+ let out = mathml;
155
+ for (const edit of edits.sort((a, b) => b.at - a.at)) out = out.slice(0, edit.at) + edit.text + out.slice(edit.at + edit.length);
156
+ return out;
157
+ }
158
+ /**
159
+ * Convert a MathML string to OMML for the `math:` option on `addText`.
160
+ *
161
+ * Canonical output form: a bare `<m:oMath>…</m:oMath>` in the `m:` namespace, with no
162
+ * namespace declarations (the `math:` option's envelope supplies the `m` prefix).
163
+ *
164
+ * @param mathml - a MathML string (e.g. `<math>…</math>`)
165
+ * @returns OMML `<m:oMath>…</m:oMath>`
166
+ */
167
+ function mathmlToOmml(mathml) {
168
+ return stripOMathNamespaces(loadMml2omml()(mathml).trim());
169
+ }
170
+ /**
171
+ * Convert a LaTeX string to OMML for the `math:` option on `addText`.
172
+ *
173
+ * Display math (the default) is returned as a full `<m:oMathPara>` centered display
174
+ * paragraph; with `{ display: false }` a bare `<m:oMath>` is returned (both forms are
175
+ * accepted by the `math:` option). Throws on invalid LaTeX, surfacing temml's parse
176
+ * position.
177
+ *
178
+ * @param latex - a LaTeX math expression, e.g. `x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}`
179
+ * @param opts - see {@link LatexToOmmlOptions}
180
+ * @returns OMML `<m:oMathPara>…</m:oMathPara>` (display) or `<m:oMath>…</m:oMath>` (inline)
181
+ * @throws {Error} if the LaTeX cannot be parsed
182
+ */
183
+ function latexToOmml(latex, opts = {}) {
184
+ const display = opts.display ?? true;
185
+ const temml = loadTemml();
186
+ let mathml;
187
+ try {
188
+ mathml = temml.renderToString(latex, {
189
+ displayMode: display,
190
+ throwOnError: true
191
+ });
192
+ } catch (err) {
193
+ const pe = err;
194
+ const pos = typeof pe.position === "number" ? ` (position ${pe.position})` : "";
195
+ throw new InvalidOptionError("math/invalid-latex", `Invalid LaTeX${pos}: ${pe.message}`, { cause: err });
196
+ }
197
+ const oMath = mathmlToOmml(markAccentedMovers(mathml));
198
+ return display ? `<m:oMathPara>${DISPLAY_PARA_PR}${oMath}</m:oMathPara>` : oMath;
199
+ }
200
+ //#endregion
201
+ export { InternalError, InvalidOptionError, MediaError, PackageReadError, TsPptxError, UnsupportedFeatureError, latexToOmml, mathmlToOmml };
202
+
203
+ //# sourceMappingURL=math.js.map