Skip to content

armgit / bento

Public Imported from GitHub
0

Bento, the office suite that fits in a file

PowerPoint export as a library and command-line tool (#88)

bluegitter80ce26300f2a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b1130a14..39ddb346 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,19 @@ pre-1.0.
## [Unreleased]
+- **Save a deck as PowerPoint, from a terminal.**
+ `node convert/cli.mjs deck.bento.html --to pptx` writes `deck.pptx`, with
+ speaker notes, links, tables, charts, pictures and hidden slides. It reports
+ what it approximated or left out, and on which slides: animations show
+ their final frame, Morph becomes a plain cut, formulas stay as their LaTeX
+ source, and code and embedded documents are not exported yet. It also says
+ which of the deck's own fonts to install, and `--report r.json` saves the
+ full report. It reads a saved deck or its document JSON. Every export is
+ checked before it is written, and a package PowerPoint would want to repair
+ is refused. Export is a library and a command-line tool rather than a
+ button in the app, so every shared file stays small and the app stays
+ focused.
+
- **Long speaker notes scroll in presenter view.** Notes that are taller than
the space beside the current and next slides now get their own vertical
scrollbar instead of being cut off.
diff --git a/convert/CONTRIBUTING.md b/convert/CONTRIBUTING.md
new file mode 100644
index 00000000..da4f1319
--- /dev/null
+++ b/convert/CONTRIBUTING.md
@@ -0,0 +1,176 @@
+# Contributing to convert/ — PowerPoint in and out
+
+`convert/` turns PowerPoint decks into Bento decks and back. It is a library
+and a command-line tool, not part of any app: nothing here ships inside a
+`.bento.html` file. Import came first: you can drop a `.pptx` on
+[bento.page/import](https://bento.page/import). Export is a library and a
+command-line tool, so every shared file stays small and the app stays
+focused.
+
+This guide is for anyone who wants to make the export better. The work is
+split into small pieces; see [Open tasks](#open-tasks).
+
+## What is where
+
+```
+convert/
+ cli.mjs bento convert: the command-line tool
+ src/index.ts the library's public entry (import + export)
+ src/api.ts import: .pptx → .bento.html (bento.page/import uses this)
+ src/export.ts export: .bento.html → .pptx
+ src/pptx.ts … the importer (theme, text, shapes, media, inheritance)
+ src/pptx-write/ the exporter
+ index.ts walks the deck, allocates ids, assembles the package
+ contract.ts the element-writer contract (read this first)
+ text.ts shapes.ts media.ts tables.ts charts.ts one writer per element type
+ code.ts embed.ts writers not written yet (stubs)
+ parts.ts the package skeleton: presentation, masters, layouts, theme, notes
+ src/xmlout.ts builds XML as plain data, escapes everything
+ page/ bento.page/import
+scripts/test-convert/ the rigs (tests); files starting with _ are helpers
+```
+
+## Set up and run
+
+You need Node 23.6 or newer. The rigs are TypeScript run directly by Node; the
+CLI and some rigs bundle with the esbuild that slides already installs.
+
+```sh
+cd slides && npm install && cd .. # once: esbuild and tsc come from here
+node scripts/test-convert.ts # every convert rig
+node scripts/test-convert/pptx-coverage.ts # one rig
+cd slides && node_modules/.bin/tsc -p ../convert # typecheck convert/
+
+# the tool itself
+node convert/cli.mjs deck.bento.html --to pptx # → deck.pptx, report on stderr
+node convert/cli.mjs deck.pptx # → deck.bento.html (needs the network
+ # or --shell slides/dist-single/…)
+```
+
+A deck to try: open bento.page/slides, save it, and export the file. Its
+starter deck uses nearly every element type.
+
+## How export works
+
+1. `bentoToPptx(html)` (`src/export.ts`) pulls the document out of the file
+ and runs it through slides' own `parseDoc`, so the writer only ever sees a
+ document the app would open. Encrypted and compact files are refused with
+ what to do instead.
+2. `exportPptx(doc)` (`pptx-write/index.ts`) walks the slides. Interactive
+ state slides are left out (they are click-reached variants, not slides in
+ the show). For each element it calls that type's **writer**.
+3. A writer turns one element into one PowerPoint shape: a `p:sp` (text,
+ shapes), `p:pic` (pictures) or `p:graphicFrame` (tables, charts). XML is
+ built with `x()` from `xmlout.ts`, which escapes every value.
+4. `index.ts` wires links, records presentation effects once per slide, and
+ writes the package with `parts.ts`: presentation, master, layout, theme,
+ notes, and the property parts PowerPoint expects.
+5. Everything the writers could not carry exactly is in the **fidelity
+ report** that comes back with the bytes.
+
+## The writer contract
+
+`pptx-write/contract.ts` is short; read it before writing a writer. In brief:
+
+- **One node or null.** Return one top-level node whose `p:cNvPr` id is
+ `ctx.shapeId`, or `null` if you emit nothing.
+- **Never throw on content. Report instead.** If the slide will still show
+ something close, add `'approximated'`. If it won't, add `'dropped'`. Use a
+ stable kebab-case code (`code-colours-flattened`) and a detail that says, in
+ plain words, what the person will see in PowerPoint. Returning `null`
+ without a `'dropped'` entry is a silent loss, and the coverage rig fails it.
+- **Package wiring goes through `ctx.media`.** Images and SVG enter the
+ package that way, deduplicated by content. Don't invent relationship ids.
+- **No app imports, no DOM.** The writer runs in Node and in browsers. Read
+ the element and `ctx`, nothing else. `scripts/test-convert/boundary.ts`
+ enforces this.
+- **Deterministic.** Same deck, same bytes. Two exports must be identical.
+- **No new dependencies.** The whole tool is dependency-free on purpose. If a
+ task seems to need one (rasterising SVG, say), open an issue first.
+
+## Testing with the harness
+
+`scripts/test-convert/_export-harness.ts` exports a deck or a single element
+and tells you what is wrong with the package:
+
+```ts
+import { exportOne } from './_export-harness.ts'
+
+const r = await exportOne({
+ type: 'code', fontSize: 18, fontFamily: 'Menlo, monospace', align: 'left',
+ valign: 'top', lineHeight: 1.4, color: '#1E2A3A', content: 'let x = 1\nx += 1',
+})
+r.problems // [] when the package is wired the way PowerPoint checks it
+r.slideXml // the slide part: assert on what your writer emitted
+r.codes // the report's codes, e.g. r.codes.has('code-colours-flattened')
+```
+
+`problems` covers what has bitten this exporter before: broken or dangling
+relationships, parts without a content type, XML that doesn't parse,
+`[Content_Types].xml` not first, missing property parts, and a notes master
+without its own theme. A package can pass the official XML schemas and still
+make PowerPoint offer to repair it; those checks are the gap between the two.
+They live in `pptx-write/verify.ts`, and every export runs them before
+writing the zip: if your writer breaks the package, the export refuses and
+says which part is wrong.
+
+Typefaces go through `pptx-write/fonts.ts` (`typefaceOf`). PowerPoint takes
+one font name, not a CSS stack. Use it rather than taking the stack's first
+family, which may be a CSS generic (`ui-monospace`) or a font only one
+operating system has (`SF Mono`).
+
+Copy the rig shape from `pptx-coverage.ts` (an `ok()` helper, `N/N checks
+passed`, exit 1 on failure). Name your rig `scripts/test-convert/pptx-<thing>.ts`;
+the runner picks it up and CI runs it.
+
+**Prove your checks can fail.** For each important check, break the code on
+purpose once (delete the line that does the thing) and watch the rig go red.
+A check that never failed hasn't been shown to work.
+
+## Walkthrough: writing the `code` writer
+
+1. Open `pptx-write/code.ts`. `CodeElIn` lists the fields you get. The stub
+ reports the element dropped and returns `null`.
+2. Look at `textSp` in `text.ts`. It builds a text box (`p:sp` with
+ `p:txBody`) from a frame, paragraphs and run properties. `emu()` in
+ `shapes.ts` converts px to PowerPoint units.
+3. Build a text box at the element's frame: one paragraph per line of
+ `content`, in the element's font (fall back to `Consolas`), size, colour
+ and alignment. Keep leading spaces: indentation is the point of code.
+4. Syntax colours are optional in a first version. If you leave them out,
+ report it: `ctx.report.add('approximated', 'code-colours-flattened',
+ ctx.where, 'code shows in one colour; syntax highlighting is not exported')`.
+5. In `scripts/test-convert/pptx-coverage.ts`, move `code` from `NOT_YET`
+ to `SAMPLE`/`MAPPED`. The rig now requires one shape and a clean package.
+6. Add `scripts/test-convert/pptx-code.ts` with your own checks: lines become
+ paragraphs, leading spaces survive, `<` and `&` in code are escaped, an
+ empty `content` doesn't crash.
+7. Run `node scripts/test-convert.ts` and the typecheck. Then **open the
+ result in PowerPoint**, the one check no rig can do. Say in your PR which
+ app and version you opened it in (PowerPoint for Mac or Windows, Keynote,
+ LibreOffice, Google Slides).
+
+## Open tasks
+
+Each task is self-contained and has a rig to extend. Tasks marked
+**good first issue** don't need deep knowledge of the format.
+
+| task | where | notes |
+|---|---|---|
+| **Export `code` elements** · good first issue | `pptx-write/code.ts` | the walkthrough above |
+| **Export `embed` elements** · good first issue | `pptx-write/embed.ts` | every embed has an SVG `view`; `svgPic` in `media.ts` already places SVG. Report `approximated` (`embed-static`): the picture travels, the live document doesn't |
+| **Line tip `bar`** · good first issue | `pptx-write/shapes.ts` | a `bar` line end exports as a diamond today (`line-tip-approximated`); find the closest real PowerPoint end, or draw it |
+| **Playable audio and video** | `pptx-write/media.ts` | today only a video's poster exports (`media-dropped`). PowerPoint embeds media as a `p:pic` with a media relationship and timing |
+| **Morph transitions** | `pptx-write/index.ts`, `parts.ts` | PowerPoint's Morph is an extension (`p159:morph` inside `mc:AlternateContent`); slides currently cut (`morph-not-exported`). Bento morphs pair elements by id, so the pairing is already in the deck |
+| **Picture fallback for SVG** | `pptx-write/media.ts` | PowerPoint 2016 shows SVG as a blank frame without a PNG fallback (`svg-no-raster-fallback`). Rasterising needs a renderer: open an issue to discuss before writing code |
+| **Export compact documents** | `src/export.ts` | `bentoToPptx` refuses `compact: true` files; slides' compact loader shows how they expand |
+| **One `bento` command** | `bin/` (new) | a small dispatcher so `bento convert …` and `bento check …` are one tool |
+
+## Before you open a pull request
+
+- `node scripts/test-convert.ts` passes, and the typecheck is clean.
+- Your writer follows `contract.ts`: no throws on content, every loss
+ reported, no app imports, no new dependencies.
+- You opened an exported deck in a real presentation app, and the PR says
+ which one.
+- New files carry the SPDX header used throughout (`MIT`).
diff --git a/convert/cli.mjs b/convert/cli.mjs
index 4e00a5bd..02adfebb 100755
--- a/convert/cli.mjs
+++ b/convert/cli.mjs
@@ -2,14 +2,18 @@
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 The Bento authors
//
-// bento convert — a PowerPoint deck to a bento/slides file, from a terminal.
+// bento convert — PowerPoint in and out, from a terminal.
//
// node convert/cli.mjs <deck.pptx> [-o out.bento.html] [--shell path | --offline]
+// node convert/cli.mjs <deck.bento.html|doc.json> --to pptx [-o out.pptx]
+//
+// Either direction takes --report <file.json>: the full fidelity report, as
+// data, for a script or a bug report.
//
// A leading `convert` is accepted and ignored, so a future `bento` dispatcher
// can call this as `bento convert …` unchanged.
//
-// The deck is written into the CURRENT signed slides shell: the release
+// IMPORT writes the deck into the CURRENT signed slides shell: the release
// manifest's signature is verified, the shell's bytes are checked against the
// signed pin, and a shell that fails either, or is older than
// MIN_SHELL_VERSION, is refused. The document then passes the same
@@ -18,6 +22,11 @@
// (development, air-gapped use; no channel check, and it says so); `--offline`
// refuses the network entirely and requires `--shell`.
//
+// EXPORT (--to pptx) reads a saved deck's #bento-doc block and writes a .pptx.
+// It needs no network. It refuses an encrypted deck, a raw compact document and
+// non-slides files, each with what to do instead. Export is a library and this
+// command, never a button in the app: the writer stays out of every shell.
+//
// The fidelity report goes to STDERR, so stdout stays clean for scripting.
// Exit codes: 0 converted, 1 refused or failed, 2 usage.
//
@@ -44,7 +53,8 @@ process.on('warning', (w) => {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
const USAGE = `usage:
- bento convert <deck.pptx> [-o out.bento.html] [--shell path | --offline]`
+ bento convert <deck.pptx> [-o out.bento.html] [--shell path | --offline] [--report r.json]
+ bento convert <deck.bento.html|doc.json> --to pptx [-o out.pptx] [--report r.json]`
function die(msg, code = 1) {
process.stderr.write(`bento convert: ${msg}\n`)
@@ -54,11 +64,13 @@ function die(msg, code = 1) {
// --- arguments ---------------------------------------------------------------
const argv = process.argv.slice(2)
if (argv[0] === 'convert') argv.shift()
-const opts = { out: null, shell: null, offline: false, input: null }
+const opts = { out: null, to: null, shell: null, offline: false, input: null, report: null }
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
const val = () => (i + 1 < argv.length ? argv[++i] : die(`${a} needs a value\n${USAGE}`, 2))
if (a === '-o' || a === '--out') opts.out = val()
+ else if (a === '--to') opts.to = val()
+ else if (a === '--report') opts.report = val()
else if (a === '--shell') opts.shell = val()
else if (a === '--offline') opts.offline = true
else if (a === '-h' || a === '--help') { process.stdout.write(USAGE + '\n'); process.exit(0) }
@@ -67,8 +79,13 @@ for (let i = 0; i < argv.length; i++) {
else opts.input = a
}
if (!opts.input) die(USAGE, 2)
-if (!/\.pptx$/i.test(opts.input)) die(`${opts.input}: expected a .pptx`, 2)
-if (opts.offline && !opts.shell) die('--offline needs --shell: there is no other shell to use', 2)
+if (opts.to && opts.to !== 'pptx') die(`--to ${opts.to}: only pptx is supported`, 2)
+const isPptx = /\.pptx$/i.test(opts.input)
+const isBento = /\.(html?|json)$/i.test(opts.input)
+const exporting = opts.to === 'pptx'
+if (exporting ? !isBento : !isPptx)
+ die(`${opts.input}: expected ${exporting ? 'a .bento.html or document .json to export' : 'a .pptx (or a .bento.html with --to pptx)'}`, 2)
+if (!exporting && opts.offline && !opts.shell) die('--offline needs --shell: there is no other shell to use', 2)
if (!fs.existsSync(opts.input)) die(`no such file: ${opts.input}`)
// --- the engine, bundled -----------------------------------------------------
@@ -77,7 +94,7 @@ if (!fs.existsSync(esbuild)) die('slides/node_modules is missing — run `cd sli
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'bento-convert-'))
const bundle = path.join(tmp, 'api.mjs')
const built = spawnSync(esbuild, [
- path.join(root, 'convert/src/api.ts'), '--bundle', '--format=esm', '--platform=node',
+ path.join(root, 'convert/src/index.ts'), '--bundle', '--format=esm', '--platform=node',
'--log-level=error', `--outfile=${bundle}`,
], { encoding: 'utf8' })
if (built.status !== 0) die(`could not build the engine:\n${built.stderr}`)
@@ -89,39 +106,38 @@ const count = (r) => [r.counts.carried ? `${r.counts.carried} carried` : '',
`${r.counts.approximated ?? 0} approximated`, `${r.counts.dropped ?? 0} dropped`].filter(Boolean).join(' · ')
function printReport(r) {
process.stderr.write(`fidelity: ${count(r)}\n`)
- // One line per (verdict, code), dropped first — the engine reports per slide,
- // so a long deck otherwise repeats the same code once per slide and the one
- // line that matters drowns. Same folding as the /import page.
- const folded = new Map()
- for (const e of r.entries) {
- if (e.verdict === 'carried') continue
- const k = `${e.verdict}\u0000${e.code}`
- const f = folded.get(k) ?? { ...e, count: 0 }
- f.count += e.count ?? 1
- folded.set(k, f)
- }
- const rank = { dropped: 0, approximated: 1 }
- for (const e of [...folded.values()].sort((a, b) => (rank[a.verdict] ?? 2) - (rank[b.verdict] ?? 2)))
- process.stderr.write(` ${e.verdict.padEnd(12)} ${e.code}${e.count > 1 ? ` ×${e.count}` : ''} — ${e.detail}\n`)
+ // One line per kind of loss, dropped first, with the slides it happened on
+ // (convert/src/report.ts foldReport; the pages use the same function).
+ for (const e of api.foldReport(r))
+ process.stderr.write(` ${e.verdict.padEnd(12)} ${e.code}${e.count > 1 ? ` ×${e.count}` : ''}${e.where ? ` (${e.where})` : ''} — ${e.detail}\n`)
+ if (opts.report) fs.writeFileSync(opts.report, JSON.stringify(r, null, 2) + '\n')
}
try {
- let shell
- if (opts.shell) {
- shell = fs.readFileSync(opts.shell, 'utf8')
- process.stderr.write(`shell: ${opts.shell} (local — NOT verified against the release channel)\n`)
+ if (exporting) {
+ const res = await api.bentoToPptx(fs.readFileSync(opts.input, 'utf8'))
+ const out = opts.out ?? opts.input.replace(/(\.bento)?\.(html?|json)$/i, '') + '.pptx'
+ fs.writeFileSync(out, res.bytes)
+ printReport(res.report)
+ process.stderr.write(`wrote ${out} (${res.bytes.length} bytes)\n`)
} else {
- const v = await api.fetchVerifiedShell()
- shell = v.html
- process.stderr.write(`shell: bento/slides ${v.version} — signature and pin verified\n`)
+ let shell
+ if (opts.shell) {
+ shell = fs.readFileSync(opts.shell, 'utf8')
+ process.stderr.write(`shell: ${opts.shell} (local — NOT verified against the release channel)\n`)
+ } else {
+ const v = await api.fetchVerifiedShell()
+ shell = v.html
+ process.stderr.write(`shell: bento/slides ${v.version} — signature and pin verified\n`)
+ }
+ const res = await api.pptxToBento(new Uint8Array(fs.readFileSync(opts.input)), shell)
+ const out = opts.out ?? opts.input.replace(/\.pptx$/i, '') + '.bento.html'
+ fs.writeFileSync(out, res.html)
+ printReport(res.report)
+ if (res.gated.length)
+ process.stderr.write(`gate: removed ${res.gated.length} value(s) the format does not allow\n`)
+ process.stderr.write(`wrote ${out} — "${res.title}", ${res.slides} slide(s)\n`)
}
- const res = await api.pptxToBento(new Uint8Array(fs.readFileSync(opts.input)), shell)
- const out = opts.out ?? opts.input.replace(/\.pptx$/i, '') + '.bento.html'
- fs.writeFileSync(out, res.html)
- printReport(res.report)
- if (res.gated.length)
- process.stderr.write(`gate: removed ${res.gated.length} value(s) the format does not allow\n`)
- process.stderr.write(`wrote ${out} — "${res.title}", ${res.slides} slide(s)\n`)
} catch (err) {
die(err instanceof api.LimitError ? `refused: ${err.message}` : err.message)
} finally {
diff --git a/convert/src/export.ts b/convert/src/export.ts
new file mode 100644
index 00000000..ded9381b
--- /dev/null
+++ b/convert/src/export.ts
@@ -0,0 +1,76 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The export, composed once: a saved bento/slides file → .pptx bytes plus the
+// fidelity report. The CLI calls this; a script or a future host can too.
+//
+// Kept apart from api.ts on purpose. bento.page/import bundles api.ts, and the
+// page has no use for a PowerPoint writer, so the writer never reaches it
+// (scripts/test-convert/boundary.ts checks the page bundle).
+
+import { exportPptx, type ExportDoc } from './pptx-write/index.ts'
+import { extractDoc } from './deliver.ts'
+import type { FidelityReport } from './report.ts'
+import { parseDoc, deriveChartPalette } from '../../slides/src/model.ts'
+import { resolveMathHtml } from '../../slides/src/maths/delimiters.ts'
+
+export interface ExportResult {
+ bytes: Uint8Array
+ title: string
+ report: FidelityReport
+}
+
+/**
+ * A saved .bento.html, or the document JSON itself (what "Copy document JSON"
+ * gives), → .pptx. Refuses, with what to do instead: an encrypted deck (this
+ * takes no passwords), a raw compact document (an authoring shape the app
+ * expands on load), and anything that is not bento/slides.
+ */
+export async function bentoToPptx(input: string): Promise<ExportResult> {
+ const raw = readInput(input)
+ if (raw?.format === 'bento/enc')
+ throw new Error('this deck is password-protected — open it in Bento and use Save ▾ Save a copy without a password first')
+ if (raw?.compact === true)
+ throw new Error('this is a compact authoring document — open it in Bento once and save it, then export the saved file')
+ if (raw?.format !== 'bento/slides')
+ throw new Error(`this is a ${String(raw?.format ?? 'non-Bento')} file; only bento/slides decks export to PowerPoint`)
+ return docToPptx(JSON.stringify(raw))
+}
+
+/**
+ * A bento/slides document (JSON text) → .pptx. The document goes through
+ * slides' own parseDoc first, so the writer only ever sees a document the app
+ * itself would open.
+ */
+export async function docToPptx(json: string): Promise<ExportResult> {
+ const doc = parseDoc(json)
+ if (!doc) throw new Error('the deck did not pass the format check')
+ // The deck's chart palette: what the app would give a new chart. The writer
+ // cannot derive it (it never imports an app), so it is passed in here.
+ // doc.theme.chartPalette still wins inside the writer when the deck has one.
+ const { bytes, report } = await exportPptx(doc as unknown as ExportDoc, {
+ chartPalette: deriveChartPalette(doc.theme.accent),
+ formulasIn: countFormulas,
+ })
+ return { bytes, title: doc.title, report }
+}
+
+/** The document in a .bento.html, or document JSON as given. JSON is
+ * recognised by its first character; a file is never guessed from its name. */
+function readInput(input: string): Record<string, unknown> {
+ const t = input.replace(/^\uFEFF/, '').trimStart()
+ if (t.startsWith('{')) {
+ try { return JSON.parse(t) as Record<string, unknown> } catch {
+ throw new Error('this looks like document JSON but does not parse')
+ }
+ }
+ return extractDoc(input) as Record<string, unknown>
+}
+
+/** How many formulas slides would typeset in this html: the app's own
+ * scanner, asked to render nothing, counting what it was offered. */
+function countFormulas(html: string): number {
+ let n = 0
+ resolveMathHtml(html, () => { n++; return null })
+ return n
+}
diff --git a/convert/src/index.ts b/convert/src/index.ts
new file mode 100644
index 00000000..680f1bdf
--- /dev/null
+++ b/convert/src/index.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The convert library's whole public surface, in one entry: PowerPoint in
+// (api.ts) and PowerPoint out (export.ts). The CLI bundles this. Hosts that
+// need only one direction import that file directly, as bento.page/import
+// does with api.ts.
+
+export * from './api.ts'
+export * from './export.ts'
+export { foldReport, slideRange, type FoldedEntry } from './report.ts'
diff --git a/convert/src/pptx-write/charts.ts b/convert/src/pptx-write/charts.ts
new file mode 100644
index 00000000..43f08295
--- /dev/null
+++ b/convert/src/pptx-write/charts.ts
@@ -0,0 +1,569 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento chart → a NATIVE c:chart part + the graphicFrame that references it.
+//
+// PR #88 mapped charts through PptxGenJS's addChart and fell back to an SVG
+// image for anything the library didn't cover. This rework writes the
+// DrawingML Charts part directly and changes the fallback: out-of-subset
+// charts become a TABLE of their data, never a picture and never a wrong
+// chart. The spike's finding stands — a clustered rendering of a stacked
+// option destroys the totals the author built the slide around, and a chart
+// that lies is worse than no chart. The data table keeps every number
+// editable and the fidelity report says what happened.
+//
+// The subset (everything charts-lite actually renders, which the bento format
+// guarantees): single-type bar/line/pie/scatter series with plain-number
+// data, plus the DUAL-AXIS pattern — series split over yAxisIndex 0/1, each
+// axis group single-type (tableToChart emits exactly this: bars left, one
+// odd-scale column as a line on the right). #88 skipped dual axis; the shape
+// is common enough in real bento decks that it is mapped here as two plot
+// groups sharing the category axis, the second pair of axes deleted/right —
+// the same wiring PowerPoint itself writes for a combo chart.
+//
+// NO EMBEDDED WORKBOOK, BY DESIGN. A chart part may carry an externalData rel
+// to an xlsx with the source table; ours carries none. PowerPoint renders
+// entirely from the literal caches (c:strCache/c:numCache) below, and "Edit
+// Data" generates a fresh sheet FROM those caches — the c:f formulas give
+// that rebuild sensible cell addresses. Embedding a real workbook would mean
+// writing a second OOXML package inside this one for zero rendering benefit.
+//
+// Data coercion mirrors the RENDERER, not the raw JSON: charts-lite coerces
+// non-numeric bar/line data ({value,itemStyle} objects, blanks) to 0, so the
+// export does too — the .pptx shows what the slide showed. Each coercion is
+// still reported ('chart-data-coerced'): a blank that became a zero changes
+// what the chart asserts, whether or not bento already rendered it that way.
+
+import { scrubC0, serialize, x, type XChild, type XNode } from '../xmlout.ts'
+import { EMU_PER_PX, type OutChart, type OutTable } from '../types.ts'
+import type { Report } from '../report.ts'
+import { tableFrame } from './tables.ts'
+
+/** The a:graphicData uri that marks a graphicFrame as a chart reference. */
+export const CHART_GRAPHIC_URI = 'http://schemas.openxmlformats.org/drawingml/2006/chart'
+
+const NS_C = 'http://schemas.openxmlformats.org/drawingml/2006/chart'
+const NS_A = 'http://schemas.openxmlformats.org/drawingml/2006/main'
+const NS_R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
+
+export interface ChartExport {
+ /** the spTree node — a chart-referencing graphicFrame, or (fallback) a table */
+ frame: XNode
+ /**
+ * The serialized c:chartSpace part. Present → the integrator must emit it
+ * as ppt/charts/chartN.xml, register a REL.chart rel with the `relId`
+ * passed in, and add a CT.chart [Content_Types] override. ABSENT → the
+ * frame is a data table, `relId` was NOT used, and no part/rel/override
+ * may be emitted (a dangling chart rel is a repair dialog).
+ */
+ chartXml?: string
+}
+
+// --- option access -----------------------------------------------------------
+// The option is ECharts-shaped free JSON (charts-lite ignores unknown keys
+// gracefully; so does this reader — absent/odd keys fall to defaults).
+
+type Dict = Record<string, unknown>
+const dict = (v: unknown): Dict => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Dict) : {})
+const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)
+const numOr = (v: unknown): number | undefined => (typeof v === 'number' && Number.isFinite(v) ? v : undefined)
+
+/** option.series may be one object or an array (ECharts allows both). */
+const seriesList = (v: unknown): Dict[] =>
+ (Array.isArray(v) ? v : v === undefined ? [] : [v]).map(dict)
+
+/** option.yAxis: object or array of up to two value-axis configs. */
+const yAxisList = (v: unknown): Dict[] => (Array.isArray(v) ? v.map(dict) : [dict(v)])
+
+// --- colours -----------------------------------------------------------------
+// Series colour resolution order = charts-lite's: explicit option.color array,
+// else the deck palette the integrator passes (doc.theme.chartPalette or
+// slides' deriveChartPalette(accent) — that derivation lives in the app, the
+// writer only consumes the result), else the ECharts stock four #88 fell back
+// to. Local hex-only conversion: chart colours are opaque fills; the css
+// parsing lives in tables.ts's cssSolid but here only the hex is wanted.
+
+const STOCK = ['#5470c6', '#91cc75', '#fac858', '#ee6666'] // #88's docPalette
+
+function hex6(css: string | undefined, fallback: string): string {
+ const raw = (css ?? '').trim()
+ const rgb = raw.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i)
+ if (rgb) {
+ return [rgb[1], rgb[2], rgb[3]]
+ .map((n) => Math.min(255, Math.max(0, Math.round(Number(n)))).toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase()
+ }
+ let hex = raw.replace(/^#/, '')
+ if (/^[0-9a-f]{3,4}$/i.test(hex)) hex = [...hex].map((c) => c + c).join('')
+ if (/^[0-9a-f]{6,8}$/i.test(hex)) return hex.slice(0, 6).toUpperCase()
+ return fallback
+}
+
+const srgbFill = (hex: string): XNode =>
+ x('a:solidFill', undefined, [x('a:srgbClr', { val: hex })])
+
+// --- literal data references -------------------------------------------------
+// c:f addresses are for the edit-time rebuild only (see header): categories
+// live in column A, series i in column B+i, row 1 is the header row.
+
+const colLetter = (i: number): string => {
+ let n = i + 1
+ let s = ''
+ while (n > 0) {
+ n--
+ s = String.fromCharCode(65 + (n % 26)) + s
+ n = Math.floor(n / 26)
+ }
+ return s
+}
+
+// scrubC0: category labels and series names are author-typed strings that
+// land verbatim in c:v — a control char must cost a character, not the export.
+const ptNodes = (vals: string[]): XChild[] =>
+ vals.map((v, i) => x('c:pt', { idx: i }, [x('c:v', undefined, [scrubC0(v)])]))
+
+const strRef = (f: string, vals: string[]): XNode =>
+ x('c:strRef', undefined, [
+ x('c:f', undefined, [f]),
+ x('c:strCache', undefined, [x('c:ptCount', { val: vals.length }), ...ptNodes(vals)]),
+ ])
+
+/** Values go through String() verbatim — 4.25 stays "4.25"; the cache must
+ * hold exactly what the deck showed, not a reformatted number. */
+const numRef = (f: string, vals: number[]): XNode =>
+ x('c:numRef', undefined, [
+ x('c:f', undefined, [f]),
+ x('c:numCache', undefined, [
+ x('c:formatCode', undefined, ['General']),
+ x('c:ptCount', { val: vals.length }),
+ ...ptNodes(vals.map((v) => String(v))),
+ ]),
+ ])
+
+const catRange = (n: number): string => `Sheet1!$A$2:$A$${n + 1}`
+const serRange = (si: number, n: number): string => `Sheet1!$${colLetter(si + 1)}$2:$${colLetter(si + 1)}$${n + 1}`
+const serNameRef = (si: number, name: string): XNode => strRef(`Sheet1!$${colLetter(si + 1)}$1`, [name])
+
+// --- axes --------------------------------------------------------------------
+// Fixed ids, unique within the part: 1001/1002 primary cat/val, 1003/1004
+// the secondary pair. Child order inside cat/valAx is schema-fixed (axId,
+// scaling, delete, axPos, [gridlines], [numFmt], crossAx, crosses) — a
+// reordered axis is a repair dialog.
+
+const AX = { cat0: 1001, val0: 1002, cat1: 1003, val1: 1004 } as const
+
+function catAx(id: number, crossId: number, deleted: boolean): XNode {
+ return x('c:catAx', undefined, [
+ x('c:axId', { val: id }),
+ x('c:scaling', undefined, [x('c:orientation', { val: 'minMax' })]),
+ // The secondary category axis exists only to complete the axis pair the
+ // schema demands — delete=1 hides it, exactly as PowerPoint writes it.
+ x('c:delete', { val: deleted ? 1 : 0 }),
+ x('c:axPos', { val: 'b' }),
+ x('c:crossAx', { val: crossId }),
+ ])
+}
+
+interface ValAxOpts {
+ pos: 'l' | 'r' | 'b'
+ min?: number
+ max?: number
+ /** axisLabel.formatter carries '{value}%' → percent tick labels */
+ pct?: boolean
+ gridlines?: boolean
+ /** secondary axis crosses at the far side */
+ crossesMax?: boolean
+ deleted?: boolean
+}
+
+function valAx(id: number, crossId: number, o: ValAxOpts): XNode {
+ const scaling: XChild[] = [x('c:orientation', { val: 'minMax' })]
+ if (o.max !== undefined) scaling.push(x('c:max', { val: o.max }))
+ if (o.min !== undefined) scaling.push(x('c:min', { val: o.min }))
+ return x('c:valAx', undefined, [
+ x('c:axId', { val: id }),
+ x('c:scaling', undefined, scaling),
+ x('c:delete', { val: o.deleted ? 1 : 0 }),
+ x('c:axPos', { val: o.pos }),
+ ...(o.gridlines ? [x('c:majorGridlines')] : []),
+ // '{value}%' appends a literal percent sign; the format code must quote
+ // it — a bare "0%" is Excel's percent FORMAT and multiplies by 100.
+ ...(o.pct ? [x('c:numFmt', { formatCode: '0"%"', sourceLinked: 0 })] : []),
+ x('c:crossAx', { val: crossId }),
+ ...(o.crossesMax ? [x('c:crosses', { val: 'max' })] : []),
+ ])
+}
+
+// --- series ------------------------------------------------------------------
+
+interface SerData {
+ /** global series index (c:idx/c:order must be unique across plot groups) */
+ gi: number
+ name: string
+ color: string
+ values: number[]
+ smooth: boolean
+}
+
+function barSer(s: SerData, labels: string[]): XNode {
+ return x('c:ser', undefined, [
+ x('c:idx', { val: s.gi }),
+ x('c:order', { val: s.gi }),
+ x('c:tx', undefined, [serNameRef(s.gi, s.name)]),
+ x('c:spPr', undefined, [srgbFill(s.color)]),
+ x('c:cat', undefined, [strRef(catRange(labels.length), labels)]),
+ x('c:val', undefined, [numRef(serRange(s.gi, s.values.length), s.values)]),
+ ])
+}
+
+function lineSer(s: SerData, labels: string[]): XNode {
+ return x('c:ser', undefined, [
+ x('c:idx', { val: s.gi }),
+ x('c:order', { val: s.gi }),
+ x('c:tx', undefined, [serNameRef(s.gi, s.name)]),
+ // A line's colour lives on its OUTLINE (28575 EMU = 2.25pt, PowerPoint's
+ // default line-chart weight), not a shape fill.
+ x('c:spPr', undefined, [x('a:ln', { w: 28575 }, [srgbFill(s.color)])]),
+ x('c:marker', undefined, [
+ x('c:symbol', { val: 'circle' }),
+ x('c:size', { val: 5 }),
+ x('c:spPr', undefined, [srgbFill(s.color)]),
+ ]),
+ x('c:cat', undefined, [strRef(catRange(labels.length), labels)]),
+ x('c:val', undefined, [numRef(serRange(s.gi, s.values.length), s.values)]),
+ x('c:smooth', { val: s.smooth ? 1 : 0 }),
+ ])
+}
+
+// --- the mapper --------------------------------------------------------------
+
+/**
+ * One bento chart element. `shapeId` is the cNvPr id; `relId` is the r:id the
+ * INTEGRATOR reserved for this chart in the slide's rels — used only when the
+ * result carries `chartXml` (see ChartExport). `palette` is the deck's chart
+ * palette (doc.theme.chartPalette, or the accent-derived set slides computes);
+ * omit and the ECharts stock colours apply.
+ */
+export function chartExport(
+ el: OutChart,
+ shapeId: number,
+ relId: string,
+ palette: string[] | undefined,
+ report: Report,
+ where: string,
+): ChartExport {
+ const option = dict(el.option)
+ const series = seriesList(option.series)
+ const optColors = Array.isArray(option.color) ? (option.color as unknown[]).map((c) => str(c) ?? '') : []
+ const colorFor = (i: number): string =>
+ hex6(optColors[i] || palette?.[i % (palette.length || 1)] || STOCK[i % STOCK.length], '5470C6')
+
+ let coerced = 0
+ const num = (v: unknown): number => {
+ // charts-lite's coercion: Number() of the leaf, non-finite (objects,
+ // blanks, text) → 0. See header — faithful to the render, but reported.
+ const n = Number(v)
+ if (Number.isFinite(n) && (typeof v === 'number' || typeof v === 'string' && v.trim() !== '')) return n
+ coerced++
+ return 0
+ }
+
+ if (el.rotation) {
+ report.add('dropped', 'chart-rotation-dropped', where, 'PowerPoint cannot rotate chart frames; the chart exports axis-aligned')
+ }
+
+ // --- subset gate: anything outside becomes the data table ------------------
+ const types = series.map((s) => str(s.type) ?? 'bar')
+ const fallback = (reason: string): ChartExport => {
+ report.add('approximated', 'chart-approximated', where,
+ `chart outside the native-export subset (${reason}) rendered as a table of its data — a wrong chart (e.g. a clustered read of a stacked series) would misstate the numbers`)
+ return { frame: dataTableFrame(el, series, option, num, shapeId, report, where) }
+ }
+
+ if (series.length === 0) return fallback('no series')
+ if (series.some((s) => s.stack !== undefined && s.stack !== null && s.stack !== false)) return fallback('stacked series')
+ const unknown = types.find((t) => !['bar', 'line', 'pie', 'scatter'].includes(t))
+ if (unknown) return fallback(`unsupported series type '${unknown}'`)
+
+ const isPie = types.includes('pie')
+ const isScatter = types.includes('scatter')
+ if (isPie && (series.length > 1 || types.length > 1)) return fallback('pie mixed with other series')
+ if (isScatter && types.some((t) => t !== 'scatter')) return fallback('scatter mixed with other series')
+ if ((isPie || isScatter) && series.some((s) => numOr(s.yAxisIndex) === 1)) return fallback('secondary axis on a non-cartesian chart')
+
+ // Split bar/line series over the two value axes (yAxisIndex 0/1); each
+ // group must be single-type — that is the whole subset for combos.
+ const groups: Array<{ axis: 0 | 1; type: 'bar' | 'line'; sers: SerData[] }> = []
+ if (!isPie && !isScatter) {
+ for (const axis of [0, 1] as const) {
+ const members = series
+ .map((s, i) => ({ s, i }))
+ .filter(({ s }) => (numOr(s.yAxisIndex) === 1 ? 1 : 0) === axis)
+ if (members.length === 0) continue
+ const groupTypes = new Set(members.map(({ i }) => types[i]))
+ if (groupTypes.size > 1) return fallback('mixed series types on one axis')
+ groups.push({
+ axis,
+ type: [...groupTypes][0] as 'bar' | 'line',
+ sers: members.map(({ s, i }) => ({
+ gi: i,
+ name: str(s.name) ?? `Series ${i + 1}`,
+ color: colorFor(i),
+ values: (Array.isArray(s.data) ? s.data : []).map(num),
+ smooth: s.smooth === true,
+ })),
+ })
+ }
+ }
+
+ // --- chart body ------------------------------------------------------------
+ const labels = (Array.isArray(dict(option.xAxis).data) ? (dict(option.xAxis).data as unknown[]) : []).map(String)
+ const yAxes = yAxisList(option.yAxis)
+ const axOpts = (i: number): { min?: number; max?: number; pct?: boolean } => ({
+ min: numOr(yAxes[i]?.min),
+ max: numOr(yAxes[i]?.max),
+ pct: (str(dict(yAxes[i]?.axisLabel).formatter) ?? '').includes('%'),
+ })
+
+ const plot: XChild[] = [x('c:layout')]
+
+ if (isPie) {
+ const s = series[0]
+ const items = (Array.isArray(s.data) ? s.data : []).map(dict)
+ const names = items.map((it, i) => str(it.name) ?? String(i + 1))
+ const values = items.map((it) => num(it.value))
+ const ser = x('c:ser', undefined, [
+ x('c:idx', { val: 0 }),
+ x('c:order', { val: 0 }),
+ x('c:tx', undefined, [serNameRef(0, str(s.name) ?? 'Series 1')]),
+ // Slice colours as data points — pie colour is per-slice, walking the
+ // same palette charts-lite walks.
+ ...items.map((_, i) =>
+ x('c:dPt', undefined, [
+ x('c:idx', { val: i }),
+ x('c:bubble3D', { val: 0 }),
+ x('c:spPr', undefined, [srgbFill(colorFor(i))]),
+ ]),
+ ),
+ x('c:cat', undefined, [strRef(catRange(names.length), names)]),
+ x('c:val', undefined, [numRef(serRange(0, values.length), values)]),
+ ])
+ // charts-lite's pie preset is a donut (radius ['38%','68%']); a plain
+ // radius (or inner 0) is a full pie. holeSize = inner/outer share of the
+ // diameter, the same visual PowerPoint's doughnut draws.
+ const radius = s.radius
+ const [inner, outer] = Array.isArray(radius)
+ ? [parseFloat(String(radius[0])) || 0, parseFloat(String(radius[1])) || 70]
+ : [0, parseFloat(String(radius ?? '70%')) || 70]
+ if (inner > 0 && outer > 0) {
+ plot.push(x('c:doughnutChart', undefined, [
+ x('c:varyColors', { val: 1 }), ser, x('c:firstSliceAng', { val: 0 }),
+ x('c:holeSize', { val: Math.min(90, Math.max(1, Math.round((inner / outer) * 100))) }),
+ ]))
+ } else {
+ plot.push(x('c:pieChart', undefined, [x('c:varyColors', { val: 1 }), ser, x('c:firstSliceAng', { val: 0 })]))
+ }
+ } else if (isScatter) {
+ // Scatter: two VALUE axes, series as x/y pairs. lineMarker style with a
+ // noFill outline per series is how PowerPoint itself writes a
+ // markers-only scatter (scatterStyle 'marker' renders, but Edit-Data
+ // round-trips shakily in older builds).
+ plot.push(x('c:scatterChart', undefined, [
+ x('c:scatterStyle', { val: 'lineMarker' }),
+ x('c:varyColors', { val: 0 }),
+ ...series.map((s, i) => {
+ // A scalar datum in a scatter series reads as (index, value) — the
+ // same shape a category series would have plotted it at.
+ const pairs = (Array.isArray(s.data) ? s.data : []).map((d, di) => (Array.isArray(d) ? d : [di, d]))
+ const color = colorFor(i)
+ return x('c:ser', undefined, [
+ x('c:idx', { val: i }),
+ x('c:order', { val: i }),
+ x('c:tx', undefined, [serNameRef(i, str(s.name) ?? `Series ${i + 1}`)]),
+ x('c:spPr', undefined, [x('a:ln', { w: 28575 }, [x('a:noFill')])]),
+ x('c:marker', undefined, [
+ x('c:symbol', { val: 'circle' }),
+ x('c:size', { val: 5 }),
+ x('c:spPr', undefined, [srgbFill(color)]),
+ ]),
+ x('c:xVal', undefined, [numRef(catRange(pairs.length), pairs.map((p) => num(p[0])))]),
+ x('c:yVal', undefined, [numRef(serRange(i, pairs.length), pairs.map((p) => num(p[1])))]),
+ ])
+ }),
+ x('c:axId', { val: AX.cat0 }),
+ x('c:axId', { val: AX.val0 }),
+ ]))
+ plot.push(valAx(AX.cat0, AX.val0, { pos: 'b' }))
+ plot.push(valAx(AX.val0, AX.cat0, { pos: 'l', gridlines: true, ...axOpts(0) }))
+ } else {
+ // bar/line, possibly dual-axis: one plot group per axis, category axis
+ // shared, the secondary pair deleted-cat + right-val crossing at max —
+ // the combo wiring PowerPoint writes natively.
+ for (const g of groups) {
+ const catId = g.axis === 0 ? AX.cat0 : AX.cat1
+ const valId = g.axis === 0 ? AX.val0 : AX.val1
+ const sers = g.sers.map((s) => (g.type === 'bar' ? barSer(s, labels) : lineSer(s, labels)))
+ plot.push(
+ g.type === 'bar'
+ ? x('c:barChart', undefined, [
+ x('c:barDir', { val: 'col' }),
+ x('c:grouping', { val: 'clustered' }),
+ x('c:varyColors', { val: 0 }),
+ ...sers,
+ x('c:axId', { val: catId }),
+ x('c:axId', { val: valId }),
+ ])
+ : x('c:lineChart', undefined, [
+ x('c:grouping', { val: 'standard' }),
+ x('c:varyColors', { val: 0 }),
+ ...sers,
+ x('c:marker', { val: 1 }),
+ x('c:axId', { val: catId }),
+ x('c:axId', { val: valId }),
+ ]),
+ )
+ }
+ const dual = groups.some((g) => g.axis === 1)
+ if (groups.some((g) => g.axis === 0)) {
+ plot.push(catAx(AX.cat0, AX.val0, false))
+ plot.push(valAx(AX.val0, AX.cat0, { pos: 'l', gridlines: true, ...axOpts(0) }))
+ }
+ if (dual) {
+ plot.push(catAx(AX.cat1, AX.val1, true))
+ plot.push(valAx(AX.val1, AX.cat1, { pos: 'r', crossesMax: true, ...axOpts(1) }))
+ }
+ }
+
+ // --- legend, title, chartSpace ---------------------------------------------
+ // legend: falsy (absent/false) = none; legend: {show:false} = none; any
+ // other object/true = shown.
+ const legendCfg = option.legend && dict(option.legend).show !== false ? dict(option.legend) : undefined
+ // Position from the ECharts anchor keys; bento's presets all say bottom,
+ // so bottom is also the default when the option is silent about position.
+ const legendPos = legendCfg
+ ? legendCfg.bottom !== undefined ? 'b'
+ : legendCfg.top !== undefined ? 't'
+ : legendCfg.left !== undefined ? 'l'
+ : legendCfg.right !== undefined ? 'r' : 'b'
+ : undefined
+
+ const titleText = str(dict(option.title).text)
+ const chartKids: XChild[] = [
+ ...(titleText
+ ? [
+ x('c:title', undefined, [
+ x('c:tx', undefined, [
+ x('c:rich', undefined, [
+ x('a:bodyPr'),
+ x('a:p', undefined, [x('a:r', undefined, [x('a:t', undefined, [scrubC0(titleText)])])]),
+ ]),
+ ]),
+ x('c:overlay', { val: 0 }),
+ ]),
+ x('c:autoTitleDeleted', { val: 0 }),
+ ]
+ // No title in the option = no title in the export: without this flag
+ // PowerPoint helpfully invents a "Chart Title" placeholder.
+ : [x('c:autoTitleDeleted', { val: 1 })]),
+ x('c:plotArea', undefined, plot),
+ ...(legendPos
+ ? [x('c:legend', undefined, [x('c:legendPos', { val: legendPos }), x('c:overlay', { val: 0 })])]
+ : []),
+ x('c:plotVisOnly', { val: 1 }),
+ x('c:dispBlanksAs', { val: 'gap' }),
+ ]
+
+ const chartXml = serialize(
+ x('c:chartSpace', { 'xmlns:c': NS_C, 'xmlns:a': NS_A, 'xmlns:r': NS_R }, [
+ x('c:chart', undefined, chartKids),
+ ]),
+ )
+
+ if (coerced > 0) {
+ report.add('approximated', 'chart-data-coerced', where,
+ `${coerced === 1 ? 'a non-numeric datum' : 'non-numeric data'} coerced to 0 — matching what charts-lite rendered, but the cache now asserts zeros`)
+ }
+
+ const morphId = (el as OutChart & { morphId?: string }).morphId
+ const frame = x('p:graphicFrame', undefined, [
+ x('p:nvGraphicFramePr', undefined, [
+ x('p:cNvPr', { id: shapeId, name: `bento:${morphId || el.id}` }),
+ x('p:cNvGraphicFramePr', undefined, [x('a:graphicFrameLocks', { noGrp: 1 })]),
+ x('p:nvPr'),
+ ]),
+ x('p:xfrm', undefined, [
+ x('a:off', { x: Math.round(el.x * EMU_PER_PX), y: Math.round(el.y * EMU_PER_PX) }),
+ x('a:ext', { cx: Math.round(el.w * EMU_PER_PX), cy: Math.round(el.h * EMU_PER_PX) }),
+ ]),
+ x('a:graphic', undefined, [
+ x('a:graphicData', { uri: CHART_GRAPHIC_URI }, [
+ // The reference element re-declares c: and r: — the slide root only
+ // declares a/p/r, and PowerPoint writes the chart ref exactly so.
+ x('c:chart', { 'xmlns:c': NS_C, 'xmlns:r': NS_R, 'r:id': relId }),
+ ]),
+ ]),
+ ])
+
+ return { frame, chartXml }
+}
+
+// --- the fallback: a table of the data ---------------------------------------
+
+/**
+ * Build the out-of-subset fallback: labels down the first column, one column
+ * per series, header row from series names — the same table→chart columns
+ * bento derives, inverted. Rendered through tables.ts so it inherits the
+ * drift-free grid and reporting. Neutral styling on purpose: this table is a
+ * stand-in the user will restyle or re-chart, not deck furniture.
+ */
+function dataTableFrame(
+ el: OutChart,
+ series: Dict[],
+ option: Dict,
+ num: (v: unknown) => number,
+ shapeId: number,
+ report: Report,
+ where: string,
+): XNode {
+ const firstPie = series.find((s) => str(s.type) === 'pie')
+ let labels: string[]
+ let cols: Array<{ name: string; values: number[] }>
+ if (firstPie) {
+ const items = (Array.isArray(firstPie.data) ? firstPie.data : []).map(dict)
+ labels = items.map((it, i) => str(it.name) ?? String(i + 1))
+ cols = [{ name: str(firstPie.name) ?? 'Value', values: items.map((it) => num(it.value)) }]
+ } else {
+ const data = series.map((s) => (Array.isArray(s.data) ? s.data : []))
+ const n = Math.max(0, ...data.map((d) => d.length))
+ const xLabels = (Array.isArray(dict(option.xAxis).data) ? (dict(option.xAxis).data as unknown[]) : []).map(String)
+ labels = Array.from({ length: n }, (_, i) => xLabels[i] ?? String(i + 1))
+ cols = series.map((s, i) => ({
+ name: str(s.name) ?? `Series ${i + 1}`,
+ // Scatter pairs collapse to their y value in the table read-out.
+ values: data[i].map((d) => num(Array.isArray(d) ? d[1] : d)),
+ }))
+ }
+
+ const table: OutTable = {
+ id: el.id,
+ type: 'table',
+ x: el.x, y: el.y, w: el.w, h: el.h,
+ rotation: el.rotation,
+ opacity: el.opacity,
+ columns: [{ w: 1.4 }, ...cols.map(() => ({ w: 1 }))],
+ header: true,
+ rows: [
+ { cells: [{ html: '' }, ...cols.map((c) => ({ html: c.name }))] },
+ ...labels.map((label, ri) => ({
+ cells: [{ html: label }, ...cols.map((c) => ({ html: c.values[ri] !== undefined ? String(c.values[ri]) : '' }))],
+ })),
+ ],
+ style: {
+ headerBg: '#EFF2F5', headerColor: '#1E2A3A', color: '#1E2A3A',
+ borderColor: '#C9CFD6', borderWidth: 1,
+ cellPadX: 10, cellPadY: 6, fontSize: 14, radius: 0,
+ },
+ }
+ return tableFrame(table, shapeId, report, where)
+}
diff --git a/convert/src/pptx-write/code.ts b/convert/src/pptx-write/code.ts
new file mode 100644
index 00000000..337955f3
--- /dev/null
+++ b/convert/src/pptx-write/code.ts
@@ -0,0 +1,40 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// `code` elements → PowerPoint. NOT YET WRITTEN: today a code element is
+// reported as dropped and nothing is emitted. This file is the place to write
+// it; convert/CONTRIBUTING.md has the walkthrough.
+//
+// What a good first version looks like: a p:sp text box at the element's
+// frame, the content one paragraph per line, in a monospace face (the
+// element's fontFamily, else "Consolas"), at its fontSize, alignment and
+// colour. Syntax colouring is optional — a first version that drops it says
+// so with an 'approximated' entry ('code-colours-flattened'). textSp in
+// text.ts shows how a text box is built; shapes.ts emu() converts px.
+//
+// When it emits something, move 'code' from NOT_YET to MAPPED in
+// scripts/test-convert/pptx-coverage.ts, and add its own checks there.
+
+import type { ElementWriter, ElFrame } from './contract.ts'
+
+/** The fields of slides' CodeElement a writer reads (restated from
+ * slides/src/model.ts; the writer never imports an app). */
+export interface CodeElIn extends ElFrame {
+ type: 'code'
+ fontSize: number
+ fontFamily: string
+ align: 'left' | 'center' | 'right'
+ valign: 'top' | 'middle' | 'bottom'
+ lineHeight: number
+ color: string
+ /** the code itself, lines separated by \n */
+ content: string
+ /** the highlighting grammar and theme, by name (colours are optional) */
+ grammarName?: string
+ themeName?: string
+}
+
+export const writeCode: ElementWriter<CodeElIn> = (_el, ctx) => {
+ ctx.report.add('dropped', 'element-unsupported', ctx.where, "element type 'code' has no pptx mapping")
+ return null
+}
diff --git a/convert/src/pptx-write/contract.ts b/convert/src/pptx-write/contract.ts
new file mode 100644
index 00000000..d7c046bc
--- /dev/null
+++ b/convert/src/pptx-write/contract.ts
@@ -0,0 +1,60 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The element-writer contract: what a writer for one bento/slides element type
+// receives, what it returns, and the rules it keeps. New writers (code.ts,
+// embed.ts) are written against this type. The older writers (text, shapes,
+// media, tables, charts) predate it and take the same things as positional
+// arguments; index.ts adapts them, and nothing here asks for them to change.
+//
+// THE RULES. A writer:
+//
+// 1. Returns ONE top-level node (p:sp, p:pic or p:graphicFrame) whose
+// p:cNvPr id is ctx.shapeId, or null when it emits nothing.
+// 2. Never throws on content. Anything it cannot carry exactly goes into
+// ctx.report: 'approximated' when the slide still shows something close,
+// 'dropped' when it does not. One stable code per kind of loss, kebab-case
+// (e.g. 'code-colours-flattened'); the detail says what the person will
+// see in PowerPoint, in plain words. Returning null without a 'dropped'
+// entry is a silent loss, and the coverage rig fails on it.
+// 3. Allocates relationships only through ctx.media (images and svg go into
+// the package that way, deduplicated by content). It never invents rIds.
+// 4. Reads only the element and ctx. It imports nothing from an app: the
+// writer is a library, and the same code runs in node and in a browser.
+// 5. Is deterministic: the same element and ctx give the same node, so two
+// exports of one deck are byte-identical.
+//
+// Link, presentation-effect and hover handling are the integrator's
+// (index.ts), not the writer's: it reports effects once per slide and wires
+// el.link onto whatever node the writer returns.
+
+import type { Report } from '../report.ts'
+import type { XNode } from '../xmlout.ts'
+import type { MediaCtx } from './media.ts'
+
+export interface WriteCtx {
+ /** the p:cNvPr id the returned node must carry */
+ shapeId: number
+ /** where losses are recorded; see rule 2 */
+ report: Report
+ /** the report location for this element, e.g. "slide 3" */
+ where: string
+ /** the package's media store: images and svg enter the package through it */
+ media: MediaCtx
+ /** the deck theme, for writers that fall back to the deck's fonts or colours */
+ theme: { background: string; color: string; accent: string; fontFamily: string }
+}
+
+/** A writer for one element type. See the rules above. */
+export type ElementWriter<E> = (el: E, ctx: WriteCtx) => XNode | null
+
+/** The frame fields every bento/slides element carries (slides/src/model.ts
+ * ElementBase, restated: the writer never imports an app). */
+export interface ElFrame {
+ id: string
+ morphId?: string
+ x: number; y: number; w: number; h: number
+ /** degrees, clockwise */
+ rotation: number
+ opacity: number
+}
diff --git a/convert/src/pptx-write/embed.ts b/convert/src/pptx-write/embed.ts
new file mode 100644
index 00000000..21c3dcea
--- /dev/null
+++ b/convert/src/pptx-write/embed.ts
@@ -0,0 +1,37 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// `embed` elements → PowerPoint. NOT YET WRITTEN: today an embed (a bento/dash
+// chart, a bento/type page, a web page) is reported as dropped and nothing is
+// emitted. This file is the place to write it; convert/CONTRIBUTING.md has the
+// walkthrough.
+//
+// Every embed carries a static render in `view`: raw <svg> markup, or
+// "asset:<key>" naming the asset that holds it. That is what PowerPoint should
+// show. svgPic in media.ts already turns svg markup into a picture with the
+// right package wiring, so a first version can hand it the view and report
+// 'approximated' ('embed-static'): the slide shows the picture, but the live
+// document behind it does not travel. A web embed (app 'web') with no view
+// stays dropped.
+//
+// When it emits something, move 'embed' from NOT_YET to MAPPED in
+// scripts/test-convert/pptx-coverage.ts, and add its own checks there.
+
+import type { ElementWriter, ElFrame } from './contract.ts'
+
+/** The fields of slides' EmbedElement a writer reads (restated from
+ * slides/src/model.ts; the writer never imports an app). */
+export interface EmbedElIn extends ElFrame {
+ type: 'embed'
+ /** the app that made it: 'bento/dash', 'bento/type', … or 'web' */
+ app: string
+ /** the static render: raw <svg> markup, or "asset:<key>" holding it */
+ view: string
+ /** app 'web' only: the page the live frame loads */
+ url?: string
+}
+
+export const writeEmbed: ElementWriter<EmbedElIn> = (_el, ctx) => {
+ ctx.report.add('dropped', 'element-unsupported', ctx.where, "element type 'embed' has no pptx mapping")
+ return null
+}
diff --git a/convert/src/pptx-write/fonts.ts b/convert/src/pptx-write/fonts.ts
new file mode 100644
index 00000000..d1758a25
--- /dev/null
+++ b/convert/src/pptx-write/fonts.ts
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// A CSS font stack → the one typeface name PowerPoint takes.
+//
+// A stack can name CSS GENERIC families ('ui-monospace', 'sans-serif',
+// 'system-ui', …). Those mean "whatever this browser picks", and are not
+// font names: written into a .pptx as a typeface, PowerPoint finds no such
+// font and substitutes its own default, so code set in 'ui-monospace, Menlo,
+// monospace' came out proportional. So the first REAL family in the stack
+// wins, and a stack of generics alone maps to a font every PowerPoint has.
+
+/** CSS generic family → a font PowerPoint can be expected to have. */
+const GENERIC: Record<string, string> = {
+ 'monospace': 'Courier New',
+ 'ui-monospace': 'Courier New',
+ 'serif': 'Times New Roman',
+ 'ui-serif': 'Times New Roman',
+ 'sans-serif': 'Arial',
+ 'ui-sans-serif': 'Arial',
+ 'system-ui': 'Arial',
+ '-apple-system': 'Arial',
+ 'blinkmacsystemfont': 'Arial',
+ 'ui-rounded': 'Arial',
+ 'cursive': 'Comic Sans MS',
+ 'fantasy': 'Impact',
+ 'math': 'Cambria Math',
+ 'emoji': 'Segoe UI Emoji',
+}
+
+/**
+ * System fonts that ship with ONE operating system and not with Office. A
+ * browser falls through a stack to the next family it has; PowerPoint takes
+ * one name and substitutes when it is missing. So naming 'SF Mono' (macOS
+ * only) gives Windows PowerPoint a proportional stand-in, while the stack's
+ * next family, 'Consolas', is installed with Office everywhere. These are
+ * skipped like generics; a deck's own fonts are never on this list.
+ */
+const ONE_PLATFORM = new Set([
+ 'sf mono', 'sfmono-regular', 'sf pro', 'sf pro text', 'sf pro display', 'new york',
+ 'menlo', 'monaco', 'helvetica neue', 'lucida grande', 'apple color emoji',
+ 'segoe ui', 'segoe ui emoji', 'segoe ui symbol', 'cascadia code', 'cascadia mono',
+ 'roboto', 'roboto mono', 'ubuntu', 'ubuntu mono', 'cantarell', 'oxygen', 'fira sans',
+ 'noto sans', 'noto color emoji', 'liberation mono', 'liberation sans', 'liberation serif',
+ 'dejavu sans', 'dejavu sans mono', 'dejavu serif', 'droid sans', 'droid sans mono',
+])
+
+const families = (stack: string): string[] =>
+ stack.split(',').map((f) => f.trim().replace(/^['"]|['"]$/g, '').trim()).filter(Boolean)
+
+/**
+ * The typeface for a CSS stack: its first family that is neither generic nor
+ * one-platform, else the PowerPoint stand-in for its first generic, else the
+ * first family it names, else `fallback`.
+ */
+export function typefaceOf(stack: string | undefined, fallback = 'Arial'): string {
+ const list = families(stack ?? '')
+ const real = list.find((f) => !(f.toLowerCase() in GENERIC) && !ONE_PLATFORM.has(f.toLowerCase()))
+ if (real) return real
+ const generic = list.find((f) => f.toLowerCase() in GENERIC)
+ if (generic) return GENERIC[generic.toLowerCase()]
+ return list[0] ?? fallback
+}
diff --git a/convert/src/pptx-write/index.ts b/convert/src/pptx-write/index.ts
new file mode 100644
index 00000000..68203c43
--- /dev/null
+++ b/convert/src/pptx-write/index.ts
@@ -0,0 +1,573 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// exportPptx — bento/slides → .pptx, the whole package.
+//
+// This is the integrator over the element writers (text/shapes/media/tables/
+// charts) and the package skeleton (parts.ts): it walks the document, allocates
+// every id the writers need (cNvPr shape ids, rel ids, part numbers), and
+// assembles the OPC package with writeZip. The ORCHESTRATION decisions are
+// PR #88's, adopted from its index.ts and credited where they bite:
+//
+// - interactive STATE slides are omitted (a state is a click-reached variant,
+// not a linear slide) and links INTO a state degrade to its visible parent
+// slide, preserving a meaningful navigation target. #88 offered an
+// includeStates option; the simple honest default is the only mode here.
+// - hyperlinks: #88's hyperlink() logic — https?:/mailto:/tel: is an external
+// rel, anything else is a slide id resolved to an internal jump
+// (ppaction://hlinksldjump); a target that resolves to nothing is reported,
+// never emitted dangling.
+// - fx/showOnHover render at their final frame and say so ONCE per slide —
+// #88's dedup rule, which the Report's (code, where) folding provides.
+// - hidden slides export as PowerPoint hidden slides (show="0") — the same
+// "in the deck, out of the show" semantics, so nothing is dropped.
+// - doc.meta → docProps/core.xml (author/subject/keywords, #88's
+// author-or-'bento/slides' default) and app.xml (company).
+//
+// WHAT THE WRITER DOES NOT DO, BY DESIGN: derive the deck's chart palette
+// (deriveChartPalette is app code in slides/src/model.ts) — the caller
+// (src/export.ts) passes it via opts.chartPalette; doc.theme.chartPalette wins when the
+// deck declares one. And no filenames or downloads: this returns BYTES plus the
+// fidelity report; naming and saving are the host's concern (#88's safeName
+// stays app-side).
+//
+// ZIP ENTRY ORDER: [Content_Types].xml is written FIRST. PowerPoint tolerates
+// any order, but a streaming consumer is entitled to refuse to type parts it
+// has already passed — third-party readers have (see zip.ts writeZip).
+
+import { writeZip, type ZipEntry } from '../../../kernel/src/convert/zip.ts'
+import { Report, type FidelityReport } from '../report.ts'
+import { scrubC0, serialize, x, type XChild, type XNode } from '../xmlout.ts'
+import {
+ CT, REL, contentTypes, relsPart, presentationXml, presentationRels,
+ presPropsXml, viewPropsXml, tableStylesXml,
+ themeXml, slideMasterXml, slideMasterRels, slideLayoutXml, slideLayoutRels,
+ notesMasterXml, notesMasterRels, notesSlideXml, notesSlideRels,
+ slidePart, slideLayoutRel, type ContentTypeOverride, type RelEntry,
+} from './parts.ts'
+import { textSp, type FieldValues, type TextElIn } from './text.ts'
+import { emu, parseColor, shapeNode, type ShapeIn } from './shapes.ts'
+import {
+ MediaStore, imagePic, svgPic, mediaPoster,
+ type ImageIn, type MediaCtx, type MediaIn, type SvgIn,
+} from './media.ts'
+import { tableFrame } from './tables.ts'
+import { chartExport } from './charts.ts'
+import type { WriteCtx } from './contract.ts'
+import { packageProblems } from './verify.ts'
+import { writeCode, type CodeElIn } from './code.ts'
+import { writeEmbed, type EmbedElIn } from './embed.ts'
+import type { OutChart, OutTable } from '../types.ts'
+
+// --- input --------------------------------------------------------------------
+// Structural mirror of the REAL bento/slides document (slides/src/model.ts is
+// the ground truth) — same inversion as every other module here: the writer
+// never imports from an app, and the real BentoDoc is a superset whose unknown
+// fields are simply never read. Element inputs reuse the writers' own In types
+// so one definition cannot drift from what its writer actually reads.
+
+/** Fields every element may carry that the INTEGRATOR reads (the writers do
+ * not): presentation effects and the hover-reveal marker (reported static),
+ * and `link` (resolved to a rel here, handed down as an id). */
+interface ElCommon {
+ link?: string
+ fx?: Record<string, unknown>
+ showOnHover?: string
+}
+
+export type ExportElement =
+ | ({ type: 'text' } & TextElIn & ElCommon)
+ | ({ type: 'shape' } & ShapeIn & ElCommon)
+ | (ImageIn & ElCommon) // OutImage already carries type: 'image'
+ | ({ type: 'svg' } & SvgIn & ElCommon)
+ | ({ type: 'chart' } & ChartElIn & ElCommon)
+ | (OutTable & { morphId?: string } & ElCommon) // type: 'table'
+ | ({ type: 'media' } & MediaIn & ElCommon)
+ | (CodeElIn & ElCommon)
+ | (EmbedElIn & ElCommon)
+
+/** OutChart with `preset` loosened to the model's optional free string —
+ * chartExport never consults it (the option's series types decide). */
+export interface ChartElIn {
+ id: string
+ morphId?: string
+ x: number; y: number; w: number; h: number
+ rotation: number
+ opacity: number
+ option: Record<string, unknown>
+ preset?: string
+}
+
+export interface ExportSlide {
+ id: string
+ name?: string
+ background: string
+ transition?: string
+ notes?: string
+ stateOf?: string
+ hidden?: boolean
+ /** hover behaviour object; presence alone is reported (rendered static) */
+ hover?: unknown
+ elements: ExportElement[]
+}
+
+export interface ExportDoc {
+ title: string
+ /** slide coordinate space, px — the package is sized from it (px * 9525) */
+ size: { width: number; height: number }
+ theme: { background: string; color: string; accent: string; fontFamily: string; chartPalette?: string[] }
+ meta?: { author?: string; company?: string; subject?: string; event?: string; keywords?: string }
+ present?: { numberHidden?: boolean }
+ assets?: Record<string, string>
+ /** the deck's own typefaces (slides' doc.fonts); only the names are read */
+ fonts?: Array<{ family: string }>
+ slides: ExportSlide[]
+}
+
+export interface ExportOpts {
+ /** Deck chart palette for charts without an explicit option.color —
+ * doc.theme.chartPalette wins over this; slides-side callers pass
+ * deriveChartPalette(doc.theme.accent) (app code the writer does not import).
+ * Both absent = the ECharts stock colours. */
+ chartPalette?: string[]
+ /** Zip timestamp. Omitted = the fixed 1980 epoch, so two exports of one
+ * deck are byte-identical (dates INSIDE the deck — {{date}} text — still
+ * freeze to export day; that is content, not metadata). */
+ at?: Date
+ /** Counts the formulas in a text element's html. Formulas export as their
+ * source text (PowerPoint does not typeset LaTeX); with this, each slide
+ * that has one says so in the report. The writer cannot find them itself
+ * (the scanner is app code: slides' maths/delimiters.ts), so the caller
+ * passes it, like chartPalette. Absent = not reported. */
+ formulasIn?: (html: string) => number
+}
+
+export interface PptxExport {
+ bytes: Uint8Array
+ report: FidelityReport
+}
+
+// --- helpers ------------------------------------------------------------------
+
+/** #88's hyperlink() test: these schemes leave the package; every other link
+ * value is a slide id. (The task brief says https?; mailto:/tel: are kept
+ * from #88 — both are ordinary external hyperlink rels in OOXML.) */
+const EXTERNAL_LINK_RE = /^(https?:|mailto:|tel:)/i
+
+/** #88's hasUnsupportedFx: the effects that run in present mode and have no
+ * OOXML mapping here — the element itself exports at its final frame. */
+const hasStaticFx = (el: ElCommon): boolean =>
+ !!(el.fx && (el.fx['enter'] || el.fx['countUp'] || el.fx['ambient'] || el.fx['loop'])) || !!el.showOnHover
+
+/** Depth-first hunt for the p:cNvPr of a finished writer node. The trees are
+ * plain data (xmlout XNodes), so the integrator can wire a hyperlink into a
+ * writer that deliberately left links out of scope (media.ts note 4) — or
+ * attach the EXTERNAL variant to shapeNode, whose linkRelId opt is
+ * slide-jump-only. hlinkClick is cNvPr's FIRST optional child in the schema,
+ * and every writer emits cNvPr with attribute-only content, so appending is
+ * safe; shapes' own slide-jump path stays untouched. */
+function attachHlink(node: XNode, rId: string, slideJump: boolean): void {
+ const cNvPr = findNamed(node, 'p:cNvPr')
+ if (!cNvPr) return
+ cNvPr.kids = [
+ ...(cNvPr.kids ?? []),
+ x('a:hlinkClick', { 'r:id': rId, ...(slideJump ? { action: 'ppaction://hlinksldjump' } : {}) }),
+ ]
+}
+
+function findNamed(node: XNode, name: string): XNode | null {
+ if (node.name === name) return node
+ for (const kid of node.kids ?? []) {
+ if (typeof kid !== 'string') {
+ const hit = findNamed(kid, name)
+ if (hit) return hit
+ }
+ }
+ return null
+}
+
+/**
+ * The per-slide p:bg. Bento backgrounds are css — overwhelmingly a solid
+ * colour; anything else (a gradient string, an image url) flattens to the
+ * theme background and is reported, #88's 'slide-background-simplified'.
+ * p:bg is a sibling of p:spTree under p:cSld, which is why slidePart takes it
+ * as an option rather than a shape (parts.ts).
+ */
+function bgNode(css: string, themeBg: string, report: Report, where: string): XNode {
+ let c = parseColor(css)
+ if (!c) {
+ report.add('approximated', 'slide-background-simplified', where,
+ `background '${css}' is not a solid colour; flattened to the theme background`)
+ c = parseColor(themeBg) ?? { hex: 'FFFFFF', alpha: 1 }
+ }
+ const fill = c.alpha <= 0
+ ? x('a:noFill')
+ : x('a:solidFill', undefined, [
+ x('a:srgbClr', { val: c.hex }, c.alpha < 1 ? [x('a:alpha', { val: Math.round(c.alpha * 100000) })] : undefined),
+ ])
+ return x('p:bg', undefined, [x('p:bgPr', undefined, [fill, x('a:effectLst')])])
+}
+
+// Package-level relationship types (docProps wiring). Not in parts.ts REL —
+// those are the ppt-internal vocabulary; these two live only in _rels/.rels.
+const REL_CORE_PROPS = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'
+const REL_APP_PROPS = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties'
+
+/** docProps/core.xml — doc.meta carried as document properties (#88 fed the
+ * same fields through PptxGenJS's author/subject/title setters). The
+ * 'bento/slides' creator default is #88's too: an empty dc:creator makes
+ * some DMS ingest pipelines file the deck under "unknown". */
+function corePropsXml(doc: ExportDoc): string {
+ const m = doc.meta ?? {}
+ // scrubC0 on every author-typed property: a control char pasted into the
+ // About dialog must cost a character, not the export (see xmlout.scrubC0).
+ const kids: XChild[] = [
+ x('dc:title', undefined, doc.title ? [scrubC0(doc.title)] : undefined),
+ x('dc:creator', undefined, [scrubC0(m.author || 'bento/slides')]),
+ ]
+ if (m.subject) kids.push(x('dc:subject', undefined, [scrubC0(m.subject)]))
+ if (m.keywords) kids.push(x('cp:keywords', undefined, [scrubC0(m.keywords)]))
+ return serialize(
+ x('cp:coreProperties', {
+ 'xmlns:cp': 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
+ 'xmlns:dc': 'http://purl.org/dc/elements/1.1/',
+ }, kids),
+ )
+}
+
+function appPropsXml(doc: ExportDoc): string {
+ const kids: XChild[] = [x('Application', undefined, ['Bento Slides'])]
+ if (doc.meta?.company) kids.push(x('Company', undefined, [scrubC0(doc.meta.company)]))
+ return serialize(
+ x('Properties', { xmlns: 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties' }, kids),
+ )
+}
+
+// --- the export ---------------------------------------------------------------
+
+/**
+ * Export one bento/slides document as a complete .pptx package.
+ *
+ * Walks doc.slides in order, skipping interactive states; element dispatch is
+ * document order, which IS z-order in both models (bento paints elements in
+ * array order; OOXML paints spTree children in document order — no sorting).
+ * Returns the package bytes and the fidelity report; throws for a deck with
+ * no linear slides at all (PowerPoint refuses an empty sldIdLst, and an
+ * all-states deck has nothing honest to export) — and, via xmlout's guards,
+ * for machine-level corruption (a non-finite frame coordinate, a control
+ * character in an element id): those are upstream bugs, not documents.
+ * Author-typed TEXT never throws: C0 controls are scrubbed at ingestion
+ * (xmlout.scrubC0) at every point where pasted content reaches a part.
+ */
+export async function exportPptx(doc: ExportDoc, opts: ExportOpts = {}): Promise<PptxExport> {
+ const report = new Report()
+
+ const exported = doc.slides.filter((s) => !s.stateOf)
+ if (exported.length === 0) {
+ throw new Error('exportPptx: the deck has no linear slides (only interactive states) — nothing to export')
+ }
+ const omitted = doc.slides.length - exported.length
+ // The deck's own fonts travel inside the .bento.html; a .pptx can embed
+ // fonts too, but this writer does not, so say which ones need installing.
+ const ownFonts = [...new Set((doc.fonts ?? []).map((f) => f.family).filter(Boolean))]
+ if (ownFonts.length) {
+ report.add('approximated', 'fonts-not-embedded', 'document',
+ `the deck's own fonts (${ownFonts.join(', ')}) are not embedded; install them where the .pptx is opened, or PowerPoint substitutes another font`)
+ }
+
+ if (omitted > 0) {
+ report.add('dropped', 'state-slides-omitted', 'document',
+ `${omitted} interactive state slide(s) omitted — a state is a click-reached variant, not a linear slide`)
+ }
+
+ // Slide id → exported slide number, with #88's degradation: a link into an
+ // omitted state retargets to the state's visible parent.
+ const slideNumbers = new Map<string, number>()
+ exported.forEach((s, i) => slideNumbers.set(s.id, i + 1))
+ for (const s of doc.slides) {
+ if (s.stateOf) {
+ const parent = slideNumbers.get(s.stateOf)
+ if (parent) slideNumbers.set(s.id, parent)
+ }
+ }
+
+ // Field context, ported from slides' render.fieldContext/model.paginates:
+ // states never paginate; hidden slides paginate only when the deck opts into
+ // office-suite numbering (present.numberHidden). One Date for the whole
+ // export so {{date}}/{{time}} agree across slides.
+ const paginates = (s: ExportSlide): boolean => !s.stateOf && (!s.hidden || !!doc.present?.numberHidden)
+ const pages = doc.slides.filter(paginates).length
+ const meta = doc.meta ?? {}
+ const now = new Date()
+
+ const palette = doc.theme.chartPalette?.length ? doc.theme.chartPalette : opts.chartPalette
+ const assets = doc.assets ?? {}
+ const store = new MediaStore() // ONE per export: byte-dedup is cross-slide
+ const enc = new TextEncoder()
+
+ const slideXml: string[] = []
+ const slideRels: string[] = []
+ const notesParts: Array<{ name: string; xml: string; rels: string }> = []
+ const chartParts: Array<{ name: string; xml: string }> = []
+ const extraOverrides: ContentTypeOverride[] = []
+ let chartCount = 0
+ let pageCounter = 0
+
+ for (let si = 0; si < exported.length; si++) {
+ const slide = exported[si]
+ const num = si + 1
+ const where = `slide ${num}`
+ if (paginates(slide)) pageCounter++
+
+ // Field values are author-typed strings that land verbatim in a:t —
+ // scrubbed like every other author-text ingestion point.
+ const fields: FieldValues = {
+ page: pageCounter, pages,
+ title: scrubC0(doc.title), date: now,
+ author: scrubC0(meta.author ?? ''), company: scrubC0(meta.company ?? ''),
+ subject: scrubC0(meta.subject ?? ''), event: scrubC0(meta.event ?? ''),
+ }
+
+ // One rel-id sequence per slide part: layout, hyperlinks, media, charts
+ // and the notesSlide all draw from it (ids are unique per RELS PART).
+ let relSeq = 0
+ const rels: RelEntry[] = []
+ const nextRelId = (): string => `rId${++relSeq}`
+ rels.push(slideLayoutRel(nextRelId()))
+ const mediaCtx: MediaCtx = { assets, store, rels, nextRelId, report }
+
+ /** el.link → an allocated rel. Reported and null when the target does not
+ * resolve (#88's missing-link-target) — a dangling r:id is a repair
+ * dialog, a dropped link is a report entry. */
+ const resolveLink = (link: string | undefined): { rId: string; external: boolean } | null => {
+ if (!link) return null
+ if (EXTERNAL_LINK_RE.test(link)) {
+ const rId = nextRelId()
+ rels.push({ id: rId, type: REL.hyperlink, target: link, external: true })
+ return { rId, external: true }
+ }
+ const target = slideNumbers.get(link)
+ if (!target) {
+ report.add('dropped', 'missing-link-target', where,
+ `link target '${link}' is not an exported slide; the link is dropped`)
+ return null
+ }
+ const rId = nextRelId()
+ rels.push({ id: rId, type: REL.slide, target: `../slides/slide${target}.xml` })
+ return { rId, external: false }
+ }
+
+ /** Post-attach a link to a writer that does not take one (pic, table,
+ * chart frames — and the external case on shapes). Resolved only when a
+ * node actually landed, so a dropped image never allocates a rel. */
+ const wireLink = (node: XNode | null, link: string | undefined): void => {
+ if (!node || !link) return
+ const l = resolveLink(link)
+ if (l) attachHlink(node, l.rId, !l.external)
+ }
+
+ const children: XChild[] = []
+ let shapeId = 2 // the spTree preamble owns id 1 (parts.ts)
+ const emit = (node: XNode | null): void => {
+ if (node) { children.push(node); shapeId++ }
+ }
+
+ for (const el of slide.elements) {
+ if (hasStaticFx(el)) {
+ // once per slide via the Report's (code, where) folding — #88's rule
+ report.add('approximated', 'presentation-effects-static', where,
+ 'entrance/count-up/ambient/hover effects render at their final frame')
+ }
+ switch (el.type) {
+ case 'text': {
+ if (opts.formulasIn && opts.formulasIn(el.html) > 0) {
+ report.add('approximated', 'maths-as-source', where,
+ 'formulas export as their source text (LaTeX); PowerPoint does not typeset them')
+ }
+ const link = resolveLink(el.link)
+ emit(textSp(el, {
+ shapeId,
+ themeFontFamily: doc.theme.fontFamily,
+ fields,
+ ...(link ? { link: { rId: link.rId, ...(link.external ? {} : { slideJump: true }) } } : {}),
+ report, where,
+ }))
+ break
+ }
+ case 'shape': {
+ const link = resolveLink(el.link)
+ // slide jumps ride shapeNode's own opt; external links are attached
+ // after the fact (linkRelId always emits the sldjump action)
+ const node = shapeNode(el, shapeId, report, where,
+ link && !link.external ? { linkRelId: link.rId } : {})
+ if (link?.external) attachHlink(node, link.rId, false)
+ emit(node)
+ break
+ }
+ case 'image': {
+ const node = imagePic(el, shapeId, where, mediaCtx)
+ wireLink(node, el.link)
+ emit(node)
+ break
+ }
+ case 'svg': {
+ const node = svgPic(el, shapeId, where, mediaCtx)
+ wireLink(node, el.link)
+ emit(node)
+ break
+ }
+ case 'chart': {
+ // Rel discipline (charts.ts ChartExport contract): the id is
+ // RESERVED up front; on the table fallback it goes unused — a gap
+ // in the rId sequence, which is legal (ids are names, not indices)
+ // — and no part/rel/override is emitted.
+ const relId = nextRelId()
+ // chartExport reads frame fields + option (and rotation, to report
+ // it); `preset` is never consulted, so the loosened input is safe.
+ const res = chartExport(el as unknown as OutChart, shapeId, relId, palette, report, where)
+ if (res.chartXml) {
+ const name = `ppt/charts/chart${++chartCount}.xml`
+ chartParts.push({ name, xml: res.chartXml })
+ rels.push({ id: relId, type: REL.chart, target: `../charts/chart${chartCount}.xml` })
+ extraOverrides.push({ partName: `/${name}`, contentType: CT.chart })
+ }
+ wireLink(res.frame, el.link)
+ emit(res.frame)
+ break
+ }
+ case 'table': {
+ const node = tableFrame(el, shapeId, report, where)
+ wireLink(node, el.link)
+ emit(node)
+ break
+ }
+ case 'media': {
+ const node = mediaPoster(el, shapeId, where, mediaCtx)
+ wireLink(node, el.link)
+ emit(node)
+ break
+ }
+ // Writers on the contract.ts interface. Both are stubs that report the
+ // element dropped until someone writes them (see their files).
+ case 'code':
+ case 'embed': {
+ const ctx: WriteCtx = { shapeId, report, where, media: mediaCtx, theme: doc.theme }
+ const node = el.type === 'code' ? writeCode(el, ctx) : writeEmbed(el, ctx)
+ wireLink(node, el.link)
+ emit(node)
+ break
+ }
+ default:
+ // A future element type must degrade to a report entry, not a
+ // refused export ("unknown option keys are ignored gracefully" is
+ // the house posture for format growth).
+ report.add('dropped', 'element-unsupported', where,
+ `element type '${(el as { type?: string }).type}' has no pptx mapping`)
+ }
+ }
+
+ // Slide-level features with no mapping, #88's codes: Morph is a PowerPoint
+ // EXTENSION (mc:AlternateContent + p14) this writer does not emit, and
+ // hover focus/reveal has no OOXML equivalent at all.
+ if (slide.transition === 'morph') {
+ report.add('dropped', 'morph-not-exported', where,
+ 'morph transition dropped (PowerPoint Morph is an extension this writer does not emit); slides cut instead')
+ }
+ if (slide.hover) {
+ report.add('approximated', 'hover-static', where,
+ 'hover focus/reveal behaviour is static in PowerPoint; every element renders visible')
+ }
+
+ if ((slide.notes ?? '').trim()) {
+ const m = notesParts.length + 1
+ const name = `ppt/notesSlides/notesSlide${m}.xml`
+ notesParts.push({
+ name,
+ xml: notesSlideXml(scrubC0(slide.notes ?? '').split(/\r?\n/)),
+ rels: notesSlideRels(num),
+ })
+ rels.push({ id: nextRelId(), type: REL.notesSlide, target: `../notesSlides/notesSlide${m}.xml` })
+ extraOverrides.push({ partName: `/${name}`, contentType: CT.notesSlide })
+ }
+
+ const part = slidePart(children, rels, {
+ bg: bgNode(slide.background, doc.theme.background, report, where),
+ ...(slide.hidden ? { hidden: true } : {}),
+ })
+ slideXml.push(part.xml)
+ slideRels.push(part.rels)
+ }
+
+ // --- assembly ---------------------------------------------------------------
+
+ const hasNotes = notesParts.length > 0
+ const n = exported.length
+
+ const overrides: ContentTypeOverride[] = [
+ { partName: '/ppt/presentation.xml', contentType: CT.presentation },
+ { partName: '/ppt/theme/theme1.xml', contentType: CT.theme },
+ { partName: '/ppt/slideMasters/slideMaster1.xml', contentType: CT.slideMaster },
+ { partName: '/ppt/slideLayouts/slideLayout1.xml', contentType: CT.slideLayout },
+ { partName: '/ppt/presProps.xml', contentType: CT.presProps },
+ { partName: '/ppt/viewProps.xml', contentType: CT.viewProps },
+ { partName: '/ppt/tableStyles.xml', contentType: CT.tableStyles },
+ ...(hasNotes ? [
+ { partName: '/ppt/notesMasters/notesMaster1.xml', contentType: CT.notesMaster },
+ { partName: '/ppt/theme/theme2.xml', contentType: CT.theme },
+ ] : []),
+ ...slideXml.map((_, i) => ({ partName: `/ppt/slides/slide${i + 1}.xml`, contentType: CT.slide })),
+ ...extraOverrides, // charts + notesSlides, gathered in the walk
+ { partName: '/docProps/core.xml', contentType: CT.coreProps },
+ { partName: '/docProps/app.xml', contentType: CT.appProps },
+ ]
+
+ const entries: ZipEntry[] = [
+ // [Content_Types].xml MUST be the first entry (see header + zip.ts).
+ { name: '[Content_Types].xml', data: enc.encode(contentTypes(overrides)) },
+ { name: '_rels/.rels', data: enc.encode(relsPart([
+ { id: 'rId1', type: REL.officeDocument, target: 'ppt/presentation.xml' },
+ { id: 'rId2', type: REL_CORE_PROPS, target: 'docProps/core.xml' },
+ { id: 'rId3', type: REL_APP_PROPS, target: 'docProps/app.xml' },
+ ])) },
+ { name: 'docProps/core.xml', data: enc.encode(corePropsXml(doc)) },
+ { name: 'docProps/app.xml', data: enc.encode(appPropsXml(doc)) },
+ // The slide is sized exactly like every element frame: px * 9525 (emu()),
+ // no per-deck scale object — see shapes.ts xfrmNode.
+ { name: 'ppt/presentation.xml', data: enc.encode(
+ presentationXml(n, { cx: emu(doc.size.width), cy: emu(doc.size.height) }, hasNotes)) },
+ { name: 'ppt/_rels/presentation.xml.rels', data: enc.encode(presentationRels(n, hasNotes)) },
+ { name: 'ppt/theme/theme1.xml', data: enc.encode(themeXml(doc.theme)) },
+ { name: 'ppt/presProps.xml', data: enc.encode(presPropsXml()) },
+ { name: 'ppt/viewProps.xml', data: enc.encode(viewPropsXml()) },
+ { name: 'ppt/tableStyles.xml', data: enc.encode(tableStylesXml()) },
+ { name: 'ppt/slideMasters/slideMaster1.xml', data: enc.encode(slideMasterXml()) },
+ { name: 'ppt/slideMasters/_rels/slideMaster1.xml.rels', data: enc.encode(slideMasterRels()) },
+ { name: 'ppt/slideLayouts/slideLayout1.xml', data: enc.encode(slideLayoutXml()) },
+ { name: 'ppt/slideLayouts/_rels/slideLayout1.xml.rels', data: enc.encode(slideLayoutRels()) },
+ ...(hasNotes ? [
+ { name: 'ppt/notesMasters/notesMaster1.xml', data: enc.encode(notesMasterXml()) },
+ { name: 'ppt/notesMasters/_rels/notesMaster1.xml.rels', data: enc.encode(notesMasterRels()) },
+ // the notes master's own theme part (see notesMasterRels)
+ { name: 'ppt/theme/theme2.xml', data: enc.encode(themeXml(doc.theme)) },
+ ] : []),
+ ...slideXml.flatMap((xml, i) => [
+ { name: `ppt/slides/slide${i + 1}.xml`, data: enc.encode(xml) },
+ { name: `ppt/slides/_rels/slide${i + 1}.xml.rels`, data: enc.encode(slideRels[i]) },
+ ]),
+ ...notesParts.flatMap((p, i) => [
+ { name: p.name, data: enc.encode(p.xml) },
+ { name: `ppt/notesSlides/_rels/notesSlide${i + 1}.xml.rels`, data: enc.encode(p.rels) },
+ ]),
+ ...chartParts.map((p) => ({ name: p.name, data: enc.encode(p.xml) })),
+ // Media bytes go in verbatim — already-compressed formats mostly, and
+ // writeZip stores anything DEFLATE would grow.
+ ...store.files().map((f) => ({ name: f.name, data: f.bytes })),
+ ]
+
+ // The self-check (verify.ts): a package with a broken wire is a writer
+ // bug, so it is refused here rather than handed to PowerPoint to repair.
+ const problems = packageProblems(new Map(entries.map((e) => [e.name, e.data])))
+ if (problems.length) throw new Error(`the PowerPoint package failed its self-check (a bug in the writer): ${problems.join('; ')}`)
+ const bytes = await writeZip(entries, opts.at ? { at: opts.at } : {})
+ return { bytes, report: report.build() }
+}
diff --git a/convert/src/pptx-write/media.ts b/convert/src/pptx-write/media.ts
new file mode 100644
index 00000000..6a0fc8d2
--- /dev/null
+++ b/convert/src/pptx-write/media.ts
@@ -0,0 +1,424 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Images and media parts — everything that becomes a p:pic and a file under
+// ppt/media/.
+//
+// A bento image's src is either a data: URI (self-contained decks embed
+// everything), an "asset:<key>" into doc.assets (which itself holds a data:
+// URI or raw markup), or an external URL. The first two carry BYTES and become
+// embedded media parts; the URL case cannot (this engine does no IO — it runs
+// in a browser tab and in node, and an export must not be a network
+// operation), so it becomes a LINKED picture: a:blip r:link with an external
+// image relationship, which PowerPoint resolves at open. Census note: p:pic is
+// the 4th most common shape in real decks (675 across 6/6 files), so this path
+// is not an edge case — it is a quarter of what a converted deck looks like.
+//
+// Identical images repeat across slides constantly (logos, footer marks — the
+// same duplicate-a-slide idiom that gave bento its morph key), so the store
+// DEDUPLICATES by bytes: forty slides with one logo produce one
+// ppt/media/imageN.png, exactly as PowerPoint itself writes it. Rel entries
+// are per-slide and cheap; the bytes are the cost worth sharing.
+//
+// Mapping decisions adopted from PR #88's exporter (slides/src/export/pptx/
+// images.ts, media.ts, svg.ts), kept through the rewrite:
+// - the shape name carries `bento:<morphId||id>` (its objectName trick) so a
+// round-trip back through the importer can recover element identity;
+// - missing/unresolvable sources are a REPORT entry, never a throw — one
+// broken asset must not kill a forty-slide export ('missing-image',
+// 'missing-svg' are its codes);
+// - svg css injects into the markup before embedding, and media data: URIs
+// fall back to the poster still.
+// Where this rewrite is HONEST where #88 was silent: cover/contain fits and
+// svg-without-raster both get report entries now (see below).
+
+import { EMU_PER_PX, type OutElementBase, type OutImage } from '../types.ts'
+import type { Report } from '../report.ts'
+import { x, type XNode } from '../xmlout.ts'
+import { REL, type RelEntry } from './parts.ts'
+
+// --- input shapes ------------------------------------------------------------
+// Structural, like ../types.ts: the writer never imports from an app. OutImage
+// already exists (the importer emits it); svg and media elements are export-
+// only inputs, declared here with exactly the fields this module reads —
+// slides/src/model.ts is the semantic ground truth for every one of them.
+
+export interface SvgIn extends OutElementBase {
+ /** key into assets holding raw SVG markup (preferred in the model: dedupes) */
+ asset?: string
+ /** raw inline markup, used when `asset` is unset */
+ markup?: string
+ /** css the renderer injects inside the svg — must travel with the bytes */
+ css?: string
+}
+
+export interface MediaIn extends OutElementBase {
+ kind: 'video' | 'audio'
+ src: string
+ /** video only: a still shown before playback (data:/asset:/URL) */
+ poster?: string
+ radius?: number
+}
+
+/** OutImage plus the optional morph key (present on real docs, not in the
+ * importer's subset — the name we emit prefers it, matching #88). */
+export type ImageIn = OutImage & { morphId?: string }
+
+// --- data: URI decoding ------------------------------------------------------
+
+const B64: Record<string, number> = {}
+for (let i = 0; i < 64; i++) {
+ B64['ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'[i]] = i
+}
+// URL-safe alphabet too: not what data: URIs are supposed to carry, but
+// content pasted through chat tools produces it and refusing costs a picture.
+B64['-'] = 62
+B64['_'] = 63
+
+/**
+ * Decode a base64 string to bytes. Hand-rolled because the two platform
+ * decoders are both wrong for the writer: Buffer is node-only, and atob
+ * round-trips through a binary STRING (one JS char per byte — an allocation
+ * disaster at 8 MB video scale, and another loop to repack anyway).
+ * Whitespace is skipped (long data URIs get wrapped by editors); padding is
+ * optional. Returns null on any other character — a corrupt src must become a
+ * report entry upstream, not a corrupt image part.
+ */
+export function decodeBase64(s: string): Uint8Array | null {
+ // Worst-case size; trimmed at the end once the real length is known.
+ const out = new Uint8Array((s.length >> 2) * 3 + 3)
+ let acc = 0
+ let bits = 0
+ let n = 0
+ for (let i = 0; i < s.length; i++) {
+ const c = s[i]
+ if (c === '=' || c === ' ' || c === '\n' || c === '\r' || c === '\t') continue
+ const v = B64[c]
+ if (v === undefined) return null
+ acc = (acc << 6) | v
+ bits += 6
+ if (bits >= 8) {
+ bits -= 8
+ out[n++] = (acc >> bits) & 0xff
+ }
+ }
+ return out.subarray(0, n)
+}
+
+export interface DecodedDataUri {
+ mime: string
+ bytes: Uint8Array
+}
+
+/**
+ * Parse a data: URI to mime + bytes. Handles both encodings the grammar
+ * allows: `;base64,<b64>` and the percent-encoded text form (which is how
+ * hand-written svg data URIs usually arrive — #88's own svgDataUri emitted
+ * base64, but pasted content does not). Returns null for anything malformed:
+ * the caller reports and moves on.
+ */
+export function decodeDataUri(uri: string): DecodedDataUri | null {
+ if (!uri.startsWith('data:')) return null
+ const comma = uri.indexOf(',')
+ if (comma < 0) return null
+ const meta = uri.slice(5, comma)
+ const params = meta.split(';')
+ const mime = (params[0] || 'text/plain').trim().toLowerCase()
+ if (params.some((p) => p.trim().toLowerCase() === 'base64')) {
+ const bytes = decodeBase64(uri.slice(comma + 1))
+ return bytes ? { mime, bytes } : null
+ }
+ try {
+ return { mime, bytes: new TextEncoder().encode(decodeURIComponent(uri.slice(comma + 1))) }
+ } catch {
+ return null // malformed %-escape
+ }
+}
+
+// --- the media store ---------------------------------------------------------
+
+/**
+ * Extension per mime — and also the SUPPORT GATE. Everything here is covered
+ * by a Default row in [Content_Types].xml (parts.ts contentTypes); a part
+ * with any other extension would need a Default the integrator does not emit,
+ * and an unmatched part is a repair dialog. So an unlisted mime (webp, bmp,
+ * tiff…) is refused at add() and reported as dropped by the callers — a
+ * missing picture with a named reason beats a deck PowerPoint refuses whole.
+ */
+const EXT_BY_MIME: Record<string, string> = {
+ 'image/png': 'png',
+ 'image/jpeg': 'jpeg',
+ 'image/jpg': 'jpeg', // wrong but seen in the wild; the bytes are jpeg
+ 'image/gif': 'gif',
+ 'image/svg+xml': 'svg',
+}
+
+// FNV-1a, 32-bit — cheap and dependency-free. Only a bucket key: colliding
+// entries compare full bytes below, so a collision costs a memcmp, never a
+// wrong picture.
+function fnv1a(bytes: Uint8Array): number {
+ let h = 0x811c9dc5
+ for (let i = 0; i < bytes.length; i++) {
+ h ^= bytes[i]
+ h = Math.imul(h, 0x01000193)
+ }
+ return h >>> 0
+}
+
+function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {
+ if (a.length !== b.length) return false
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
+ return true
+}
+
+export interface MediaFile {
+ /** full part name inside the package, e.g. 'ppt/media/image3.png' */
+ name: string
+ bytes: Uint8Array
+}
+
+/**
+ * The package's media parts, numbered imageN in add order (PowerPoint's own
+ * naming — media1/media2 is reserved for real embedded audio/video, which
+ * M-export-0 does not produce). One store per EXPORT, shared by every slide,
+ * because dedup across slides is the whole point.
+ */
+export class MediaStore {
+ private parts: MediaFile[] = []
+ private byHash = new Map<string, MediaFile[]>()
+
+ /** Register bytes under a mime; returns the part name (existing on dedup),
+ * or null for a mime outside the supported set (see EXT_BY_MIME). */
+ add(bytes: Uint8Array, mime: string): string | null {
+ const ext = EXT_BY_MIME[mime]
+ if (!ext) return null
+ const key = `${ext}:${bytes.length}:${fnv1a(bytes)}`
+ const bucket = this.byHash.get(key)
+ if (bucket) {
+ for (const f of bucket) if (bytesEqual(f.bytes, bytes)) return f.name
+ }
+ const file: MediaFile = { name: `ppt/media/image${this.parts.length + 1}.${ext}`, bytes }
+ this.parts.push(file)
+ if (bucket) bucket.push(file)
+ else this.byHash.set(key, [file])
+ return file.name
+ }
+
+ files(): readonly MediaFile[] {
+ return this.parts
+ }
+}
+
+// --- per-slide context -------------------------------------------------------
+
+/** What one slide's worth of pic-building needs. The integrator owns rel id
+ * allocation (ids are unique per RELS PART, and layout/notes/hyperlink rels
+ * come from the same sequence), so it passes the allocator in. */
+export interface MediaCtx {
+ /** doc.assets — "asset:<key>" resolves here */
+ assets: Record<string, string>
+ store: MediaStore
+ /** the slide's rel list; this module pushes image rels into it */
+ rels: RelEntry[]
+ nextRelId(): string
+ report: Report
+}
+
+/** "asset:<key>" → the asset's value; anything else passes through. The same
+ * resolution as slides' render.resolveAsset, restated because the writer
+ * cannot import from an app. */
+function resolveSrc(assets: Record<string, string>, ref: string): string {
+ return ref.startsWith('asset:') ? (assets[ref.slice(6)] ?? '') : ref
+}
+
+/** Slide parts live at ppt/slides/, media at ppt/media/ — one hop up. */
+const relTarget = (partName: string): string => `../${partName.slice('ppt/'.length)}`
+
+// --- p:pic assembly ----------------------------------------------------------
+
+/** a:xfrm from the element frame. EMU are integers by definition; rot is in
+ * 60000ths of a degree and omitted at zero (matching what PowerPoint writes,
+ * which keeps output diffable against native files). */
+function xfrm(el: OutElementBase): XNode {
+ return x('a:xfrm', el.rotation ? { rot: Math.round(el.rotation * 60000) } : undefined, [
+ x('a:off', { x: Math.round(el.x * EMU_PER_PX), y: Math.round(el.y * EMU_PER_PX) }),
+ x('a:ext', { cx: Math.round(el.w * EMU_PER_PX), cy: Math.round(el.h * EMU_PER_PX) }),
+ ])
+}
+
+/** rect, or roundRect when the element carries a corner radius. The adj
+ * handle is the radius as a fraction of the SHORTER side in 1000ths of a
+ * percent, capped at 50% — the same conversion, css px → geometry guide,
+ * in both directions of the round trip. */
+function picGeom(el: { w: number; h: number }, radius: number | undefined): XNode {
+ if (!radius || radius <= 0) return x('a:prstGeom', { prst: 'rect' }, [x('a:avLst')])
+ const short = Math.min(el.w, el.h)
+ const adj = short > 0 ? Math.min(50000, Math.round((radius / short) * 100000)) : 0
+ return x('a:prstGeom', { prst: 'roundRect' }, [
+ x('a:avLst', undefined, [x('a:gd', { name: 'adj', fmla: `val ${adj}` })]),
+ ])
+}
+
+interface PicOpts {
+ shapeId: number
+ name: string
+ /** children of a:blip, e.g. alphaModFix or the svgBlip extLst */
+ blipKids?: XNode[]
+ /** external (linked) picture: blip uses r:link instead of r:embed */
+ link?: boolean
+}
+
+function pic(el: OutElementBase, relId: string, radius: number | undefined, opts: PicOpts): XNode {
+ const blipKids: XNode[] = []
+ if (el.opacity < 1) {
+ // Whole-picture transparency lives ON the blip in OOXML (alphaModFix in
+ // 1000ths of a percent), not on the shape — #88 reached the same place
+ // through PptxGenJS's `transparency` option.
+ blipKids.push(x('a:alphaModFix', { amt: Math.round(el.opacity * 100000) }))
+ }
+ if (opts.blipKids) blipKids.push(...opts.blipKids)
+ return x('p:pic', undefined, [
+ x('p:nvPicPr', undefined, [
+ x('p:cNvPr', { id: opts.shapeId, name: opts.name }),
+ x('p:cNvPicPr', undefined, [x('a:picLocks', { noChangeAspect: 1 })]),
+ x('p:nvPr'),
+ ]),
+ x('p:blipFill', undefined, [
+ x('a:blip', { [opts.link ? 'r:link' : 'r:embed']: relId }, blipKids),
+ // Always stretch-to-frame: see the fit note in imagePic.
+ x('a:stretch', undefined, [x('a:fillRect')]),
+ ]),
+ x('p:spPr', undefined, [xfrm(el), picGeom(el, radius)]),
+ ])
+}
+
+const bentoName = (el: { id: string; morphId?: string }): string => `bento:${el.morphId || el.id}`
+
+/**
+ * One image element → a p:pic (registering its media part and rel), or null
+ * with a report entry when nothing usable can be emitted.
+ *
+ * FIT. OOXML's blipFill stretch fills the frame exactly — that IS bento's
+ * 'fill'. 'cover' and 'contain' need the intrinsic pixel size of the image to
+ * compute a srcRect crop or an inset frame, and this engine cannot decode
+ * image dimensions (no DOM, no codecs — a deliberate boundary). So both emit
+ * stretch and report 'image-fit-approximated': the picture is present at the
+ * right place and size, possibly at the wrong aspect. #88 shipped the same
+ * stretch mapping SILENTLY; the report entry is the difference between an
+ * approximation and a lie.
+ */
+export function imagePic(el: ImageIn, shapeId: number, where: string, ctx: MediaCtx): XNode | null {
+ const src = resolveSrc(ctx.assets, el.src)
+ if (!src) {
+ ctx.report.add('dropped', 'missing-image', where, 'image source is empty or its asset reference is dangling')
+ return null
+ }
+
+ if (el.fit !== 'fill') {
+ ctx.report.add('approximated', 'image-fit-approximated', where,
+ `fit '${el.fit}' needs the image's intrinsic size to crop/inset; exported as stretch (right frame, aspect may differ)`)
+ }
+
+ if (src.startsWith('data:')) {
+ const decoded = decodeDataUri(src)
+ const partName = decoded && ctx.store.add(decoded.bytes, decoded.mime)
+ if (!partName) {
+ ctx.report.add('dropped', 'missing-image', where,
+ decoded
+ ? `image format '${decoded.mime}' has no PowerPoint-safe extension; dropped`
+ : 'image data: URI is malformed; dropped')
+ return null
+ }
+ const relId = ctx.nextRelId()
+ ctx.rels.push({ id: relId, type: REL.image, target: relTarget(partName) })
+ return pic(el, relId, el.radius, { shapeId, name: bentoName(el) })
+ }
+
+ // External URL: a LINKED picture (r:link + TargetMode=External). PowerPoint
+ // fetches it at open — the only bytes-free option an IO-less engine has,
+ // and an honest one: the deck referenced the network before export too.
+ const relId = ctx.nextRelId()
+ ctx.rels.push({ id: relId, type: REL.image, target: src, external: true })
+ ctx.report.add('approximated', 'image-linked-not-embedded', where,
+ 'external image URL kept as a linked picture; PowerPoint loads it at open (blank when offline)')
+ return pic(el, relId, el.radius, { shapeId, name: bentoName(el), link: true })
+}
+
+// The registered extension-list URI for svgBlip — a fixed GUID from MS-ODRAWXML,
+// not something we mint. PowerPoint keys the feature off this exact string.
+const SVG_EXT_URI = '{96DAC541-7B7A-43D3-8B79-37D633B846F1}'
+const NS_ASVG = 'http://schemas.microsoft.com/office/drawing/2016/SVG/main'
+
+/**
+ * One svg element → a p:pic whose blip carries asvg:svgBlip.
+ *
+ * The svgBlip extension expects r:embed to point at a RASTER fallback with the
+ * vector riding in extLst; the engine cannot rasterize (same no-codec boundary
+ * as image fits), so r:embed points at the svg part itself and the report says
+ * so: modern PowerPoint (2019+/365) reads the svgBlip and renders the vector,
+ * PowerPoint 2016 falls back to r:embed, cannot decode svg, and shows a blank
+ * frame. 'svg-no-raster-fallback' carries that detail — the user learns which
+ * audience sees what, instead of discovering it in a meeting.
+ *
+ * The css-injection point (splice a <style> into the root tag) is #88's
+ * svg.ts approach verbatim; without it, hover/animation styling that slides
+ * keeps in el.css would silently vanish from the exported artwork.
+ */
+export function svgPic(el: SvgIn, shapeId: number, where: string, ctx: MediaCtx): XNode | null {
+ let markup = (el.asset ? ctx.assets[el.asset] : el.markup) ?? ''
+ if (!markup.trim()) {
+ ctx.report.add('dropped', 'missing-svg', where, 'svg element has no markup (empty or dangling asset reference)')
+ return null
+ }
+ if (el.css) markup = markup.replace(/<svg([^>]*)>/i, `<svg$1><style>${el.css}</style>`)
+ // Standalone svg FILES need the namespace declared; inline markup in a deck
+ // often omits it (the HTML parser never cared). #88 fixed this through the
+ // DOM (setAttribute + XMLSerializer); textually here.
+ if (!/<svg[^>]*\sxmlns=/i.test(markup)) {
+ markup = markup.replace(/<svg/i, '<svg xmlns="http://www.w3.org/2000/svg"')
+ }
+
+ const partName = ctx.store.add(new TextEncoder().encode(markup), 'image/svg+xml')
+ if (!partName) return null // unreachable: svg is always in EXT_BY_MIME
+ const relId = ctx.nextRelId()
+ ctx.rels.push({ id: relId, type: REL.image, target: relTarget(partName) })
+ ctx.report.add('approximated', 'svg-no-raster-fallback', where,
+ 'svg embedded without a raster fallback: PowerPoint 2019+/365 renders it, PowerPoint 2016 shows a blank frame')
+
+ const svgBlip = x('a:extLst', undefined, [
+ x('a:ext', { uri: SVG_EXT_URI }, [
+ // asvg is not in the slide root's xmlns trio; PowerPoint itself declares
+ // it inline on the svgBlip element, so we match that shape exactly.
+ x('asvg:svgBlip', { 'xmlns:asvg': NS_ASVG, 'r:embed': relId }),
+ ]),
+ ])
+ return pic(el, relId, undefined, { shapeId, name: bentoName(el), blipKids: [svgBlip] })
+}
+
+/**
+ * One media (video/audio) element. M-export-0 does not emit playable media —
+ * a real p:pic+videoFile part pair needs the poster embedded as the pic AND
+ * the clip bytes, and clips are routinely URLs or 8 MB embeds — so every
+ * media element is reported 'media-dropped', and when a video carries a
+ * decodable poster, that still is exported in its place (the slide keeps its
+ * visual weight; #88's data-URI branch did the same poster fallback). Returns
+ * the poster p:pic or null.
+ */
+export function mediaPoster(el: MediaIn, shapeId: number, where: string, ctx: MediaCtx): XNode | null {
+ ctx.report.add('dropped', 'media-dropped', where,
+ `${el.kind} not exported (M-export-0 has no playable-media pipeline)` +
+ (el.poster ? '; its poster image stands in on the slide' : ''))
+ const poster = el.poster ? resolveSrc(ctx.assets, el.poster) : ''
+ if (!poster) return null
+ if (poster.startsWith('data:')) {
+ const decoded = decodeDataUri(poster)
+ const partName = decoded && ctx.store.add(decoded.bytes, decoded.mime)
+ if (!partName) return null // the media-dropped entry above already covers it
+ const relId = ctx.nextRelId()
+ ctx.rels.push({ id: relId, type: REL.image, target: relTarget(partName) })
+ return pic(el, relId, el.radius, { shapeId, name: bentoName(el) })
+ }
+ const relId = ctx.nextRelId()
+ ctx.rels.push({ id: relId, type: REL.image, target: poster, external: true })
+ return pic(el, relId, el.radius, { shapeId, name: bentoName(el), link: true })
+}
diff --git a/convert/src/pptx-write/parts.ts b/convert/src/pptx-write/parts.ts
new file mode 100644
index 00000000..c0952798
--- /dev/null
+++ b/convert/src/pptx-write/parts.ts
@@ -0,0 +1,538 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The .pptx package skeleton — every part that is CONTAINER, not content.
+//
+// A .pptx is an OPC package: a ZIP whose parts are typed by [Content_Types].xml
+// and wired together by .rels documents. PowerPoint validates the wiring before
+// it looks at a single shape, and it validates strictly: a slide whose rels do
+// not reach a layout, a layout that does not reach a master, or a master
+// without a theme is a "repair" dialog, not a degraded render. So this module
+// owns the whole chain and the export pipeline only ever fills in spTrees.
+//
+// OUR EXPORT IS FLAT BY DESIGN. A bento/slides deck was either authored flat
+// or resolved flat at import (the importer collapses the layout/master cascade
+// into each slide — that resolution is its whole job). There is nothing left
+// for a master to contribute, so the ONE master, ONE blank layout and ONE theme
+// emitted here exist to satisfy the reader, not to carry style. The census
+// makes the contrast concrete: real decks carry 82–90 layouts and 2–4 masters,
+// and round-tripping through Bento deliberately loses that scaffolding. The
+// theme is not entirely decorative though — doc.theme's colours and first font
+// family go into clrScheme/fontScheme (a mapping adopted from PR #88's
+// exporter, which fed the same two slots through PptxGenJS.theme), so a user
+// who inserts a NEW shape in PowerPoint gets deck-coloured defaults instead of
+// Office blue.
+//
+// The classic hand-writer traps, encoded here so no caller can re-trip them:
+// - p:sldId ids must be >= 256 (and < 2147483648). PptxGenJS hid this from
+// PR #88; a floor of 1 is refused by PowerPoint. SLD_ID_FLOOR below.
+// - p:sldMasterId/p:sldLayoutId ids live in a DIFFERENT range: >= 2147483648.
+// - every p:spTree must open with the nvGrpSpPr/grpSpPr preamble, even an
+// empty one — the schema requires the group-shape header on the root group.
+// - a slideLayout/notesSlide must carry p:clrMapOvr, a master p:clrMap.
+//
+// Part builders return SERIALIZED STRINGS, not trees: a part is finished the
+// moment it is built, and the only consumer is writeZip (via TextEncoder).
+
+import { serialize, x, type XChild, type XNode } from '../xmlout.ts'
+import { typefaceOf } from './fonts.ts'
+
+// --- namespaces, relationship types, content types ---------------------------
+// Mirrors of xml.ts's NS table, plus the write-side vocabularies. Declared as
+// consts so the integrator and every element mapper spell them identically.
+
+const NS_A = 'http://schemas.openxmlformats.org/drawingml/2006/main'
+const NS_P = 'http://schemas.openxmlformats.org/presentationml/2006/main'
+const NS_R = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
+
+/** The xmlns trio every PresentationML part root declares. */
+export const PML_XMLNS: Record<string, string> = {
+ 'xmlns:a': NS_A,
+ 'xmlns:p': NS_P,
+ 'xmlns:r': NS_R,
+}
+
+/** Relationship TYPE URIs (the values of //Relationship/@Type). */
+export const REL = {
+ officeDocument: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
+ slideMaster: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideMaster',
+ slideLayout: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slideLayout',
+ slide: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide',
+ notesMaster: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesMaster',
+ notesSlide: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/notesSlide',
+ theme: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
+ image: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
+ chart: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart',
+ hyperlink: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
+ video: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/video',
+ audio: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio',
+ media: 'http://schemas.microsoft.com/office/2007/relationships/media',
+ presProps: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/presProps',
+ viewProps: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/viewProps',
+ tableStyles: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles',
+} as const
+
+/** Content types for the per-part overrides in [Content_Types].xml. */
+export const CT = {
+ presentation: 'application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml',
+ slide: 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml',
+ slideMaster: 'application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml',
+ slideLayout: 'application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml',
+ notesSlide: 'application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml',
+ notesMaster: 'application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml',
+ theme: 'application/vnd.openxmlformats-officedocument.theme+xml',
+ chart: 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml',
+ coreProps: 'application/vnd.openxmlformats-package.core-properties+xml',
+ appProps: 'application/vnd.openxmlformats-officedocument.extended-properties+xml',
+ presProps: 'application/vnd.openxmlformats-officedocument.presentationml.presProps+xml',
+ viewProps: 'application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml',
+ tableStyles: 'application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml',
+} as const
+
+// --- [Content_Types].xml -----------------------------------------------------
+
+export interface ContentTypeOverride {
+ /** absolute part name, leading slash included: '/ppt/slides/slide1.xml' */
+ partName: string
+ contentType: string
+}
+
+/**
+ * The package's type map. Extension DEFAULTS cover rels/xml and every image
+ * format the export can embed; each XML part whose type is more specific than
+ * "application/xml" needs an OVERRIDE row (presentation, every slide, every
+ * notesSlide, master, layout, theme, every chart) — a slide typed as plain xml
+ * is invisible to PowerPoint even though its rels resolve.
+ *
+ * jpg and jpeg both map to image/jpeg: which extension an embedded image gets
+ * depends on the data-URI's mime spelling upstream, and a missing default for
+ * the one that occurs is a repair dialog.
+ */
+export function contentTypes(overrides: ContentTypeOverride[]): string {
+ const defaults: Array<[string, string]> = [
+ ['rels', 'application/vnd.openxmlformats-package.relationships+xml'],
+ ['xml', 'application/xml'],
+ ['png', 'image/png'],
+ ['jpeg', 'image/jpeg'],
+ ['jpg', 'image/jpeg'],
+ ['gif', 'image/gif'],
+ ['svg', 'image/svg+xml'],
+ ]
+ return serialize(
+ x('Types', { xmlns: 'http://schemas.openxmlformats.org/package/2006/content-types' }, [
+ ...defaults.map(([ext, ct]) => x('Default', { Extension: ext, ContentType: ct })),
+ ...overrides.map((o) => x('Override', { PartName: o.partName, ContentType: o.contentType })),
+ ]),
+ )
+}
+
+// --- .rels documents ---------------------------------------------------------
+
+export interface RelEntry {
+ /** 'rId1'… — unique within ONE rels part only */
+ id: string
+ /** a REL.* URI */
+ type: string
+ /** part-relative target ('../slideLayouts/slideLayout1.xml') or, for
+ * external, the raw URL */
+ target: string
+ /** hyperlinks and linked media leave the package; everything else is
+ * internal and must NOT carry TargetMode (PowerPoint reads its absence as
+ * Internal) */
+ external?: boolean
+}
+
+/** One .rels document. Order is irrelevant to consumers; we keep caller order
+ * so output is deterministic and diffable. */
+export function relsPart(rels: RelEntry[]): string {
+ return serialize(
+ x('Relationships', { xmlns: 'http://schemas.openxmlformats.org/package/2006/relationships' },
+ rels.map((r) =>
+ x('Relationship', {
+ Id: r.id,
+ Type: r.type,
+ Target: r.target,
+ ...(r.external ? { TargetMode: 'External' } : {}),
+ }),
+ ),
+ ),
+ )
+}
+
+// --- presentation.xml --------------------------------------------------------
+
+/** PowerPoint refuses p:sldId values below 256 (ECMA-376 constrains the id to
+ * 256 <= id < 2147483648). The classic hand-writer trap: nothing else in the
+ * file hints at it, the whole deck is just "unreadable". */
+export const SLD_ID_FLOOR = 256
+
+/** p:sldMasterId / p:sldLayoutId live ABOVE the slide-id range: >= 2^31. */
+export const MASTER_ID_BASE = 2147483648
+
+/**
+ * The presentation part. The r:id convention is FIXED here and mirrored by
+ * `presentationRels` — the two must be used together:
+ *
+ * rId1 -> slideMasters/slideMaster1.xml
+ * rId2 … rId(1+slideCount) -> slides/slide<i>.xml (slide i, 1-based)
+ * rId(2+slideCount) -> notesMasters/notesMaster1.xml (when notes exist)
+ *
+ * `hasNotes` must be true iff any notesSlide part is emitted: a notesSlide
+ * without a notesMaster in the chain is a repair dialog, and a dangling
+ * notesMaster rel (no part) is one too.
+ *
+ * p:notesSz is required in practice (PowerPoint writes it always; some readers
+ * NPE without it) — portrait letter, the native default.
+ */
+export function presentationXml(slideCount: number, sizeEMU: { cx: number; cy: number }, hasNotes = false): string {
+ const sldIds: XChild[] = []
+ for (let i = 0; i < slideCount; i++) {
+ sldIds.push(x('p:sldId', { id: SLD_ID_FLOOR + i, 'r:id': `rId${2 + i}` }))
+ }
+ return serialize(
+ x('p:presentation', PML_XMLNS, [
+ x('p:sldMasterIdLst', undefined, [x('p:sldMasterId', { id: MASTER_ID_BASE, 'r:id': 'rId1' })]),
+ // schema order: notesMasterIdLst sits BETWEEN sldMasterIdLst and sldIdLst
+ ...(hasNotes
+ ? [x('p:notesMasterIdLst', undefined, [x('p:notesMasterId', { 'r:id': `rId${2 + slideCount}` })])]
+ : []),
+ x('p:sldIdLst', undefined, sldIds),
+ // EMU are integers by definition; a fractional px * 9525 upstream must
+ // not leak a decimal point into cx/cy.
+ x('p:sldSz', { cx: Math.round(sizeEMU.cx), cy: Math.round(sizeEMU.cy) }),
+ x('p:notesSz', { cx: 6858000, cy: 9144000 }),
+ ]),
+ )
+}
+
+/** The rels partner of `presentationXml` — same convention, generated so the
+ * two can never drift apart. */
+export function presentationRels(slideCount: number, hasNotes = false): string {
+ const rels: RelEntry[] = [
+ { id: 'rId1', type: REL.slideMaster, target: 'slideMasters/slideMaster1.xml' },
+ ]
+ for (let i = 0; i < slideCount; i++) {
+ rels.push({ id: `rId${2 + i}`, type: REL.slide, target: `slides/slide${i + 1}.xml` })
+ }
+ if (hasNotes) {
+ rels.push({ id: `rId${2 + slideCount}`, type: REL.notesMaster, target: 'notesMasters/notesMaster1.xml' })
+ }
+ // The theme rel plus the three property parts every real producer ships.
+ // All four are schema-OPTIONAL, and their absence is exactly what macOS
+ // PowerPoint's repair dialog objects to: the sample from the first cut of
+ // this writer carried none of them, unzip -t and an OPC validator both
+ // passed, and PowerPoint still offered to "repair" it. python-pptx,
+ // PptxGenJS and PowerPoint itself all emit them; a hand writer that skips
+ // "optional" boilerplate is betting against every reader's expectations.
+ let next = 2 + slideCount + (hasNotes ? 1 : 0)
+ rels.push({ id: `rId${next++}`, type: REL.theme, target: 'theme/theme1.xml' })
+ rels.push({ id: `rId${next++}`, type: REL.presProps, target: 'presProps.xml' })
+ rels.push({ id: `rId${next++}`, type: REL.viewProps, target: 'viewProps.xml' })
+ rels.push({ id: `rId${next++}`, type: REL.tableStyles, target: 'tableStyles.xml' })
+ return relsPart(rels)
+}
+
+/** Minimal presentation/view properties and table-style parts — content-free,
+ * but their PRESENCE is load-bearing (see presentationRels). The tblStyleLst
+ * def GUID is the well-known "no style" default every producer uses. */
+export function presPropsXml(): string {
+ return serialize(x('p:presentationPr', { 'xmlns:a': NS_A, 'xmlns:r': NS_R, 'xmlns:p': NS_P }))
+}
+export function viewPropsXml(): string {
+ return serialize(x('p:viewPr', { 'xmlns:a': NS_A, 'xmlns:r': NS_R, 'xmlns:p': NS_P }))
+}
+export function tableStylesXml(): string {
+ return serialize(x('a:tblStyleLst', { 'xmlns:a': NS_A, def: '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}' }))
+}
+
+// --- theme / master / layout chain -------------------------------------------
+
+/** '#abc', '#aabbcc', '#aabbccdd', rgb()/rgba() → 'AABBCC'. Alpha is DROPPED —
+ * clrScheme slots are opaque by definition; translucency lives on shapes.
+ * Anything unparseable (a gradient string, a css keyword) falls back — the
+ * theme is defaults-for-new-shapes, not rendering, so a safe colour beats a
+ * refused file. Normalization shape adopted from PR #88's pptxColor. */
+function hex6(css: string, fallback: string): string {
+ const raw = (css ?? '').trim()
+ const rgb = raw.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)/i)
+ if (rgb) {
+ return [rgb[1], rgb[2], rgb[3]]
+ .map((n) => Math.min(255, Math.max(0, Math.round(Number(n)))).toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase()
+ }
+ let hex = raw.replace(/^#/, '')
+ if (/^[0-9a-f]{3,4}$/i.test(hex)) hex = [...hex].map((c) => c + c).join('')
+ if (/^[0-9a-f]{6,8}$/i.test(hex)) return hex.slice(0, 6).toUpperCase()
+ return fallback
+}
+
+/** First family of a css font stack, quotes stripped — 'Inter, sans-serif' →
+ * 'Inter'. (The same reduction PR #88 fed to PptxGenJS's theme.) */
+function firstFamily(fontFamily: string): string {
+ return typefaceOf(fontFamily)
+}
+
+const srgb = (val: string): XNode => x('a:srgbClr', { val })
+const schemeSlot = (name: string, val: string): XNode => x(`a:${name}`, undefined, [srgb(val)])
+
+/**
+ * theme1.xml. clrScheme carries the deck: dk1 = doc.theme.color (the ink),
+ * lt1 = doc.theme.background, accent1 = doc.theme.accent; the remaining slots
+ * are the stock Office values — Bento's theme has exactly three colours, and
+ * inventing five more accents here would put made-up colours one click away in
+ * PowerPoint's colour picker. fontScheme carries doc.theme.fontFamily's first
+ * family as BOTH major and minor latin (Bento has one deck font, not a
+ * heading/body pair).
+ *
+ * fmtScheme is boilerplate but NOT optional: the schema demands exactly 3 fill
+ * styles, 3 line styles, 3 effect styles and 3 background fills, and PowerPoint
+ * repairs a theme without them. All reference phClr so they stay neutral.
+ */
+export function themeXml(theme: { background: string; color: string; accent: string; fontFamily: string }): string {
+ const dk1 = hex6(theme.color, '000000')
+ const lt1 = hex6(theme.background, 'FFFFFF')
+ const accent1 = hex6(theme.accent, '4472C4')
+ const face = firstFamily(theme.fontFamily)
+
+ const clrScheme = x('a:clrScheme', { name: 'Bento' }, [
+ schemeSlot('dk1', dk1),
+ schemeSlot('lt1', lt1),
+ schemeSlot('dk2', dk1),
+ schemeSlot('lt2', lt1),
+ schemeSlot('accent1', accent1),
+ schemeSlot('accent2', 'ED7D31'),
+ schemeSlot('accent3', 'A5A5A5'),
+ schemeSlot('accent4', 'FFC000'),
+ schemeSlot('accent5', '5B9BD5'),
+ schemeSlot('accent6', '70AD47'),
+ schemeSlot('hlink', '0563C1'),
+ schemeSlot('folHlink', '954F72'),
+ ])
+
+ const fontSet = (tag: string): XNode =>
+ x(tag, undefined, [
+ x('a:latin', { typeface: face }),
+ x('a:ea', { typeface: '' }),
+ x('a:cs', { typeface: '' }),
+ ])
+ const fontScheme = x('a:fontScheme', { name: 'Bento' }, [fontSet('a:majorFont'), fontSet('a:minorFont')])
+
+ const phFill = x('a:solidFill', undefined, [x('a:schemeClr', { val: 'phClr' })])
+ const phGrad = (): XNode =>
+ x('a:gradFill', { rotWithShape: 1 }, [
+ x('a:gsLst', undefined, [
+ x('a:gs', { pos: 0 }, [x('a:schemeClr', { val: 'phClr' }, [x('a:lumMod', { val: 110000 })])]),
+ x('a:gs', { pos: 100000 }, [x('a:schemeClr', { val: 'phClr' }, [x('a:lumMod', { val: 90000 })])]),
+ ]),
+ x('a:lin', { ang: 5400000, scaled: 0 }),
+ ])
+ const phLn = (w: number): XNode =>
+ x('a:ln', { w, cap: 'flat', cmpd: 'sng', algn: 'ctr' }, [phFill, x('a:prstDash', { val: 'solid' })])
+ const fmtScheme = x('a:fmtScheme', { name: 'Office' }, [
+ x('a:fillStyleLst', undefined, [phFill, phGrad(), phGrad()]),
+ x('a:lnStyleLst', undefined, [phLn(6350), phLn(12700), phLn(19050)]),
+ x('a:effectStyleLst', undefined, [
+ x('a:effectStyle', undefined, [x('a:effectLst')]),
+ x('a:effectStyle', undefined, [x('a:effectLst')]),
+ x('a:effectStyle', undefined, [x('a:effectLst')]),
+ ]),
+ x('a:bgFillStyleLst', undefined, [phFill, phFill, phGrad()]),
+ ])
+
+ return serialize(
+ x('a:theme', { 'xmlns:a': NS_A, name: 'Bento' }, [
+ x('a:themeElements', undefined, [clrScheme, fontScheme, fmtScheme]),
+ ]),
+ )
+}
+
+/** The root group header every p:spTree must open with — id 1 is the group
+ * itself, so real shape ids start at 2. */
+function spTreePreamble(): XChild[] {
+ return [
+ x('p:nvGrpSpPr', undefined, [
+ x('p:cNvPr', { id: 1, name: '' }),
+ x('p:cNvGrpSpPr'),
+ x('p:nvPr'),
+ ]),
+ x('p:grpSpPr', undefined, [
+ x('a:xfrm', undefined, [
+ x('a:off', { x: 0, y: 0 }),
+ x('a:ext', { cx: 0, cy: 0 }),
+ x('a:chOff', { x: 0, y: 0 }),
+ x('a:chExt', { cx: 0, cy: 0 }),
+ ]),
+ ]),
+ ]
+}
+
+const spTree = (children: XChild[]): XNode => x('p:spTree', undefined, [...spTreePreamble(), ...children])
+
+// The identity colour map: Bento slides arrive with resolved colours, so the
+// master's map exists only because p:clrMap is a required element with twelve
+// required attributes.
+const CLR_MAP_ATTRS = {
+ bg1: 'lt1', tx1: 'dk1', bg2: 'lt2', tx2: 'dk2',
+ accent1: 'accent1', accent2: 'accent2', accent3: 'accent3', accent4: 'accent4',
+ accent5: 'accent5', accent6: 'accent6', hlink: 'hlink', folHlink: 'folHlink',
+} as const
+
+/** slideMaster1.xml: white bg, empty spTree — pure scaffolding (see header).
+ * Its rels (`slideMasterRels`) reach the one layout and the theme; the layout
+ * id here must match that rels' rId1. */
+export function slideMasterXml(): string {
+ return serialize(
+ x('p:sldMaster', PML_XMLNS, [
+ x('p:cSld', undefined, [
+ x('p:bg', undefined, [
+ x('p:bgPr', undefined, [
+ x('a:solidFill', undefined, [srgb('FFFFFF')]),
+ x('a:effectLst'),
+ ]),
+ ]),
+ spTree([]),
+ ]),
+ x('p:clrMap', CLR_MAP_ATTRS),
+ x('p:sldLayoutIdLst', undefined, [
+ x('p:sldLayoutId', { id: MASTER_ID_BASE + 1, 'r:id': 'rId1' }),
+ ]),
+ ]),
+ )
+}
+
+export function slideMasterRels(): string {
+ return relsPart([
+ { id: 'rId1', type: REL.slideLayout, target: '../slideLayouts/slideLayout1.xml' },
+ { id: 'rId2', type: REL.theme, target: '../theme/theme1.xml' },
+ ])
+}
+
+/** slideLayout1.xml: type="blank", empty spTree, colours mapped straight
+ * through to the master. Every exported slide points here. */
+export function slideLayoutXml(): string {
+ return serialize(
+ x('p:sldLayout', { ...PML_XMLNS, type: 'blank' }, [
+ x('p:cSld', { name: 'Blank' }, [spTree([])]),
+ x('p:clrMapOvr', undefined, [x('a:masterClrMapping')]),
+ ]),
+ )
+}
+
+export function slideLayoutRels(): string {
+ return relsPart([{ id: 'rId1', type: REL.slideMaster, target: '../slideMasters/slideMaster1.xml' }])
+}
+
+/** notesMaster1.xml — required the moment any notesSlide exists (the reader
+ * walks notesSlide → notesMaster → theme and repairs on a broken link). It
+ * shares theme1.xml rather than duplicating it as a theme2: OPC allows many
+ * rels to one part, and the notes surface has no styling of its own to lose. */
+export function notesMasterXml(): string {
+ return serialize(
+ x('p:notesMaster', PML_XMLNS, [
+ x('p:cSld', undefined, [spTree([])]),
+ x('p:clrMap', CLR_MAP_ATTRS),
+ // notesStyle is OPTIONAL in the schema and its absence is a PowerPoint
+ // repair prompt — found by bisection: a one-slide deck whose only extra
+ // feature was a speaker note repaired, and every real notesMaster
+ // carries this element. One level is enough; readers inherit the rest.
+ x('p:notesStyle', undefined, [
+ x('a:lvl1pPr', undefined, [x('a:defRPr', { sz: 1200 })]),
+ ]),
+ ]),
+ )
+}
+
+export function notesMasterRels(): string {
+ // The notes master gets its OWN theme part, never a share of the slide
+ // master's. Same bisection: every real producer pairs each master with its
+ // own theme (slideMaster->theme1, notesMaster->theme2), and PowerPoint's
+ // repair dialog is the price of assuming the association can be many-to-one.
+ return relsPart([{ id: 'rId1', type: REL.theme, target: '../theme/theme2.xml' }])
+}
+
+// --- notesSlide --------------------------------------------------------------
+
+/**
+ * notesSlideN.xml: the speaker notes as plain paragraphs in the body
+ * placeholder (ph type="body" idx="1" is where PowerPoint's notes pane reads
+ * and edits). Bento notes are a single plain-text string; the caller splits on
+ * newlines — an empty line becomes an empty a:p, preserving the author's
+ * paragraph rhythm. A txBody must contain at least one a:p, so zero paragraphs
+ * still emits one empty.
+ *
+ * Pair with `notesSlideRels(n)` for the slide it annotates.
+ */
+export function notesSlideXml(paragraphs: string[]): string {
+ const paras: XChild[] = (paragraphs.length ? paragraphs : ['']).map((text) =>
+ text ? x('a:p', undefined, [x('a:r', undefined, [x('a:t', undefined, [text])])]) : x('a:p'),
+ )
+ return serialize(
+ x('p:notes', PML_XMLNS, [
+ x('p:cSld', undefined, [
+ spTree([
+ x('p:sp', undefined, [
+ x('p:nvSpPr', undefined, [
+ x('p:cNvPr', { id: 2, name: 'Notes Placeholder 1' }),
+ x('p:cNvSpPr', undefined, [x('a:spLocks', { noGrp: 1 })]),
+ x('p:nvPr', undefined, [x('p:ph', { type: 'body', idx: 1 })]),
+ ]),
+ x('p:spPr'),
+ x('p:txBody', undefined, [x('a:bodyPr'), x('a:lstStyle'), ...paras]),
+ ]),
+ ]),
+ ]),
+ x('p:clrMapOvr', undefined, [x('a:masterClrMapping')]),
+ ]),
+ )
+}
+
+/** Rels for notesSlideN.xml: the notes master plus the slide it belongs to
+ * (PowerPoint writes both, and the back-link is how the notes pane binds). */
+export function notesSlideRels(slideNumber: number): string {
+ return relsPart([
+ { id: 'rId1', type: REL.notesMaster, target: '../notesMasters/notesMaster1.xml' },
+ { id: 'rId2', type: REL.slide, target: `../slides/slide${slideNumber}.xml` },
+ ])
+}
+
+// --- slides ------------------------------------------------------------------
+
+/** The rel every slide's rels MUST contain — include it in `relEntries` (the
+ * integrator allocates ids; this helper just fixes type and target). A slide
+ * that cannot reach a layout is refused outright. */
+export function slideLayoutRel(id: string): RelEntry {
+ return { id, type: REL.slideLayout, target: '../slideLayouts/slideLayout1.xml' }
+}
+
+export interface SlidePartOpts {
+ /** a ready p:bg node (background is per-slide in bento); emitted before the
+ * spTree — p:bg is a sibling of p:spTree under p:cSld, not a shape */
+ bg?: XNode
+ /** hidden interactive-state slides exported for link targets */
+ hidden?: boolean
+}
+
+/**
+ * slideN.xml plus its rels. `spTreeChildren` are the finished sp/pic/graphicFrame
+ * nodes from the element mappers; `relEntries` is everything those mappers
+ * allocated (images, charts, hyperlinks, its notesSlide) AND the layout rel —
+ * pass `slideLayoutRel(...)` with an id from the same allocation so ids stay
+ * unique within the part.
+ */
+export function slidePart(
+ spTreeChildren: XChild[],
+ relEntries: RelEntry[],
+ opts: SlidePartOpts = {},
+): { xml: string; rels: string } {
+ const xml = serialize(
+ x('p:sld', { ...PML_XMLNS, ...(opts.hidden ? { show: 0 } : {}) }, [
+ x('p:cSld', undefined, [
+ ...(opts.bg ? [opts.bg] : []),
+ spTree(spTreeChildren),
+ ]),
+ x('p:clrMapOvr', undefined, [x('a:masterClrMapping')]),
+ ]),
+ )
+ return { xml, rels: relsPart(relEntries) }
+}
diff --git a/convert/src/pptx-write/shapes.ts b/convert/src/pptx-write/shapes.ts
new file mode 100644
index 00000000..3194e997
--- /dev/null
+++ b/convert/src/pptx-write/shapes.ts
@@ -0,0 +1,566 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Bento shape → p:sp / p:cxnSp — and the frame/colour helpers every element
+// writer shares (`emu`, `xfrmNode`, `parseColor`, `solidFill`).
+//
+// The mapping decisions here are adopted from PR #88's exporter
+// (slides/src/export/pptx/shapes.ts + color.ts), which proved them against
+// real PowerPoint through PptxGenJS; this module re-expresses them as direct
+// OOXML so the writer stays first-party (no vendored dependency — see
+// docs/DECISIONS.md 2026-08-02). Where #88's library hid a raw-OOXML trap
+// (EMU integrality, schema child order, the a:lin `scaled` flag), the trap is
+// documented at the line that avoids it.
+//
+// UNITS. Bento is CSS px at 96dpi throughout; OOXML wants EMU (px * 9525,
+// always an integer — a decimal point in an off/ext/w attribute is a repair
+// dialog), angles in 60000ths of a degree, and percentages in 1000ths of a
+// percent (100% = 100000).
+//
+// THE LINE GOTCHA, kept from #88: a bento line's colour lives in FILL, not
+// stroke — the renderer paints lines as a stroked SVG line whose stroke attr
+// is what morphs tween, so `fill` is the authored colour and `stroke` is
+// meaningless on lines. Reading `stroke` here exports every line invisible.
+
+import { x, type XChild, type XNode } from '../xmlout.ts'
+import type { Report } from '../report.ts'
+import { EMU_PER_PX } from '../types.ts'
+
+// --- the input shape (structural, never imported from slides/) ---------------
+// The exporter's input is the REAL bento/slides document — a superset of the
+// convert engine's OutShape. These fields mirror slides/src/model.ts
+// ShapeElement; unknown extra fields simply never get read.
+
+export interface ShadowIn { x?: number; y?: number; blur: number; color: string }
+export interface GradientIn { angle: number; stops: Array<{ at: number; color: string }> }
+
+export interface ShapeIn {
+ id: string
+ morphId?: string
+ x: number; y: number; w: number; h: number
+ rotation: number
+ opacity: number
+ shadow?: ShadowIn | ShadowIn[]
+ blur?: number
+ blend?: string
+ backdropFilter?: number
+ shape: 'rect' | 'ellipse' | 'triangle' | 'arrow' | 'line' | 'path'
+ fill: string
+ fillGradient?: GradientIn
+ stroke: string
+ strokeWidth: number
+ radius: number
+ strokeDash?: number
+ strokeStyle?: 'solid' | 'dashed' | 'dotted'
+ lineStart?: 'none' | 'arrow' | 'dot' | 'bar'
+ lineEnd?: 'none' | 'arrow' | 'dot' | 'bar'
+ d?: string
+ pathBox?: [number, number, number, number]
+ from?: unknown
+ to?: unknown
+}
+
+// --- shared frame helper -----------------------------------------------------
+
+/** px → EMU, rounded. EMU are integers BY DEFINITION — `String(1.5)` in a
+ * cx attribute is silently unreadable, so every px→EMU conversion in the
+ * writer must round exactly once, here. */
+export const emu = (px: number): number => Math.round(px * EMU_PER_PX)
+
+export interface Frame { x: number; y: number; w: number; h: number; rotation?: number }
+
+/**
+ * The a:xfrm every element writer places its element with. Bento px map to
+ * EMU 1:1 through EMU_PER_PX (the integrator sizes the slide the same way,
+ * so no per-deck scale factor exists — unlike #88's inch-based geometry).
+ * Rotation is degrees clockwise in both models; OOXML just counts it in
+ * 60000ths. rot is omitted at 0 because PowerPoint omits it — matching the
+ * native shape keeps diffs against real files readable.
+ */
+export function xfrmNode(f: Frame): XNode {
+ const deg = (((f.rotation ?? 0) % 360) + 360) % 360
+ return x('a:xfrm', deg ? { rot: Math.round(deg * 60000) } : undefined, [
+ x('a:off', { x: emu(f.x), y: emu(f.y) }),
+ x('a:ext', { cx: emu(f.w), cy: emu(f.h) }),
+ ])
+}
+
+// --- colours -----------------------------------------------------------------
+// Ported from #88's color.ts: bento authors solid colours as #hex (3/4/6/8
+// digits) or rgb()/rgba() (comma or space separated, alpha 0..1 or %), plus
+// 'transparent'/'none'. OOXML wants six uppercase hex digits with alpha as a
+// separate a:alpha child in 1000ths of a percent.
+
+const clamp = (n: number, lo: number, hi: number) => Math.min(Math.max(n, lo), hi)
+
+/** hex 'RRGGBB' (uppercase) + alpha 0..1. */
+export interface ParsedColor { hex: string; alpha: number }
+
+/**
+ * Parse a bento colour. `transparent`/`none`/empty → alpha 0 (a real value:
+ * "no paint"). Anything unparseable (css keywords, hsl()) → null so the
+ * caller can pick a fallback AND report — #88 fell back silently, but silent
+ * black is exactly the kind of change the fidelity report exists to admit.
+ */
+export function parseColor(value: string | undefined): ParsedColor | null {
+ const raw = (value ?? '').trim()
+ if (!raw || raw === 'none' || raw === 'transparent') return { hex: '000000', alpha: 0 }
+ const rgb = raw.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+)%?)?\s*\)$/i)
+ if (rgb) {
+ const alphaRaw = rgb[4]
+ // A bare number > 1 is a percentage ('50' in 'rgba(0,0,0,50%)' — the
+ // regex eats the % sign); #88's heuristic, kept verbatim.
+ const alpha = alphaRaw === undefined ? 1 : Number(alphaRaw) > 1 ? Number(alphaRaw) / 100 : Number(alphaRaw)
+ return {
+ hex: [rgb[1], rgb[2], rgb[3]]
+ .map((n) => clamp(Math.round(Number(n)), 0, 255).toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase(),
+ alpha: clamp(alpha, 0, 1),
+ }
+ }
+ let hex = raw.replace(/^#/, '')
+ if (/^[0-9a-f]{3,4}$/i.test(hex)) hex = [...hex].map((c) => c + c).join('')
+ if (/^[0-9a-f]{6,8}$/i.test(hex)) {
+ return {
+ hex: hex.slice(0, 6).toUpperCase(),
+ alpha: hex.length === 8 ? parseInt(hex.slice(6), 16) / 255 : 1,
+ }
+ }
+ return null
+}
+
+/** a:srgbClr, with an a:alpha child only when translucent — PowerPoint never
+ * writes a redundant alpha="100000" and neither do we. */
+function srgbNode(c: ParsedColor, opacity = 1): XNode {
+ const a = clamp(c.alpha * clamp(opacity, 0, 1), 0, 1)
+ return x('a:srgbClr', { val: c.hex }, a < 1 ? [x('a:alpha', { val: Math.round(a * 100000) })] : undefined)
+}
+
+/**
+ * a:solidFill (or a:noFill for transparent) from a css colour — the shared
+ * door for text/table writers that need a colour without a Report handle.
+ * Unparseable falls back to opaque black; shapes' own path goes through
+ * `fillOf` below, which reports the fallback.
+ */
+export function solidFill(css: string | undefined, opacity = 1): XNode {
+ const c = parseColor(css) ?? { hex: '000000', alpha: 1 }
+ if (c.alpha * opacity <= 0) return x('a:noFill')
+ return x('a:solidFill', undefined, [srgbNode(c, opacity)])
+}
+
+/** parseColor with the fidelity report on the failure path. */
+function colorOf(css: string | undefined, report: Report, where: string): ParsedColor {
+ const c = parseColor(css)
+ if (c) return c
+ report.add('approximated', 'color-unparsed', where, `colour '${css}' not parseable; exported as black`)
+ return { hex: '000000', alpha: 1 }
+}
+
+// --- gradient ----------------------------------------------------------------
+
+/**
+ * CSS gradient angle → OOXML a:lin@ang. CSS measures the gradient VECTOR
+ * clockwise from "to top" (0 = bottom→top, 90 = left→right — render.ts
+ * cssLinearGradient); OOXML measures it clockwise from 3 o'clock in a y-down
+ * space (0 = left→right, 5400000 = top→bottom). Same rotation direction on
+ * screen, origins 90° apart — so the whole conversion is a -90° phase shift.
+ * This is the exact inverse of the importer's ooxml→css step; the rig
+ * round-trips 90° through both conventions by hand.
+ */
+export function cssAngleToOoxml(cssDeg: number): number {
+ return Math.round(((((cssDeg - 90) % 360) + 360) % 360) * 60000)
+}
+
+/**
+ * a:gradFill from a bento GradientFill. Stop positions are 0..1 → 1000ths of
+ * a percent. `scaled="0"` is load-bearing: a CSS angle is a TRUE angle in the
+ * element's space, while scaled="1" tells PowerPoint the angle was authored
+ * in a unit square and must be skewed by the shape's aspect ratio — with it
+ * set, every gradient on a non-square shape leans wrong.
+ */
+function gradFillNode(g: GradientIn, opacity: number, report: Report, where: string): XNode {
+ const stops = g.stops.map((s) =>
+ x('a:gs', { pos: Math.round(clamp(s.at, 0, 1) * 100000) }, [srgbNode(colorOf(s.color, report, where), opacity)]),
+ )
+ return x('a:gradFill', { rotWithShape: 1 }, [
+ x('a:gsLst', undefined, stops),
+ x('a:lin', { ang: cssAngleToOoxml(g.angle), scaled: 0 }),
+ ])
+}
+
+/** A gradient is only emittable as a:gradFill with TWO OR MORE stops —
+ * CT_GradientStopList's gs has minOccurs="2", so a one-stop gsLst is a
+ * schema-invalid part (repair dialog). SVG paints a one-stop gradient as
+ * that solid colour, so the honest export of a degenerate gradient is the
+ * stop's solid fill — same pixels, valid part. */
+const gradientStops = (el: ShapeIn): number => el.fillGradient?.stops.length ?? 0
+
+/** The shape's interior paint: gradient wins over solid (model contract —
+ * `fill` is kept as the solid fallback), transparent → explicit a:noFill. */
+function fillOf(el: ShapeIn, report: Report, where: string): XNode {
+ if (gradientStops(el) >= 2) return gradFillNode(el.fillGradient!, el.opacity, report, where)
+ // one stop = solid of that stop (see gradientStops); zero = el.fill
+ const css = gradientStops(el) === 1 ? el.fillGradient!.stops[0].color : el.fill
+ const c = colorOf(css, report, where)
+ if (c.alpha * el.opacity <= 0) return x('a:noFill')
+ return x('a:solidFill', undefined, [srgbNode(c, el.opacity)])
+}
+
+// --- stroke ------------------------------------------------------------------
+
+/** Bento tip → OOXML arrowhead. arrow/dot have faithful twins; 'bar' (a flat
+ * perpendicular tick) has NO OOXML twin — the arrowhead vocabulary is
+ * triangle/stealth/diamond/oval/arrow only. #88 chose diamond as the least
+ * dishonest blocky tip; we keep that choice but say so in the report. */
+function tipType(kind: string | undefined, report: Report, where: string): string | null {
+ if (!kind || kind === 'none') return null
+ if (kind === 'arrow') return 'triangle'
+ if (kind === 'dot') return 'oval'
+ report.add('approximated', 'line-tip-approximated', where, `line tip 'bar' has no PowerPoint arrowhead; exported as diamond`)
+ return 'diamond'
+}
+
+/**
+ * a:ln. Child order is schema-fixed: fill, prstDash, headEnd, tailEnd.
+ * A shape with no stroke gets an EXPLICIT a:ln/a:noFill — omitting a:ln
+ * entirely leaves the outline to the theme's line style, and "no stroke in
+ * bento" must not become "thin Office-blue outline in PowerPoint".
+ */
+function lnOf(el: ShapeIn, report: Report, where: string): XNode {
+ const isLine = el.shape === 'line'
+ if (!isLine && el.strokeWidth <= 0) return x('a:ln', undefined, [x('a:noFill')])
+ // The renderer draws lines at max(strokeWidth, 2)px — a 0-width bento line
+ // is still visible on canvas, so it must stay visible in PowerPoint.
+ const wPx = isLine ? Math.max(el.strokeWidth, 2) : el.strokeWidth
+ const dotted = el.strokeStyle === 'dotted'
+ // strokeStyle wins over the legacy px-count strokeDash (model contract).
+ const dashed = el.strokeStyle === 'dashed' || (!el.strokeStyle && (el.strokeDash ?? 0) > 0)
+ // THE line gotcha (see header): a line's colour is its FILL. A gradient
+ // fill on a line becomes a gradient STROKE — a:ln accepts gradFill.
+ const paintCss = isLine
+ ? gradientStops(el) === 1 ? el.fillGradient!.stops[0].color : el.fill
+ : el.stroke
+ const paint = isLine && gradientStops(el) >= 2
+ ? gradFillNode(el.fillGradient!, el.opacity, report, where)
+ : (() => {
+ const c = colorOf(paintCss, report, where)
+ return c.alpha * el.opacity <= 0 ? x('a:noFill') : x('a:solidFill', undefined, [srgbNode(c, el.opacity)])
+ })()
+ const kids: XChild[] = [paint]
+ if (dotted) kids.push(x('a:prstDash', { val: 'sysDot' }))
+ else if (dashed) kids.push(x('a:prstDash', { val: 'dash' }))
+ if (isLine) {
+ const head = tipType(el.lineStart, report, where)
+ const tail = tipType(el.lineEnd, report, where)
+ if (head) kids.push(x('a:headEnd', { type: head, w: 'med', len: 'med' }))
+ if (tail) kids.push(x('a:tailEnd', { type: tail, w: 'med', len: 'med' }))
+ }
+ // Round caps match the renderer (round unless dashed); dotted NEEDS them or
+ // sysDot renders as square specks.
+ const cap = dotted || (isLine && !dashed) ? 'rnd' : undefined
+ return x('a:ln', { w: emu(wPx), ...(cap ? { cap } : {}) }, kids)
+}
+
+// --- shadow ------------------------------------------------------------------
+
+// PowerPoint's shadow UI edits blur up to 100pt and distance up to 200pt;
+// values beyond render but become uneditable sliders. #88 clamped to those
+// limits (via PptxGenJS's validation) and we keep the clamp so a re-opened
+// shadow is always a shadow the user can adjust.
+const MAX_BLUR_EMU = 1270000 // 100pt
+const MAX_DIST_EMU = 2540000 // 200pt
+
+/**
+ * a:effectLst with one a:outerShdw, or null when shadowless. x/y offsets
+ * become polar dist+dir (dir clockwise from 3 o'clock — atan2 in a y-down
+ * space is already clockwise, no sign flip). rotWithShape="0" because CSS
+ * drop-shadow applies after the element's transform: the shadow direction is
+ * a screen-space fact that must not rotate with the shape. Stacked shadows
+ * (bento allows an array) keep the first — the elevation shadow by
+ * convention — and report; #88's simplification, kept.
+ */
+function effectsOf(el: ShapeIn, report: Report, where: string): XNode | null {
+ const s = Array.isArray(el.shadow) ? el.shadow[0] : el.shadow
+ if (Array.isArray(el.shadow) && el.shadow.length > 1) {
+ report.add('approximated', 'multiple-shadows-simplified', where, 'stacked shadows exported as the first only')
+ }
+ if (!s) return null
+ const dx = s.x ?? 0
+ const dy = s.y ?? 0
+ const dir = Math.round((((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360) * 60000)
+ return x('a:effectLst', undefined, [
+ x('a:outerShdw', {
+ blurRad: Math.min(emu(s.blur), MAX_BLUR_EMU),
+ dist: Math.min(emu(Math.hypot(dx, dy)), MAX_DIST_EMU),
+ dir,
+ rotWithShape: 0,
+ }, [srgbNode(colorOf(s.color, report, where), el.opacity)]),
+ ])
+}
+
+// --- geometry ----------------------------------------------------------------
+
+/**
+ * a:custGeom from the SVG path subset bento emits (M/L/H/V/C/Q/Z, absolute
+ * and relative; S/T resolved exactly via control-point reflection). Path
+ * coordinates are ST_AdjCoordinate — INTEGERS — so the path space is scaled
+ * to EMU (px * 9525): sub-pixel curve detail survives the integer floor.
+ * Arcs (A) have no custGeom primitive; they degrade to a straight line to
+ * the arc's endpoint and the report says so — as does any command letter
+ * outside the vocabulary, which additionally stops the parse (continuing
+ * past an unknown command means guessing at its argument count, and a
+ * miscounted queue turns every coordinate after it into garbage).
+ */
+function custGeomNode(el: ShapeIn, report: Report, where: string): XNode {
+ const [bx, by, bw, bh] = el.pathBox ?? [0, 0, el.w, el.h]
+ const pw = Math.max(emu(bw), 1)
+ const ph = Math.max(emu(bh), 1)
+ const px = (v: number) => Math.round((v - bx) * EMU_PER_PX)
+ const py = (v: number) => Math.round((v - by) * EMU_PER_PX)
+ const pt = (X: number, Y: number): XNode => x('a:pt', { x: px(X), y: py(Y) })
+
+ const segs: XChild[] = []
+ let approx = false
+ // tokenizer: command letters and numbers; anything else is caught below
+ const src = el.d ?? ''
+ const tokens = src.match(/[MmLlHhVvCcQqZzAaSsTt]|-?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][+-]?\d+)?/g) ?? []
+ const junk = src.replace(/[MmLlHhVvCcQqZzAaSsTt0-9eE+\-.,\s]/g, '')
+
+ let i = 0
+ let cx = 0, cy = 0 // current point (absolute px)
+ let sx = 0, sy = 0 // subpath start
+ let pcx: number | null = null, pcy = 0 // previous cubic ctrl2 (for S)
+ let pqx: number | null = null, pqy = 0 // previous quad ctrl (for T)
+ const num = () => Number(tokens[i++])
+ const isNum = () => i < tokens.length && !/^[A-Za-z]$/.test(tokens[i])
+
+ let stopped = false
+ while (i < tokens.length && !stopped) {
+ const cmd = tokens[i++]
+ const rel = cmd === cmd.toLowerCase()
+ // S/T reflection state survives only through their own families
+ const keepsCubic = 'CcSs'.includes(cmd)
+ const keepsQuad = 'QqTt'.includes(cmd)
+ switch (cmd.toUpperCase()) {
+ case 'M': {
+ let first = true
+ while (isNum()) {
+ const X = num() + (rel ? cx : 0)
+ const Y = num() + (rel ? cy : 0)
+ if (first) {
+ segs.push(x('a:moveTo', undefined, [pt(X, Y)]))
+ sx = X; sy = Y
+ } else {
+ // extra coordinate pairs after M are implicit lineto (SVG spec)
+ segs.push(x('a:lnTo', undefined, [pt(X, Y)]))
+ }
+ cx = X; cy = Y
+ first = false
+ }
+ break
+ }
+ case 'L':
+ while (isNum()) {
+ cx = num() + (rel ? cx : 0)
+ cy = num() + (rel ? cy : 0)
+ segs.push(x('a:lnTo', undefined, [pt(cx, cy)]))
+ }
+ break
+ case 'H':
+ while (isNum()) {
+ cx = num() + (rel ? cx : 0)
+ segs.push(x('a:lnTo', undefined, [pt(cx, cy)]))
+ }
+ break
+ case 'V':
+ while (isNum()) {
+ cy = num() + (rel ? cy : 0)
+ segs.push(x('a:lnTo', undefined, [pt(cx, cy)]))
+ }
+ break
+ case 'C':
+ while (isNum()) {
+ const x1 = num() + (rel ? cx : 0), y1 = num() + (rel ? cy : 0)
+ const x2 = num() + (rel ? cx : 0), y2 = num() + (rel ? cy : 0)
+ const X = num() + (rel ? cx : 0), Y = num() + (rel ? cy : 0)
+ segs.push(x('a:cubicBezTo', undefined, [pt(x1, y1), pt(x2, y2), pt(X, Y)]))
+ pcx = x2; pcy = y2
+ cx = X; cy = Y
+ }
+ break
+ case 'S':
+ while (isNum()) {
+ // first control = reflection of the previous cubic's second control
+ // about the current point (current point when the previous command
+ // was not a cubic) — resolving it here keeps S EXACT, not approximated
+ const x1: number = pcx === null ? cx : 2 * cx - pcx
+ const y1: number = pcx === null ? cy : 2 * cy - pcy
+ const x2 = num() + (rel ? cx : 0), y2 = num() + (rel ? cy : 0)
+ const X = num() + (rel ? cx : 0), Y = num() + (rel ? cy : 0)
+ segs.push(x('a:cubicBezTo', undefined, [pt(x1, y1), pt(x2, y2), pt(X, Y)]))
+ pcx = x2; pcy = y2
+ cx = X; cy = Y
+ }
+ break
+ case 'Q':
+ while (isNum()) {
+ const x1 = num() + (rel ? cx : 0), y1 = num() + (rel ? cy : 0)
+ const X = num() + (rel ? cx : 0), Y = num() + (rel ? cy : 0)
+ segs.push(x('a:quadBezTo', undefined, [pt(x1, y1), pt(X, Y)]))
+ pqx = x1; pqy = y1
+ cx = X; cy = Y
+ }
+ break
+ case 'T':
+ while (isNum()) {
+ const x1: number = pqx === null ? cx : 2 * cx - pqx
+ const y1: number = pqx === null ? cy : 2 * cy - pqy
+ const X = num() + (rel ? cx : 0), Y = num() + (rel ? cy : 0)
+ segs.push(x('a:quadBezTo', undefined, [pt(x1, y1), pt(X, Y)]))
+ pqx = x1; pqy = y1
+ cx = X; cy = Y
+ }
+ break
+ case 'A':
+ while (isNum()) {
+ num(); num(); num(); num(); num() // rx ry rot large-arc sweep: unused
+ const X = num() + (rel ? cx : 0)
+ const Y = num() + (rel ? cy : 0)
+ segs.push(x('a:lnTo', undefined, [pt(X, Y)]))
+ cx = X; cy = Y
+ approx = true
+ }
+ break
+ case 'Z':
+ segs.push(x('a:close'))
+ cx = sx; cy = sy
+ break
+ default:
+ stopped = true // unreachable given the tokenizer, kept as a belt
+ }
+ if (!keepsCubic) pcx = null
+ if (!keepsQuad) pqx = null
+ }
+ if (junk) {
+ approx = true
+ stopped = true
+ }
+ if (approx || stopped) {
+ report.add('approximated', 'path-approximated', where,
+ 'path uses commands outside the M/L/H/V/C/S/Q/T/Z subset; arcs flattened to lines')
+ }
+ // A pathLst with zero commands is a repair dialog; an unusable d degrades
+ // to the element's box outline (visible, selectable, honestly reported).
+ if (segs.length === 0) {
+ segs.push(
+ x('a:moveTo', undefined, [pt(bx, by)]),
+ x('a:lnTo', undefined, [pt(bx + bw, by)]),
+ x('a:lnTo', undefined, [pt(bx + bw, by + bh)]),
+ x('a:lnTo', undefined, [pt(bx, by + bh)]),
+ x('a:close'),
+ )
+ }
+ return x('a:custGeom', undefined, [
+ x('a:avLst'),
+ x('a:gdLst'),
+ x('a:ahLst'),
+ x('a:cxnLst'),
+ x('a:rect', { l: 0, t: 0, r: pw, b: ph }),
+ x('a:pathLst', undefined, [x('a:path', { w: pw, h: ph }, segs)]),
+ ])
+}
+
+/** Preset geometry for the non-path kinds. roundRect's adj is the corner
+ * radius as a fraction of min(w,h) in 1000ths of a percent, clamped to 0.5
+ * (PowerPoint's own maximum) — #88's formula, kept verbatim. */
+function geomOf(el: ShapeIn, report: Report, where: string): XNode {
+ if (el.shape === 'path') return custGeomNode(el, report, where)
+ if (el.shape === 'rect' && el.radius > 0) {
+ const adj = Math.round(Math.min(el.radius / Math.max(Math.min(el.w, el.h), 1), 0.5) * 100000)
+ return x('a:prstGeom', { prst: 'roundRect' }, [
+ x('a:avLst', undefined, [x('a:gd', { name: 'adj', fmla: `val ${adj}` })]),
+ ])
+ }
+ const prst =
+ el.shape === 'ellipse' ? 'ellipse'
+ : el.shape === 'triangle' ? 'triangle'
+ : el.shape === 'arrow' ? 'rightArrow' // #88's mapping: bento arrows point right at rest
+ : el.shape === 'line' ? 'line'
+ : 'rect'
+ return x('a:prstGeom', { prst }, [x('a:avLst')])
+}
+
+// --- the shape node ----------------------------------------------------------
+
+export interface ShapeOpts {
+ /** rel id of an already-allocated slide-jump hyperlink rel (bento `link`
+ * targets a slide; the integrator resolves slide id → rel). Emitted as
+ * a:hlinkClick with the sldjump action inside cNvPr. */
+ linkRelId?: string
+}
+
+/**
+ * One bento shape element → a finished spTree child.
+ *
+ * - line → p:cxnSp with prst="line" (what PowerPoint itself writes
+ * for a drawn line; the census' 141 prst=line agree)
+ * - path → p:sp with a:custGeom from d/pathBox
+ * - everything → p:sp with a preset geometry
+ *
+ * `shapeId` is the cNvPr id — the integrator numbers from 2 up (the spTree
+ * preamble claims 1). `where` is the report location ('slide 4'). The name
+ * attr carries `bento:<morph key>` (#88's objectName) so a future re-import
+ * can restore morph pairing.
+ */
+export function shapeNode(el: ShapeIn, shapeId: number, report: Report, where: string, opts: ShapeOpts = {}): XNode {
+ // Effects with no OOXML expression at all: named, not silently shed.
+ if (el.blur) report.add('dropped', 'shape-blur-dropped', where, 'element gaussian blur has no shape-level OOXML equivalent')
+ if (el.blend) report.add('dropped', 'blend-mode-dropped', where, 'mix-blend-mode has no OOXML equivalent')
+ if (el.backdropFilter) report.add('dropped', 'backdrop-filter-dropped', where, 'frosted-glass backdrop blur has no OOXML equivalent')
+
+ const cNvPr = x(
+ 'p:cNvPr',
+ { id: shapeId, name: `bento:${el.morphId || el.id}` },
+ opts.linkRelId ? [x('a:hlinkClick', { 'r:id': opts.linkRelId, action: 'ppaction://hlinksldjump' })] : undefined,
+ )
+ const effects = effectsOf(el, report, where)
+
+ if (el.shape === 'line') {
+ // Live connector anchoring is editor-derived geometry; the exported line
+ // keeps the correct absolute endpoints but stops following its elements.
+ if (el.from || el.to) {
+ report.add('approximated', 'connector-detached', where, 'connector exported as a free line (no longer follows its elements)')
+ }
+ // Bento draws the line horizontally across the element box's vertical
+ // CENTER (render.ts: y1 = y2 = h/2); OOXML's line runs corner to corner.
+ // Collapsing the box to zero height at the centerline makes the two
+ // agree — and since both models rotate about the box center, rotation
+ // survives the collapse untouched.
+ const spPr = x('p:spPr', undefined, [
+ xfrmNode({ x: el.x, y: el.y + el.h / 2, w: el.w, h: 0, rotation: el.rotation }),
+ geomOf(el, report, where),
+ lnOf(el, report, where),
+ ...(effects ? [effects] : []),
+ ])
+ return x('p:cxnSp', undefined, [
+ x('p:nvCxnSpPr', undefined, [cNvPr, x('p:cNvCxnSpPr'), x('p:nvPr')]),
+ spPr,
+ ])
+ }
+
+ const spPr = x('p:spPr', undefined, [
+ xfrmNode(el),
+ geomOf(el, report, where),
+ fillOf(el, report, where),
+ lnOf(el, report, where),
+ ...(effects ? [effects] : []),
+ ])
+ return x('p:sp', undefined, [
+ x('p:nvSpPr', undefined, [cNvPr, x('p:cNvSpPr'), x('p:nvPr')]),
+ spPr,
+ // An empty txBody makes the shape typeable in PowerPoint (and mirrors
+ // what PowerPoint writes for every shape it creates).
+ x('p:txBody', undefined, [x('a:bodyPr'), x('a:lstStyle'), x('a:p')]),
+ ])
+}
diff --git a/convert/src/pptx-write/tables.ts b/convert/src/pptx-write/tables.ts
new file mode 100644
index 00000000..ddd5caf6
--- /dev/null
+++ b/convert/src/pptx-write/tables.ts
@@ -0,0 +1,340 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// bento table → p:graphicFrame holding a DrawingML a:tbl.
+//
+// The mapping is a rework of PR #88's tables.ts (which drove PptxGenJS's
+// addTable): per-cell resolved fills (headerBg / zebra / cell override),
+// element opacity folded into every colour, header row → bold + firstRow,
+// borders from the table-wide borderColor/Width, cell padding as margins.
+// What PptxGenJS hid — and this module now owns — is the raw OOXML shape:
+//
+// - a:tblGrid's gridCol widths are EMU integers and PowerPoint lays the
+// table out from THEM, not from the frame. Bento columns are fractional
+// weights, so the split must round without drift: widths are computed as
+// differences of rounded cumulative edges, which sums exactly to the
+// frame width by construction (three equal thirds of 100 come out
+// 33+34+33, never 33+33+33 = a table narrower than its frame).
+// - every a:tr carries an h; the same drift-free split divides the frame
+// height (PowerPoint treats row heights as minimums and grows rows to
+// fit wrapped text, so equal rows is the right default — the browser's
+// table-layout:fixed did the same balancing on the bento side).
+// - a:tcPr's children are ORDERED: lnL/lnR/lnT/lnB must precede the fill,
+// or the part is schema-invalid (a repair dialog, not a rendering bug).
+//
+// Cell content: bento cells hold the same sanitized inline-HTML subset as
+// text elements. Until the text mapper's rich tokenizer is shared, cells go
+// through a plain-text strip (tags removed, entities decoded, <br> = new
+// paragraph) — the INTEGRATOR should reroute htmlParagraphs through the text
+// module's run tokenizer when it lands, so bold/italic spans inside cells
+// stop flattening. Cell-level bold/color/align survive regardless (they are
+// model fields, not markup).
+//
+// Not carried, reported instead: rotation (PowerPoint cannot rotate a table
+// frame — it silently ignores rot on p:graphicFrame) and the outer corner
+// radius (a:tbl has no rounded-outline concept). Both were #88 warnings;
+// same verdicts here through the fidelity report.
+
+import { scrubC0, x, type XChild, type XNode } from '../xmlout.ts'
+import { typefaceOf } from './fonts.ts'
+import { EMU_PER_PX, type OutTable, type OutTableCell } from '../types.ts'
+import type { Report } from '../report.ts'
+
+/** The a:graphicData uri that marks a graphicFrame as a table. */
+export const TABLE_GRAPHIC_URI = 'http://schemas.openxmlformats.org/drawingml/2006/table'
+
+// --- colour ------------------------------------------------------------------
+// css solid → OOXML hex + separate alpha. Shape adopted from PR #88's
+// pptxColor/combineTransparency pair (colour and transparency travel apart in
+// DrawingML: a:srgbClr@val is opaque, a:alpha is a child). Shared with
+// charts.ts (its fallback table and series fills); the integrator may hoist
+// this beside the shape mapper's colour code when consolidating.
+
+export interface CssSolid {
+ /** 'RRGGBB' uppercase */
+ hex: string
+ /** 0..1; 0 = fully transparent (emit no fill at all) */
+ alpha: number
+}
+
+const clamp = (n: number, lo: number, hi: number) => Math.min(Math.max(n, lo), hi)
+
+export function cssSolid(value: string | undefined, fallback: string): CssSolid {
+ const raw = (value ?? '').trim()
+ if (!raw || raw === 'none' || raw === 'transparent') return { hex: fallback, alpha: 0 }
+ const rgb = raw.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+)%?\s*)?\)$/i)
+ if (rgb) {
+ const a = rgb[4] === undefined ? 1 : Number(rgb[4]) > 1 ? Number(rgb[4]) / 100 : Number(rgb[4])
+ return {
+ hex: [rgb[1], rgb[2], rgb[3]]
+ .map((n) => clamp(Math.round(Number(n)), 0, 255).toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase(),
+ alpha: clamp(a, 0, 1),
+ }
+ }
+ let hex = raw.replace(/^#/, '')
+ if (/^[0-9a-f]{3,4}$/i.test(hex)) hex = [...hex].map((c) => c + c).join('')
+ if (/^[0-9a-f]{6,8}$/i.test(hex)) {
+ return { hex: hex.slice(0, 6).toUpperCase(), alpha: hex.length === 8 ? parseInt(hex.slice(6), 16) / 255 : 1 }
+ }
+ // Unparseable (a gradient string, a css keyword): a safe colour beats a
+ // refused file — same posture as the theme builder in parts.ts.
+ return { hex: fallback, alpha: 1 }
+}
+
+/** a:solidFill for a css colour with the element's opacity folded in, or null
+ * when the result is fully transparent (the correct emission is NO fill —
+ * alpha val="0" renders the same but bloats every cell). */
+export function solidFill(css: string | undefined, fallback: string, opacity = 1): XNode | null {
+ const c = cssSolid(css, fallback)
+ const a = c.alpha * clamp(opacity, 0, 1)
+ if (a <= 0) return null
+ return x('a:solidFill', undefined, [
+ x('a:srgbClr', { val: c.hex }, a < 1 ? [x('a:alpha', { val: Math.round(a * 100000) })] : undefined),
+ ])
+}
+
+// --- inline html → plain paragraphs ------------------------------------------
+
+const NAMED_ENTITIES: Record<string, string> = {
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
+}
+
+/**
+ * Sanitized inline HTML → plain-text paragraphs. <br> and closed block tags
+ * split; every other tag is stripped; the five named entities bento's
+ * sanitizer can emit (plus numeric refs) decode. Trailing empty paragraphs
+ * drop but interior blanks survive — an author's deliberate empty line in a
+ * cell keeps its height. See the header: the integrator swaps this for the
+ * text module's tokenizer to keep intra-cell bold/italic.
+ */
+export function htmlParagraphs(html: string): string[] {
+ const text = html
+ .replace(/<br\s*\/?>/gi, '\n')
+ .replace(/<\/(?:p|div|li)\s*>/gi, '\n')
+ .replace(/<[^>]*>/g, '')
+ .replace(/&(#x?[0-9a-fA-F]+|\w+);/g, (m, body: string) => {
+ if (body[0] === '#') {
+ const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10)
+ // Refuse surrogate-range and out-of-range refs the same way the
+ // parser does; a lone surrogate would poison the emitted part.
+ if (!Number.isFinite(code) || code < 0x20 && code !== 9 && code !== 10 && code !== 13 || code > 0x10ffff) return ''
+ return String.fromCodePoint(code)
+ }
+ return NAMED_ENTITIES[body] ?? m
+ })
+ // Literal C0 controls get the same treatment as encoded ones above: dropped
+ // at ingestion (one bad pasted byte costs a character, not the export).
+ const paras = scrubC0(text).split('\n')
+ while (paras.length > 1 && paras[paras.length - 1].trim() === '') paras.pop()
+ return paras
+}
+
+// --- drift-free EMU split ----------------------------------------------------
+
+/**
+ * Split `totalEmu` across fractional weights so the parts are integers AND
+ * sum exactly to the total: each part is the difference of two rounded
+ * cumulative edges. Independent per-part rounding drifts by up to
+ * weights.length/2 EMU — invisible on screen, but the rig (and a strict
+ * diff against PowerPoint's own output) sees a table that no longer fills
+ * its frame. Non-positive weights collapse to zero-width columns rather
+ * than throwing: a zero-weight column exists in the model, so it must
+ * exist in the grid (cell counts have to match gridCol counts).
+ */
+export function splitEmu(weights: number[], totalEmu: number): number[] {
+ const ws = weights.map((w) => (Number.isFinite(w) && w > 0 ? w : 0))
+ const total = ws.reduce((a, b) => a + b, 0) || 1
+ let acc = 0
+ let prevEdge = 0
+ return ws.map((w) => {
+ acc += w
+ const edge = Math.round((totalEmu * acc) / total)
+ const part = edge - prevEdge
+ prevEdge = edge
+ return part
+ })
+}
+
+// --- style defaults ----------------------------------------------------------
+// Mirrors slides' DEFAULT_TABLE_STYLE (model.ts) so an OutTable whose style
+// object is sparse — importer output, hand-written JSON — exports the same
+// look the bento renderer would have given it.
+
+interface TableStyleIn {
+ headerBg: string
+ headerColor: string
+ zebra?: string
+ borderColor: string
+ borderWidth: number
+ cellPadX: number
+ cellPadY: number
+ fontSize: number
+ fontFamily?: string
+ color: string
+ radius: number
+}
+
+const num = (v: unknown, d: number): number => (typeof v === 'number' && Number.isFinite(v) ? v : d)
+const str = (v: unknown): string | undefined => (typeof v === 'string' && v ? v : undefined)
+
+function readStyle(style: Record<string, unknown> | undefined): TableStyleIn {
+ const s = style ?? {}
+ return {
+ headerBg: str(s.headerBg) ?? '#1E2A3A',
+ headerColor: str(s.headerColor) ?? '#FFFFFF',
+ zebra: str(s.zebra),
+ borderColor: str(s.borderColor) ?? 'rgba(30,42,58,0.14)',
+ borderWidth: num(s.borderWidth, 1),
+ cellPadX: num(s.cellPadX, 16),
+ cellPadY: num(s.cellPadY, 11),
+ fontSize: num(s.fontSize, 18),
+ fontFamily: str(s.fontFamily),
+ color: str(s.color) ?? '#1E2A3A',
+ radius: num(s.radius, 10),
+ }
+}
+
+/** First family of a css stack, quotes stripped — the run-level a:latin wants
+ * one typeface name. Absent = omit; the theme's minor font (the deck font,
+ * per parts.ts) then applies. */
+const firstFamily = (stack: string | undefined): string | undefined =>
+ stack?.trim() ? typefaceOf(stack) : undefined
+
+// --- the mapper --------------------------------------------------------------
+
+const ALIGN_MAP: Record<string, string> = { center: 'ctr', right: 'r', justify: 'just' }
+
+/**
+ * One bento table element → a finished p:graphicFrame node for slidePart's
+ * spTreeChildren. `shapeId` is the cNvPr id (the integrator numbers from 2 —
+ * the spTree preamble owns 1); `where` is the report locus ('slide 3').
+ */
+export function tableFrame(el: OutTable, shapeId: number, report: Report, where: string): XNode {
+ const st = readStyle(el.style)
+ const cx = Math.round(el.w * EMU_PER_PX)
+ const cy = Math.round(el.h * EMU_PER_PX)
+ const colW = splitEmu(el.columns.map((c) => c.w), cx)
+ const rowH = splitEmu(el.rows.map(() => 1), cy)
+ const opacity = clamp(num(el.opacity, 1), 0, 1)
+ const borderW = Math.round(Math.max(st.borderWidth, 0) * EMU_PER_PX)
+
+ // One border description shared by all four sides of every cell — bento
+ // draws a uniform grid (border on every cell in renderTableHtml), so the
+ // doubled inner edges PowerPoint collapses are what the browser collapsed
+ // too. Fresh nodes per cell: xmlout trees are plain data, but sharing one
+ // node across thousands of cells makes any later in-place edit a
+ // spooky-action bug.
+ const borderSides = (): XChild[] => {
+ if (borderW <= 0) return []
+ return ['a:lnL', 'a:lnR', 'a:lnT', 'a:lnB'].map((side) =>
+ x(side, { w: borderW, cap: 'flat' }, [
+ solidFill(st.borderColor, '000000', opacity) ?? x('a:noFill'),
+ x('a:prstDash', { val: 'solid' }),
+ ]),
+ )
+ }
+
+ const face = firstFamily(st.fontFamily)
+ // bento px → pt → centipoints, clamped to ST_TextFontSize's 100..400000
+ const szCentiPt = clamp(Math.round(st.fontSize * 0.75 * 100), 100, 400000)
+
+ const cellNode = (cell: OutTableCell | undefined, ri: number): XNode => {
+ const isHeader = el.header && ri === 0
+ // Zebra parity follows render.ts (the on-screen truth): body rows count
+ // from 0 below the header and stripe the ODD ones. PR #88 striped
+ // ri % 2 === 0 of the RAW index, which matches only when a header row is
+ // present — the header-less case was off by one there.
+ const bodyIndex = el.header ? ri - 1 : ri
+ const stripe = !isHeader && st.zebra && bodyIndex % 2 === 1 ? st.zebra : undefined
+ const bg = cell?.bg || (isHeader ? st.headerBg : stripe)
+ const fg = cell?.color || (isHeader ? st.headerColor : st.color)
+ const bold = (cell?.bold ?? false) || isHeader
+ const algn = ALIGN_MAP[cell?.align ?? '']
+
+ const paras = htmlParagraphs(cell?.html ?? '')
+ // Fresh rPr nodes per paragraph (not one shared subtree) — plain data,
+ // but sharing invites spooky-action edits later.
+ const runProps = (): XNode => {
+ const kids: XChild[] = []
+ const fill = solidFill(fg, '000000', opacity)
+ if (fill) kids.push(fill)
+ if (face) kids.push(x('a:latin', { typeface: face }))
+ return x('a:rPr', { sz: szCentiPt, ...(bold ? { b: 1 } : {}) }, kids.length ? kids : undefined)
+ }
+ const pNodes: XChild[] = (paras.length ? paras : ['']).map((text) => {
+ const pKids: XChild[] = []
+ if (algn) pKids.push(x('a:pPr', { algn }))
+ if (text) {
+ pKids.push(x('a:r', undefined, [runProps(), x('a:t', undefined, [text])]))
+ } else {
+ // An empty paragraph still declares its size so empty rows keep the
+ // same height PowerPoint would give a populated one.
+ pKids.push(x('a:endParaRPr', { sz: szCentiPt }))
+ }
+ return x('a:p', undefined, pKids)
+ })
+
+ // tcPr child order is fixed by the schema: borders, THEN fill.
+ const tcPrKids: XChild[] = [...borderSides()]
+ const bgFill = solidFill(bg, 'FFFFFF', opacity)
+ if (bgFill) tcPrKids.push(bgFill)
+ return x('a:tc', undefined, [
+ x('a:txBody', undefined, [x('a:bodyPr'), x('a:lstStyle'), ...pNodes]),
+ x('a:tcPr', {
+ marL: Math.round(st.cellPadX * EMU_PER_PX),
+ marR: Math.round(st.cellPadX * EMU_PER_PX),
+ marT: Math.round(st.cellPadY * EMU_PER_PX),
+ marB: Math.round(st.cellPadY * EMU_PER_PX),
+ // Browsers vertically centre td content by default and bento renders
+ // cells with vertical-align:middle explicitly — anchor ctr matches.
+ anchor: 'ctr',
+ }, tcPrKids.length ? tcPrKids : undefined),
+ ])
+ }
+
+ const rows: XChild[] = el.rows.map((row, ri) =>
+ x('a:tr', { h: rowH[ri] },
+ // Cell count MUST equal gridCol count in every row — a ragged model row
+ // (mid-edit collab state) pads with empty cells rather than emitting an
+ // invalid tr.
+ el.columns.map((_, ci) => cellNode(row.cells[ci], ri)),
+ ),
+ )
+
+ // firstRow/bandRow are style FLAGS, not styling: with no a:tableStyleId we
+ // paint every cell explicitly (nothing for a style to contribute), but the
+ // flags mean a user who applies a PowerPoint table style later gets the
+ // header/banding treatment in the right places. #88's firstRow mapping.
+ const tbl = x('a:tbl', undefined, [
+ x('a:tblPr', { ...(el.header ? { firstRow: 1 } : {}), ...(st.zebra ? { bandRow: 1 } : {}) }),
+ x('a:tblGrid', undefined, colW.map((w) => x('a:gridCol', { w }))),
+ ...rows,
+ ])
+
+ if (el.rotation) {
+ report.add('dropped', 'table-rotation-dropped', where,
+ 'PowerPoint cannot rotate tables; the table exports axis-aligned (same limitation PR #88 hit)')
+ }
+ if (st.radius > 0) {
+ report.add('dropped', 'table-radius-dropped', where,
+ 'a:tbl has no outer corner radius; corners export square')
+ }
+
+ const morphId = (el as OutTable & { morphId?: string }).morphId
+ return x('p:graphicFrame', undefined, [
+ x('p:nvGraphicFramePr', undefined, [
+ // name carries the bento identity (morph key) so a round-trip can
+ // re-pair elements — #88's objectName convention.
+ x('p:cNvPr', { id: shapeId, name: `bento:${morphId || el.id}` }),
+ x('p:cNvGraphicFramePr', undefined, [x('a:graphicFrameLocks', { noGrp: 1 })]),
+ x('p:nvPr'),
+ ]),
+ x('p:xfrm', undefined, [
+ x('a:off', { x: Math.round(el.x * EMU_PER_PX), y: Math.round(el.y * EMU_PER_PX) }),
+ x('a:ext', { cx, cy }),
+ ]),
+ x('a:graphic', undefined, [x('a:graphicData', { uri: TABLE_GRAPHIC_URI }, [tbl])]),
+ ])
+}
diff --git a/convert/src/pptx-write/text.ts b/convert/src/pptx-write/text.ts
new file mode 100644
index 00000000..bbcdaf55
--- /dev/null
+++ b/convert/src/pptx-write/text.ts
@@ -0,0 +1,445 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Bento text element → p:sp with a p:txBody.
+//
+// The mapping decisions here are PR #88's (its exporter drove real PowerPoint
+// through PptxGenJS and learned where the bodies are); the emission is
+// first-party OOXML through xmlout. Adopted from #88 and credited inline where
+// they bite: the b/i/u/br run walker with its trailing-break trim, CODE →
+// Courier New, fontWeight ≥ 600 → bold, per-run hyperlinks, zero text-box
+// insets, shrink-to-fit, the `bento:<id>` object name, and the
+// text-gradient/effects report codes. Where this module DIVERGES from #88 it
+// says so and why — a first-party writer is not bound by PptxGenJS's blind
+// spots (strike-through, hollow glyphs, real letter-spacing).
+//
+// No DOM anywhere: the input html is the sanitizer's inline subset
+// (render.ts ALLOWED_TAGS: B I U BR SPAN DIV P STRONG EM S CODE — attributes
+// already stripped), which a ~40-line tokenizer covers completely. The writer
+// must run under node, and pulling in a DOM shim for eleven known tags would
+// be the dependency this rework exists to delete.
+
+import { EMU_PER_PX } from '../types.ts'
+import type { Report } from '../report.ts'
+import { typefaceOf } from './fonts.ts'
+import { scrubC0, x, type XChild, type XNode } from '../xmlout.ts'
+
+// --- input --------------------------------------------------------------------
+// Structural subset of slides' TextElement (same inversion as types.ts: the
+// writer never imports from an app). The real element is a superset; unknown
+// fields are ignored, the effect-shaped ones are read only to REPORT them.
+
+export interface TextElIn {
+ id: string
+ morphId?: string
+ x: number; y: number; w: number; h: number
+ /** degrees, clockwise */
+ rotation: number
+ opacity: number
+ /** sanitized inline html (render.ts sanitizeHtml's subset) */
+ html: string
+ /** px — bento's canvas unit, NOT points */
+ fontSize: number
+ fontFamily: string
+ fontWeight: number
+ color: string
+ align: 'left' | 'center' | 'right'
+ valign: 'top' | 'middle' | 'bottom'
+ /** multiplier (1.25 = 125%) */
+ lineHeight: number
+ /** px tracking for letter-spaced caps labels */
+ letterSpacing?: number
+ textStroke?: { width: number; color: string; fill?: string }
+ placeholder?: string
+ colorGradient?: unknown
+ shadow?: unknown
+ blur?: number
+ blend?: string
+ backdropFilter?: number
+}
+
+/** Values dynamic field tokens resolve against — same shape render.ts's
+ * FieldContext computes per slide; the caller ports fieldContext's arithmetic
+ * (page = 1-based position among non-state slides). */
+export interface FieldValues {
+ page: number
+ pages: number
+ title: string
+ date: Date
+ author: string
+ company: string
+ subject: string
+ event: string
+}
+
+export interface TextSpOpts {
+ /** p:cNvPr id — the integrator allocates, starting at 2 (the spTree preamble
+ * claims 1) */
+ shapeId: number
+ /** doc.theme.fontFamily — the fallback when the element has no stack */
+ themeFontFamily: string
+ /** omit = {{tokens}} stay literal text, mirroring resolveFields without ctx */
+ fields?: FieldValues
+ /** element `link` mapped upstream: the integrator allocates the rel (slide
+ * jump or external URL) and hands the id down */
+ link?: { rId: string; slideJump?: boolean }
+ report?: Report
+ /** source location for report entries, e.g. 'slide 4' */
+ where?: string
+}
+
+// --- colour -------------------------------------------------------------------
+// Ported from #88's pptxColor, alpha kept 0..1 instead of a transparency
+// percentage (raw OOXML wants a:alpha in 1000ths of a percent, so the
+// percentage detour would just round twice).
+
+export interface CssColor { hex: string; alpha: number }
+
+const clamp = (n: number, lo: number, hi: number) => Math.min(Math.max(n, lo), hi)
+
+/** '#abc', '#aabbccdd', rgb()/rgba(), 'transparent' → six-digit hex + alpha.
+ * Unparseable input falls back opaque: a wrong-but-visible colour beats an
+ * invisible run the author cannot diagnose. */
+export function cssColor(value?: string, fallback = '000000'): CssColor {
+ const raw = (value ?? '').trim()
+ if (!raw || raw === 'none' || raw === 'transparent') return { hex: fallback, alpha: 0 }
+ const rgb = raw.match(/^rgba?\(\s*([\d.]+)[,\s]+([\d.]+)[,\s]+([\d.]+)(?:\s*[,/]\s*([\d.]+)%?)?\s*\)$/i)
+ if (rgb) {
+ const a = rgb[4] === undefined ? 1 : Number(rgb[4]) > 1 ? Number(rgb[4]) / 100 : Number(rgb[4])
+ return {
+ hex: [rgb[1], rgb[2], rgb[3]]
+ .map((n) => clamp(Math.round(Number(n)), 0, 255).toString(16).padStart(2, '0'))
+ .join('')
+ .toUpperCase(),
+ alpha: clamp(a, 0, 1),
+ }
+ }
+ let hex = raw.replace(/^#/, '')
+ if (/^[0-9a-f]{3,4}$/i.test(hex)) hex = [...hex].map((c) => c + c).join('')
+ if (/^[0-9a-f]{6,8}$/i.test(hex)) {
+ return { hex: hex.slice(0, 6).toUpperCase(), alpha: hex.length === 8 ? parseInt(hex.slice(6), 16) / 255 : 1 }
+ }
+ return { hex: fallback, alpha: 1 }
+}
+
+/** a:solidFill; a:alpha only when translucent — PowerPoint writes opaque
+ * colours bare, and matching the native shape keeps diffs readable. */
+function solidFill(hex: string, alpha: number): XNode {
+ return x('a:solidFill', undefined, [
+ x('a:srgbClr', { val: hex }, alpha < 1 ? [x('a:alpha', { val: Math.round(clamp(alpha, 0, 1) * 100000) })] : undefined),
+ ])
+}
+
+// --- the inline-html tokenizer ------------------------------------------------
+
+export interface RunStyle {
+ bold?: boolean
+ italic?: boolean
+ underline?: boolean
+ strike?: boolean
+ /** CODE → Courier New, #88's mapping (OOXML has no semantic code run) */
+ code?: boolean
+}
+
+export interface InlineRun {
+ text: string
+ style: RunStyle
+ /** a line break follows this run. A FLAG, not a token — #88's breakLine
+ * semantics, kept exactly: consecutive <br><br> collapse into one break. */
+ breakAfter: boolean
+}
+
+// Entities the sanitizer's innerHTML round-trip can emit: the five XML-ish
+// named ones, &nbsp; (contentEditable's favourite), and numeric references.
+const NAMED_ENTITIES: Record<string, string> = {
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ',
+}
+
+function decodeEntities(s: string): string {
+ return s.replace(/&(#[0-9]+|#[xX][0-9a-fA-F]+|[a-zA-Z]+);/g, (m, body: string) => {
+ if (body[0] === '#') {
+ const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10)
+ // C0 controls (minus tab/lf/cr) are unrepresentable in XML 1.0 — xmlout
+ // would throw on the whole part. One corrupt entity must not kill an
+ // export, so it decodes to nothing.
+ if (!Number.isFinite(code) || code > 0x10ffff) return m
+ if (code < 0x20 && code !== 9 && code !== 10 && code !== 13) return ''
+ return String.fromCodePoint(code)
+ }
+ return NAMED_ENTITIES[body.toLowerCase()] ?? m
+ })
+}
+
+const sameStyle = (a: RunStyle, b: RunStyle): boolean =>
+ !a.bold === !b.bold && !a.italic === !b.italic && !a.underline === !b.underline &&
+ !a.strike === !b.strike && !a.code === !b.code
+
+/**
+ * Parse the sanitized inline subset into flat styled runs — #88's richRuns
+ * walker without the DOM. b/strong, i/em, u, s/strike nest via a style stack;
+ * br marks a break; span is transparent; any other tag (the sanitizer should
+ * have unwrapped it, but paste boundaries have leaked before) contributes only
+ * its children's text. Attributes are skipped unparsed — the sanitizer strips
+ * them, and nothing here should trust one that survived.
+ *
+ * ONE deliberate divergence from #88: div/p mark a break on OPEN as well as on
+ * close. contentEditable's most common shape is `line1<div>line2</div>` — the
+ * first line bare, each further line wrapped — and close-only breaking glues
+ * line1 to line2 (a real #88 bug, visible in its own output). The breakAfter
+ * flag is idempotent, so `</div><div>` seams still collapse to one break.
+ *
+ * The TRAILING-BREAK TRIM is #88's, kept exactly: contentEditable loves to
+ * leave a final <br> (or an empty trailing <div>), and without the trim every
+ * exported box gains a phantom empty line that PowerPoint then includes in
+ * anchor math — a bottom-anchored label visibly floats one line high. The rig
+ * demonstrates the phantom by passing trimTrailingBreak=false.
+ */
+export function parseInlineHtml(html: string, trimTrailingBreak = true): InlineRun[] {
+ const runs: InlineRun[] = []
+ const stack: RunStyle[] = [{}]
+
+ const pushText = (raw: string) => {
+ // The canvas paints this html with white-space:normal, so runs of
+ // ordinary whitespace collapse to one space in every Bento surface — the
+ // export matches the PAINT, not the markup. &nbsp; (U+00A0) is not in the
+ // class and survives, which is exactly how authors spell a hard space.
+ // scrubC0: a LITERAL control char (a bad paste, a corrupt import) gets the
+ // same treatment the entity decoder gives an encoded one — dropped, so it
+ // costs a character instead of throwing away the whole export at serialize.
+ let text = scrubC0(decodeEntities(raw)).replace(/[ \t\r\n]+/g, ' ')
+ const last = runs[runs.length - 1]
+ // browser layout also eats whitespace at a line start / across a seam
+ if (!last || last.breakAfter || last.text.endsWith(' ')) text = text.replace(/^ +/, '')
+ if (!text) return
+ const style = stack[stack.length - 1]
+ if (last && !last.breakAfter && sameStyle(last.style, style)) last.text += text
+ else runs.push({ text, style: { ...style }, breakAfter: false })
+ }
+
+ const markBreak = () => {
+ if (runs.length) runs[runs.length - 1].breakAfter = true
+ else runs.push({ text: '', style: {}, breakAfter: true })
+ }
+
+ const TAG = /<\/?([a-zA-Z][a-zA-Z0-9]*)(?:[\s/][^>]*)?>/g
+ let pos = 0
+ for (let m = TAG.exec(html); m; m = TAG.exec(html)) {
+ if (m.index > pos) pushText(html.slice(pos, m.index))
+ pos = m.index + m[0].length
+ const closing = m[0][1] === '/'
+ const tag = m[1].toUpperCase()
+ if (tag === 'BR') { markBreak(); continue }
+ if (tag === 'DIV' || tag === 'P') { if (runs.length) markBreak(); continue }
+ const next = { ...stack[stack.length - 1] }
+ switch (tag) {
+ case 'B': case 'STRONG': next.bold = true; break
+ case 'I': case 'EM': next.italic = true; break
+ case 'U': next.underline = true; break
+ case 'S': case 'STRIKE': next.strike = true; break
+ case 'CODE': next.code = true; break
+ default: continue // span + unknown: transparent, children pass through
+ }
+ if (closing) { if (stack.length > 1) stack.pop() }
+ else stack.push(next)
+ }
+ if (pos < html.length) pushText(html.slice(pos))
+
+ if (trimTrailingBreak && runs.length) runs[runs.length - 1].breakAfter = false
+ return runs
+}
+
+// --- dynamic fields -----------------------------------------------------------
+// resolveFields' semantics PORTED, not imported (the writer does not reach into slides/):
+// same token grammar, same zero-pad rule ({{page:2}} → "06"), same
+// empty-string default for missing doc-props. The two tokens PowerPoint can
+// keep LIVE become a:fld — {{page}} → type="slidenum" (330 census hits, THE
+// footer field) and {{date}} → type="datetime"; every other token freezes to
+// the text it resolved to at export time.
+
+const FIELD_RE = /\{\{\s*(page|pages|title|date|time|author|company|subject|event)(?::([^}]*))?\s*\}\}/gi
+
+const pad = (n: number, arg?: string): string => {
+ const w = parseInt(arg ?? '', 10)
+ return w > 0 ? String(n).padStart(w, '0') : String(n)
+}
+
+type Piece =
+ | { kind: 'text'; text: string }
+ | { kind: 'fld'; type: 'slidenum' | 'datetime'; cached: string; frozenPad: boolean }
+
+function splitFields(text: string, ctx: FieldValues | undefined, onFrozen: (token: string) => void): Piece[] {
+ if (!ctx || text.indexOf('{{') < 0) return [{ kind: 'text', text }]
+ const pieces: Piece[] = []
+ let pos = 0
+ FIELD_RE.lastIndex = 0
+ for (let m = FIELD_RE.exec(text); m; m = FIELD_RE.exec(text)) {
+ if (m.index > pos) pieces.push({ kind: 'text', text: text.slice(pos, m.index) })
+ pos = m.index + m[0].length
+ const arg = m[2]
+ switch (m[1].toLowerCase()) {
+ case 'page':
+ // the cached a:t honours the pad; the live field re-renders unpadded
+ // the moment PowerPoint recomputes — an approximation, reported below
+ pieces.push({ kind: 'fld', type: 'slidenum', cached: pad(ctx.page, arg), frozenPad: parseInt(arg ?? '', 10) > 0 })
+ break
+ case 'date':
+ pieces.push({ kind: 'fld', type: 'datetime', cached: ctx.date.toLocaleDateString(), frozenPad: false })
+ break
+ case 'pages': pieces.push({ kind: 'text', text: pad(ctx.pages, arg) }); onFrozen('pages'); break
+ case 'title': pieces.push({ kind: 'text', text: ctx.title }); onFrozen('title'); break
+ case 'time':
+ pieces.push({ kind: 'text', text: ctx.date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) })
+ onFrozen('time')
+ break
+ case 'author': pieces.push({ kind: 'text', text: ctx.author }); onFrozen('author'); break
+ case 'company': pieces.push({ kind: 'text', text: ctx.company }); onFrozen('company'); break
+ case 'subject': pieces.push({ kind: 'text', text: ctx.subject }); onFrozen('subject'); break
+ case 'event': pieces.push({ kind: 'text', text: ctx.event }); onFrozen('event'); break
+ }
+ }
+ if (pos < text.length) pieces.push({ kind: 'text', text: text.slice(pos) })
+ return pieces
+}
+
+// --- the shape ----------------------------------------------------------------
+
+const pxEmu = (px: number): number => Math.round(px * EMU_PER_PX)
+
+const ANCHOR: Record<TextElIn['valign'], string> = { top: 't', middle: 'ctr', bottom: 'b' }
+const ALGN: Record<TextElIn['align'], string> = { left: 'l', center: 'ctr', right: 'r' }
+
+/** The stack's typeface (fonts.ts: first real family, generics mapped) —
+ * #88's firstFont, which took the first family even when it was generic. */
+const firstFont = (stack: string): string => typefaceOf(stack)
+
+const stripTags = (html: string): string => html.replace(/<[^>]*>/g, '')
+
+/**
+ * One bento text element as a finished p:sp. Returns null for an UNFILLED
+ * placeholder (#88's skip: present mode hides those, so exporting the prompt
+ * text would show scaffolding the author never sees).
+ *
+ * Emits its own a:xfrm — the shapes module has the same needs and the
+ * integrator dedups the helper when both are in the tree.
+ */
+export function textSp(el: TextElIn, opts: TextSpOpts): XNode | null {
+ if (el.placeholder && !stripTags(el.html).trim()) return null
+
+ const report = opts.report
+ const where = opts.where ?? ''
+ // #88's report codes, carried over: these visual features have no OOXML
+ // text-run equivalent and flatten to the base colour / plain glyphs.
+ if (el.colorGradient) report?.add('approximated', 'text-gradient-flattened', where, 'text gradient fill flattened to the solid colour')
+ if (el.shadow || el.blur || el.blend || el.backdropFilter) {
+ report?.add('approximated', 'text-effects-simplified', where, 'shadow/blur/blend effects on text dropped')
+ }
+
+ const face = firstFont(el.fontFamily || opts.themeFontFamily)
+ const ink = cssColor(el.color)
+ // element opacity composes into every run's alpha — a text sp has no fill
+ // of its own to carry it (#88 routed this through combineTransparency)
+ const alpha = ink.alpha * clamp(el.opacity, 0, 1)
+ const hollow = el.textStroke?.fill === 'none'
+
+ // Character properties shared by every run: OOXML has no element-level run
+ // style on a plain text box (lstStyle defaults do not survive user edits
+ // well), so the element's typography rides on each a:rPr and per-run
+ // overrides merge in. fontWeight ≥ 600 → bold is #88's threshold.
+ const runRPr = (style: RunStyle): XNode => {
+ // px*75 = px→pt→centipoints; clamped to ST_TextFontSize's legal range
+ // (100..400000 = 1pt..4000pt) — a sub-1.34px fontSize would otherwise
+ // emit a schema-invalid sz and risk a repair dialog.
+ const attrs: Record<string, string | number> = { sz: clamp(Math.round(el.fontSize * 75), 100, 400000) }
+ if (el.fontWeight >= 600 || style.bold) attrs.b = 1
+ if (style.italic) attrs.i = 1
+ if (style.underline) attrs.u = 'sng'
+ // first-party win over #88: PptxGenJS had no strike-through API, raw
+ // OOXML has an attribute
+ if (style.strike) attrs.strike = 'sngStrike'
+ // spc is centipoints (3px tracking → 2.25pt → 225). #88 capped this at
+ // 0.1pt working around a PptxGenJS/LibreOffice interaction; the raw
+ // attribute renders correctly in PowerPoint, so the real value goes out.
+ if (el.letterSpacing) attrs.spc = Math.round(el.letterSpacing * 75)
+ const kids: XChild[] = []
+ // schema order within CT_TextCharacterProperties: ln, fill, latin, hlink
+ if (el.textStroke?.width) {
+ const sc = cssColor(el.textStroke.color)
+ kids.push(x('a:ln', { w: pxEmu(el.textStroke.width) }, [solidFill(sc.hex, sc.alpha)]))
+ }
+ // hollow glyphs (textStroke fill:'none'): outline above + noFill interior —
+ // expressible in raw OOXML, another thing PptxGenJS could not say
+ kids.push(hollow ? x('a:noFill') : solidFill(ink.hex, alpha))
+ kids.push(x('a:latin', { typeface: style.code ? 'Courier New' : face }))
+ if (opts.link) {
+ // per-RUN hyperlinks, #88's hard-won fix: shape-level links on rich
+ // text produced dangling rel ids; rPr-level is also where PowerPoint
+ // itself puts them
+ kids.push(x('a:hlinkClick', {
+ 'r:id': opts.link.rId,
+ ...(opts.link.slideJump ? { action: 'ppaction://hlinksldjump' } : {}),
+ }))
+ }
+ return x('a:rPr', attrs, kids)
+ }
+
+ // runs → a:r / a:fld / a:br
+ let frozenTokens = 0
+ let padLost = false
+ let fldSeq = 0
+ const paraKids: XChild[] = []
+ for (const run of parseInlineHtml(el.html)) {
+ if (run.text) {
+ for (const piece of splitFields(run.text, opts.fields, () => { frozenTokens++ })) {
+ if (piece.kind === 'text') {
+ if (piece.text) paraKids.push(x('a:r', undefined, [runRPr(run.style), x('a:t', undefined, [piece.text])]))
+ } else {
+ if (piece.frozenPad) padLost = true
+ // the id must be GUID-shaped; deterministic from shapeId + ordinal
+ // so identical input bytes give identical output (diffable exports)
+ const guid = `{BE27B040-0000-4000-8000-${(opts.shapeId * 4096 + fldSeq++).toString(16).toUpperCase().padStart(12, '0')}}`
+ paraKids.push(x('a:fld', { id: guid, type: piece.type }, [runRPr(run.style), x('a:t', undefined, [piece.cached])]))
+ }
+ }
+ }
+ if (run.breakAfter) paraKids.push(x('a:br', undefined, [runRPr(run.style)]))
+ }
+ if (frozenTokens) report?.add('approximated', 'text-field-frozen', where, 'dynamic field resolved to literal text (PowerPoint will not re-compute it)')
+ if (padLost) report?.add('approximated', 'text-field-pad-lost', where, 'zero-padded {{page:N}} exported as a live slide-number field; the pad is lost when PowerPoint re-renders it')
+
+ const pPr = x('a:pPr', { algn: ALGN[el.align] },
+ el.lineHeight > 0 && Number.isFinite(el.lineHeight)
+ ? [x('a:lnSpc', undefined, [x('a:spcPct', { val: Math.round(el.lineHeight * 100000) })])]
+ : undefined)
+
+ const rot = ((el.rotation % 360) + 360) % 360
+
+ return x('p:sp', undefined, [
+ x('p:nvSpPr', undefined, [
+ // `bento:<morph key>` object name (#88): survives a round-trip through
+ // PowerPoint's selection pane, so re-import can restore morph pairing
+ x('p:cNvPr', { id: opts.shapeId, name: `bento:${el.morphId || el.id}` }),
+ x('p:cNvSpPr', { txBox: 1 }),
+ x('p:nvPr'),
+ ]),
+ x('p:spPr', undefined, [
+ x('a:xfrm', rot ? { rot: Math.round(rot * 60000) } : undefined, [
+ x('a:off', { x: pxEmu(el.x), y: pxEmu(el.y) }),
+ x('a:ext', { cx: pxEmu(el.w), cy: pxEmu(el.h) }),
+ ]),
+ x('a:prstGeom', { prst: 'rect' }, [x('a:avLst')]),
+ x('a:noFill'),
+ ]),
+ x('p:txBody', undefined, [
+ // zero insets + shrink-to-fit, both #88's: bento paints text flush to
+ // its box and the box is authored FIXED — normAutofit keeps overflow
+ // inside it instead of spilling over neighbouring shapes
+ x('a:bodyPr', { wrap: 'square', lIns: 0, tIns: 0, rIns: 0, bIns: 0, anchor: ANCHOR[el.valign] }, [
+ x('a:normAutofit'),
+ ]),
+ x('a:lstStyle'),
+ // a txBody must contain at least one a:p; an empty element still
+ // exports as an (empty) editable box
+ x('a:p', undefined, [pPr, ...paraKids]),
+ ]),
+ ])
+}
diff --git a/convert/src/pptx-write/verify.ts b/convert/src/pptx-write/verify.ts
new file mode 100644
index 00000000..6bb1b078
--- /dev/null
+++ b/convert/src/pptx-write/verify.ts
@@ -0,0 +1,104 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The package self-check: run on every export before the zip is written, so
+// a package PowerPoint would offer to repair is never handed to anyone.
+//
+// It checks what has bitten this writer before. Every rel target exists,
+// every r:id in a part resolves in that part's own rels, every part has a
+// content type (and no content type names a missing part), every XML part
+// parses, [Content_Types].xml comes first, and the parts the schema calls
+// optional but PowerPoint requires are present. A notes master must also
+// carry notesStyle and own its theme. Anything found is a WRITER bug, never
+// the deck's fault, so exportPptx refuses rather than reporting.
+//
+// The test harness (scripts/test-convert/_export-harness.ts) re-exports these;
+// pptx-write.ts proves each check with a negative control.
+
+import { parseXml, kids, attr, NS } from '../xml.ts'
+
+/** Parts in package order, by name. */
+export type Parts = Map<string, Uint8Array>
+
+const dec = new TextDecoder()
+const text = (parts: Parts, name: string): string => dec.decode(parts.get(name) ?? new Uint8Array())
+
+function resolvePath(baseDir: string, target: string): string {
+ const segs = baseDir ? baseDir.split('/') : []
+ for (const part of target.split('/')) {
+ if (part === '..') segs.pop()
+ else if (part !== '.' && part !== '') segs.push(part)
+ }
+ return segs.join('/')
+}
+
+/** Every internal rel target in every .rels part must be a part. */
+export function brokenRels(parts: Parts): string[] {
+ const broken: string[] = []
+ for (const [name, data] of parts) {
+ if (!name.endsWith('.rels')) continue
+ // ppt/slides/_rels/slide1.xml.rels belongs to ppt/slides/slide1.xml —
+ // rels resolve against the OWNER part's directory, not the _rels dir.
+ const baseDir = name === '_rels/.rels' ? '' : name.slice(0, name.indexOf('/_rels/'))
+ for (const rel of kids(parseXml(dec.decode(data)), NS.rel, 'Relationship')) {
+ if (attr(rel, 'TargetMode') === 'External') continue
+ const target = resolvePath(baseDir, attr(rel, 'Target') ?? '')
+ if (!parts.has(target)) broken.push(`${name} -> ${target}`)
+ }
+ }
+ return broken
+}
+
+/** Every r:id/r:embed/r:link in a part must name a rel in ITS rels part. */
+export function danglingRefs(xml: string, relsXml: string): string[] {
+ const ids = new Set([...relsXml.matchAll(/Id="(rId\d+)"/g)].map((m) => m[1]))
+ const missing: string[] = []
+ for (const m of xml.matchAll(/r:(?:id|embed|link)="([^"]+)"/g)) {
+ if (!ids.has(m[1])) missing.push(m[1])
+ }
+ return missing
+}
+
+/** Parts PowerPoint needs that the schema calls optional (without them it
+ * offers to repair the file). */
+const REQUIRED = ['ppt/presProps.xml', 'ppt/viewProps.xml', 'ppt/tableStyles.xml', 'docProps/core.xml', 'docProps/app.xml']
+
+/** Everything wrong with a package, as readable lines. [] = nothing found. */
+export function packageProblems(parts: Parts): string[] {
+ const out: string[] = []
+ if ([...parts.keys()][0] !== '[Content_Types].xml') out.push('[Content_Types].xml is not the first part')
+ for (const name of parts.keys()) {
+ if (!/\.(xml|rels)$/.test(name)) continue
+ try { parseXml(text(parts, name)) } catch (e) { out.push(`${name} does not parse: ${e}`) }
+ }
+ try { for (const b of brokenRels(parts)) out.push(`broken rel ${b}`) } catch { /* reported as a parse failure above */ }
+ for (const name of parts.keys()) {
+ if (name.endsWith('.rels') || !name.endsWith('.xml')) continue
+ const slash = name.lastIndexOf('/')
+ const rels = `${name.slice(0, slash)}/_rels/${name.slice(slash + 1)}.rels`
+ if (!parts.has(rels)) continue
+ for (const id of danglingRefs(text(parts, name), text(parts, rels))) out.push(`${name}: ${id} has no rel`)
+ }
+ let ct = null
+ try { ct = parseXml(text(parts, '[Content_Types].xml')) } catch { /* reported above */ }
+ if (ct) {
+ const overrides = new Set(kids(ct, NS.ct, 'Override').map((o) => attr(o, 'PartName')))
+ const defaults = new Set(kids(ct, NS.ct, 'Default').map((d) => (attr(d, 'Extension') ?? '').toLowerCase()))
+ for (const name of parts.keys()) {
+ if (name === '[Content_Types].xml') continue
+ const ext = name.slice(name.lastIndexOf('.') + 1).toLowerCase()
+ if (!overrides.has(`/${name}`) && !defaults.has(ext)) out.push(`${name} has no content type`)
+ }
+ for (const o of overrides) if (o && !parts.has(o.slice(1))) out.push(`content type for missing part ${o}`)
+ }
+ for (const r of REQUIRED) if (!parts.has(r)) out.push(`missing ${r} (PowerPoint requires it)`)
+ const nm = 'ppt/notesMasters/notesMaster1.xml'
+ if (parts.has(nm)) {
+ if (!/<p:notesStyle>/.test(text(parts, nm))) out.push('notes master has no p:notesStyle')
+ const themeOf = (rels: string) => /Target="\.\.\/theme\/(theme\d+\.xml)"/.exec(rels)?.[1]
+ const own = themeOf(text(parts, 'ppt/notesMasters/_rels/notesMaster1.xml.rels'))
+ if (!own || own === themeOf(text(parts, 'ppt/slideMasters/_rels/slideMaster1.xml.rels')))
+ out.push('notes master does not own a theme part')
+ }
+ return out
+}
diff --git a/convert/src/report.ts b/convert/src/report.ts
index ec007ce8..d2d621b5 100644
--- a/convert/src/report.ts
+++ b/convert/src/report.ts
@@ -70,3 +70,55 @@ export class Report {
return { entries, counts, provenance: Object.fromEntries(this.prov) }
}
}
+
+/** One line for a person: a (verdict, code) with every place it happened. */
+export interface FoldedEntry {
+ verdict: Verdict
+ code: string
+ detail: string
+ count: number
+ /** "slides 3, 5–7", "the whole deck", or both joined; '' when unknown */
+ where: string
+}
+
+/**
+ * The report as a person reads it. The writers record each loss per slide, so
+ * one kind of loss can appear on a dozen slides; this folds it to one line
+ * per (verdict, code), dropped first, and keeps WHERE: "slides 3, 5–7".
+ * Carried entries are left out (they are not losses). Shared by the CLI and
+ * every page, so they cannot word it differently.
+ */
+export function foldReport(report: FidelityReport): FoldedEntry[] {
+ const groups = new Map<string, { e: FidelityEntry; count: number; slides: Set<number>; other: Set<string> }>()
+ for (const e of report.entries) {
+ if (e.verdict === 'carried') continue
+ const key = `${e.verdict}\u0000${e.code}`
+ const g = groups.get(key) ?? { e, count: 0, slides: new Set<number>(), other: new Set<string>() }
+ g.count += e.count
+ const m = /^slide (\d+)\b/.exec(e.where)
+ if (m) g.slides.add(Number(m[1]))
+ else if (e.where) g.other.add(e.where === 'document' ? 'the whole deck' : e.where)
+ groups.set(key, g)
+ }
+ const rank: Record<string, number> = { dropped: 0, approximated: 1 }
+ return [...groups.values()]
+ .map(({ e, count, slides, other }) => ({
+ verdict: e.verdict, code: e.code, detail: e.detail, count,
+ where: [slideRange([...slides]), ...other].filter(Boolean).join('; '),
+ }))
+ .sort((a, b) => (rank[a.verdict] ?? 2) - (rank[b.verdict] ?? 2))
+}
+
+/** [3, 5, 6, 7] → "slides 3, 5–7"; [4] → "slide 4"; [] → "". */
+export function slideRange(nums: number[]): string {
+ const s = [...new Set(nums)].sort((a, b) => a - b)
+ if (!s.length) return ''
+ const runs: string[] = []
+ for (let i = 0; i < s.length; i++) {
+ let j = i
+ while (j + 1 < s.length && s[j + 1] === s[j] + 1) j++
+ runs.push(j > i + 1 ? `${s[i]}–${s[j]}` : j === i + 1 ? `${s[i]}, ${s[j]}` : `${s[i]}`)
+ i = j
+ }
+ return `${s.length === 1 ? 'slide' : 'slides'} ${runs.join(', ')}`
+}
diff --git a/convert/src/xmlout.ts b/convert/src/xmlout.ts
new file mode 100644
index 00000000..c3cdffcc
--- /dev/null
+++ b/convert/src/xmlout.ts
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The XML emitter — the write-side twin of xml.ts.
+//
+// Every OOXML part the export engine produces goes through this one door, and
+// the door is strict on purpose. A malformed emitted part is the worst kind of
+// export bug: nothing fails here, the ZIP is valid, and the user discovers the
+// problem days later when PowerPoint says "needs repair" (or just refuses) with
+// no hint of which of forty parts is at fault. So everything that could make a
+// part malformed is a THROW at build time, where a rig can see it:
+//
+// - element and attribute names are checked against the XML name grammar
+// (the same shape xml.ts accepts — ASCII names with at most one colon,
+// which is all OOXML ever uses);
+// - control characters below 0x20 (except tab/lf/cr) are rejected in text
+// and attribute values — they are unrepresentable in XML 1.0, escaped or
+// not, and one stray \x00 from a corrupted string corrupts the whole part;
+// - non-finite numbers are rejected — String(NaN) is "NaN", which serializes
+// happily and then poisons a cx/cy/sz attribute silently.
+//
+// What it does NOT do: namespaces. The parser resolves them for real because
+// input files are other people's; output is ours, and every part we emit
+// declares the conventional prefixes (a:, p:, r:) on its root — real consumers
+// accept nothing else gracefully, so there is nothing to abstract. Prefixed
+// names are just names here.
+
+export type XChild = XNode | string
+
+export interface XNode {
+ name: string
+ attrs?: Record<string, string | number>
+ kids?: XChild[]
+}
+
+/** Build one node. Sugar over the literal shape — `kids` may mix nodes and
+ * text, matching how mixed content actually occurs (an a:t with one string). */
+export function x(name: string, attrs?: Record<string, string | number>, kids?: XChild[]): XNode {
+ return { name, attrs, kids }
+}
+
+// The name shape xml.ts's NAME_RE parses: an ASCII NCName, optionally
+// prefixed. Stricter than the XML spec (no unicode names) — OOXML is ASCII
+// throughout, and anything outside this shape in OUR output is a bug, not a
+// document.
+const NAME_RE = /^[A-Za-z_][\w.-]*(?::[A-Za-z_][\w.-]*)?$/
+
+// C0 controls minus tab (09), lf (0a), cr (0d): illegal in XML 1.0 in any
+// form. There is no escape for them — &#0; is ALSO a well-formedness error —
+// so the only correct handling is refusal.
+const BAD_CHARS = /[\x00-\x08\x0b\x0c\x0e-\x1f]/
+
+/**
+ * Strip the unrepresentable C0 controls from AUTHOR-authored text (pasted
+ * content, imported docs, chart labels, speaker notes). The writers scrub at
+ * ingestion so one stray byte costs a character, not the whole export —
+ * mirroring how the text tokenizer already treats a C0 arriving as a numeric
+ * entity. Programmer-built strings do NOT go through this: for them the
+ * serializer's throwing guard below is the correct posture (a control char in
+ * an id or a part name is an upstream bug a rig must see).
+ */
+export const scrubC0 = (s: string): string => s.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '')
+
+function checkText(s: string, where: string): string {
+ const m = BAD_CHARS.exec(s)
+ if (m) {
+ const code = m[0].charCodeAt(0).toString(16).padStart(2, '0')
+ throw new Error(`xmlout: control character U+00${code.toUpperCase()} in ${where} — not representable in XML`)
+ }
+ return s
+}
+
+// Text escapes the three characters that can change structure; attributes add
+// the quote (we always emit double-quoted values). `>` is not strictly
+// required outside `]]>` but escaping it unconditionally costs nothing and
+// removes the special case.
+const escText = (s: string): string =>
+ s.replace(/[&<>]/g, (c) => (c === '&' ? '&amp;' : c === '<' ? '&lt;' : '&gt;'))
+const escAttr = (s: string): string =>
+ s.replace(/[&<>"]/g, (c) => (c === '&' ? '&amp;' : c === '<' ? '&lt;' : c === '>' ? '&gt;' : '&quot;'))
+
+function attrValue(name: string, v: string | number): string {
+ if (typeof v === 'number') {
+ // A non-finite number in an attribute is always an upstream arithmetic
+ // bug (divide by zero in a geometry mapper); "NaN" in a cx= attribute is
+ // exactly the silent corruption this module exists to prevent.
+ if (!Number.isFinite(v)) throw new Error(`xmlout: non-finite number for attribute "${name}"`)
+ return String(v)
+ }
+ return escAttr(checkText(v, `attribute "${name}"`))
+}
+
+function write(out: string[], node: XNode): void {
+ if (!NAME_RE.test(node.name)) throw new Error(`xmlout: invalid element name "${node.name}"`)
+ out.push('<', node.name)
+ if (node.attrs) {
+ for (const [k, v] of Object.entries(node.attrs)) {
+ if (!NAME_RE.test(k)) throw new Error(`xmlout: invalid attribute name "${k}" on <${node.name}>`)
+ out.push(' ', k, '="', attrValue(k, v), '"')
+ }
+ }
+ const kids = node.kids
+ if (!kids || kids.length === 0) {
+ out.push('/>')
+ return
+ }
+ out.push('>')
+ for (const kid of kids) {
+ if (typeof kid === 'string') out.push(escText(checkText(kid, `text inside <${node.name}>`)))
+ else write(out, kid)
+ }
+ out.push('</', node.name, '>')
+}
+
+/**
+ * Serialize one document: the XML declaration plus the tree, no trailing
+ * newline. Empty elements self-close — PowerPoint reads either form, but
+ * self-closing is what it writes, and matching the native shape keeps diffs
+ * against real files readable.
+ *
+ * `standalone` defaults to true (`standalone="yes"`), which is what every
+ * OOXML part carries; pass false to omit the attribute entirely.
+ */
+export function serialize(root: XNode, standalone = true): string {
+ const out: string[] = [
+ standalone
+ ? '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
+ : '<?xml version="1.0" encoding="UTF-8"?>',
+ ]
+ write(out, root)
+ return out.join('')
+}
diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md
index e1ccf35d..dae76cba 100644
--- a/docs/DECISIONS.md
+++ b/docs/DECISIONS.md
@@ -10107,3 +10107,73 @@ and still green.
Pointers: spaces/src/share.ts, spaces/src/editor.ts `confirmInviteHistory`,
scripts/test-spaces-copytiers.ts (the invite-choice rows and the planted
builder that ignores the option).
+
+## 2026-10-05 — PowerPoint export is a library and a command-line tool, never an app button
+
+**The decision.** Import came first (bento.page/import). Export ships as
+`convert/src/export.ts` and `bento convert deck.bento.html --to pptx`, not as
+a command inside slides, so every shared file stays small and the app stays
+focused. The writer (`convert/src/pptx-write/`, about 3,500 lines) never
+enters a shell. `scripts/test-convert/boundary.ts` fails if any app imports
+`convert/`, if the writer uses a DOM global, or if any part of the writer
+reaches the bento.page/import bundle. That last check was mutation-tested:
+a page that calls the writer is caught, and an unused re-export, which
+esbuild tree-shakes away, correctly passes.
+
+**Whose code it is.** The writer is built on the mappings contributed in
+#88 (cherry-picked with their author's authorship), with a first-party
+integrator and the package boilerplate PowerPoint needs.
+
+**Schema-valid is not PowerPoint-valid.** Every part of an early export
+passed the ECMA-376 transitional schemas, and PowerPoint for Mac still
+offered to repair the file. The missing pieces are parts the schema calls
+optional and the reader requires: `presProps.xml`, `viewProps.xml`,
+`tableStyles.xml`, a presentation→theme relationship, `p:notesStyle` in the
+notes master, and a notes master that owns its own theme part rather than
+sharing the slide master's. All are pinned by the rigs, and the shared
+harness (`scripts/test-convert/_export-harness.ts`, `packageProblems`) checks
+them for any export. The class is open-ended, so a change to the writer
+still ends with one exported deck opened in real PowerPoint.
+
+**Built for contributors.** Element writers follow one contract
+(`pptx-write/contract.ts`): one node or null, every loss reported, no app
+imports, no new dependencies, deterministic output. The two element types
+with no writer yet, `code` and `embed`, have stub writers that report
+themselves dropped. `scripts/test-convert/pptx-coverage.ts` reads the element
+types from slides' `SlideElement` union and fails when slides adds a type
+the exporter does not handle, or when a writer drops an element without
+reporting it. `convert/CONTRIBUTING.md` walks through writing one and lists
+the open tasks.
+
+## 2026-10-06 — PowerPoint export: one typeface per stack, a self-check on every export, a report that names slides
+
+Measured against an earlier converter built on a third-party PowerPoint
+library, on six real decks. Ours was already smaller (the starter deck
+exports at 61 KB against 9.4 MB, because nothing is rasterised and images are
+stored once). It was also more editable: gradients, connectors, custom paths
+and charts stay native, and hard shadows and strikethrough survive. These
+behaviours were taken from that converter; no code was taken:
+
+- **The report names slides.** `foldReport` (convert/src/report.ts) folds
+ the writer's per-slide entries to one line per kind of loss and keeps
+ where it happened ("slides 3, 5–7"). The CLI and the pages share it.
+- **Formulas and fonts are reported.** Formulas already exported as their
+ LaTeX source and now say so (`maths-as-source`). They are found by slides'
+ own scanner (`maths/delimiters.ts`), passed in by `export.ts` because the
+ writer imports no app. The deck's own fonts are named
+ (`fonts-not-embedded`), since the .pptx does not carry them.
+- **A self-check on every export** (`pptx-write/verify.ts`, the checks the
+ rigs used). A package with a broken relationship, an untyped part or a
+ missing required part is a writer bug, and the export refuses it rather
+ than handing PowerPoint a file to repair.
+- **Document JSON in, report JSON out** (`--report`).
+
+**One typeface per stack.** PowerPoint takes a single font name and
+substitutes silently when it is missing; it cannot fall through a CSS stack.
+Both converters wrote `ui-monospace`, which is a CSS generic and not a font.
+`typefaceOf` (`pptx-write/fonts.ts`) takes the stack's first family that is
+neither a CSS generic nor a font only one operating system ships ('SF Mono',
+'Menlo', 'Helvetica Neue', 'Segoe UI', …). slides' monospace stack therefore
+becomes Consolas, which Office installs on Windows and macOS. A stack of
+generics alone maps to a font every PowerPoint has (monospace → Courier New,
+sans-serif → Arial). The deck's own fonts are never skipped.
diff --git a/scripts/postbuild-compress.mjs b/scripts/postbuild-compress.mjs
index 54781c7d..3937a232 100644
--- a/scripts/postbuild-compress.mjs
+++ b/scripts/postbuild-compress.mjs
@@ -252,6 +252,11 @@ const linkedRe = /<style[^>]*\brel="stylesheet"[^>]*>([\s\S]*?)<\/style>/
const styleM = html.match(linkedRe)
?? headPart.match(/<style(?=[\s>])[^>]*>([\s\S]*?)<\/style>/)
if (!styleM) throw new Error('app stylesheet not found')
+// Belt for the braces above: a matched block that is not CSS means the
+// extractor grabbed the wrong <style> again — refuse loudly, never ship it.
+if (!styleM[1].includes('{') || styleM[1].trimStart().startsWith('<')) {
+ throw new Error('extracted app stylesheet does not look like CSS')
+}
const js = mod[1]
const css = styleM[1]
diff --git a/scripts/test-convert/_export-harness.ts b/scripts/test-convert/_export-harness.ts
new file mode 100644
index 00000000..da152d85
--- /dev/null
+++ b/scripts/test-convert/_export-harness.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// The export test harness: export a deck (or one element), get the package
+// back as parts, and ask what is wrong with it.
+//
+// const r = await exportOne({ type: 'code', ...frame(80, 80, 400, 200), content: 'x = 1', … })
+// r.problems // [] when the package is wired the way PowerPoint checks it
+// r.slideXml // the slide part, to assert on what the writer emitted
+// r.codes // the fidelity report's codes
+//
+// packageProblems() is the same wiring check pptx-write.ts proves with
+// negative controls: every rel target exists, every r:id resolves in its own
+// rels part, every part is typed, every XML part parses, [Content_Types].xml
+// comes first, and the boilerplate PowerPoint requires (but the schema calls
+// optional) is present. A package can be schema-valid and still make
+// PowerPoint offer to repair it; that is why these checks exist, and why the
+// last step for any writer change is opening a real deck in real PowerPoint.
+//
+// Files whose names start with `_` are helpers, not rigs: the runner
+// (scripts/test-convert.ts) skips them.
+
+import { readZip, type ZipParts } from '../../kernel/src/convert/zip.ts'
+import { packageProblems } from '../../convert/src/pptx-write/verify.ts'
+import { exportPptx, type ExportDoc, type ExportElement, type ExportOpts } from '../../convert/src/pptx-write/index.ts'
+import type { FidelityReport } from '../../convert/src/report.ts'
+
+const dec = new TextDecoder()
+export const partText = (parts: ZipParts, name: string): string => dec.decode(parts.get(name) ?? new Uint8Array())
+
+/** An element frame, as every bento/slides element carries one. */
+export const frame = (x: number, y: number, w: number, h: number) => ({ x, y, w, h, rotation: 0, opacity: 1 })
+
+/** A one-slide deck around the given elements. */
+export function deck(elements: unknown[], over: Partial<ExportDoc> = {}): ExportDoc {
+ return {
+ title: 'Harness deck',
+ size: { width: 1280, height: 720 },
+ theme: { background: '#ffffff', color: '#1e2a3a', accent: '#ff7a59', fontFamily: 'Inter, sans-serif' },
+ slides: [{ id: 's1', background: '#ffffff', elements: elements as ExportElement[] }],
+ ...over,
+ }
+}
+
+export interface Exported {
+ parts: ZipParts
+ report: FidelityReport
+ /** the report's codes, for `codes.has('…')` */
+ codes: Set<string>
+ /** ppt/slides/slide1.xml */
+ slideXml: string
+ /** what is wrong with the package; [] when nothing is */
+ problems: string[]
+}
+
+export async function exportDeck(doc: ExportDoc, opts: ExportOpts = {}): Promise<Exported> {
+ const { bytes, report } = await exportPptx(doc, opts)
+ const parts = await readZip(bytes)
+ return {
+ parts,
+ report,
+ codes: new Set(report.entries.map((e) => e.code)),
+ slideXml: partText(parts, 'ppt/slides/slide1.xml'),
+ problems: packageProblems(parts),
+ }
+}
+
+/** Export a one-slide deck holding just this element. */
+export const exportOne = (element: unknown, opts: ExportOpts = {}): Promise<Exported> =>
+ exportDeck(deck([{ id: 'el1', ...frame(80, 80, 400, 200), ...(element as object) }]), opts)
+
+// --- the wiring checks -------------------------------------------------------
+// They live in the library now (convert/src/pptx-write/verify.ts): every
+// export runs them before writing the zip. Re-exported here for the rigs.
+export { brokenRels, danglingRefs, packageProblems } from '../../convert/src/pptx-write/verify.ts'
diff --git a/scripts/test-convert/boundary.ts b/scripts/test-convert/boundary.ts
index 1e063a3c..82912b47 100644
--- a/scripts/test-convert/boundary.ts
+++ b/scripts/test-convert/boundary.ts
@@ -56,11 +56,23 @@ for (const zone of ['slides/src', 'dash/src', 'spaces/src', 'type/src', 'kernel/
console.log('the engine is DOM-free')
const esbuild = path.join(root, 'slides/node_modules/.bin/esbuild')
const DOM = /(?<![.\w$"'`])(document|window|DOMParser|XMLSerializer|localStorage|sessionStorage|navigator|HTMLElement|Image|FileReader|createElement)(?=\s*[.(\[])/g
-for (const entry of ['convert/src/pptx.ts', 'convert/src/limits.ts']) {
+for (const entry of ['convert/src/pptx.ts', 'convert/src/pptx-write/index.ts', 'convert/src/limits.ts']) {
const r = spawnSync(esbuild, [path.join(root, entry), '--bundle', '--format=esm', '--minify', '--platform=neutral', '--log-level=error'], { encoding: 'utf8' })
const hits = [...new Set([...(r.stdout ?? '').matchAll(DOM)].map(m => m[1]))]
ok(r.status === 0 && r.stdout.length > 1000 && hits.length === 0, `${entry} and all it reaches use no DOM global (${hits.join(', ') || 'none'})`)
}
+console.log('the PowerPoint writer stays off the import page')
+{
+ // bento.page/import bundles api.ts, never export.ts. These strings exist
+ // only in the writer (package parts PowerPoint requires), so finding one
+ // in the page's bundle means the writer leaked into it.
+ const r = spawnSync(esbuild, [path.join(root, 'convert/page/import-page.ts'), '--bundle', '--format=esm', '--minify',
+ '--platform=browser', '--log-level=error'], { encoding: 'utf8' })
+ const leaked = ['presProps', 'notesMaster', 'tableStyles'].filter((w) => (r.stdout ?? '').includes(w))
+ ok(r.status === 0 && r.stdout.length > 1000 && leaked.length === 0,
+ `the page bundle carries no part of the writer (${leaked.join(', ') || 'none found'})`)
+}
+
console.log(`\n${checks - failures}/${checks} checks passed`)
if (failures) process.exit(1)
diff --git a/scripts/test-convert/cli.ts b/scripts/test-convert/cli.ts
index c405db07..ac4015eb 100644
--- a/scripts/test-convert/cli.ts
+++ b/scripts/test-convert/cli.ts
@@ -7,8 +7,8 @@
// Offline by construction — every import here passes --shell, so nothing is
// fetched. The signed-channel path is the delivery rig's (deliver.ts), which
// drives the real verifySigned with a throwaway key. What this rig owns is the
-// command line: usage and refusals, the import itself, and that a converted
-// file OPENS — booted in headless Chrome through
+// command line: usage and refusals, the import, the export and the round trip,
+// the notes fix end to end, and that a converted file OPENS — booted in headless Chrome through
// scripts/bento-check.mjs, the same harness CI already trusts.
//
// Like the bento-check rig: without Chrome or a built shell it SKIPS locally,
@@ -19,6 +19,7 @@ import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
+import { readZip } from '../../kernel/src/convert/zip.ts'
import { fxMinimal } from './_fixtures.ts'
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '../..')
@@ -53,12 +54,20 @@ const docOf = (html: string) => {
return JSON.parse(html.slice(s, html.indexOf(CLOSE, s)))
}
+const deckWith = (doc: unknown) => {
+ const html = fs.readFileSync(shell, 'utf8')
+ const s = html.indexOf(BLOCK) + BLOCK.length
+ return html.slice(0, s) + JSON.stringify(doc).replace(/</g, '\\u003c') + html.slice(html.indexOf(CLOSE, s))
+}
+
console.log('usage')
{
const r = run([])
ok(r.code === 2 && /usage:/.test(r.err), 'no arguments → exit 2 and the usage')
ok(run(['x.pptx', '--offline']).code === 2, '--offline without --shell → exit 2 (checked before touching the disk)')
- ok(run(['x.bento.html']).code === 2, 'an input that is not a .pptx → exit 2')
+ ok(run(['x.bento.html']).code === 2, 'a .bento.html without --to pptx → exit 2 (export is asked for, never guessed)')
+ ok(run(['x.bento.html', '--to', 'docx']).code === 2, '--to docx → exit 2')
+ ok(run(['x.pptx', '--to', 'pptx']).code === 2, '--to pptx on a .pptx → exit 2')
ok(run(['x.pptx', '--frobnicate']).code === 2, 'an unknown option → exit 2')
ok(run(['missing.pptx', '--shell', shell]).code === 1, 'a missing input → exit 1')
const h = run(['--help'])
@@ -82,6 +91,64 @@ const imported = path.join(tmp, 'rig.bento.html')
ok(gate.status === 0, 'the output passes the splice-contract gate every release runs')
}
+console.log('export, and the round trip')
+{
+ const out = path.join(tmp, 'back.pptx')
+ const r = run([imported, '--to', 'pptx', '-o', out])
+ ok(r.code === 0 && fs.existsSync(out), `the imported deck exports back to .pptx (exit ${r.code})`)
+ const parts = await readZip(new Uint8Array(fs.readFileSync(out)))
+ ok(parts.has('ppt/presentation.xml') && parts.has('[Content_Types].xml'), 'the .pptx is a real package')
+ // The notes fix, end to end through the CLI: a deck with speaker notes must
+ // carry notesStyle in its notes master and a notes-master theme of its own.
+ const base = docOf(fs.readFileSync(imported, 'utf8'))
+ base.slides[0].notes = 'A speaker note.'
+ const noted = path.join(tmp, 'noted.bento.html')
+ fs.writeFileSync(noted, deckWith(base))
+ const nr = run([noted, '--to', 'pptx', '-o', path.join(tmp, 'noted.pptx')])
+ const np = await readZip(new Uint8Array(fs.readFileSync(path.join(tmp, 'noted.pptx'))))
+ const nm = new TextDecoder().decode(np.get('ppt/notesMasters/notesMaster1.xml') ?? new Uint8Array())
+ const nmRels = new TextDecoder().decode(np.get('ppt/notesMasters/_rels/notesMaster1.xml.rels') ?? new Uint8Array())
+ ok(nr.code === 0 && /<p:notesStyle>/.test(nm), 'a deck with notes exports a notes master carrying p:notesStyle')
+ ok(np.has('ppt/theme/theme2.xml') && /theme2\.xml/.test(nmRels),
+ 'and the notes master owns its own theme part (theme2.xml), not a share of the slide master’s')
+}
+
+console.log('the report, and document JSON in')
+{
+ // export the imported deck once more, asking for the report as data
+ const rj = path.join(tmp, 'report.json')
+ const r = run([imported, '--to', 'pptx', '-o', path.join(tmp, 'again.pptx'), '--report', rj])
+ let rep: { entries?: unknown[]; counts?: unknown } = {}
+ try { rep = JSON.parse(fs.readFileSync(rj, 'utf8')) } catch { /* reported below */ }
+ ok(r.code === 0 && Array.isArray(rep.entries) && !!rep.counts, '--report writes the full fidelity report as JSON')
+ // a deck with an omitted state names "the whole deck"; per-slide losses name slides
+ const base = docOf(fs.readFileSync(imported, 'utf8'))
+ base.slides[0].transition = 'morph'
+ const json = path.join(tmp, 'doc.json')
+ fs.writeFileSync(json, JSON.stringify(base))
+ const j = run([json, '--to', 'pptx', '-o', path.join(tmp, 'from-json.pptx')])
+ ok(j.code === 0 && fs.existsSync(path.join(tmp, 'from-json.pptx')), `document JSON exports like a .bento.html (exit ${j.code})`)
+ ok(/morph-not-exported \(slide 1\)/.test(j.err), 'each report line names the slides it happened on')
+}
+
+console.log('export refusals, each saying what to do')
+{
+ const refuse = (name: string, doc: unknown, want: RegExp, msg: string) => {
+ const f = path.join(tmp, name)
+ fs.writeFileSync(f, deckWith(doc))
+ const r = run([f, '--to', 'pptx', '-o', path.join(tmp, name + '.pptx')])
+ ok(r.code === 1 && want.test(r.err) && !fs.existsSync(path.join(tmp, name + '.pptx')), msg)
+ }
+ refuse('enc.bento.html', { format: 'bento/enc', v: 1, it: 1, salt: '', iv: '', data: '' },
+ /password/, 'an encrypted deck is refused, pointing at "save a copy without a password"')
+ refuse('compact.bento.html', { format: 'bento/slides', compact: true, slides: [] },
+ /compact/, 'a raw compact document is refused, pointing at opening and saving it once')
+ refuse('spaces.bento.html', { format: 'bento/spaces', pages: [] },
+ /only bento\/slides/, 'a non-slides file is refused')
+ const fresh = run([shell, '--to', 'pptx', '-o', path.join(tmp, 'fresh.pptx')])
+ ok(fresh.code === 1 && /empty/.test(fresh.err), 'a fresh shell (empty #bento-doc) is refused, not exported as nothing')
+}
+
console.log('it opens')
{
const CHROME = [process.env.BENTO_CHROME, '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
diff --git a/scripts/test-convert/pptx-charts.ts b/scripts/test-convert/pptx-charts.ts
new file mode 100644
index 00000000..f077e39e
--- /dev/null
+++ b/scripts/test-convert/pptx-charts.ts
@@ -0,0 +1,256 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write chart-mapper rig: charts.ts.
+//
+// node scripts/test-convert/pptx-charts.ts (Node ≥ 23.6 strips types natively)
+//
+// The emitted c:chartSpace part is re-read with the convert engine's parser.
+// The claims checked — series counts, numCache values VERBATIM, dual-axis
+// wiring, the deleted secondary category axis — are the ones PowerPoint
+// validates before rendering a chart. The NEGATIVE controls pin the fallback
+// contract: a stacked or mixed-type option must NOT produce a c:chart (a
+// clustered rendering of a stacked series misstates the totals — the spike's
+// core finding), it must produce a data TABLE and a 'chart-approximated'
+// report entry.
+
+import { parseXml, kids, kid, attr, textOf, descendants, NS, type XElem } from '../../convert/src/xml.ts'
+import { serialize, x } from '../../convert/src/xmlout.ts'
+import { Report } from '../../convert/src/report.ts'
+import type { OutChart } from '../../convert/src/types.ts'
+import { chartExport, CHART_GRAPHIC_URI } from '../../convert/src/pptx-write/charts.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const chartEl = (option: Record<string, unknown>): OutChart => ({
+ id: 'c1', type: 'chart', preset: 'bar',
+ x: 400, y: 190, w: 800, h: 520, rotation: 0, opacity: 1,
+ option,
+})
+
+const parseFrame = (frame: ReturnType<typeof x>): XElem =>
+ kids(parseXml(serialize(x('root', { 'xmlns:a': NS.a, 'xmlns:p': NS.p, 'xmlns:r': NS.r }, [frame]))))[0]
+
+const PALETTE = ['#E8A87C', '#5C7A8A']
+
+// --- native bar + dual-axis line ---------------------------------------------
+console.log('bar/line with a secondary axis')
+
+{
+ // The tableToChart pattern: bars on the left axis, a percent line on the
+ // right — the dual-axis shape #88 skipped and the rework must carry.
+ const report = new Report()
+ const out = chartExport(chartEl({
+ legend: { bottom: 0 },
+ xAxis: { type: 'category', data: ['Q1', 'Q2', 'Q3'] },
+ yAxis: [{ type: 'value' }, { type: 'value', max: 100, axisLabel: { formatter: '{value}%' } }],
+ series: [
+ { type: 'bar', name: 'Revenue', data: [12, 4.25, 0] },
+ { type: 'bar', name: 'Cost', data: [8, 3, 1] },
+ { type: 'line', name: 'Margin', yAxisIndex: 1, smooth: true, data: [33, 29, 41] },
+ ],
+ }), 5, 'rId9', PALETTE, report, 'slide 4')
+
+ ok(out.chartXml !== undefined, 'in-subset chart emits a native part')
+ const space = parseXml(out.chartXml!)
+ ok(space.ns === NS.c && space.local === 'chartSpace', 'root is c:chartSpace in the chart namespace')
+ const chart = kid(space, NS.c, 'chart')!
+ const plot = kid(chart, NS.c, 'plotArea')!
+
+ const barChart = kid(plot, NS.c, 'barChart')!
+ const lineChart = kid(plot, NS.c, 'lineChart')!
+ ok(kids(barChart, NS.c, 'ser').length === 2, 'two bar series in the primary group')
+ ok(kids(lineChart, NS.c, 'ser').length === 1, 'one line series in the secondary group')
+
+ // numCache values VERBATIM — 4.25 must not reformat, 0 must survive.
+ const barSer0 = kids(barChart, NS.c, 'ser')[0]
+ const cache = kid(kid(kid(barSer0, NS.c, 'val')!, NS.c, 'numRef')!, NS.c, 'numCache')!
+ ok(attr(kid(cache, NS.c, 'ptCount')!, 'val') === '3', 'ptCount matches the data length')
+ const vals = kids(cache, NS.c, 'pt').map((p) => textOf(kid(p, NS.c, 'v')!))
+ ok(vals.join(',') === '12,4.25,0', 'numCache values are verbatim (4.25 not reformatted, 0 kept)')
+ ok(kids(cache, NS.c, 'pt').map((p) => attr(p, 'idx')).join(',') === '0,1,2', 'pt idx sequence intact')
+
+ // Category cache + series name references (the edit-time rebuild addresses).
+ const catCache = kid(kid(kid(barSer0, NS.c, 'cat')!, NS.c, 'strRef')!, NS.c, 'strCache')!
+ ok(kids(catCache, NS.c, 'pt').map((p) => textOf(p)).join(',') === 'Q1,Q2,Q3', 'category strCache carries the x labels')
+ ok(textOf(kid(kid(kid(barSer0, NS.c, 'tx')!, NS.c, 'strRef')!, NS.c, 'f')!) === 'Sheet1!$B$1', 'series name ref addresses column B row 1')
+
+ // idx/order globally unique across the two plot groups.
+ const allIdx = descendants(plot, NS.c, 'ser').map((s) => attr(kid(s, NS.c, 'idx')!, 'val'))
+ ok(new Set(allIdx).size === 3 && allIdx.join(',') === '0,1,2', 'c:idx unique and global across plot groups')
+
+ // Dual-axis wiring: primary pair on the bars, secondary pair on the line,
+ // secondary catAx deleted, secondary valAx on the right crossing at max.
+ const axIdsOf = (g: XElem) => kids(g, NS.c, 'axId').map((a) => attr(a, 'val'))
+ ok(axIdsOf(barChart).join(',') === '1001,1002', 'bar group references the primary axis pair')
+ ok(axIdsOf(lineChart).join(',') === '1003,1004', 'line group references the secondary axis pair')
+ const catAxes = kids(plot, NS.c, 'catAx')
+ const valAxes = kids(plot, NS.c, 'valAx')
+ ok(catAxes.length === 2 && valAxes.length === 2, 'two category + two value axes present')
+ const cat1 = catAxes.find((a) => attr(kid(a, NS.c, 'axId')!, 'val') === '1003')!
+ ok(attr(kid(cat1, NS.c, 'delete')!, 'val') === '1', 'secondary category axis is deleted (hidden)')
+ const val1 = valAxes.find((a) => attr(kid(a, NS.c, 'axId')!, 'val') === '1004')!
+ ok(attr(kid(val1, NS.c, 'axPos')!, 'val') === 'r', 'secondary value axis sits on the right')
+ ok(attr(kid(val1, NS.c, 'crosses')!, 'val') === 'max', 'secondary value axis crosses at max')
+ ok(attr(kid(val1, NS.c, 'numFmt')!, 'formatCode') === '0"%"', "'{value}%' formatter → quoted-literal percent format (not Excel's ×100 percent)")
+ ok(attr(kid(kid(val1, NS.c, 'scaling')!, NS.c, 'max')!, 'val') === '100', 'per-axis max carried into c:scaling')
+ const val0 = valAxes.find((a) => attr(kid(a, NS.c, 'axId')!, 'val') === '1002')!
+ ok(kid(val0, NS.c, 'majorGridlines') !== undefined, 'primary value axis keeps gridlines (charts-lite draws them)')
+ ok(attr(kid(cat1, NS.c, 'crossAx')!, 'val') === '1004', 'axis pairs cross-reference each other')
+
+ // Series colouring: first bar takes the deck palette, line styles its outline.
+ ok(attr(kid(kid(kid(barSer0, NS.c, 'spPr')!, NS.a, 'solidFill')!, NS.a, 'srgbClr')!, 'val') === 'E8A87C',
+ 'series colour from the deck palette')
+ const lineSer = kids(lineChart, NS.c, 'ser')[0]
+ ok(kid(kid(kid(lineSer, NS.c, 'spPr')!, NS.a, 'ln')!, NS.a, 'solidFill') !== undefined, 'line series colour lives on the outline')
+ ok(attr(kid(lineSer, NS.c, 'smooth')!, 'val') === '1', 'smooth carried onto the line series')
+
+ ok(attr(kid(kid(chart, NS.c, 'legend')!, NS.c, 'legendPos')!, 'val') === 'b', 'legend bottom (the house preset position)')
+ ok(attr(kid(chart, NS.c, 'autoTitleDeleted')!, 'val') === '1', 'no title in the option → autoTitleDeleted (no phantom "Chart Title")')
+ ok(kid(chart, NS.c, 'plotVisOnly') !== undefined && attr(kid(chart, NS.c, 'dispBlanksAs')!, 'val') === 'gap',
+ 'plotVisOnly + dispBlanksAs gap (census shape)')
+ ok(report.build().entries.length === 0, 'clean chart adds no report entries')
+
+ // The frame references the part by the integrator's rel id.
+ const frame = parseFrame(out.frame)
+ const gd = kid(kid(frame, NS.a, 'graphic')!, NS.a, 'graphicData')!
+ ok(attr(gd, 'uri') === CHART_GRAPHIC_URI, 'graphicData carries the chart uri')
+ ok(attr(kid(gd, NS.c, 'chart')!, 'r:id') === 'rId9', 'c:chart reference carries the reserved rel id')
+ ok(attr(kid(kid(frame, NS.p, 'nvGraphicFramePr')!, NS.p, 'cNvPr')!, 'id') === '5', 'cNvPr id from the caller')
+}
+
+// --- pie / doughnut ----------------------------------------------------------
+console.log('pie')
+
+{
+ const report = new Report()
+ const out = chartExport(chartEl({
+ legend: { bottom: 0 },
+ series: [{
+ type: 'pie', radius: ['38%', '68%'],
+ data: [{ name: 'Alpha', value: 42 }, { name: 'Beta', value: 28 }, { name: 'Gamma', value: 18 }],
+ }],
+ }), 2, 'rId2', PALETTE, report, 'slide 5')
+ ok(out.chartXml !== undefined, 'pie is in-subset')
+ const space = parseXml(out.chartXml!)
+ const dough = descendants(space, NS.c, 'doughnutChart')[0]
+ ok(dough !== undefined, "charts-lite's ['38%','68%'] radius → doughnutChart")
+ ok(attr(kid(dough, NS.c, 'holeSize')!, 'val') === '56', 'holeSize = inner/outer share (38/68 → 56%)')
+ const ser = kid(dough, NS.c, 'ser')!
+ ok(kids(ser, NS.c, 'dPt').length === 3, 'one dPt per slice')
+ ok(attr(descendants(kids(ser, NS.c, 'dPt')[1], NS.a, 'srgbClr')[0], 'val') === '5C7A8A',
+ 'slice colours walk the palette per data point')
+ ok(kids(kid(kid(kid(ser, NS.c, 'cat')!, NS.c, 'strRef')!, NS.c, 'strCache')!, NS.c, 'pt').map((p) => textOf(p)).join(',') === 'Alpha,Beta,Gamma',
+ 'slice names in the category cache')
+ ok(attr(kid(dough, NS.c, 'varyColors')!, 'val') === '1', 'pie varies colours by point')
+
+ const plain = chartExport(chartEl({ series: [{ type: 'pie', radius: '70%', data: [{ name: 'A', value: 1 }] }] }),
+ 2, 'rId2', PALETTE, new Report(), 'slide 5')
+ ok(descendants(parseXml(plain.chartXml!), NS.c, 'pieChart').length === 1, 'zero inner radius → pieChart, not doughnut')
+}
+
+// --- scatter -----------------------------------------------------------------
+console.log('scatter')
+
+{
+ const out = chartExport(chartEl({
+ xAxis: { type: 'value' }, yAxis: { type: 'value' },
+ series: [{ type: 'scatter', name: 'Pts', data: [[1, 2], [3, 4.5], [5, 6]] }],
+ }), 2, 'rId3', PALETTE, new Report(), 'slide 6')
+ ok(out.chartXml !== undefined, 'scatter is in-subset')
+ const space = parseXml(out.chartXml!)
+ const sc = descendants(space, NS.c, 'scatterChart')[0]
+ ok(sc !== undefined && attr(kid(sc, NS.c, 'scatterStyle')!, 'val') === 'lineMarker', 'scatterChart with lineMarker style')
+ const ser = kid(sc, NS.c, 'ser')!
+ const xs = kids(kid(kid(kid(ser, NS.c, 'xVal')!, NS.c, 'numRef')!, NS.c, 'numCache')!, NS.c, 'pt').map((p) => textOf(p))
+ const ys = kids(kid(kid(kid(ser, NS.c, 'yVal')!, NS.c, 'numRef')!, NS.c, 'numCache')!, NS.c, 'pt').map((p) => textOf(p))
+ ok(xs.join(',') === '1,3,5' && ys.join(',') === '2,4.5,6', 'pairs split into xVal/yVal caches verbatim')
+ ok(descendants(kid(ser, NS.c, 'spPr')!, NS.a, 'noFill').length === 1, 'series outline noFill (markers only, no joining line)')
+ ok(kids(descendants(space, NS.c, 'plotArea')[0], NS.c, 'valAx').length === 2, 'scatter carries two VALUE axes (no category axis)')
+}
+
+// --- the fallback contract ---------------------------------------------------
+console.log('out-of-subset → data table (never a wrong chart)')
+
+/** True when the frame is a TABLE graphicFrame with zero chart traces. */
+function isDataTable(out: { frame: ReturnType<typeof x>; chartXml?: string }): boolean {
+ if (out.chartXml !== undefined) return false
+ const frame = parseFrame(out.frame)
+ return descendants(frame, NS.a, 'tbl').length === 1 && descendants(frame, NS.c, 'chart').length === 0
+}
+
+{
+ // NEGATIVE CONTROL (the spike's core case): a stacked option must not emit
+ // a c:chart — a clustered read of stacked bars destroys the totals.
+ const report = new Report()
+ const out = chartExport(chartEl({
+ xAxis: { data: ['a', 'b'] },
+ series: [
+ { type: 'bar', name: 'North', stack: 'total', data: [3, 4] },
+ { type: 'bar', name: 'South', stack: 'total', data: [5, 6] },
+ ],
+ }), 2, 'rId4', PALETTE, report, 'slide 7')
+ ok(out.chartXml === undefined, 'NEGATIVE: stacked option emits NO c:chart part')
+ ok(isDataTable(out), 'stacked option renders as a table graphicFrame instead')
+ const entry = report.build().entries.find((e) => e.code === 'chart-approximated')
+ ok(entry !== undefined && entry.verdict === 'approximated', "fallback reports 'chart-approximated'")
+
+ // The table carries the actual numbers: header row of series names, labels
+ // down the first column.
+ const tbl = descendants(parseFrame(out.frame), NS.a, 'tbl')[0]
+ const trs = kids(tbl, NS.a, 'tr')
+ ok(trs.length === 3, 'header + one row per category')
+ const rowText = (r: number) => kids(trs[r], NS.a, 'tc').map((tc) => descendants(tc, NS.a, 't').map(textOf).join(''))
+ ok(rowText(0).join('|') === '|North|South', 'header row carries the series names')
+ ok(rowText(1).join('|') === 'a|3|5', 'data rows carry label + every series value')
+}
+
+{
+ // Mixed types on ONE axis is outside the subset (dual-axis mixing is not).
+ const mixed = chartExport(chartEl({
+ xAxis: { data: ['a'] },
+ series: [{ type: 'bar', data: [1] }, { type: 'line', data: [2] }],
+ }), 2, 'rId5', PALETTE, new Report(), 'slide 8')
+ ok(isDataTable(mixed), 'NEGATIVE: bar+line on the SAME axis falls back to a table')
+
+ const radar = chartExport(chartEl({ series: [{ type: 'radar', data: [1] }] }),
+ 2, 'rId5', PALETTE, new Report(), 'slide 8')
+ ok(isDataTable(radar), 'NEGATIVE: unknown series type falls back to a table')
+
+ const twoPies = chartExport(chartEl({ series: [{ type: 'pie', data: [] }, { type: 'pie', data: [] }] }),
+ 2, 'rId5', PALETTE, new Report(), 'slide 8')
+ ok(isDataTable(twoPies), 'NEGATIVE: multi-series pie falls back to a table')
+
+ const pieFallback = chartExport(chartEl({
+ series: [{ type: 'pie', stack: 'x', name: 'Share', data: [{ name: 'A', value: 7 }] }],
+ }), 2, 'rId5', PALETTE, new Report(), 'slide 8')
+ const tbl = descendants(parseFrame(pieFallback.frame), NS.a, 'tbl')[0]
+ const row1 = kids(kids(tbl, NS.a, 'tr')[1], NS.a, 'tc').map((tc) => descendants(tc, NS.a, 't').map(textOf).join(''))
+ ok(row1.join('|') === 'A|7', 'pie fallback tables slice names and values')
+}
+
+// --- data coercion mirrors the renderer --------------------------------------
+console.log('data coercion')
+
+{
+ const report = new Report()
+ const out = chartExport(chartEl({
+ xAxis: { data: ['a', 'b', 'c'] },
+ series: [{ type: 'bar', name: 'S', data: [1, null, { value: 5 }] }],
+ }), 2, 'rId6', PALETTE, report, 'slide 9')
+ // One bar series = exactly one numCache (names and categories are strCache).
+ const cache = descendants(parseXml(out.chartXml!), NS.c, 'numCache')[0]
+ const vals = kids(cache, NS.c, 'pt').map((p) => textOf(p))
+ ok(vals.join(',') === '1,0,0', 'null and {value} objects coerce to 0 — exactly what charts-lite rendered')
+ ok(report.build().entries.some((e) => e.code === 'chart-data-coerced' && e.verdict === 'approximated'),
+ 'coercion is reported even though the render already showed zeros')
+}
+
+console.log(`\n${checks} checks, ${failures} failures`)
+if (failures > 0) process.exit(1)
diff --git a/scripts/test-convert/pptx-coverage.ts b/scripts/test-convert/pptx-coverage.ts
new file mode 100644
index 00000000..59a8c33a
--- /dev/null
+++ b/scripts/test-convert/pptx-coverage.ts
@@ -0,0 +1,109 @@
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// Export coverage: every bento/slides element type is either written to
+// PowerPoint (MAPPED) or honestly reported as not yet (NOT_YET). Nothing is
+// silently lost, and a type slides adds later cannot slip past the exporter.
+//
+// node scripts/test-convert/pptx-coverage.ts
+//
+// The element types are read from slides/src/model.ts (the SlideElement
+// union), not listed here by hand. So when slides adds an element type, this
+// rig fails until the exporter has a `case` for it in pptx-write/index.ts
+// and the type is listed below.
+//
+// FOR CONTRIBUTORS: when you write code.ts or embed.ts, this rig is where you
+// say so. Move the type from NOT_YET to MAPPED and give it a SAMPLE; the rig
+// then requires that it emits a shape with a clean package, and that it no
+// longer reports itself unsupported. Your writer's own detailed checks go in
+// a rig of its own (pptx-code.ts, say), built on ./_export-harness.ts.
+
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { exportOne, frame } from './_export-harness.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+
+/** A minimal element of each type the exporter writes. */
+const SAMPLE: Record<string, object> = {
+ text: { type: 'text', html: 'Hello', fontSize: 24, fontFamily: 'Inter, sans-serif', fontWeight: 400,
+ color: '#1E2A3A', align: 'left', valign: 'top', lineHeight: 1.2 },
+ shape: { type: 'shape', shape: 'rect', fill: '#FF7A59', stroke: '#000000', strokeWidth: 0, radius: 0 },
+ image: { type: 'image', fit: 'cover',
+ src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' },
+ svg: { type: 'svg', markup: '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>' },
+ chart: { type: 'chart', option: { xAxis: { data: ['A', 'B'] }, yAxis: {}, series: [{ type: 'bar', name: 'S', data: [1, 2] }] } },
+ table: { type: 'table', columns: [{ w: 1 }], header: false, rows: [{ cells: [{ html: 'x' }] }], style: { radius: 0 } },
+ // media exports its poster as a picture; playback itself is not written yet
+ // (reported 'media-dropped' — a contributor task, see CONTRIBUTING.md)
+ media: { type: 'media', kind: 'video', src: 'data:video/mp4;base64,AAAA',
+ poster: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==' },
+}
+const MAPPED = Object.keys(SAMPLE)
+
+/** Types with no writer yet. Each is a task a contributor can take; see
+ * convert/CONTRIBUTING.md. Their writers report them dropped. */
+const NOT_YET: Record<string, object> = {
+ code: { type: 'code', fontSize: 18, fontFamily: 'Menlo, monospace', align: 'left', valign: 'top',
+ lineHeight: 1.4, color: '#1E2A3A', content: 'let x = 1\nx += 1' },
+ embed: { type: 'embed', app: 'bento/dash', view: '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>' },
+}
+
+// --- what slides says exists -------------------------------------------------
+const model = fs.readFileSync(path.join(root, 'slides/src/model.ts'), 'utf8')
+const union = /export type SlideElement =([^;]*?)(?:\n\n|\n\/\*\*|\nexport )/.exec(model)?.[1] ?? ''
+const ifaceNames = [...union.matchAll(/\b([A-Z]\w*Element)\b/g)].map((m) => m[1])
+const typeOf = (iface: string): string | undefined =>
+ new RegExp(`export interface ${iface}\\b[^{]*\\{[^}]*?\\btype: '([a-z]+)'`).exec(model)?.[1]
+const modelTypes = ifaceNames.map(typeOf)
+
+console.log('every element type slides defines is accounted for')
+ok(ifaceNames.length >= 9 && modelTypes.every(Boolean),
+ `read ${ifaceNames.length} element types from slides' SlideElement union (${modelTypes.join(', ')})`)
+const index = fs.readFileSync(path.join(root, 'convert/src/pptx-write/index.ts'), 'utf8')
+const cases = new Set([...index.matchAll(/case '([a-z]+)':/g)].map((m) => m[1]))
+for (const t of modelTypes as string[]) {
+ const listed = MAPPED.includes(t) ? 'MAPPED' : t in NOT_YET ? 'NOT_YET' : ''
+ ok(cases.has(t) && listed !== '',
+ `'${t}': ${cases.has(t) ? 'has a case in pptx-write/index.ts' : 'NO case in pptx-write/index.ts'}, ${listed || 'listed in neither MAPPED nor NOT_YET in this rig'}`)
+}
+for (const t of [...MAPPED, ...Object.keys(NOT_YET)])
+ ok((modelTypes as string[]).includes(t), `'${t}' still exists in slides' model`)
+
+// cNvPr ids above 1: the spTree's own group is 1, so any id ≥ 2 is an element
+const shapesIn = (xml: string) => [...xml.matchAll(/<p:cNvPr id="(\d+)"/g)].filter((m) => m[1] !== '1').length
+
+console.log('mapped types emit a shape and a clean package')
+for (const t of MAPPED) {
+ const r = await exportOne(SAMPLE[t])
+ ok(r.problems.length === 0 && shapesIn(r.slideXml) === 1 && !r.codes.has('element-unsupported'),
+ `${t}: one shape, nothing wrong with the package${r.problems.length ? ` (${r.problems.join('; ')})` : ''}`)
+}
+
+console.log('not-yet types are reported, never silently lost')
+for (const [t, el] of Object.entries(NOT_YET)) {
+ const r = await exportOne(el)
+ const said = r.report.entries.find((e) => e.code === 'element-unsupported' && e.detail.includes(`'${t}'`))
+ ok(!!said && shapesIn(r.slideXml) === 0 && r.problems.length === 0,
+ `${t}: reported dropped ("${said?.detail ?? 'NO REPORT'}"), no shape, the rest of the package clean`)
+}
+
+console.log('a type nobody has heard of')
+{
+ const r = await exportOne({ type: 'hologram' })
+ ok(r.codes.has('element-unsupported') && r.problems.length === 0,
+ 'an unknown future element type degrades to a report entry; the export still succeeds')
+}
+
+console.log(`\nopen for contributors: ${Object.keys(NOT_YET).join(', ')}`)
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-media.ts b/scripts/test-convert/pptx-media.ts
new file mode 100644
index 00000000..d310486a
--- /dev/null
+++ b/scripts/test-convert/pptx-media.ts
@@ -0,0 +1,268 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write media rig: data-URI decoding, the deduplicating media store, and
+// p:pic assembly for images / svg / media posters.
+//
+// node scripts/test-convert/pptx-media.ts (Node ≥ 23.6 strips types natively)
+//
+// Same discipline as pptx-parts.ts: every emitted structure is re-read with
+// the convert engine's own PARSER (written for other people's files, with its
+// own strict grammar), and the NEGATIVE controls have each been observed
+// failing — a decoder that never returns null and a reporter that fires on
+// every fit are both indistinguishable from correct output until PowerPoint
+// meets them.
+
+import { parseXml, kids, kid, attr, textOf, NS, type XElem } from '../../convert/src/xml.ts'
+import { serialize, x } from '../../convert/src/xmlout.ts'
+import { PML_XMLNS, REL, type RelEntry } from '../../convert/src/pptx-write/parts.ts'
+import {
+ decodeBase64, decodeDataUri, MediaStore,
+ imagePic, svgPic, mediaPoster,
+ type ImageIn, type SvgIn, type MediaIn, type MediaCtx,
+} from '../../convert/src/pptx-write/media.ts'
+import { Report } from '../../convert/src/report.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const bytesEq = (a: Uint8Array | null, b: number[]): boolean =>
+ !!a && a.length === b.length && b.every((v, i) => a[i] === v)
+
+// A fresh ctx per scenario: report/rels/store state is what the checks read.
+function makeCtx(assets: Record<string, string> = {}): MediaCtx & { relN: () => number } {
+ const rels: RelEntry[] = []
+ const report = new Report()
+ let n = 0
+ return {
+ assets, store: new MediaStore(), rels, report,
+ nextRelId: () => `rId${++n}`,
+ relN: () => n,
+ }
+}
+
+// Serialized pics carry p:/a:/r: prefixes that only resolve under a root
+// declaring the trio — exactly the situation inside a real slide part.
+function parsePic(node: ReturnType<typeof x>): XElem {
+ const root = parseXml(serialize(x('p:sld', PML_XMLNS, [node])))
+ const pic = kid(root, NS.p, 'pic')
+ if (!pic) throw new Error('no p:pic under wrapper root')
+ return pic
+}
+
+const findEntry = (report: Report, code: string) => report.build().entries.find((e) => e.code === code)
+
+const baseFrame = { x: 10, y: 20, w: 320, h: 240, rotation: 0, opacity: 1 }
+
+// --- data-URI decoding -------------------------------------------------------
+console.log('data: URI decoding')
+
+// Known-vector round-trips (RFC 4648 test vectors, computed independently).
+ok(bytesEq(decodeBase64('TWFu'), [77, 97, 110]), 'base64 "TWFu" → "Man" bytes')
+ok(bytesEq(decodeBase64('TWE='), [77, 97]), 'base64 one-pad "TWE=" → 2 bytes')
+ok(bytesEq(decodeBase64('TQ=='), [77]), 'base64 two-pad "TQ==" → 1 byte')
+ok(bytesEq(decodeBase64('TQ'), [77]), 'missing padding tolerated (editors strip it)')
+ok(bytesEq(decodeBase64('TW\n Fu\t'), [77, 97, 110]), 'whitespace inside base64 skipped (wrapped data URIs)')
+ok(bytesEq(decodeBase64('_w=='), [255]), 'URL-safe alphabet accepted')
+
+{
+ const d = decodeDataUri('data:image/png;base64,AAECAwQF')
+ ok(!!d && d.mime === 'image/png' && bytesEq(d.bytes, [0, 1, 2, 3, 4, 5]), 'data: URI decodes mime + bytes')
+}
+{
+ const d = decodeDataUri('data:image/svg+xml,%3Csvg%3E%3C%2Fsvg%3E')
+ ok(!!d && d.mime === 'image/svg+xml' && new TextDecoder().decode(d!.bytes) === '<svg></svg>',
+ 'percent-encoded (non-base64) data: URI decodes')
+}
+// NEGATIVE controls — each seen FAIL by feeding the good path the bad input.
+ok(decodeBase64('TW@u') === null, 'NEGATIVE: base64 with an illegal character returns null')
+ok(decodeDataUri('data:image/png;base64,@@@@') === null, 'NEGATIVE: data: URI with corrupt base64 returns null')
+ok(decodeDataUri('https://example.com/a.png') === null, 'NEGATIVE: a plain URL is not a data: URI')
+ok(decodeDataUri('data:image/png;base64') === null, 'NEGATIVE: data: URI without a comma returns null')
+
+// --- MediaStore dedup --------------------------------------------------------
+console.log('MediaStore')
+
+{
+ const store = new MediaStore()
+ const a = new Uint8Array([1, 2, 3])
+ const n1 = store.add(a, 'image/png')
+ const n2 = store.add(new Uint8Array([1, 2, 3]), 'image/png')
+ const n3 = store.add(new Uint8Array([9, 9, 9]), 'image/jpeg')
+ ok(n1 === 'ppt/media/image1.png', 'first part named ppt/media/image1.png')
+ ok(n2 === n1, 'identical bytes dedupe to the same part')
+ ok(n3 === 'ppt/media/image2.jpeg', 'distinct bytes get the next number, ext from mime')
+ ok(store.files().length === 2, 'store holds 2 files after 3 adds')
+ // Same length + plausible-collision shape must still separate on content.
+ const n4 = store.add(new Uint8Array([3, 2, 1]), 'image/png')
+ ok(n4 !== n1 && store.files().length === 3, 'same-length different bytes are NOT deduped')
+ ok(store.add(new Uint8Array([1]), 'image/webp') === null, 'NEGATIVE: unsupported mime (webp) is refused')
+}
+
+// --- imagePic ----------------------------------------------------------------
+console.log('imagePic')
+
+{
+ const ctx = makeCtx()
+ const el: ImageIn = {
+ id: 'img-1', morphId: 'hero', type: 'image', ...baseFrame, rotation: 45, opacity: 0.5,
+ src: 'data:image/png;base64,AAECAwQF', fit: 'fill', radius: 12,
+ }
+ const node = imagePic(el, 7, 'slide 1', ctx)
+ ok(!!node, 'embedded image produces a node')
+ const pic = parsePic(node!)
+ const cNvPr = kid(kid(pic, NS.p, 'nvPicPr')!, NS.p, 'cNvPr')!
+ ok(attr(cNvPr, 'id') === '7' && attr(cNvPr, 'name') === 'bento:hero',
+ 'cNvPr carries the given shape id and bento:<morphId> name (#88 objectName)')
+ const blip = kid(kid(pic, NS.p, 'blipFill')!, NS.a, 'blip')!
+ ok(attr(blip, 'r:embed') === 'rId1', 'blip r:embed = allocated rel id')
+ ok(ctx.rels.length === 1 && ctx.rels[0].type === REL.image && ctx.rels[0].target === '../media/image1.png'
+ && !ctx.rels[0].external, 'rel entry: image type, ../media target, internal')
+ const amf = kid(blip, NS.a, 'alphaModFix')
+ ok(!!amf && attr(amf!, 'amt') === '50000', 'opacity 0.5 → alphaModFix amt=50000 (1000ths of a percent)')
+ ok(!!kid(kid(pic, NS.p, 'blipFill')!, NS.a, 'stretch'), 'blipFill carries a:stretch')
+ const xf = kid(kid(pic, NS.p, 'spPr')!, NS.a, 'xfrm')!
+ ok(attr(xf, 'rot') === String(45 * 60000), 'rotation in 60000ths of a degree')
+ const off = kid(xf, NS.a, 'off')!
+ const ext = kid(xf, NS.a, 'ext')!
+ ok(attr(off, 'x') === String(10 * 9525) && attr(off, 'y') === String(20 * 9525), 'a:off in EMU (px * 9525)')
+ ok(attr(ext, 'cx') === String(320 * 9525) && attr(ext, 'cy') === String(240 * 9525), 'a:ext in EMU')
+ const geom = kid(kid(pic, NS.p, 'spPr')!, NS.a, 'prstGeom')!
+ ok(attr(geom, 'prst') === 'roundRect', 'radius → prstGeom roundRect')
+ const gd = kid(kid(geom, NS.a, 'avLst')!, NS.a, 'gd')!
+ // 12px of min(320,240)=240 → 5% → 5000 in 1000ths of a percent
+ ok(attr(gd, 'fmla') === 'val 5000', 'roundRect adj = radius/shorter-side in 1000ths of a percent')
+ ok(findEntry(ctx.report, 'image-fit-approximated') === undefined,
+ "NEGATIVE: fit 'fill' (= OOXML stretch exactly) reports NO fit approximation")
+}
+
+{
+ const ctx = makeCtx()
+ const el: ImageIn = {
+ id: 'img-2', type: 'image', ...baseFrame,
+ src: 'data:image/png;base64,AAECAwQF', fit: 'cover',
+ }
+ const node = imagePic(el, 2, 'slide 2', ctx)
+ const e = findEntry(ctx.report, 'image-fit-approximated')
+ ok(!!node && !!e && e!.verdict === 'approximated', "fit 'cover' reports image-fit-approximated (was silent in #88)")
+ const geom = kid(kid(parsePic(node!), NS.p, 'spPr')!, NS.a, 'prstGeom')!
+ ok(attr(geom, 'prst') === 'rect', 'no radius → prstGeom rect')
+ const blip = kid(kid(parsePic(node!), NS.p, 'blipFill')!, NS.a, 'blip')!
+ ok(kid(blip, NS.a, 'alphaModFix') === undefined, 'NEGATIVE: full opacity emits no alphaModFix')
+}
+
+{
+ // Cross-slide dedup: two slides, one logo → one part, one rel EACH.
+ const ctx = makeCtx()
+ const logo = (id: string): ImageIn =>
+ ({ id, type: 'image', ...baseFrame, src: 'data:image/png;base64,AAECAwQF', fit: 'fill' })
+ imagePic(logo('a'), 2, 'slide 1', ctx)
+ imagePic(logo('b'), 3, 'slide 2', ctx)
+ ok(ctx.store.files().length === 1, 'identical image on two slides → ONE media part')
+ ok(ctx.rels.length === 2 && ctx.rels[0].target === ctx.rels[1].target, 'both rels point at the shared part')
+}
+
+{
+ // asset: resolution + the two drop paths.
+ const ctx = makeCtx({ pic: 'data:image/gif;base64,AAECAwQF' })
+ ok(imagePic({ id: 'a', type: 'image', ...baseFrame, src: 'asset:pic', fit: 'fill' }, 2, 's1', ctx) !== null
+ && ctx.store.files()[0].name.endsWith('.gif'), 'asset:<key> resolves through ctx.assets (ext from its mime)')
+ ok(imagePic({ id: 'b', type: 'image', ...baseFrame, src: 'asset:gone', fit: 'fill' }, 3, 's1', ctx) === null
+ && !!findEntry(ctx.report, 'missing-image'), 'NEGATIVE: dangling asset ref → null + missing-image dropped')
+ const before = ctx.store.files().length
+ ok(imagePic({ id: 'c', type: 'image', ...baseFrame, src: 'data:image/webp;base64,AAECAwQF', fit: 'fill' }, 4, 's1', ctx) === null
+ && ctx.store.files().length === before, 'NEGATIVE: unsupported mime → null, nothing registered')
+}
+
+{
+ // External URL → linked picture.
+ const ctx = makeCtx()
+ const node = imagePic({ id: 'u', type: 'image', ...baseFrame, src: 'https://example.com/a.png', fit: 'fill' }, 2, 's1', ctx)
+ const blip = kid(kid(parsePic(node!), NS.p, 'blipFill')!, NS.a, 'blip')!
+ ok(attr(blip, 'r:link') === 'rId1' && attr(blip, 'r:embed') === undefined, 'URL image uses r:link, not r:embed')
+ ok(ctx.rels[0].external === true && ctx.rels[0].target === 'https://example.com/a.png',
+ 'its rel is TargetMode=External at the raw URL')
+ ok(!!findEntry(ctx.report, 'image-linked-not-embedded'), 'linked image is reported approximated')
+}
+
+// --- svgPic ------------------------------------------------------------------
+console.log('svgPic')
+
+{
+ const ctx = makeCtx({ art: '<svg viewBox="0 0 10 10"><rect width="10" height="10"/></svg>' })
+ const el: SvgIn = { id: 'svg-1', ...baseFrame, asset: 'art', css: '.a{fill:red}' }
+ const node = svgPic(el, 4, 'slide 3', ctx)
+ ok(!!node, 'svg element produces a node')
+ const pic = parsePic(node!)
+ const blip = kid(kid(pic, NS.p, 'blipFill')!, NS.a, 'blip')!
+ ok(attr(blip, 'r:embed') === 'rId1', 'svg blip r:embed points at the svg part (no raster to point at)')
+ const extLst = kid(blip, NS.a, 'extLst')!
+ const ext = kid(extLst, NS.a, 'ext')!
+ ok(attr(ext, 'uri') === '{96DAC541-7B7A-43D3-8B79-37D633B846F1}', 'extLst ext uri is the registered svgBlip GUID')
+ const svgBlip = kids(ext).find((k) => k.local === 'svgBlip')
+ ok(!!svgBlip && svgBlip!.ns === NS.asvg, 'asvg:svgBlip resolves to the 2016/SVG namespace through the parser')
+ ok(!!svgBlip && attr(svgBlip!, 'r:embed') === 'rId1', 'svgBlip r:embed matches the blip rel')
+ ok(ctx.rels[0].target === '../media/image1.svg', 'svg part registered as ../media/image1.svg')
+ const entry = findEntry(ctx.report, 'svg-no-raster-fallback')
+ ok(!!entry && entry!.verdict === 'approximated' && entry!.detail.includes('2016'),
+ 'svg-no-raster-fallback reported, detail names the PowerPoint 2016 blank-frame case')
+ const markup = new TextDecoder().decode(ctx.store.files()[0].bytes)
+ ok(markup.includes('<style>.a{fill:red}</style>'), 'el.css injected into the embedded markup (#88 svg.ts)')
+ ok(/^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/.test(markup), 'missing xmlns injected on the root tag')
+ // And the bytes we embedded are themselves well-formed XML.
+ ok(parseXml(markup).local === 'svg', 'embedded svg bytes re-parse as XML')
+}
+
+{
+ const ctx = makeCtx({ art: '<svg xmlns="http://www.w3.org/2000/svg"/>' })
+ svgPic({ id: 's', ...baseFrame, asset: 'art' }, 2, 's1', ctx)
+ const markup = new TextDecoder().decode(ctx.store.files()[0].bytes)
+ ok((markup.match(/xmlns="http:\/\/www\.w3\.org\/2000\/svg"/g) ?? []).length === 1,
+ 'NEGATIVE: an already-declared xmlns is not doubled')
+ const ctx2 = makeCtx()
+ ok(svgPic({ id: 'e', ...baseFrame, markup: ' ' }, 2, 's1', ctx2) === null
+ && !!findEntry(ctx2.report, 'missing-svg'), 'NEGATIVE: blank markup → null + missing-svg dropped')
+}
+
+// --- mediaPoster -------------------------------------------------------------
+console.log('mediaPoster')
+
+{
+ const ctx = makeCtx()
+ const el: MediaIn = {
+ id: 'vid-1', ...baseFrame, kind: 'video',
+ src: 'data:video/mp4;base64,AAAA', poster: 'data:image/jpeg;base64,AAECAwQF', radius: 8,
+ }
+ const node = mediaPoster(el, 5, 'slide 4', ctx)
+ ok(!!node, 'video with a poster emits the poster p:pic')
+ const entry = findEntry(ctx.report, 'media-dropped')
+ ok(!!entry && entry!.verdict === 'dropped' && entry!.detail.includes('poster'),
+ 'media-dropped reported; detail says the poster stands in')
+ ok(ctx.rels[0].type === REL.image && ctx.rels[0].target === '../media/image1.jpeg',
+ 'poster registered as an image part (video bytes never touch the package)')
+ const geom = kid(kid(parsePic(node!), NS.p, 'spPr')!, NS.a, 'prstGeom')!
+ ok(attr(geom, 'prst') === 'roundRect', 'video radius carries onto the poster pic')
+}
+
+{
+ const ctx = makeCtx()
+ const node = mediaPoster({ id: 'au-1', ...baseFrame, kind: 'audio', src: 'data:audio/mp3;base64,AAAA' }, 2, 's1', ctx)
+ ok(node === null && ctx.store.files().length === 0, 'audio (no poster) emits nothing')
+ const entry = findEntry(ctx.report, 'media-dropped')
+ ok(!!entry && !entry!.detail.includes('poster'), 'NEGATIVE: media-dropped detail omits poster when there is none')
+}
+
+{
+ // textOf sanity on our own output — the whole pic tree contains no stray text.
+ const ctx = makeCtx()
+ const node = imagePic({ id: 'q', type: 'image', ...baseFrame, src: 'data:image/png;base64,AAECAwQF', fit: 'fill' }, 2, 's1', ctx)
+ ok(textOf(parsePic(node!)).trim() === '', 'p:pic tree is element-only (no accidental text nodes)')
+}
+
+console.log(`\n${checks} checks, ${failures} failures`)
+if (failures > 0) process.exit(1)
diff --git a/scripts/test-convert/pptx-parts.ts b/scripts/test-convert/pptx-parts.ts
new file mode 100644
index 00000000..e688c4bc
--- /dev/null
+++ b/scripts/test-convert/pptx-parts.ts
@@ -0,0 +1,272 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write package-skeleton rig: xmlout + parts.
+//
+// node scripts/test-convert/pptx-parts.ts (Node ≥ 23.6 strips types natively)
+//
+// The emitter and the part builders are checked against the convert engine's
+// own PARSER (convert/src/xml.ts) — code written for reading other
+// people's files, months apart from the writer, with its own strict grammar.
+// Not proof PowerPoint accepts the output (only PowerPoint is), but every
+// structural claim here — namespaces resolve, escaping round-trips, required
+// children present, id floors respected — is one PowerPoint checks before it
+// opens a file, and the NEGATIVE controls show each guard actually firing:
+// an emitter whose validation never throws is indistinguishable from no
+// validation at all.
+
+import { parseXml, kids, kid, attr, textOf, NS, type XElem } from '../../convert/src/xml.ts'
+import { serialize, x } from '../../convert/src/xmlout.ts'
+import {
+ CT, REL, SLD_ID_FLOOR, MASTER_ID_BASE,
+ contentTypes, relsPart, presentationXml, presentationRels,
+ themeXml, slideMasterXml, slideMasterRels, slideLayoutXml, slideLayoutRels,
+ notesMasterXml, notesMasterRels, notesSlideXml, notesSlideRels,
+ slidePart, slideLayoutRel,
+} from '../../convert/src/pptx-write/parts.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+function throws(fn: () => unknown, msg: string) {
+ let threw = false
+ try { fn() } catch { threw = true }
+ ok(threw, msg)
+}
+
+// --- xmlout: the emitter -----------------------------------------------------
+console.log('xmlout')
+
+ok(
+ serialize(x('root', { a: 1, b: 'two' }, [x('leaf'), 'text'])) ===
+ '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root a="1" b="two"><leaf/>text</root>',
+ 'serializes declaration, attributes, self-closing empty, mixed content',
+)
+ok(serialize(x('r'), false) === '<?xml version="1.0" encoding="UTF-8"?><r/>', 'standalone=false omits the attribute')
+
+{
+ // Escaping round-trip THROUGH THE PARSER: what goes in comes back out.
+ const nasty = 'Q3 & Q4 <Results> "final" > 100%'
+ const doc = serialize(x('t', { title: nasty }, [nasty]))
+ const back = parseXml(doc)
+ ok(textOf(back) === nasty, 'text escaping round-trips & < > through parseXml')
+ ok(back.attrs.get('title') === nasty, 'attribute escaping round-trips & < > " through parseXml')
+ ok(doc.includes('&amp;') && doc.includes('&lt;') && doc.includes('&quot;'), 'escapes are actually in the bytes')
+}
+
+// Negative controls — each guard observed firing. Removing any throw in
+// xmlout.ts turns exactly one of these into a FAIL (verified by building the
+// bad output by hand first: parseXml accepts none of them either).
+throws(() => serialize(x('two words')), 'NEGATIVE: element name with a space is refused')
+throws(() => serialize(x('a:b:c')), 'NEGATIVE: element name with two colons is refused')
+throws(() => serialize(x('r', { 'bad name': 1 })), 'NEGATIVE: attribute name with a space is refused')
+throws(() => serialize(x('r', undefined, ['ok\x00bad'])), 'NEGATIVE: NUL in text is refused')
+throws(() => serialize(x('r', { v: 'a\x07b' })), 'NEGATIVE: BEL in an attribute value is refused')
+throws(() => serialize(x('r', { cx: NaN })), 'NEGATIVE: NaN attribute is refused')
+ok(serialize(x('r', undefined, ['a\tb\nc'])).includes('a\tb\nc'), 'tab and newline in text pass (legal XML)')
+
+// --- [Content_Types].xml -----------------------------------------------------
+console.log('[Content_Types].xml')
+
+{
+ const doc = parseXml(contentTypes([{ partName: '/ppt/presentation.xml', contentType: CT.presentation }]))
+ ok(doc.ns === NS.ct && doc.local === 'Types', 'root is ct:Types with the content-types namespace')
+ const defaults = kids(doc, NS.ct, 'Default')
+ const exts = defaults.map((d) => attr(d, 'Extension'))
+ for (const e of ['rels', 'xml', 'png', 'jpeg', 'gif', 'svg']) ok(exts.includes(e), `default for .${e} present`)
+ const ov = kids(doc, NS.ct, 'Override')
+ ok(ov.length === 1 && attr(ov[0], 'ContentType') === CT.presentation, 'presentation override carried')
+}
+
+// --- .rels -------------------------------------------------------------------
+console.log('.rels')
+
+{
+ const doc = parseXml(relsPart([
+ { id: 'rId1', type: REL.slideLayout, target: '../slideLayouts/slideLayout1.xml' },
+ { id: 'rId2', type: REL.hyperlink, target: 'https://bento.page/?a=1&b=2', external: true },
+ ]))
+ ok(doc.ns === NS.rel, 'root resolves to the package relationships namespace')
+ const rels = kids(doc, NS.rel, 'Relationship')
+ ok(attr(rels[0], 'TargetMode') === undefined, 'internal rel carries no TargetMode')
+ ok(attr(rels[1], 'TargetMode') === 'External', 'external rel carries TargetMode="External"')
+ ok(attr(rels[1], 'Target') === 'https://bento.page/?a=1&b=2', 'URL with & round-trips')
+}
+
+// --- presentation.xml --------------------------------------------------------
+console.log('presentation.xml')
+
+/** The property PowerPoint enforces: every sldId in [256, 2^31). */
+function sldIdsValid(root: XElem): boolean {
+ const lst = kid(root, NS.p, 'sldIdLst')
+ if (!lst) return false
+ const ids = kids(lst, NS.p, 'sldId').map((s) => Number(attr(s, 'id')))
+ return ids.length > 0 && ids.every((id) => id >= 256 && id < 2147483648) && new Set(ids).size === ids.length
+}
+
+{
+ const doc = parseXml(presentationXml(3, { cx: 12192000, cy: 6858000 }, true))
+ ok(doc.ns === NS.p && doc.local === 'presentation', 'root is p:presentation in the presentationml namespace')
+ ok(sldIdsValid(doc), `every sldId is unique and >= ${SLD_ID_FLOOR}`)
+ const masters = kids(kid(doc, NS.p, 'sldMasterIdLst')!, NS.p, 'sldMasterId')
+ ok(Number(attr(masters[0], 'id')) >= MASTER_ID_BASE, 'sldMasterId id is in the >= 2^31 range')
+ ok(attr(masters[0], 'id') !== attr(kids(kid(doc, NS.p, 'sldIdLst')!, NS.p, 'sldId')[0], 'id'), 'master and slide id ranges are disjoint')
+ const slideRIds = kids(kid(doc, NS.p, 'sldIdLst')!, NS.p, 'sldId').map((s) => attr(s, 'id') && attr(s, 'r:id'))
+ ok(slideRIds.join(',') === 'rId2,rId3,rId4', 'slide r:ids are rId2..rId4 (rId1 = master)')
+ const order = doc.children.filter((c): c is XElem => typeof c !== 'string').map((c) => c.local)
+ ok(order.join(',') === 'sldMasterIdLst,notesMasterIdLst,sldIdLst,sldSz,notesSz',
+ 'children in schema order (notesMasterIdLst between masters and slides)')
+ ok(attr(kid(doc, NS.p, 'notesMasterIdLst')!.children[0] as XElem, 'r:id') === 'rId5', 'notesMaster takes the rId after the slides')
+ const sz = kid(doc, NS.p, 'sldSz')!
+ ok(attr(sz, 'cx') === '12192000' && attr(sz, 'cy') === '6858000', 'sldSz carries the EMU size')
+
+ // The rels partner must honour the same convention.
+ const rels = kids(parseXml(presentationRels(3, true)), NS.rel, 'Relationship')
+ const byId = new Map(rels.map((r) => [attr(r, 'Id'), r]))
+ ok(attr(byId.get('rId1')!, 'Type') === REL.slideMaster, 'presentationRels rId1 is the master')
+ ok(attr(byId.get('rId3')!, 'Target') === 'slides/slide2.xml', 'presentationRels rId3 is slide2 (matches the xml side)')
+ ok(attr(byId.get('rId5')!, 'Type') === REL.notesMaster, 'presentationRels rId5 is the notes master')
+}
+
+{
+ // NEGATIVE control for the id floor: the same check run over a presentation
+ // built with a floor of 1 (what a hand-writer naively emits, and what
+ // PptxGenJS silently protected PR #88 from) must FAIL.
+ const bad = serialize(x('p:presentation', { 'xmlns:p': NS.p, 'xmlns:r': NS.r }, [
+ x('p:sldIdLst', undefined, [
+ x('p:sldId', { id: 1, 'r:id': 'rId2' }),
+ x('p:sldId', { id: 2, 'r:id': 'rId3' }),
+ ]),
+ ]))
+ ok(!sldIdsValid(parseXml(bad)), 'NEGATIVE: a sldId floor of 1 is caught by the id check')
+ ok(SLD_ID_FLOOR === 256, 'the exported floor constant is 256')
+}
+
+// --- theme / master / layout chain -------------------------------------------
+console.log('theme + master + layout')
+
+{
+ const doc = parseXml(themeXml({
+ background: '#FDF6EC', color: 'rgb(30, 42, 58)', accent: '#E8A87C',
+ fontFamily: '"Inter", system-ui, sans-serif',
+ }))
+ ok(doc.ns === NS.a && doc.local === 'theme', 'root is a:theme in the drawingml namespace')
+ const scheme = kid(kid(doc, NS.a, 'themeElements')!, NS.a, 'clrScheme')!
+ const slots = kids(scheme).map((s) => s.local)
+ ok(slots.join(',') === 'dk1,lt1,dk2,lt2,accent1,accent2,accent3,accent4,accent5,accent6,hlink,folHlink',
+ 'clrScheme carries all 12 slots in schema order')
+ const val = (name: string) => attr(kid(kid(scheme, NS.a, name)!, NS.a, 'srgbClr')!, 'val')
+ ok(val('lt1') === 'FDF6EC', 'lt1 = doc.theme.background (hex normalized)')
+ ok(val('dk1') === '1E2A3A', 'dk1 = doc.theme.color (rgb() normalized to hex)')
+ ok(val('accent1') === 'E8A87C', 'accent1 = doc.theme.accent')
+ const fonts = kid(kid(doc, NS.a, 'themeElements')!, NS.a, 'fontScheme')!
+ const major = attr(kid(kid(fonts, NS.a, 'majorFont')!, NS.a, 'latin')!, 'typeface')
+ const minor = attr(kid(kid(fonts, NS.a, 'minorFont')!, NS.a, 'latin')!, 'typeface')
+ ok(major === 'Inter' && minor === 'Inter', 'first family, quotes stripped, as both major and minor latin')
+ const fmt = kid(kid(doc, NS.a, 'themeElements')!, NS.a, 'fmtScheme')!
+ ok(kids(kid(fmt, NS.a, 'fillStyleLst')!).length === 3, 'fmtScheme has 3 fill styles')
+ ok(kids(kid(fmt, NS.a, 'lnStyleLst')!).length === 3, 'fmtScheme has 3 line styles')
+ ok(kids(kid(fmt, NS.a, 'effectStyleLst')!).length === 3, 'fmtScheme has 3 effect styles')
+ ok(kids(kid(fmt, NS.a, 'bgFillStyleLst')!).length === 3, 'fmtScheme has 3 background fills')
+}
+
+/** spTree must open nvGrpSpPr(cNvPr id=1) + grpSpPr — the preamble PowerPoint
+ * requires on the root group even when the tree is otherwise empty. */
+function preambleOk(cSld: XElem): boolean {
+ const tree = kid(cSld, NS.p, 'spTree')
+ if (!tree) return false
+ const els = kids(tree)
+ return els[0]?.local === 'nvGrpSpPr'
+ && attr(kid(els[0], NS.p, 'cNvPr')!, 'id') === '1'
+ && els[1]?.local === 'grpSpPr'
+}
+
+{
+ const master = parseXml(slideMasterXml())
+ ok(master.ns === NS.p && master.local === 'sldMaster', 'master root is p:sldMaster')
+ ok(preambleOk(kid(master, NS.p, 'cSld')!), 'master spTree carries the group preamble (and nothing else)')
+ const clrMap = kid(master, NS.p, 'clrMap')!
+ ok(['bg1', 'tx1', 'bg2', 'tx2', 'accent1', 'accent6', 'hlink', 'folHlink'].every((a) => attr(clrMap, a) !== undefined),
+ 'clrMap carries the full 12-attribute mapping')
+ const layoutId = kids(kid(master, NS.p, 'sldLayoutIdLst')!, NS.p, 'sldLayoutId')[0]
+ ok(Number(attr(layoutId, 'id')) >= MASTER_ID_BASE && attr(layoutId, 'r:id') === 'rId1', 'layout id >= 2^31, wired to rId1')
+ const mrels = kids(parseXml(slideMasterRels()), NS.rel, 'Relationship')
+ ok(mrels.some((r) => attr(r, 'Type') === REL.slideLayout) && mrels.some((r) => attr(r, 'Type') === REL.theme),
+ 'master rels reach the layout and the theme')
+
+ const layout = parseXml(slideLayoutXml())
+ ok(attr(layout, 'type') === 'blank', 'layout is type="blank"')
+ ok(kid(kid(layout, NS.p, 'clrMapOvr')!, NS.a, 'masterClrMapping') !== undefined, 'layout defers colours to the master')
+ ok(preambleOk(kid(layout, NS.p, 'cSld')!), 'layout spTree carries the group preamble')
+ const lrels = kids(parseXml(slideLayoutRels()), NS.rel, 'Relationship')
+ ok(attr(lrels[0], 'Type') === REL.slideMaster, 'layout rels reach the master')
+
+ const nm = parseXml(notesMasterXml())
+ ok(nm.local === 'notesMaster' && kid(nm, NS.p, 'clrMap') !== undefined, 'notesMaster carries cSld + clrMap')
+ // Both pinned by bisection against real macOS PowerPoint (2026-08-24): a
+ // one-slide deck whose ONLY extra feature was a speaker note raised the
+ // repair dialog until the notes master carried a notesStyle AND its own
+ // theme part. Schema-optional, reader-required — same class as presProps.
+ ok(kid(nm, NS.p, 'notesStyle') !== undefined, 'notesMaster carries notesStyle (absence = repair dialog)')
+ ok(attr(kids(parseXml(notesMasterRels()), NS.rel, 'Relationship')[0], 'Target') === '../theme/theme2.xml',
+ 'notesMaster has its OWN theme part, never a share of the slide master\'s')
+}
+
+// --- notesSlide --------------------------------------------------------------
+console.log('notesSlide')
+
+{
+ const title = 'Ship it & <win> — margin > cost'
+ const doc = parseXml(notesSlideXml([title, '', 'second para']))
+ ok(doc.ns === NS.p && doc.local === 'notes', 'root is p:notes')
+ const sp = kid(kid(kid(doc, NS.p, 'cSld')!, NS.p, 'spTree')!, NS.p, 'sp')!
+ const ph = kid(kid(kid(sp, NS.p, 'nvSpPr')!, NS.p, 'nvPr')!, NS.p, 'ph')!
+ ok(attr(ph, 'type') === 'body' && attr(ph, 'idx') === '1', 'notes text lives in the body placeholder (idx 1)')
+ const paras = kids(kid(sp, NS.p, 'txBody')!, NS.a, 'p')
+ ok(paras.length === 3, 'three paragraphs (empty line preserved as empty a:p)')
+ ok(textOf(paras[0]) === title, 'title with & < > round-trips through the notes body')
+ ok(paras[1].children.length === 0, 'blank line is an empty a:p')
+ const empty = parseXml(notesSlideXml([]))
+ ok(kids(kid(kids(kid(kid(empty, NS.p, 'cSld')!, NS.p, 'spTree')!, NS.p, 'sp')[0], NS.p, 'txBody')!, NS.a, 'p').length === 1,
+ 'zero paragraphs still emits one a:p (txBody may not be empty)')
+ const nrels = kids(parseXml(notesSlideRels(4)), NS.rel, 'Relationship')
+ ok(attr(nrels[0], 'Type') === REL.notesMaster && attr(nrels[1], 'Target') === '../slides/slide4.xml',
+ 'notesSlide rels reach the notes master and its slide')
+}
+
+// --- slidePart ---------------------------------------------------------------
+console.log('slidePart')
+
+{
+ const shape = x('p:sp', undefined, [
+ x('p:nvSpPr', undefined, [x('p:cNvPr', { id: 2, name: 'Title & <co>' }), x('p:cNvSpPr'), x('p:nvPr')]),
+ x('p:spPr'),
+ ])
+ const bg = x('p:bg', undefined, [x('p:bgPr', undefined, [
+ x('a:solidFill', undefined, [x('a:srgbClr', { val: '112233' })]), x('a:effectLst'),
+ ])])
+ const { xml, rels } = slidePart([shape], [slideLayoutRel('rId1')], { bg, hidden: true })
+
+ const doc = parseXml(xml)
+ ok(doc.ns === NS.p && doc.local === 'sld', 'root is p:sld with resolving namespaces')
+ ok(attr(doc, 'show') === '0', 'hidden slide carries show="0"')
+ const cSld = kid(doc, NS.p, 'cSld')!
+ const order = cSld.children.filter((c): c is XElem => typeof c !== 'string').map((c) => c.local)
+ ok(order.join(',') === 'bg,spTree', 'p:bg precedes p:spTree under p:cSld')
+ ok(preambleOk(cSld), 'spTree opens with the mandatory group preamble')
+ const treeKids = kids(kid(cSld, NS.p, 'spTree')!)
+ ok(treeKids[2]?.local === 'sp', 'caller children come after the preamble')
+ ok(attr(kid(kids(treeKids[2])[0], NS.p, 'cNvPr')!, 'name') === 'Title & <co>', 'shape name attribute escaping round-trips')
+ ok(kid(doc, NS.p, 'clrMapOvr') !== undefined, 'slide carries clrMapOvr')
+ const srels = kids(parseXml(rels), NS.rel, 'Relationship')
+ ok(attr(srels[0], 'Type') === REL.slideLayout && attr(srels[0], 'Target') === '../slideLayouts/slideLayout1.xml',
+ 'slide rels carry the layout rel from slideLayoutRel()')
+}
+
+console.log(`\n${checks} checks, ${failures} failures`)
+if (failures > 0) process.exit(1)
diff --git a/scripts/test-convert/pptx-report.ts b/scripts/test-convert/pptx-report.ts
new file mode 100644
index 00000000..327fbb83
--- /dev/null
+++ b/scripts/test-convert/pptx-report.ts
@@ -0,0 +1,107 @@
+// @bundle — reaches slides' model and maths scanner, whose imports are extensionless
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+//
+// What a person learns from an export, and the typefaces PowerPoint is told
+// to use:
+// · foldReport/slideRange: one line per kind of loss, dropped first, with
+// the slides it happened on ("slides 3, 5–7"), the whole deck named as such;
+// · formulas are reported (maths-as-source) using slides' own scanner, so
+// prose with dollar signs is not;
+// · the deck's own fonts are named as not embedded;
+// · document JSON exports like a .bento.html;
+// · typefaceOf: CSS generics and one-platform system fonts are skipped.
+
+import { foldReport, slideRange, type FidelityReport } from '../../convert/src/report.ts'
+import { bentoToPptx } from '../../convert/src/export.ts'
+import { typefaceOf } from '../../convert/src/pptx-write/fonts.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+console.log('slide ranges')
+for (const [nums, want] of [
+ [[4], 'slide 4'], [[3, 5, 6, 7], 'slides 3, 5–7'], [[2, 3], 'slides 2, 3'],
+ [[7, 1, 2, 3, 3], 'slides 1–3, 7'], [[], ''],
+] as Array<[number[], string]>) ok(slideRange(nums) === want, `${JSON.stringify(nums)} → "${want}" (got "${slideRange(nums)}")`)
+
+console.log('folding')
+{
+ const report: FidelityReport = {
+ counts: { carried: 1, approximated: 3, dropped: 2 }, provenance: {},
+ entries: [
+ { code: 'a', verdict: 'approximated', where: 'slide 2', detail: 'A', count: 1 },
+ { code: 'a', verdict: 'approximated', where: 'slide 3', detail: 'A', count: 2 },
+ { code: 'd', verdict: 'dropped', where: 'document', detail: 'D', count: 1 },
+ { code: 'd', verdict: 'dropped', where: 'slide 9', detail: 'D', count: 1 },
+ { code: 'c', verdict: 'carried', where: 'slide 1', detail: 'C', count: 1 },
+ ],
+ }
+ const f = foldReport(report)
+ ok(f.length === 2 && f[0].code === 'd' && f[1].code === 'a', 'one line per code, dropped first, carried left out')
+ ok(f[1].count === 3 && f[1].where === 'slides 2, 3', `counts add up and the slides are kept (${f[1].count}, "${f[1].where}")`)
+ ok(f[0].where === 'slide 9; the whole deck', `deck-level and slide-level places both show ("${f[0].where}")`)
+}
+
+console.log('typefaces')
+for (const [stack, want] of [
+ ["'Instrument Sans', 'Helvetica Neue', sans-serif", 'Instrument Sans'],
+ ["ui-monospace, 'SF Mono', Menlo, Consolas, 'Liberation Mono', 'Courier New', monospace", 'Consolas'],
+ ["ui-monospace, 'SF Mono', Menlo, monospace", 'Courier New'],
+ ['system-ui, -apple-system, sans-serif', 'Arial'],
+ ['Georgia, serif', 'Georgia'],
+ ['serif', 'Times New Roman'],
+ ['Menlo', 'Menlo'],
+ ['', 'Arial'],
+] as Array<[string, string]>) ok(typefaceOf(stack) === want, `${JSON.stringify(stack)} → ${want} (got ${typefaceOf(stack)})`)
+
+console.log('the report, through a real export of document JSON')
+const docWith = (elements: unknown[], extra: object = {}) => JSON.stringify({
+ format: 'bento/slides', version: 1, title: 'Rig', size: { width: 1280, height: 720 },
+ theme: { background: '#ffffff', color: '#1e2a3a', accent: '#ff7a59', fontFamily: 'Inter, sans-serif' },
+ slides: [
+ { id: 's1', background: '#ffffff', elements: [] },
+ { id: 's2', background: '#ffffff', elements },
+ ],
+ ...extra,
+})
+const text = (id: string, html: string) => ({
+ type: 'text', id, x: 80, y: 80, w: 600, h: 100, rotation: 0, opacity: 1, html,
+ fontSize: 24, fontFamily: 'Inter, sans-serif', fontWeight: 400, color: '#1e2a3a', align: 'left', valign: 'top', lineHeight: 1.2,
+})
+{
+ let r: Awaited<ReturnType<typeof bentoToPptx>> | null = null
+ let why = ''
+ try { r = await bentoToPptx(docWith([text('t1', 'Roots: $$ax^2 + bx + c = 0$$')])) } catch (e) { why = (e as Error).message }
+ ok(!!r && r.bytes.length > 1000, `document JSON exports, no .bento.html around it${why ? ` (refused: ${why})` : ''}`)
+ const m = r ? foldReport(r.report).find((e) => e.code === 'maths-as-source') : undefined
+ ok(!!m && m.where === 'slide 2', `a formula is reported, on its slide (${m ? m.where : 'NOT REPORTED'})`)
+ // The counter IS slides' scanner, so it agrees with the app by construction:
+ // prices are prose, an escaped \$ is literal, and (since slides fixed the
+ // pairing) a price beside an escaped dollar is prose too.
+ for (const p of ['It costs $5 and $10', 'and \\$x\\$ is literal', 'It costs $5 and $10, and \\$x\\$ is literal']) {
+ const prose = await bentoToPptx(docWith([text('t1', p)]))
+ ok(!prose.report.entries.some((e) => e.code === 'maths-as-source'), `prose is not reported as a formula: ${JSON.stringify(p)}`)
+ }
+}
+{
+ const r = await bentoToPptx(docWith([], { fonts: [{ family: 'Fraunces', asset: 'f1' }, { family: 'Fraunces', asset: 'f2' }] }))
+ const e = r.report.entries.find((x) => x.code === 'fonts-not-embedded')
+ ok(!!e && /Fraunces/.test(e.detail) && (e.detail.match(/Fraunces/g) ?? []).length === 1,
+ `the deck's own fonts are named once each (${e?.detail ?? 'NOT REPORTED'})`)
+ const none = await bentoToPptx(docWith([]))
+ ok(!none.report.entries.some((x) => x.code === 'fonts-not-embedded'), 'no own fonts, no entry')
+}
+{
+ let msg = ''
+ try { await bentoToPptx('{"format": "bento/slides", ') } catch (e) { msg = (e as Error).message }
+ ok(/does not parse/.test(msg), `broken JSON is refused in plain words (${msg})`)
+}
+
+console.log(`\n${checks - failures}/${checks} checks passed`)
+if (failures) process.exit(1)
diff --git a/scripts/test-convert/pptx-shapes.ts b/scripts/test-convert/pptx-shapes.ts
new file mode 100644
index 00000000..2cb42412
--- /dev/null
+++ b/scripts/test-convert/pptx-shapes.ts
@@ -0,0 +1,350 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write shape-mapper rig: bento shape → p:sp / p:cxnSp.
+//
+// node scripts/test-convert/pptx-shapes.ts (Node ≥ 23.6 strips types natively)
+//
+// Every emitted node is re-read through the convert engine's own PARSER
+// (convert/src/xml.ts) and checked against HAND-COMPUTED EMU/angle/
+// percentage values — the arithmetic is done twice, once in the module and
+// once on paper here, so a unit slip (px vs pt, degree vs 60000ths) fails a
+// number, not a vibe. NEGATIVE controls exercise the honesty paths: an
+// unsupported arc command must produce a report entry and a parseable path,
+// never garbage coordinates; a 'bar' tip must confess it has no OOXML twin.
+
+import { parseXml, kids, kid, attr, NS, type XElem } from '../../convert/src/xml.ts'
+import { serialize, x } from '../../convert/src/xmlout.ts'
+import { PML_XMLNS } from '../../convert/src/pptx-write/parts.ts'
+import { Report } from '../../convert/src/report.ts'
+import {
+ emu, xfrmNode, parseColor, solidFill, cssAngleToOoxml, shapeNode, type ShapeIn,
+} from '../../convert/src/pptx-write/shapes.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+// A defaulted bento shape; tests override what they exercise.
+function shape(over: Partial<ShapeIn>): ShapeIn {
+ return {
+ id: 'el1', x: 100, y: 50, w: 200, h: 100, rotation: 0, opacity: 1,
+ shape: 'rect', fill: '#336699', stroke: 'transparent', strokeWidth: 0, radius: 0,
+ ...over,
+ }
+}
+
+// Emit one shape and re-read it through the parser. Standalone sp/cxnSp nodes
+// carry no xmlns of their own (the slide root declares the trio), so the rig
+// wraps them the way slidePart would.
+function emit(el: ShapeIn, report = new Report()): XElem {
+ const node = shapeNode(el, 2, report, 'slide 1')
+ const doc = parseXml(serialize(x('root', PML_XMLNS, [node])))
+ const sp = doc.children.find((c) => typeof c !== 'string') as XElem
+ return sp
+}
+
+const spPr = (sp: XElem) => kid(sp, NS.p, 'spPr')!
+const codes = (r: Report) => r.build().entries.map((e) => e.code)
+
+// --- shared helpers ----------------------------------------------------------
+console.log('frame/xfrm helper')
+
+ok(emu(100) === 952500, 'emu: 100px = 952500 EMU (100 * 9525)')
+ok(emu(1.5) === 14288, 'emu rounds to an integer (1.5px = 14287.5 → 14288)')
+
+{
+ const n = parseXml(serialize(x('r', { 'xmlns:a': NS.a }, [xfrmNode({ x: 100, y: 50, w: 200, h: 100, rotation: 45 })])))
+ const xf = kid(n, NS.a, 'xfrm')!
+ const off = kid(xf, NS.a, 'off')!
+ const ext = kid(xf, NS.a, 'ext')!
+ ok(attr(off, 'x') === '952500' && attr(off, 'y') === '476250', 'xfrm off: (100,50)px = (952500,476250) EMU')
+ ok(attr(ext, 'cx') === '1905000' && attr(ext, 'cy') === '952500', 'xfrm ext: 200×100px = 1905000×952500 EMU')
+ ok(attr(xf, 'rot') === '2700000', 'xfrm rot: 45° = 2700000 (60000ths of a degree)')
+}
+{
+ const n = parseXml(serialize(x('r', { 'xmlns:a': NS.a }, [xfrmNode({ x: 0, y: 0, w: 10, h: 10 })])))
+ ok(attr(kid(n, NS.a, 'xfrm')!, 'rot') === undefined, 'rot omitted at 0 (matches native PowerPoint output)')
+}
+
+// --- colours -----------------------------------------------------------------
+console.log('colours')
+
+ok(JSON.stringify(parseColor('#336699')) === '{"hex":"336699","alpha":1}', '#rrggbb parses opaque')
+ok(JSON.stringify(parseColor('#36c')) === '{"hex":"3366CC","alpha":1}', '#rgb shorthand doubles')
+{
+ const c = parseColor('rgba(255, 0, 0, 0.5)')!
+ ok(c.hex === 'FF0000' && c.alpha === 0.5, 'rgba() splits into hex + alpha')
+}
+ok(parseColor('transparent')!.alpha === 0, 'transparent = alpha 0')
+ok(parseColor('chartreuse') === null, 'NEGATIVE: css keyword is refused (null), not silently guessed')
+
+{
+ const n = parseXml(serialize(x('r', { 'xmlns:a': NS.a }, [solidFill('rgba(255,0,0,0.5)')])))
+ const clr = kid(kid(n, NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(clr, 'val') === 'FF0000', 'solidFill: rgba colour lands in srgbClr@val')
+ ok(attr(kid(clr, NS.a, 'alpha')!, 'val') === '50000', 'solidFill: alpha 0.5 = 50000 (1000ths of a percent)')
+}
+{
+ const n = parseXml(serialize(x('r', { 'xmlns:a': NS.a }, [solidFill('#ff0000', 0.5)])))
+ const clr = kid(kid(n, NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(kid(clr, NS.a, 'alpha')!, 'val') === '50000', 'element opacity multiplies into fill alpha (#88 combineTransparency)')
+}
+
+// --- rect / roundRect --------------------------------------------------------
+console.log('rect and roundRect')
+
+{
+ const r = new Report()
+ const sp = emit(shape({}), r)
+ ok(sp.local === 'sp' && sp.ns === NS.p, 'rect emits p:sp')
+ const geom = kid(spPr(sp), NS.a, 'prstGeom')!
+ ok(attr(geom, 'prst') === 'rect', 'radius 0 → prst=rect')
+ ok(kid(geom, NS.a, 'avLst') !== undefined, 'prstGeom carries its (empty) avLst')
+ const nv = kid(sp, NS.p, 'nvSpPr')!
+ ok(attr(kid(nv, NS.p, 'cNvPr')!, 'name') === 'bento:el1', 'cNvPr name carries bento:<morph key> (#88 objectName)')
+ ok(attr(kid(nv, NS.p, 'cNvPr')!, 'id') === '2', 'cNvPr id is the caller-assigned shape id')
+ const fill = kid(kid(spPr(sp), NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(fill, 'val') === '336699', 'fill colour carried')
+ const ln = kid(spPr(sp), NS.a, 'ln')!
+ ok(kid(ln, NS.a, 'noFill') !== undefined, 'strokeWidth 0 → explicit a:ln/a:noFill (never theme-default outline)')
+ ok(kid(sp, NS.p, 'txBody') !== undefined, 'p:sp carries an empty txBody (typeable in PowerPoint)')
+ ok(r.build().entries.length === 0, 'plain rect reports nothing')
+}
+{
+ // radius 12 on a 200×100 box: 12/min(200,100) = 0.12 → 12000
+ const sp = emit(shape({ radius: 12 }))
+ const geom = kid(spPr(sp), NS.a, 'prstGeom')!
+ ok(attr(geom, 'prst') === 'roundRect', 'radius > 0 → roundRect')
+ const gd = kid(kid(geom, NS.a, 'avLst')!, NS.a, 'gd')!
+ ok(attr(gd, 'fmla') === 'val 12000', 'roundRect adj: 12px / min(200,100) = 0.12 → 12000 (fraction in 100000ths)')
+}
+{
+ // radius 80 on 100×60: 80/60 = 1.33 → clamped to 0.5 (#88's clamp)
+ const sp = emit(shape({ w: 100, h: 60, radius: 80 }))
+ const gd = kid(kid(kid(spPr(sp), NS.a, 'prstGeom')!, NS.a, 'avLst')!, NS.a, 'gd')!
+ ok(attr(gd, 'fmla') === 'val 50000', 'roundRect adj clamps at 0.5 (PowerPoint\'s own maximum)')
+}
+
+// --- other presets -----------------------------------------------------------
+console.log('ellipse / triangle / arrow')
+
+for (const [kind, prst] of [['ellipse', 'ellipse'], ['triangle', 'triangle'], ['arrow', 'rightArrow']] as const) {
+ const sp = emit(shape({ shape: kind }))
+ ok(attr(kid(spPr(sp), NS.a, 'prstGeom')!, 'prst') === prst, `${kind} → prst=${prst}`)
+}
+
+// --- lines -------------------------------------------------------------------
+console.log('lines')
+
+{
+ const el = shape({ shape: 'line', fill: '#ff0000', stroke: '#00ff00', strokeWidth: 4, y: 50, h: 20 })
+ const sp = emit(el)
+ ok(sp.local === 'cxnSp' && sp.ns === NS.p, 'line emits p:cxnSp')
+ ok(attr(kid(spPr(sp), NS.a, 'prstGeom')!, 'prst') === 'line', 'line geometry is prst=line (the census\'s 141)')
+ const ln = kid(spPr(sp), NS.a, 'ln')!
+ const clr = kid(kid(ln, NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(clr, 'val') === 'FF0000', 'GOTCHA: line colour comes from FILL (#ff0000), never stroke (#00ff00)')
+ ok(attr(ln, 'w') === String(emu(4)), 'line width: strokeWidth px → EMU on a:ln@w')
+ const xf = kid(spPr(sp), NS.a, 'xfrm')!
+ ok(attr(kid(xf, NS.a, 'off')!, 'y') === String(emu(60)), 'line box collapses to the centerline: y 50 + h/2 = 60px')
+ ok(attr(kid(xf, NS.a, 'ext')!, 'cy') === '0', 'line box collapses to zero height (bento draws at h/2, OOXML corner-to-corner)')
+ ok(kid(sp, NS.p, 'nvCxnSpPr') !== undefined, 'cxnSp carries nvCxnSpPr, not nvSpPr')
+}
+{
+ const ln0 = kid(spPr(emit(shape({ shape: 'line', strokeWidth: 0 }))), NS.a, 'ln')!
+ ok(attr(ln0, 'w') === String(emu(2)), 'a 0-width bento line stays visible: renderer\'s max(sw,2)px floor kept')
+}
+
+// --- dash + tips -------------------------------------------------------------
+console.log('stroke style and tips')
+
+{
+ const ln = kid(spPr(emit(shape({ shape: 'line', strokeStyle: 'dotted', strokeWidth: 2 }))), NS.a, 'ln')!
+ ok(attr(kid(ln, NS.a, 'prstDash')!, 'val') === 'sysDot', 'dotted → prstDash sysDot')
+ ok(attr(ln, 'cap') === 'rnd', 'dotted gets round caps (or sysDot renders square specks)')
+}
+{
+ const ln = kid(spPr(emit(shape({ strokeStyle: 'dashed', stroke: '#000000', strokeWidth: 2 }))), NS.a, 'ln')!
+ ok(attr(kid(ln, NS.a, 'prstDash')!, 'val') === 'dash', 'dashed → prstDash dash')
+}
+{
+ const ln = kid(spPr(emit(shape({ strokeDash: 6, stroke: '#000000', strokeWidth: 2 }))), NS.a, 'ln')!
+ ok(attr(kid(ln, NS.a, 'prstDash')!, 'val') === 'dash', 'legacy strokeDash px-count still maps to dash')
+}
+{
+ const r = new Report()
+ const ln = kid(spPr(emit(shape({ shape: 'line', strokeWidth: 2, lineStart: 'arrow', lineEnd: 'dot' }), r)), NS.a, 'ln')!
+ ok(attr(kid(ln, NS.a, 'headEnd')!, 'type') === 'triangle', 'lineStart arrow → headEnd triangle')
+ ok(attr(kid(ln, NS.a, 'tailEnd')!, 'type') === 'oval', 'lineEnd dot → tailEnd oval')
+ ok(r.build().entries.length === 0, 'faithful tips report nothing')
+}
+{
+ const r = new Report()
+ const ln = kid(spPr(emit(shape({ shape: 'line', strokeWidth: 2, lineEnd: 'bar' }), r)), NS.a, 'ln')!
+ ok(attr(kid(ln, NS.a, 'tailEnd')!, 'type') === 'diamond', 'bar tip exports as diamond (#88\'s least-dishonest pick)')
+ ok(codes(r).includes('line-tip-approximated'), 'NEGATIVE: bar has no OOXML twin — the report says so')
+}
+
+// --- gradients ---------------------------------------------------------------
+console.log('gradients')
+
+// The angle inversion, hand-computed against both conventions. CSS 90° is
+// left→right; OOXML left→right is 0. CSS 180° is top→bottom; OOXML top→bottom
+// is 90° = 5400000 (the same value parts.ts's theme uses for its vertical
+// gradient). The importer converts ooxml→css by the +90 shift; this is its
+// exact inverse, so 90 must round-trip to 0.
+ok(cssAngleToOoxml(90) === 0, 'css 90° (left→right) → ooxml 0')
+ok(cssAngleToOoxml(180) === 5400000, 'css 180° (top→bottom) → ooxml 5400000')
+ok(cssAngleToOoxml(0) === 16200000, 'css 0° (bottom→top) → ooxml 16200000')
+ok(cssAngleToOoxml(45) === 18900000, 'css 45° → ooxml 315° = 18900000 (wraps, stays positive)')
+
+{
+ const r = new Report()
+ const sp = emit(shape({
+ fillGradient: { angle: 90, stops: [{ at: 0, color: '#ff0000' }, { at: 0.25, color: 'rgba(0,0,255,0.5)' }, { at: 1, color: '#00ff00' }] },
+ }), r)
+ const grad = kid(spPr(sp), NS.a, 'gradFill')!
+ const gs = kids(kid(grad, NS.a, 'gsLst')!, NS.a, 'gs')
+ ok(gs.length === 3, 'every stop becomes an a:gs')
+ ok(attr(gs[1], 'pos') === '25000', 'stop at 0.25 → pos 25000 (1000ths of a percent)')
+ const mid = kid(gs[1], NS.a, 'srgbClr')!
+ ok(attr(mid, 'val') === '0000FF' && attr(kid(mid, NS.a, 'alpha')!, 'val') === '50000', 'rgba stop keeps its own alpha')
+ const lin = kid(grad, NS.a, 'lin')!
+ ok(attr(lin, 'ang') === '0', 'gradient angle inverted from CSS convention')
+ ok(attr(lin, 'scaled') === '0', 'scaled=0: a CSS angle is a TRUE angle, never aspect-skewed')
+ ok(kid(spPr(sp), NS.a, 'solidFill') === undefined, 'gradient wins over the solid fallback fill')
+ ok(r.build().entries.length === 0, 'clean gradient reports nothing')
+}
+
+{
+ // CT_GradientStopList requires gs minOccurs=2: a ONE-stop gradient must not
+ // emit a schema-invalid gsLst. SVG paints one stop as solid, so the honest
+ // (and valid) export is that stop's solidFill.
+ const sp = emit(shape({ fill: '#00ff00', fillGradient: { angle: 90, stops: [{ at: 0, color: '#ff0000' }] } }))
+ ok(kid(spPr(sp), NS.a, 'gradFill') === undefined, 'NEGATIVE: one-stop gradient emits NO a:gradFill (gsLst needs 2+ gs)')
+ const oneClr = kid(kid(spPr(sp), NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(oneClr, 'val') === 'FF0000', 'one-stop gradient exports as that stop’s solid colour (what SVG painted)')
+}
+
+// --- alpha and noFill --------------------------------------------------------
+console.log('opacity and transparency')
+
+{
+ const sp = emit(shape({ fill: 'rgba(255,0,0,0.5)', opacity: 0.5 }))
+ const clr = kid(kid(spPr(sp), NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(kid(clr, NS.a, 'alpha')!, 'val') === '25000', 'fill alpha × element opacity: 0.5 × 0.5 → 25000')
+}
+{
+ const sp = emit(shape({ fill: 'transparent' }))
+ ok(kid(spPr(sp), NS.a, 'noFill') !== undefined, 'transparent fill → explicit a:noFill')
+}
+{
+ const r = new Report()
+ const sp = emit(shape({ fill: 'papayawhip' }), r)
+ const clr = kid(kid(spPr(sp), NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(clr, 'val') === '000000', 'unparseable colour falls back to black…')
+ ok(codes(r).includes('color-unparsed'), 'NEGATIVE: …and the fallback is reported, not silent (#88 was silent here)')
+}
+
+// --- shadows -----------------------------------------------------------------
+console.log('shadows')
+
+{
+ const r = new Report()
+ const sp = emit(shape({ shadow: { x: 3, y: 4, blur: 8, color: 'rgba(0,0,0,0.4)' } }), r)
+ const shdw = kid(kid(spPr(sp), NS.a, 'effectLst')!, NS.a, 'outerShdw')!
+ ok(attr(shdw, 'dist') === '47625', 'offset (3,4)px → dist = hypot·9525 = 47625 EMU')
+ // atan2(4,3) = 53.13010235…° clockwise (y-down is already clockwise) × 60000
+ ok(attr(shdw, 'dir') === '3187806', 'dir = atan2(4,3) = 53.1301° → 3187806 (60000ths)')
+ ok(attr(shdw, 'blurRad') === '76200', 'blur 8px → blurRad 76200 EMU')
+ ok(attr(shdw, 'rotWithShape') === '0', 'rotWithShape=0: CSS drop-shadow is screen-space, never rotates with the shape')
+ const clr = kid(shdw, NS.a, 'srgbClr')!
+ ok(attr(kid(clr, NS.a, 'alpha')!, 'val') === '40000', 'shadow colour alpha carried')
+ ok(r.build().entries.length === 0, 'single shadow reports nothing')
+}
+{
+ // 300px blur = 225pt, beyond PowerPoint's editable 100pt — clamped (#88)
+ const sp = emit(shape({ shadow: { blur: 300, color: '#000000' } }))
+ const shdw = kid(kid(spPr(sp), NS.a, 'effectLst')!, NS.a, 'outerShdw')!
+ ok(attr(shdw, 'blurRad') === '1270000', 'blur clamps at 100pt so the shadow stays editable in PowerPoint')
+}
+{
+ const r = new Report()
+ const sp = emit(shape({ shadow: [{ blur: 8, color: '#000000' }, { blur: 20, color: '#ffffff' }] }), r)
+ const shdws = kids(kid(spPr(sp), NS.a, 'effectLst')!, NS.a, 'outerShdw')
+ ok(shdws.length === 1, 'stacked shadows export the first only…')
+ ok(codes(r).includes('multiple-shadows-simplified'), 'NEGATIVE: …and say so (#88\'s code, kept)')
+}
+
+// --- custGeom ----------------------------------------------------------------
+console.log('custGeom (path shapes)')
+
+{
+ const r = new Report()
+ const el = shape({ shape: 'path', d: 'M0 0 L10 0 L10 5 Z', pathBox: [0, 0, 10, 5], w: 200, h: 100 })
+ const sp = emit(el, r)
+ const geom = kid(spPr(sp), NS.a, 'custGeom')!
+ const path = kid(kid(geom, NS.a, 'pathLst')!, NS.a, 'path')!
+ ok(attr(path, 'w') === '95250' && attr(path, 'h') === '47625', 'path space is pathBox scaled to EMU: 10×5px → 95250×47625')
+ const segNames = path.children.filter((c) => typeof c !== 'string').map((c) => (c as XElem).local)
+ ok(segNames.join(',') === 'moveTo,lnTo,lnTo,close', 'M/L/L/Z → moveTo, lnTo, lnTo, close')
+ const ln2 = kids(path, NS.a, 'lnTo')[1]
+ const p2 = kid(ln2, NS.a, 'pt')!
+ ok(attr(p2, 'x') === '95250' && attr(p2, 'y') === '47625', 'point (10,5)px lands at (95250,47625) — integers, EMU-scaled')
+ ok(r.build().entries.length === 0, 'supported subset reports nothing')
+}
+{
+ // cubic + relative commands + pathBox with a non-zero origin
+ const el = shape({ shape: 'path', d: 'M2 1 c 4 0 4 3 8 3', pathBox: [2, 1, 8, 3] })
+ const path = kid(kid(kid(spPr(emit(el)), NS.a, 'custGeom')!, NS.a, 'pathLst')!, NS.a, 'path')!
+ const cub = kid(path, NS.a, 'cubicBezTo')!
+ const pts = kids(cub, NS.a, 'pt')
+ ok(pts.length === 3, 'C emits cubicBezTo with three points')
+ // relative c from (2,1): ctrl1 (6,1) → box-local (4,0) → (38100, 0)
+ ok(attr(pts[0], 'x') === '38100' && attr(pts[0], 'y') === '0', 'relative coords resolve against the current point, offset by pathBox origin')
+ ok(attr(pts[2], 'x') === String(emu(8)) && attr(pts[2], 'y') === String(emu(3)), 'cubic endpoint lands where the model authored it')
+}
+{
+ const r = new Report()
+ const el = shape({ shape: 'path', d: 'M0 0 A5 5 0 0 1 10 0 L10 5', pathBox: [0, 0, 10, 5] })
+ const sp = emit(el, r)
+ const path = kid(kid(kid(spPr(sp), NS.a, 'custGeom')!, NS.a, 'pathLst')!, NS.a, 'path')!
+ ok(codes(r).includes('path-approximated'), 'NEGATIVE: an arc command reports path-approximated')
+ const firstLn = kids(path, NS.a, 'lnTo')[0]
+ const pt = kid(firstLn, NS.a, 'pt')!
+ ok(attr(pt, 'x') === '95250' && attr(pt, 'y') === '0', 'NEGATIVE: the arc degrades to a line to its ENDPOINT — parseable geometry, not garbage')
+ const nums = path.children.filter((c) => typeof c !== 'string')
+ .flatMap((c) => kids(c as XElem, NS.a, 'pt'))
+ .flatMap((p) => [attr(p, 'x'), attr(p, 'y')])
+ ok(nums.every((n) => n !== undefined && /^-?\d+$/.test(n)), 'NEGATIVE: every emitted coordinate is a plain integer (no NaN leaked)')
+}
+{
+ const r = new Report()
+ emit(shape({ shape: 'path', d: 'M0 0 W nonsense', pathBox: [0, 0, 10, 5] }), r)
+ ok(codes(r).includes('path-approximated'), 'NEGATIVE: an unknown command letter reports rather than guessing arg counts')
+}
+
+// --- effects with no OOXML expression ---------------------------------------
+console.log('dropped effects')
+
+{
+ const r = new Report()
+ emit(shape({ blur: 4, blend: 'screen', backdropFilter: 10 }), r)
+ const c = codes(r)
+ ok(c.includes('shape-blur-dropped') && c.includes('blend-mode-dropped') && c.includes('backdrop-filter-dropped'),
+ 'blur / blend / backdropFilter each report as dropped')
+}
+{
+ const r = new Report()
+ emit(shape({ shape: 'line', strokeWidth: 2, from: { el: 'other', side: 'auto' } }), r)
+ ok(codes(r).includes('connector-detached'), 'an anchored connector reports that it stops following its elements')
+}
+
+// -----------------------------------------------------------------------------
+console.log(`\n${checks} checks, ${failures} failures`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-convert/pptx-tables.ts b/scripts/test-convert/pptx-tables.ts
new file mode 100644
index 00000000..cfefb8a3
--- /dev/null
+++ b/scripts/test-convert/pptx-tables.ts
@@ -0,0 +1,229 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write table-mapper rig: tables.ts.
+//
+// node scripts/test-convert/pptx-tables.ts (Node ≥ 23.6 strips types natively)
+//
+// Emitted graphicFrames are re-read with the convert engine's own parser
+// (convert/src/xml.ts) — same posture as pptx-parts: not proof
+// PowerPoint accepts the file, but every claim checked (grid sums, schema
+// child order in tcPr, escaping, cell counts) is one PowerPoint validates.
+// The NEGATIVE controls are computations verified to fail: naive per-column
+// rounding really does lose an EMU, and PR #88's zebra parity really does
+// stripe the wrong rows on a header-less table.
+
+import { parseXml, kids, kid, attr, textOf, descendants, NS, type XElem } from '../../convert/src/xml.ts'
+import { serialize, x } from '../../convert/src/xmlout.ts'
+import { Report } from '../../convert/src/report.ts'
+import { EMU_PER_PX, type OutTable } from '../../convert/src/types.ts'
+import {
+ tableFrame, splitEmu, htmlParagraphs, cssSolid, TABLE_GRAPHIC_URI,
+} from '../../convert/src/pptx-write/tables.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+function throws(fn: () => unknown, msg: string) {
+ let threw = false
+ try { fn() } catch { threw = true }
+ ok(threw, msg)
+}
+
+/** Wrap a frame in a root that declares the conventional prefixes — a slide
+ * root does this in the real package; the rig parses frames standalone. */
+const parseFrame = (frame: ReturnType<typeof x>): XElem =>
+ kids(parseXml(serialize(x('root', { 'xmlns:a': NS.a, 'xmlns:p': NS.p, 'xmlns:r': NS.r }, [frame]))))[0]
+
+const baseTable = (over: Partial<OutTable> = {}): OutTable => ({
+ id: 't1', type: 'table',
+ x: 100, y: 80, w: 600, h: 300, rotation: 0, opacity: 1,
+ columns: [{ w: 2 }, { w: 1 }, { w: 1 }],
+ header: true,
+ rows: [
+ { cells: [{ html: 'Region' }, { html: 'Q3' }, { html: 'Q4' }] },
+ { cells: [{ html: 'EMEA &amp; APAC' }, { html: '1,204', align: 'center' }, { html: '9<br>ish' }] },
+ { cells: [{ html: 'AMER' }, { html: '388' }] }, // ragged on purpose
+ ],
+ style: {
+ headerBg: '#1E2A3A', headerColor: '#FFFFFF', zebra: 'rgba(30,42,58,0.05)',
+ borderColor: '#C9CFD6', borderWidth: 2, cellPadX: 16, cellPadY: 11,
+ fontSize: 18, color: '#1E2A3A', radius: 0, fontFamily: '"Inter", sans-serif',
+ },
+ ...over,
+})
+
+// --- splitEmu ----------------------------------------------------------------
+console.log('splitEmu (drift-free grid arithmetic)')
+
+{
+ const parts = splitEmu([1, 1, 1], 100)
+ ok(parts.reduce((a, b) => a + b, 0) === 100, 'three equal thirds of 100 sum to exactly 100')
+ ok(parts.join(',') === '33,34,33', 'the extra unit lands mid-sequence (cumulative-edge rounding)')
+ // NEGATIVE control, seen to fail: the naive per-part computation loses a unit.
+ const naive = [1, 1, 1].map(() => Math.round(100 / 3))
+ ok(naive.reduce((a, b) => a + b, 0) !== 100, 'NEGATIVE: naive per-column rounding does NOT sum to the total')
+
+ const awkward = splitEmu([0.37, 1.21, 0.055, 2.9], 5715001)
+ ok(awkward.reduce((a, b) => a + b, 0) === 5715001, 'awkward fractional weights still sum exactly (odd EMU total)')
+ ok(splitEmu([0, 1], 1000).join(',') === '0,1000', 'zero-weight column keeps a zero-width gridCol (cell counts must match)')
+ ok(splitEmu([-2, 1], 1000)[0] === 0, 'negative weight clamps to a zero-width column instead of corrupting the sum')
+}
+
+// --- htmlParagraphs / cssSolid ------------------------------------------------
+console.log('cell text + colour helpers')
+
+{
+ ok(htmlParagraphs('<b>Bold</b> &amp; <i>quiet</i>').join('|') === 'Bold & quiet', 'tags strip, entities decode')
+ ok(htmlParagraphs('line1<br>line2').join('|') === 'line1|line2', '<br> splits paragraphs')
+ ok(htmlParagraphs('tail<br><br>').join('|') === 'tail', 'trailing empties drop')
+ ok(htmlParagraphs('a<br><br>b').length === 3, 'interior blank paragraph survives (deliberate empty line)')
+ ok(htmlParagraphs('&#x2192; &#65;').join('') === '→ A', 'numeric character references decode (hex + decimal)')
+ ok(htmlParagraphs('&bogus;').join('') === '&bogus;', 'unknown named entity passes through literally')
+
+ ok(cssSolid('rgba(30,42,58,0.05)', '000000').hex === '1E2A3A', 'rgba() → hex')
+ ok(Math.abs(cssSolid('rgba(30,42,58,0.05)', '000000').alpha - 0.05) < 1e-9, 'rgba() alpha separates from the colour')
+ ok(cssSolid('#abc', '000000').hex === 'AABBCC', 'short hex expands')
+ ok(cssSolid('transparent', 'FFFFFF').alpha === 0, 'transparent = alpha 0 (emit no fill)')
+ ok(cssSolid('conic-gradient(red, blue)', 'ABCDEF').hex === 'ABCDEF', 'unparseable colour falls back instead of corrupting')
+}
+
+// --- the full frame ----------------------------------------------------------
+console.log('tableFrame')
+
+{
+ const report = new Report()
+ const el = baseTable()
+ const frame = parseFrame(tableFrame(el, 7, report, 'slide 2'))
+
+ ok(frame.ns === NS.p && frame.local === 'graphicFrame', 'root is p:graphicFrame')
+ ok(attr(kid(kid(frame, NS.p, 'nvGraphicFramePr')!, NS.p, 'cNvPr')!, 'id') === '7', 'cNvPr carries the caller shape id')
+ ok(attr(kid(kid(frame, NS.p, 'nvGraphicFramePr')!, NS.p, 'cNvPr')!, 'name') === 'bento:t1', 'name carries the bento identity (#88 objectName convention)')
+ const xfrm = kid(frame, NS.p, 'xfrm')!
+ ok(attr(kid(xfrm, NS.a, 'off')!, 'x') === String(100 * EMU_PER_PX), 'p:xfrm offset in EMU')
+ const gd = kid(kid(frame, NS.a, 'graphic')!, NS.a, 'graphicData')!
+ ok(attr(gd, 'uri') === TABLE_GRAPHIC_URI, 'graphicData carries the table uri')
+
+ const tbl = kid(gd, NS.a, 'tbl')!
+ const tblPr = kid(tbl, NS.a, 'tblPr')!
+ ok(attr(tblPr, 'firstRow') === '1' && attr(tblPr, 'bandRow') === '1', 'header → firstRow, zebra → bandRow')
+
+ // Grid: EMU integers summing exactly to the frame width, 2:1:1.
+ const cx = Math.round(600 * EMU_PER_PX)
+ const cols = kids(kid(tbl, NS.a, 'tblGrid')!, NS.a, 'gridCol').map((c) => Number(attr(c, 'w')))
+ ok(cols.length === 3, 'one gridCol per column')
+ ok(cols.reduce((a, b) => a + b, 0) === cx, `gridCol widths sum exactly to the frame width (${cx} EMU)`)
+ ok(cols[0] === cols[1] + cols[2], 'weights honoured (2 = 1 + 1)')
+ ok(cols.every((w) => Number.isInteger(w)), 'widths are integers (EMU never fractional)')
+
+ // Rows: heights sum to the frame height; ragged row padded to grid width.
+ const trs = kids(tbl, NS.a, 'tr')
+ ok(trs.length === 3, 'one a:tr per model row')
+ ok(trs.map((t) => Number(attr(t, 'h'))).reduce((a, b) => a + b, 0) === Math.round(300 * EMU_PER_PX),
+ 'row heights sum exactly to the frame height')
+ ok(trs.every((t) => kids(t, NS.a, 'tc').length === 3, ), 'every row carries exactly gridCol-many cells (ragged row padded)')
+
+ const cellAt = (r: number, c: number) => kids(trs[r], NS.a, 'tc')[c]
+ const tcPrOf = (r: number, c: number) => kid(cellAt(r, c), NS.a, 'tcPr')!
+ const fillHex = (tcPr: XElem) => {
+ const f = kid(tcPr, NS.a, 'solidFill')
+ return f ? attr(kid(f, NS.a, 'srgbClr')!, 'val') : undefined
+ }
+
+ // Header row: bold, header colours.
+ const hdrRun = descendants(cellAt(0, 0), NS.a, 'rPr')[0]
+ ok(attr(hdrRun, 'b') === '1', 'header row runs are bold')
+ ok(attr(hdrRun, 'sz') === '1350', 'font size 18px → 13.5pt → sz=1350 centipoints')
+ ok(attr(kid(hdrRun, NS.a, 'latin')!, 'typeface') === 'Inter', 'first font family, quotes stripped, on the run')
+ ok(fillHex(tcPrOf(0, 0)) === '1E2A3A', 'header cell fill = headerBg')
+ ok(attr(kid(descendants(cellAt(0, 0), NS.a, 'solidFill')[0], NS.a, 'srgbClr')!, 'val') === 'FFFFFF',
+ 'header text colour = headerColor')
+
+ // tcPr: schema order (borders BEFORE fill), margins, anchor.
+ {
+ const tcPr = tcPrOf(0, 0)
+ const order = kids(tcPr).map((k) => k.local)
+ ok(order.join(',') === 'lnL,lnR,lnT,lnB,solidFill', 'tcPr children in schema order: borders then fill')
+ ok(attr(tcPr, 'marL') === String(16 * EMU_PER_PX) && attr(tcPr, 'marT') === String(11 * EMU_PER_PX),
+ 'cell padding → margins in EMU')
+ ok(attr(tcPr, 'anchor') === 'ctr', 'cells anchor centre (browser td default bento renders with)')
+ const ln = kid(tcPr, NS.a, 'lnL')!
+ ok(attr(ln, 'w') === String(2 * EMU_PER_PX), 'border width 2px → EMU on every side')
+ ok(attr(kid(kid(ln, NS.a, 'solidFill')!, NS.a, 'srgbClr')!, 'val') === 'C9CFD6', 'border colour carried')
+ }
+
+ // Zebra with a header: body rows count below the header, odd ones stripe.
+ ok(fillHex(tcPrOf(1, 0)) === undefined, 'first body row (bodyIndex 0) unstriped — transparent means NO fill node')
+ ok(fillHex(tcPrOf(2, 0)) === '1E2A3A', 'second body row (bodyIndex 1) striped with the zebra colour')
+ {
+ const stripe = kid(kid(tcPrOf(2, 0), NS.a, 'solidFill')!, NS.a, 'srgbClr')!
+ ok(attr(kid(stripe, NS.a, 'alpha')!, 'val') === '5000', 'zebra rgba alpha 0.05 → a:alpha val=5000')
+ }
+
+ // Cell content: entities, alignment, <br> paragraphs.
+ ok(textOf(descendants(cellAt(1, 0), NS.a, 't')[0]) === 'EMEA & APAC', '&amp; decodes then re-escapes cleanly through the emitter')
+ ok(attr(descendants(cellAt(1, 1), NS.a, 'pPr')[0], 'algn') === 'ctr', 'cell align=center → pPr algn=ctr')
+ ok(kids(kid(cellAt(1, 2), NS.a, 'txBody')!, NS.a, 'p').length === 2, '<br> in a cell = two a:p paragraphs')
+
+ ok(report.build().entries.length === 0, 'clean table adds no report entries')
+}
+
+{
+ // Zebra parity WITHOUT a header — the case that separates render.ts's rule
+ // (bodyIndex odd) from PR #88's (raw index even). render.ts is the
+ // on-screen truth; under #88's parity these two assertions fail.
+ const report = new Report()
+ const el = baseTable({
+ header: false,
+ rows: [0, 1, 2, 3].map((i) => ({ cells: [{ html: `r${i}` }, { html: '' }, { html: '' }] })),
+ })
+ const tbl = kid(kid(kid(parseFrame(tableFrame(el, 2, report, 'slide 1')), NS.a, 'graphic')!, NS.a, 'graphicData')!, NS.a, 'tbl')!
+ const rowFill = (r: number) => kid(kid(kids(kids(tbl, NS.a, 'tr')[r], NS.a, 'tc')[0], NS.a, 'tcPr')!, NS.a, 'solidFill')
+ ok(rowFill(0) === undefined && rowFill(2) === undefined, 'NEGATIVE (#88 parity): even rows of a header-less table are NOT striped')
+ ok(rowFill(1) !== undefined && rowFill(3) !== undefined, 'header-less table stripes odd rows, matching render.ts')
+ ok(attr(kid(tbl, NS.a, 'tblPr')!, 'firstRow') === undefined, 'no header → no firstRow flag')
+}
+
+{
+ // Opacity folds into every colour; rotation and radius report.
+ const report = new Report()
+ const el = baseTable({ opacity: 0.5, rotation: 15 })
+ ;(el.style as Record<string, unknown>).radius = 10
+ const frame = parseFrame(tableFrame(el, 2, report, 'slide 3'))
+ const firstFill = descendants(frame, NS.a, 'solidFill')[0]
+ ok(attr(kid(kid(firstFill, NS.a, 'srgbClr')!, NS.a, 'alpha')!, 'val') === '50000',
+ 'element opacity 0.5 → a:alpha val=50000 on fills (#88 combineTransparency semantics)')
+ const codes = report.build().entries.map((e) => `${e.verdict}:${e.code}`).sort()
+ ok(codes.join(' ') === 'dropped:table-radius-dropped dropped:table-rotation-dropped',
+ 'rotation and radius each report as dropped')
+}
+
+{
+ // Sparse style object: defaults fill in (mirroring slides DEFAULT_TABLE_STYLE).
+ const report = new Report()
+ const el = baseTable({ style: undefined })
+ const frame = parseFrame(tableFrame(el, 2, report, 'slide 1'))
+ ok(attr(descendants(frame, NS.a, 'rPr')[0], 'sz') === '1350', 'missing style → default 18px font (sz=1350)')
+ ok(descendants(frame, NS.a, 'lnL').length > 0, 'missing style → default 1px border still drawn')
+}
+
+// A C0 control character in AUTHOR text is scrubbed at ingestion (one bad
+// pasted byte costs a character, not the export) — while the emitter's own
+// throwing guard still backstops the part. If the scrub ever disappears,
+// serialize throws here and this block fails loudly instead of shipping a
+// part PowerPoint refuses.
+{
+ const el = baseTable()
+ el.rows[1].cells[0].html = 'bad\x07cell'
+ const xml = serialize(x('root', { 'xmlns:a': NS.a, 'xmlns:p': NS.p, 'xmlns:r': NS.r }, [tableFrame(el, 2, new Report(), 'slide 1')]))
+ ok(xml.includes('badcell') && !xml.includes('\x07'),
+ 'a C0 control character in cell text is scrubbed at ingestion (export survives, char is gone)')
+}
+
+console.log(`\n${checks} checks, ${failures} failures`)
+if (failures > 0) process.exit(1)
diff --git a/scripts/test-convert/pptx-text.ts b/scripts/test-convert/pptx-text.ts
new file mode 100644
index 00000000..38673a1f
--- /dev/null
+++ b/scripts/test-convert/pptx-text.ts
@@ -0,0 +1,260 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write text rig: the inline-html tokenizer + the p:sp emitter.
+//
+// node scripts/test-convert/pptx-text.ts (Node ≥ 23.6 strips types natively)
+//
+// Emitted shapes are re-read through the convert engine's own PARSER
+// (convert/src/xml.ts) — independent code with its own strict grammar,
+// so escaping claims are round-trip facts, not string.includes hopes. The
+// NEGATIVE controls each demonstrate a failure mode that was OBSERVED (the
+// phantom trailing line is reproduced live by disabling the trim).
+
+import { parseXml, descendants, kid, kids, attr, textOf, NS, type XElem } from '../../convert/src/xml.ts'
+import { serialize, x } from '../../convert/src/xmlout.ts'
+import { PML_XMLNS } from '../../convert/src/pptx-write/parts.ts'
+import {
+ parseInlineHtml, cssColor, textSp,
+ type FieldValues, type TextElIn, type TextSpOpts,
+} from '../../convert/src/pptx-write/text.ts'
+import { Report } from '../../convert/src/report.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+// A minimal, fully-typical bento text element; tests override what they probe.
+function el(over: Partial<TextElIn> = {}): TextElIn {
+ return {
+ id: 'e1', x: 100, y: 50, w: 400, h: 120, rotation: 0, opacity: 1,
+ html: 'Hello', fontSize: 24, fontFamily: 'Inter, sans-serif', fontWeight: 400,
+ color: '#1E2A3A', align: 'left', valign: 'top', lineHeight: 1.25,
+ ...over,
+ }
+}
+
+const fields: FieldValues = {
+ page: 6, pages: 12, title: 'Q3 & Q4 <Results>', date: new Date('2026-08-23T12:00:00'),
+ author: 'Ada', company: 'Bento', subject: '', event: '',
+}
+
+function emit(e: TextElIn, over: Partial<TextSpOpts> = {}): XElem {
+ const sp = textSp(e, { shapeId: 2, themeFontFamily: 'Arial', ...over })
+ if (!sp) throw new Error('textSp returned null for a non-placeholder element')
+ // wrap with the xmlns trio a real slide root declares, then re-parse
+ const root = parseXml(serialize(x('root', PML_XMLNS, [sp])))
+ const parsed = kid(root, NS.p, 'sp')
+ if (!parsed) throw new Error('no p:sp in parsed output')
+ return parsed
+}
+
+const runsOf = (sp: XElem) => descendants(sp, NS.a, 'r')
+const rPrOf = (r: XElem) => kid(r, NS.a, 'rPr')
+
+// --- tokenizer ---------------------------------------------------------------
+console.log('tokenizer')
+
+{
+ const runs = parseInlineHtml('<b>x<i>y</i></b>')
+ ok(runs.length === 2, 'nested <b>x<i>y</i></b> yields two runs')
+ ok(runs[0].text === 'x' && runs[0].style.bold === true && !runs[0].style.italic, 'outer run is bold only')
+ ok(runs[1].text === 'y' && runs[1].style.bold === true && runs[1].style.italic === true, 'inner run inherits bold and adds italic')
+}
+{
+ // Literal C0 controls (a bad paste, a corrupt import) are scrubbed at
+ // ingestion — the same fate the entity decoder gives &#7; — so one stray
+ // byte costs a character, never the whole export at serialize time.
+ const runs = parseInlineHtml('bad\x07paste')
+ ok(runs.length === 1 && runs[0].text === 'badpaste', 'literal C0 control in html is scrubbed, run survives')
+}
+{
+ const runs = parseInlineHtml('a<br>b')
+ ok(runs.length === 2 && runs[0].breakAfter && !runs[1].breakAfter, 'br becomes a break flag between runs')
+}
+{
+ const runs = parseInlineHtml('line1<div>line2</div><div>line3</div>')
+ ok(runs.length === 3 && runs[0].breakAfter && runs[1].breakAfter && !runs[2].breakAfter,
+ 'contentEditable shape line1<div>line2</div><div>line3</div> keeps three lines (break on div OPEN too)')
+}
+{
+ const runs = parseInlineHtml('<span>a</span><mark>b</mark>')
+ ok(runs.length === 1 && runs[0].text === 'ab' && !runs[0].style.bold, 'span and unknown tags are transparent (children pass through)')
+}
+{
+ const runs = parseInlineHtml('A &amp;&nbsp;B &lt;C&gt; &#66;')
+ ok(runs[0].text === 'A & B <C> B', 'entities decode: named, nbsp survives collapse, numeric')
+}
+{
+ const runs = parseInlineHtml('a \n\t b')
+ ok(runs.length === 1 && runs[0].text === 'a b', 'whitespace collapses to the painted form (white-space: normal)')
+}
+
+// --- trailing-break trim -----------------------------------------------------
+console.log('trailing-break trim')
+
+{
+ // NEGATIVE control, observed live: WITHOUT the trim, contentEditable's
+ // stray final <br> becomes a trailing a:br — a phantom empty line that
+ // shifts bottom-anchored text a full line up.
+ const untrimmed = parseInlineHtml('Hello<br>', false)
+ ok(untrimmed.length === 1 && untrimmed[0].breakAfter === true,
+ 'NEGATIVE: without the trim the stray final <br> survives as a phantom line break')
+ const trimmed = parseInlineHtml('Hello<br>')
+ ok(trimmed.length === 1 && trimmed[0].breakAfter === false, 'the trim clears exactly that trailing break')
+ const inner = parseInlineHtml('a<br>b')
+ ok(inner[0].breakAfter === true, 'an interior break is untouched by the trim')
+}
+{
+ const sp = emit(el({ html: 'Hello<br>' }))
+ ok(descendants(sp, NS.a, 'br').length === 0, 'emitted txBody carries no trailing a:br')
+ const sp2 = emit(el({ html: 'a<br>b' }))
+ ok(descendants(sp2, NS.a, 'br').length === 1, 'interior a:br emitted between runs')
+}
+
+// --- escaping through the emitter, both directions ---------------------------
+console.log('escaping')
+
+{
+ const nasty = 'Q3 & Q4 <Results> "final"'
+ // direction 1: author text with live characters — sanitizer spells them as
+ // entities; the tokenizer decodes, xmlout re-escapes, the parser gets the
+ // original characters back
+ const sp = emit(el({ html: 'Q3 &amp; Q4 &lt;Results&gt; "final"' }))
+ const r = runsOf(sp)[0]
+ ok(textOf(kid(r, NS.a, 't')!) === nasty, 'entity input round-trips to live characters through parseXml')
+ const xml = serialize(textSp(el({ html: 'Q3 &amp; Q4 &lt;Results&gt;' }), { shapeId: 2, themeFontFamily: 'Arial' })!)
+ ok(xml.includes('&amp;') && xml.includes('&lt;') && !xml.includes('<Results>'), 'the escapes are in the output bytes (direction 2)')
+}
+
+// --- field mapping -----------------------------------------------------------
+console.log('dynamic fields')
+
+{
+ const sp = emit(el({ html: '{{page}} of {{pages}}' }), { fields })
+ const flds = descendants(sp, NS.a, 'fld')
+ ok(flds.length === 1 && attr(flds[0], 'type') === 'slidenum', '{{page}} becomes a live a:fld type="slidenum"')
+ ok(textOf(kid(flds[0], NS.a, 't')!) === '6', 'slidenum field caches the resolved page number')
+ ok(/^\{[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}\}$/.test(attr(flds[0], 'id') ?? ''), 'field id is GUID-shaped')
+ const texts = runsOf(sp).map((r) => textOf(kid(r, NS.a, 't')!))
+ ok(texts.join('|') === ' of |12', '{{pages}} freezes to literal text around the field')
+}
+{
+ const sp = emit(el({ html: '{{date}}' }), { fields })
+ const fld = descendants(sp, NS.a, 'fld')[0]
+ ok(attr(fld, 'type') === 'datetime' && textOf(kid(fld, NS.a, 't')!).length > 0, '{{date}} becomes a:fld type="datetime" with cached text')
+}
+{
+ const sp = emit(el({ html: 'by {{author}} — {{title}}' }), { fields })
+ const t = runsOf(sp).map((r) => textOf(kid(r, NS.a, 't')!)).join('')
+ ok(t === 'by Ada — Q3 & Q4 <Results>', 'doc-prop tokens resolve to literals, live characters intact')
+}
+{
+ const report = new Report()
+ emit(el({ html: 'p. {{page:2}}' }), { fields, report, where: 'slide 1' })
+ const built = report.build()
+ ok(descendants(emit(el({ html: 'p. {{page:2}}' }), { fields }), NS.a, 'fld').length === 1
+ && built.entries.some((e) => e.code === 'text-field-pad-lost'),
+ '{{page:2}} stays a live field and the lost zero-pad is reported')
+}
+{
+ const sp = emit(el({ html: '{{page}} intact' })) // no fields ctx
+ ok(descendants(sp, NS.a, 'fld').length === 0
+ && runsOf(sp).map((r) => textOf(kid(r, NS.a, 't')!)).join('') === '{{page}} intact',
+ 'NEGATIVE: without a field context tokens stay literal (resolveFields parity)')
+}
+
+// --- centipoints and percentages ---------------------------------------------
+console.log('unit arithmetic')
+
+{
+ const sp = emit(el({ fontSize: 24, letterSpacing: 3, lineHeight: 1.5 }))
+ const rPr = rPrOf(runsOf(sp)[0])!
+ ok(attr(rPr, 'sz') === '1800', 'fontSize 24px → 18pt → sz="1800" centipoints')
+ ok(attr(rPr, 'spc') === '225', 'letterSpacing 3px → 2.25pt → spc="225" centipoints (uncapped, unlike #88)')
+ const spcPct = descendants(sp, NS.a, 'spcPct')[0]
+ ok(attr(spcPct, 'val') === '150000', 'lineHeight 1.5 → a:spcPct val="150000" (1000ths of a percent)')
+}
+{
+ const sp = emit(el({ fontSize: 18 }))
+ ok(attr(rPrOf(runsOf(sp)[0])!, 'sz') === '1350', 'fontSize 18px → 13.5pt → sz="1350" (fractional pt lands exactly in centipoints)')
+}
+
+// --- geometry, rotation, opacity ---------------------------------------------
+console.log('frame')
+
+{
+ const sp = emit(el({ x: 100, y: 50, w: 400, h: 120, rotation: 45 }))
+ const xfrm = descendants(sp, NS.a, 'xfrm')[0]
+ const off = kid(xfrm, NS.a, 'off')!
+ const ext = kid(xfrm, NS.a, 'ext')!
+ ok(attr(off, 'x') === String(100 * 9525) && attr(off, 'y') === String(50 * 9525), 'px → EMU offsets (×9525)')
+ ok(attr(ext, 'cx') === String(400 * 9525) && attr(ext, 'cy') === String(120 * 9525), 'px → EMU extents')
+ ok(attr(xfrm, 'rot') === '2700000', 'rotation 45° → rot="2700000" (60000ths of a degree)')
+ ok(attr(descendants(emit(el()), NS.a, 'xfrm')[0], 'rot') === undefined, 'rotation 0 omits rot (native shape)')
+ ok(attr(descendants(emit(el({ rotation: -90 })), NS.a, 'xfrm')[0], 'rot') === '16200000', 'negative rotation normalizes to 0..360')
+}
+{
+ const sp = emit(el({ color: 'rgba(255,0,0,0.5)', opacity: 0.5 }))
+ const srgb = descendants(sp, NS.a, 'srgbClr')[0]
+ ok(attr(srgb, 'val') === 'FF0000', 'rgba red → srgbClr FF0000')
+ ok(attr(kid(srgb, NS.a, 'alpha')!, 'val') === '25000', 'color alpha × element opacity compose: 0.5·0.5 → a:alpha 25000')
+ ok(cssColor('#1E2A3A').hex === '1E2A3A' && cssColor('#1E2A3A').alpha === 1, 'hex parses opaque')
+ ok(cssColor('bogus(1,2)').hex === '000000', 'NEGATIVE: unparseable colour falls back instead of emitting garbage')
+}
+
+// --- element-level style, alignment, anchoring -------------------------------
+console.log('style plumbing')
+
+{
+ const sp = emit(el({ fontWeight: 700, align: 'center', valign: 'bottom', fontFamily: '"Space Grotesk", sans-serif' }))
+ ok(attr(rPrOf(runsOf(sp)[0])!, 'b') === '1', 'fontWeight 700 → b="1" (#88 threshold ≥600)')
+ ok(attr(descendants(sp, NS.a, 'pPr')[0], 'algn') === 'ctr', 'align center → algn="ctr"')
+ const bodyPr = descendants(sp, NS.a, 'bodyPr')[0]
+ ok(attr(bodyPr, 'anchor') === 'b', 'valign bottom → bodyPr anchor="b"')
+ ok(attr(bodyPr, 'lIns') === '0' && kid(bodyPr, NS.a, 'normAutofit') !== undefined, 'zero insets + normAutofit (#88 margin:0 / fit:shrink)')
+ ok(attr(kid(rPrOf(runsOf(sp)[0])!, NS.a, 'latin')!, 'typeface') === 'Space Grotesk', 'first family, quotes stripped → a:latin')
+}
+{
+ const sp = emit(el({ html: '<u>u</u><s>s</s><code>c</code>' }))
+ const [u, s, c] = runsOf(sp)
+ ok(attr(rPrOf(u)!, 'u') === 'sng', '<u> → u="sng"')
+ ok(attr(rPrOf(s)!, 'strike') === 'sngStrike', '<s> → strike="sngStrike" (beyond #88: PptxGenJS had no strike)')
+ ok(attr(kid(rPrOf(c)!, NS.a, 'latin')!, 'typeface') === 'Courier New', '<code> → Courier New (#88 mapping)')
+}
+{
+ const sp = emit(el({ textStroke: { width: 2, color: '#F7A600', fill: 'none' } }))
+ const rPr = rPrOf(runsOf(sp)[0])!
+ const ln = kid(rPr, NS.a, 'ln')!
+ ok(attr(ln, 'w') === String(2 * 9525), 'textStroke width 2px → a:ln w in EMU')
+ ok(kid(rPr, NS.a, 'noFill') !== undefined, "textStroke fill:'none' → hollow glyphs via a:noFill interior")
+}
+{
+ const sp = emit(el(), { link: { rId: 'rId7', slideJump: true } })
+ const hl = kid(rPrOf(runsOf(sp)[0])!, NS.a, 'hlinkClick')!
+ ok(attr(hl, 'id') === 'rId7' && attr(hl, 'action') === 'ppaction://hlinksldjump',
+ 'link rides on every run rPr (#88 per-run fix) with the slide-jump action')
+}
+
+// --- placeholder skip and shape identity -------------------------------------
+console.log('shape identity')
+
+{
+ ok(textSp(el({ html: ' <br> ', placeholder: 'Click to add title' }), { shapeId: 2, themeFontFamily: 'Arial' }) === null,
+ 'NEGATIVE: unfilled placeholder exports nothing (#88 skip — present mode hides it too)')
+ ok(textSp(el({ html: 'Real title', placeholder: 'Click to add title' }), { shapeId: 2, themeFontFamily: 'Arial' }) !== null,
+ 'a FILLED placeholder exports normally')
+ const sp = emit(el({ id: 'e1', morphId: 'tile-a' }), { shapeId: 9 })
+ const cNvPr = descendants(sp, NS.p, 'cNvPr')[0]
+ ok(attr(cNvPr, 'id') === '9' && attr(cNvPr, 'name') === 'bento:tile-a', 'cNvPr carries the allocated id and bento:<morph key> name (#88)')
+ const empty = emit(el({ html: '' }))
+ ok(kids(kid(kid(empty, NS.p, 'txBody')!, NS.a, 'p')!, NS.a, 'r').length === 0
+ && kid(empty, NS.p, 'txBody') !== undefined, 'empty text still emits a txBody with one (empty) a:p')
+}
+
+console.log(`\n${checks} checks, ${failures} failing`)
+process.exit(failures ? 1 : 0)
diff --git a/scripts/test-convert/pptx-write.ts b/scripts/test-convert/pptx-write.ts
new file mode 100644
index 00000000..aa5e6f54
--- /dev/null
+++ b/scripts/test-convert/pptx-write.ts
@@ -0,0 +1,451 @@
+#!/usr/bin/env node
+// SPDX-License-Identifier: MIT
+// Copyright (c) 2026 The Bento authors
+// pptx-write end-to-end rig: exportPptx over a representative deck.
+//
+// node scripts/test-convert/pptx-write.ts (Node ≥ 23.6 strips types natively)
+//
+// The whole pipeline under one roof: a bento doc built in code (every element
+// type, fx, links, notes, a hidden slide, an interactive state) goes through
+// exportPptx, the bytes come back through the kernel's OWN zip reader and XML
+// parser, and the package's wiring is asserted the way PowerPoint checks it:
+// every rel target exists, every r:id resolves in its own rels part, every XML
+// part is typed in [Content_Types].xml. The NEGATIVE controls doctor the
+// output and watch each checker actually fail — a rel checker that never finds
+// a break proves nothing about the packages it passes.
+
+import { readZip, type ZipParts } from '../../kernel/src/convert/zip.ts'
+import { parseXml, kids, kid, attr, textOf, descendants, NS, type XElem } from '../../convert/src/xml.ts'
+import { exportPptx, type ExportDoc, type ExportElement } from '../../convert/src/pptx-write/index.ts'
+import type { FidelityReport } from '../../convert/src/report.ts'
+import { brokenRels, danglingRefs, packageProblems } from './_export-harness.ts'
+
+let failures = 0
+let checks = 0
+function ok(cond: boolean, msg: string) {
+ checks++
+ if (!cond) { failures++; console.log(` FAIL ${msg}`) }
+ else console.log(` ok ${msg}`)
+}
+
+const dec = new TextDecoder()
+const partText = (parts: ZipParts, name: string): string => dec.decode(parts.get(name) ?? new Uint8Array())
+const partXml = (parts: ZipParts, name: string): XElem => parseXml(partText(parts, name))
+
+// --- wiring checkers (the rig's own, exercised by negative controls below) ---
+
+// brokenRels and danglingRefs live in the shared harness; the negative
+// controls below prove the harness's copies, the ones every rig uses.
+
+const codesOf = (report: FidelityReport): Set<string> => new Set(report.entries.map((e) => e.code))
+
+// --- the representative deck -------------------------------------------------
+
+// 1×1 png — real bytes so a thumbnailer opening the result sees a picture.
+const PNG =
+ 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
+
+const frame = (x: number, y: number, w: number, h: number) => ({ x, y, w, h, rotation: 0, opacity: 1 })
+
+const el = (v: unknown): ExportElement => v as ExportElement
+
+function buildDoc(): ExportDoc {
+ return {
+ title: 'Rig deck',
+ size: { width: 1280, height: 720 },
+ theme: {
+ background: '#FFFFFF', color: '#1E2A3A', accent: '#FF7A59',
+ fontFamily: 'Inter, sans-serif', chartPalette: ['#FF9F7A', '#5B7C99'],
+ },
+ meta: { author: 'Andy', company: 'Nybl', subject: 'Rig coverage', keywords: 'rig,pptx' },
+ assets: {},
+ slides: [
+ {
+ id: 's1', background: '#FFFFFF', transition: 'fade',
+ notes: 'Welcome to the rig\n\nSecond paragraph',
+ elements: [
+ el({
+ type: 'text', id: 't1', ...frame(96, 80, 800, 90),
+ html: 'Q3 <b>Results</b> &amp; <i>outlook</i>', fontSize: 40, fontFamily: 'Inter, sans-serif',
+ fontWeight: 400, color: '#1E2A3A', align: 'left', valign: 'top', lineHeight: 1.2,
+ }),
+ el({
+ type: 'text', id: 't2', ...frame(96, 620, 300, 40), link: 's2',
+ html: 'p. {{page}}/{{pages}}', fontSize: 18, fontFamily: 'Inter, sans-serif',
+ fontWeight: 400, color: '#5B7C99', align: 'left', valign: 'bottom', lineHeight: 1,
+ }),
+ el({
+ type: 'shape', id: 'grad1', ...frame(700, 200, 300, 200), link: 'https://bento.page',
+ shape: 'rect', fill: '#FF0000', stroke: 'none', strokeWidth: 0, radius: 12,
+ fillGradient: { angle: 90, stops: [{ at: 0, color: '#FF0000' }, { at: 1, color: '#0000FF' }] },
+ shadow: { x: 0, y: 6, blur: 18, color: 'rgba(0,0,0,0.35)' },
+ }),
+ el({
+ type: 'shape', id: 'line1', ...frame(96, 200, 400, 40),
+ shape: 'line', fill: '#222222', stroke: '#000000', strokeWidth: 3, radius: 0, lineEnd: 'arrow',
+ }),
+ ],
+ },
+ {
+ id: 's2', background: '#1E2A3A', transition: 'morph', elements: [
+ el({
+ type: 'chart', id: 'c-bar', ...frame(96, 96, 500, 400), fx: { enter: 'fade-up' },
+ option: { xAxis: { data: ['A', 'B', 'C'] }, yAxis: {}, series: [{ type: 'bar', name: 'Rev', data: [3, 5, 2] }] },
+ }),
+ el({
+ type: 'chart', id: 'c-dual', ...frame(650, 96, 500, 400), fx: { countUp: true },
+ option: {
+ xAxis: { data: ['Q1', 'Q2'] },
+ yAxis: [{}, { axisLabel: { formatter: '{value}%' } }],
+ series: [
+ { type: 'bar', name: 'Amount', data: [10, 20] },
+ { type: 'line', name: 'Share', data: [5, 7], yAxisIndex: 1 },
+ ],
+ },
+ }),
+ el({
+ type: 'chart', id: 'c-stack', ...frame(96, 520, 500, 160),
+ option: {
+ xAxis: { data: ['A', 'B'] },
+ series: [
+ { type: 'bar', name: 'S1', stack: 'x', data: [1, 2] },
+ { type: 'bar', name: 'S2', stack: 'x', data: [3, 4] },
+ ],
+ },
+ }),
+ ],
+ },
+ {
+ id: 's3', background: '#FFFFFF', elements: [
+ el({ type: 'image', id: 'img1', ...frame(96, 96, 320, 200), src: PNG, fit: 'cover', radius: 8 }),
+ el({
+ type: 'svg', id: 'sv1', ...frame(500, 96, 200, 200),
+ markup: '<svg viewBox="0 0 10 10"><rect class="x" width="10" height="10"/></svg>',
+ css: '.x{fill:red}',
+ }),
+ el({
+ type: 'table', id: 'tb1', ...frame(96, 360, 500, 200),
+ columns: [{ w: 1 }, { w: 1 }], header: true,
+ rows: [
+ { cells: [{ html: 'Region' }, { html: 'Total' }] },
+ { cells: [{ html: 'North' }, { html: '42' }] },
+ ],
+ // radius 0 explicitly: tables.ts merges the deck DEFAULT style,
+ // whose rounded corners would (correctly) report table-radius-dropped
+ style: { headerBg: '#1E2A3A', headerColor: '#FFFFFF', borderColor: '#DDDDDD', borderWidth: 1, color: '#1E2A3A', radius: 0 },
+ }),
+ el({ type: 'media', id: 'md1', ...frame(700, 360, 200, 60), kind: 'audio', src: 'data:audio/mp3;base64,AAAA' }),
+ el({
+ type: 'shape', id: 's3link', ...frame(960, 96, 120, 60), link: 'state1',
+ shape: 'rect', fill: '#5B7C99', stroke: 'none', strokeWidth: 0, radius: 0,
+ }),
+ el({
+ type: 'shape', id: 's3bad', ...frame(960, 200, 120, 60), link: 'nope',
+ shape: 'rect', fill: '#5B7C99', stroke: 'none', strokeWidth: 0, radius: 0,
+ }),
+ ],
+ },
+ {
+ id: 's4', background: '#F5F7FA', hidden: true, elements: [
+ // byte-identical to img1: must dedup to ONE media part across slides
+ el({ type: 'image', id: 'img2', ...frame(96, 96, 200, 120), src: PNG, fit: 'fill' }),
+ ],
+ },
+ {
+ id: 'state1', background: '#FFFFFF', stateOf: 's1', elements: [
+ el({
+ type: 'text', id: 'stx', ...frame(96, 96, 400, 60),
+ html: 'state detail', fontSize: 24, fontFamily: 'Inter, sans-serif',
+ fontWeight: 400, color: '#1E2A3A', align: 'left', valign: 'top', lineHeight: 1.2,
+ }),
+ ],
+ },
+ ],
+ }
+}
+
+// --- run ---------------------------------------------------------------------
+
+const { bytes, report } = await exportPptx(buildDoc())
+const parts = await readZip(bytes)
+
+console.log('package')
+ok(bytes.length > 0, `export produced ${bytes.length} bytes`)
+ok([...parts.keys()][0] === '[Content_Types].xml', '[Content_Types].xml is the FIRST zip entry')
+
+const required = [
+ '_rels/.rels', 'docProps/core.xml', 'docProps/app.xml',
+ 'ppt/presentation.xml', 'ppt/_rels/presentation.xml.rels',
+ 'ppt/theme/theme1.xml',
+ 'ppt/slideMasters/slideMaster1.xml', 'ppt/slideMasters/_rels/slideMaster1.xml.rels',
+ 'ppt/slideLayouts/slideLayout1.xml', 'ppt/slideLayouts/_rels/slideLayout1.xml.rels',
+ 'ppt/notesMasters/notesMaster1.xml', 'ppt/notesMasters/_rels/notesMaster1.xml.rels',
+ 'ppt/slides/slide1.xml', 'ppt/slides/slide2.xml', 'ppt/slides/slide3.xml', 'ppt/slides/slide4.xml',
+ 'ppt/slides/_rels/slide1.xml.rels', 'ppt/slides/_rels/slide2.xml.rels',
+ 'ppt/slides/_rels/slide3.xml.rels', 'ppt/slides/_rels/slide4.xml.rels',
+ 'ppt/notesSlides/notesSlide1.xml', 'ppt/notesSlides/_rels/notesSlide1.xml.rels',
+ 'ppt/charts/chart1.xml', 'ppt/charts/chart2.xml',
+]
+for (const name of required) ok(parts.has(name), `part present: ${name}`)
+ok(!parts.has('ppt/slides/slide5.xml'), 'state slide is NOT exported as a slide part')
+ok(!parts.has('ppt/charts/chart3.xml'), 'stacked chart produced no chart part (table fallback)')
+
+const mediaNames = [...parts.keys()].filter((n) => n.startsWith('ppt/media/'))
+ok(mediaNames.filter((n) => n.endsWith('.png')).length === 1,
+ 'byte-identical images on two slides dedup to ONE png part')
+ok(mediaNames.filter((n) => n.endsWith('.svg')).length === 1, 'svg element embedded as one svg part')
+
+console.log('every XML part parses with the kernel parser')
+{
+ let parsed = 0
+ let threw = ''
+ for (const name of parts.keys()) {
+ if (!name.endsWith('.xml') && !name.endsWith('.rels')) continue
+ try { partXml(parts, name); parsed++ } catch (e) { threw = `${name}: ${e}` }
+ }
+ ok(threw === '', threw || `${parsed} XML parts parse clean`)
+}
+
+console.log('wiring')
+ok(brokenRels(parts).length === 0, 'every internal rel target exists in the zip')
+{
+ const problems = packageProblems(parts)
+ ok(problems.length === 0, problems.length ? `harness: ${problems.join('; ')}` : 'the harness finds nothing wrong with the whole package')
+}
+{
+ let bad = ''
+ for (let i = 1; i <= 4; i++) {
+ const missing = danglingRefs(partText(parts, `ppt/slides/slide${i}.xml`), partText(parts, `ppt/slides/_rels/slide${i}.xml.rels`))
+ if (missing.length) bad = `slide${i}: ${missing.join(',')}`
+ }
+ ok(bad === '', bad || 'every r:id/r:embed/r:link in every slide resolves in its rels')
+}
+{
+ const ct = partXml(parts, '[Content_Types].xml')
+ const overridden = new Set(kids(ct, NS.ct, 'Override').map((o) => attr(o, 'PartName')))
+ for (const name of ['/ppt/presentation.xml', '/ppt/slides/slide1.xml', '/ppt/slides/slide4.xml',
+ '/ppt/notesSlides/notesSlide1.xml', '/ppt/notesMasters/notesMaster1.xml',
+ '/ppt/charts/chart1.xml', '/ppt/charts/chart2.xml', '/docProps/core.xml', '/docProps/app.xml']) {
+ ok(overridden.has(name), `content-type override present: ${name}`)
+ }
+ let stray = ''
+ for (const name of overridden) if (name && !parts.has(name.slice(1))) stray = name
+ ok(stray === '', stray ? `override for missing part ${stray}` : 'no override points at a missing part')
+}
+
+console.log('presentation.xml')
+{
+ const pres = partXml(parts, 'ppt/presentation.xml')
+ const ids = kids(kid(pres, NS.p, 'sldIdLst')!, NS.p, 'sldId')
+ ok(ids.length === 4, 'sldIdLst lists 4 slides (states omitted, hidden kept)')
+ ok(ids.every((s) => parseInt(attr(s, 'id') ?? '0', 10) >= 256), 'every sldId is >= 256')
+ const sz = kid(pres, NS.p, 'sldSz')!
+ ok(attr(sz, 'cx') === String(1280 * 9525) && attr(sz, 'cy') === String(720 * 9525),
+ 'slide size is doc.size px * 9525 (1280x720 -> 12192000x6858000)')
+ ok(!!kid(pres, NS.p, 'notesMasterIdLst'), 'notesMasterIdLst present (deck has notes)')
+}
+
+console.log('slide 1 — text, fields, shapes, links')
+{
+ const s1 = partXml(parts, 'ppt/slides/slide1.xml')
+ const bold = descendants(s1, NS.a, 'r').find((r) => textOf(r) === 'Results')
+ ok(!!bold && attr(kid(bold!, NS.a, 'rPr')!, 'b') === '1', 'inline <b>Results</b> is a bold run')
+ const italic = descendants(s1, NS.a, 'r').find((r) => textOf(r) === 'outlook')
+ ok(!!italic && attr(kid(italic!, NS.a, 'rPr')!, 'i') === '1', 'inline <i>outlook</i> is an italic run')
+ ok(descendants(s1, NS.a, 'r').some((r) => textOf(r).includes('&')), 'entity &amp; decoded into run text')
+ const fld = descendants(s1, NS.a, 'fld')
+ ok(fld.length === 1 && attr(fld[0], 'type') === 'slidenum' && textOf(fld[0]) === '1',
+ '{{page}} is a LIVE slidenum field cached "1"')
+ // splitFields emits one a:r per piece: '…/' between the tokens, then the
+ // frozen '{{pages}}' value as its own run.
+ ok(descendants(s1, NS.a, 't').some((t) => textOf(t) === '3'),
+ '{{pages}} froze to "3" (hidden slide and state do not paginate)')
+ ok(descendants(s1, NS.a, 'gradFill').length === 1
+ && descendants(s1, NS.a, 'gs').length === 2, 'gradient fill carried with both stops')
+ ok(descendants(s1, NS.a, 'outerShdw').length === 1, 'shadow carried as a:outerShdw')
+ const cxn = descendants(s1, NS.p, 'cxnSp')
+ ok(cxn.length === 1, 'line element exports as p:cxnSp')
+ ok(attr(descendants(cxn[0], NS.a, 'tailEnd')[0] ?? cxn[0], 'type') === 'triangle',
+ "lineEnd 'arrow' becomes a triangle tailEnd")
+
+ const rels = partXml(parts, 'ppt/slides/_rels/slide1.xml.rels')
+ const relById = new Map(kids(rels, NS.rel, 'Relationship').map((r) => [attr(r, 'Id'), r]))
+ const links = descendants(s1, NS.a, 'hlinkClick')
+ const jump = links.find((l) => attr(l, 'action') === 'ppaction://hlinksldjump')
+ ok(!!jump && attr(relById.get(attr(jump!, 'id'))!, 'Target') === '../slides/slide2.xml',
+ 'internal link is a sldjump action whose rel targets slide2.xml')
+ const ext = links.find((l) => attr(l, 'action') === undefined)
+ const extRel = ext && relById.get(attr(ext, 'id'))
+ ok(!!extRel && attr(extRel!, 'TargetMode') === 'External' && attr(extRel!, 'Target') === 'https://bento.page',
+ 'external link is an External-mode hyperlink rel (no jump action)')
+}
+
+console.log('slide 2 — charts')
+{
+ const s2 = partXml(parts, 'ppt/slides/slide2.xml')
+ ok(descendants(s2, NS.p, 'graphicFrame').length === 3, 'three graphic frames (2 charts + 1 fallback table)')
+ ok(descendants(s2, NS.a, 'tbl').length === 1, 'stacked chart downgraded to a data TABLE, not a wrong chart')
+ const rels = partXml(parts, 'ppt/slides/_rels/slide2.xml.rels')
+ const chartRels = kids(rels, NS.rel, 'Relationship').filter((r) => (attr(r, 'Type') ?? '').endsWith('/chart'))
+ ok(chartRels.length === 2, 'exactly two chart rels (the reserved fallback rId stays unused)')
+
+ const c1 = partXml(parts, 'ppt/charts/chart1.xml')
+ ok(c1.ns === NS.c && c1.local === 'chartSpace', 'chart1 root is c:chartSpace')
+ ok(descendants(c1, NS.c, 'barChart').length === 1, 'chart1 is a bar chart')
+ const vals = descendants(c1, NS.c, 'numCache').flatMap((nc) => descendants(nc, NS.c, 'v').map(textOf))
+ ok(['3', '5', '2'].every((v) => vals.includes(v)), 'chart1 numCache carries the series values')
+
+ const c2 = partXml(parts, 'ppt/charts/chart2.xml')
+ ok(descendants(c2, NS.c, 'valAx').length === 2, 'dual-axis chart carries two value axes')
+ ok(descendants(c2, NS.c, 'barChart').length === 1 && descendants(c2, NS.c, 'lineChart').length === 1,
+ 'dual-axis chart is one bar group + one line group')
+}
+
+console.log('slide 3 — image, svg, table, media, link degradation')
+{
+ const s3 = partXml(parts, 'ppt/slides/slide3.xml')
+ ok(descendants(s3, NS.p, 'pic').length === 2, 'image + svg export as p:pic; dropped audio adds none')
+ ok(descendants(s3, NS.asvg, 'svgBlip').length === 1, 'svg pic carries asvg:svgBlip')
+ const svgName = mediaNames.find((n) => n.endsWith('.svg'))!
+ const svgText = partText(parts, svgName)
+ ok(svgText.includes('xmlns="http://www.w3.org/2000/svg"'), 'svg part gained the xmlns the inline markup lacked')
+ ok(svgText.includes('<style>.x{fill:red}</style>'), 'el.css spliced into the embedded svg markup')
+ ok(descendants(s3, NS.a, 'tbl').length === 1
+ && descendants(s3, NS.a, 'gridCol').length === 2, 'table exports with its 2-column grid')
+
+ const rels = partXml(parts, 'ppt/slides/_rels/slide3.xml.rels')
+ const relById = new Map(kids(rels, NS.rel, 'Relationship').map((r) => [attr(r, 'Id'), r]))
+ const jump = descendants(s3, NS.a, 'hlinkClick').find((l) => attr(l, 'action') === 'ppaction://hlinksldjump')
+ ok(!!jump && attr(relById.get(attr(jump!, 'id'))!, 'Target') === '../slides/slide1.xml',
+ "link into the omitted state retargets to the state's parent slide (#88 degradation)")
+}
+
+console.log('slide 4 — hidden')
+{
+ const s4 = partXml(parts, 'ppt/slides/slide4.xml')
+ ok(attr(s4, 'show') === '0', 'hidden slide carries show="0"')
+}
+
+console.log('notes')
+{
+ const notes = partXml(parts, 'ppt/notesSlides/notesSlide1.xml')
+ const paras = descendants(notes, NS.a, 'p')
+ ok(paras.length === 3, 'notes keep the paragraph rhythm (text, blank, text)')
+ ok(textOf(notes).includes('Welcome to the rig') && textOf(notes).includes('Second paragraph'),
+ 'both notes paragraphs carried')
+ const rels = partXml(parts, 'ppt/notesSlides/_rels/notesSlide1.xml.rels')
+ const targets = kids(rels, NS.rel, 'Relationship').map((r) => attr(r, 'Target'))
+ ok(targets.includes('../notesMasters/notesMaster1.xml') && targets.includes('../slides/slide1.xml'),
+ 'notesSlide rels reach the notes master and back-link its slide')
+}
+
+console.log('docProps')
+{
+ const core = partXml(parts, 'docProps/core.xml')
+ const DC = 'http://purl.org/dc/elements/1.1/'
+ ok(textOf(kid(core, DC, 'creator')!) === 'Andy', 'doc.meta.author -> dc:creator')
+ ok(textOf(kid(core, DC, 'title')!) === 'Rig deck', 'doc.title -> dc:title')
+ const app = partXml(parts, 'docProps/app.xml')
+ const EP = 'http://schemas.openxmlformats.org/officeDocument/2006/extended-properties'
+ ok(textOf(kid(app, EP, 'Company')!) === 'Nybl', 'doc.meta.company -> app.xml Company')
+}
+
+console.log('fidelity report')
+{
+ const expected = new Set([
+ 'state-slides-omitted',
+ 'presentation-effects-static',
+ 'morph-not-exported',
+ 'chart-approximated',
+ 'image-fit-approximated',
+ 'svg-no-raster-fallback',
+ 'media-dropped',
+ 'missing-link-target',
+ 'text-field-frozen',
+ ])
+ const got = codesOf(report)
+ const extra = [...got].filter((c) => !expected.has(c))
+ const missing = [...expected].filter((c) => !got.has(c))
+ ok(extra.length === 0 && missing.length === 0,
+ `report codes EXACTLY as expected${extra.length ? ` (extra: ${extra})` : ''}${missing.length ? ` (missing: ${missing})` : ''}`)
+ const fx = report.entries.find((e) => e.code === 'presentation-effects-static')
+ ok(!!fx && fx!.where === 'slide 2' && fx!.count === 2,
+ 'fx on two elements folds into ONE entry per slide (count 2) — #88 dedup rule')
+ const states = report.entries.find((e) => e.code === 'state-slides-omitted')
+ ok(!!states && states!.count === 1 && states!.verdict === 'dropped', 'state omission reported once, as dropped')
+}
+
+console.log('determinism')
+{
+ const again = await exportPptx(buildDoc())
+ const same = again.bytes.length === bytes.length && again.bytes.every((b, i) => b === bytes[i])
+ ok(same, 'two exports of the same doc are byte-identical (fixed zip timestamp)')
+}
+
+console.log('negative controls')
+{
+ // Each checker observed FAILING on doctored input — otherwise a green run
+ // only proves the checkers are inert.
+ const doctored = new Map(parts)
+ doctored.delete('ppt/slides/slide2.xml')
+ ok(brokenRels(doctored).length > 0, 'NEGATIVE: rel checker catches a deleted part')
+ ok(danglingRefs('<p:sp r:embed="rId99"/>', partText(parts, 'ppt/slides/_rels/slide1.xml.rels')).length === 1,
+ 'NEGATIVE: ref checker catches an unknown rId')
+ {
+ const noProps = new Map(parts)
+ noProps.delete('ppt/presProps.xml')
+ ok(packageProblems(noProps).some((p) => /presProps/.test(p)), 'NEGATIVE: the harness catches a missing presProps.xml')
+ const noStyle = new Map(parts)
+ noStyle.set('ppt/notesMasters/notesMaster1.xml', new TextEncoder().encode(
+ partText(parts, 'ppt/notesMasters/notesMaster1.xml').replace(/<p:notesStyle>[\s\S]*<\/p:notesStyle>/, '')))
+ ok(packageProblems(noStyle).some((p) => /notesStyle/.test(p)), 'NEGATIVE: the harness catches a notes master without notesStyle')
+ const untyped = new Map(parts)
+ untyped.set('ppt/stray.bin', new Uint8Array([1]))
+ ok(packageProblems(untyped).some((p) => /stray\.bin has no content type/.test(p)), 'NEGATIVE: the harness catches an untyped part')
+ }
+
+ let threw = false
+ try {
+ await exportPptx({ ...buildDoc(), slides: buildDoc().slides.filter((s) => s.stateOf) })
+ } catch { threw = true }
+ ok(threw, 'NEGATIVE: a deck with only state slides is refused, not exported empty')
+
+ // A broken/breaking element degrades to a report entry, never a dead export.
+ const mini = await exportPptx({
+ ...buildDoc(),
+ slides: [{
+ id: 'm1', background: '#FFFFFF', elements: [
+ el({ type: 'image', id: 'bmp1', ...frame(0, 0, 100, 100), src: 'data:image/bmp;base64,AAAA', fit: 'fill' }),
+ el({ type: 'wormhole', id: 'w1', ...frame(0, 0, 10, 10) }),
+ ],
+ }],
+ })
+ const miniParts = await readZip(mini.bytes)
+ const miniCodes = codesOf(mini.report)
+ ok(miniCodes.has('missing-image') && miniCodes.has('element-unsupported') && miniCodes.size === 2,
+ 'NEGATIVE: unsupported image mime + unknown element type each report, nothing else fires')
+ ok([...miniParts.keys()].every((n) => !n.startsWith('ppt/media/')), 'NEGATIVE: refused bmp writes no media part')
+
+ // --- the boilerplate PowerPoint actually requires ---------------------------
+ // presProps, viewProps, tableStyles and a presentation->theme rel are all
+ // schema-OPTIONAL, and the first cut of this writer shipped without them:
+ // unzip -t passed, a 192-check OPC validation passed, and real macOS
+ // PowerPoint still raised its "found a problem / Repair" dialog on an
+ // otherwise-valid file. Every real producer emits them. Their absence is
+ // invisible to structural checks, so their PRESENCE is pinned here.
+ for (const part of ['ppt/presProps.xml', 'ppt/viewProps.xml', 'ppt/tableStyles.xml']) {
+ ok(miniParts.has(part), `${part} present — its absence is a PowerPoint repair prompt`)
+ }
+ const presRels = new TextDecoder().decode(miniParts.get('ppt/_rels/presentation.xml.rels')!)
+ for (const kind of ['theme', 'presProps', 'viewProps', 'tableStyles']) {
+ ok(presRels.includes(`relationships/${kind}"`), `presentation.xml.rels carries the ${kind} rel`)
+ }
+ const ctypes = new TextDecoder().decode(miniParts.get('[Content_Types].xml')!)
+ ok(['presProps', 'viewProps', 'tableStyles'].every((k) => ctypes.includes(`${k}+xml`)),
+ 'the three property parts are declared in [Content_Types].xml')
+ ok(descendants(partXml(miniParts, 'ppt/slides/slide1.xml'), NS.p, 'pic').length === 0,
+ 'NEGATIVE: dropped image leaves no p:pic behind')
+}
+
+console.log(`\n${checks} checks, ${failures} failures`)
+if (failures > 0) process.exit(1)