pptx-ts 0.0.1 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +116 -269
- package/dist/autopage-odPz7zZO.js +536 -0
- package/dist/autopage-odPz7zZO.js.map +1 -0
- package/dist/binary-string-CKVAYI3M.js +24 -0
- package/dist/binary-string-CKVAYI3M.js.map +1 -0
- package/dist/body-insets-Dw_BeWD_.js +54 -0
- package/dist/body-insets-Dw_BeWD_.js.map +1 -0
- package/dist/browser.d.ts +29 -9
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +41 -14
- package/dist/browser.js.map +1 -1
- package/dist/clip-Bl01BPcN.d.ts +67 -0
- package/dist/clip-Bl01BPcN.d.ts.map +1 -0
- package/dist/diagnostics-D8ot4Ei7.d.ts +244 -0
- package/dist/diagnostics-D8ot4Ei7.d.ts.map +1 -0
- package/dist/embedded-fonts-DarT9aoa.d.ts +20 -0
- package/dist/embedded-fonts-DarT9aoa.d.ts.map +1 -0
- package/dist/entry-compose-DCnvBZz2.d.ts +1046 -0
- package/dist/entry-compose-DCnvBZz2.d.ts.map +1 -0
- package/dist/{enums-CvRYniUA.d.ts → enums-BUKTUB6V.d.ts} +21 -13
- package/dist/{enums-CvRYniUA.d.ts.map → enums-BUKTUB6V.d.ts.map} +1 -1
- package/dist/{errors-Bvln0H-7.js → errors-C4oENPcu.js} +92 -2
- package/dist/errors-C4oENPcu.js.map +1 -0
- package/dist/families.d.ts +260 -0
- package/dist/families.d.ts.map +1 -0
- package/dist/families.js +57 -0
- package/dist/families.js.map +1 -0
- package/dist/{fit-BKs0zxMI.js → fit-Cb7naFj6.js} +249 -167
- package/dist/fit-Cb7naFj6.js.map +1 -0
- package/dist/font-metrics-v5fn7s7e.d.ts +613 -0
- package/dist/font-metrics-v5fn7s7e.d.ts.map +1 -0
- package/dist/grid-DikTjFey.js +187 -0
- package/dist/grid-DikTjFey.js.map +1 -0
- package/dist/{html-dom-B0I0QSbU.js → html-dom-Iuog2wdK.js} +121 -91
- package/dist/html-dom-Iuog2wdK.js.map +1 -0
- package/dist/html.d.ts +6 -6
- package/dist/html.d.ts.map +1 -1
- package/dist/html.js +7 -6
- package/dist/html.js.map +1 -1
- package/dist/image-size-CvN2iCA4.js +1611 -0
- package/dist/image-size-CvN2iCA4.js.map +1 -0
- package/dist/index.d.ts +24 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +31 -11
- package/dist/index.js.map +1 -1
- package/dist/inspect.d.ts +40 -31
- package/dist/inspect.d.ts.map +1 -1
- package/dist/inspect.js +40 -48
- package/dist/inspect.js.map +1 -1
- package/dist/math.d.ts +7 -5
- package/dist/math.d.ts.map +1 -1
- package/dist/math.js +16 -7
- package/dist/math.js.map +1 -1
- package/dist/measure.d.ts +12 -225
- package/dist/measure.d.ts.map +1 -1
- package/dist/measure.js +3 -3
- package/dist/node.d.ts +22 -8
- package/dist/node.d.ts.map +1 -1
- package/dist/node.js +27 -7
- package/dist/node.js.map +1 -1
- package/dist/notes-Dh12JAbn.js +3264 -0
- package/dist/notes-Dh12JAbn.js.map +1 -0
- package/dist/options-internal-WqgMf720.js +43 -0
- package/dist/options-internal-WqgMf720.js.map +1 -0
- package/dist/{package-CaOLXSNi.d.ts → package-J49Ck6S2.d.ts} +27 -12
- package/dist/package-J49Ck6S2.d.ts.map +1 -0
- package/dist/playbtn-CUqQdoDf.js +22 -0
- package/dist/playbtn-CUqQdoDf.js.map +1 -0
- package/dist/{slide-js0QpRV-.d.ts → pres-C6qgOFAa.d.ts} +1021 -1370
- package/dist/pres-C6qgOFAa.d.ts.map +1 -0
- package/dist/{presentation-Cp7vzlAw.js → presentation-DGYlAWhl.js} +3208 -2727
- package/dist/presentation-DGYlAWhl.js.map +1 -0
- package/dist/{presentation-types-DP_8jog7.d.ts → presentation-types-8jLQHI4M.d.ts} +1070 -683
- package/dist/presentation-types-8jLQHI4M.d.ts.map +1 -0
- package/dist/read.d.ts +9 -9
- package/dist/read.d.ts.map +1 -1
- package/dist/read.js +4 -4
- package/dist/script.d.ts +80 -66
- package/dist/script.d.ts.map +1 -1
- package/dist/script.js +2399 -1139
- package/dist/script.js.map +1 -1
- package/dist/{shapes-BemroU-z.js → shapes-re0KyQk_.js} +2807 -1609
- package/dist/shapes-re0KyQk_.js.map +1 -0
- package/dist/slide-Dx2ZeVZ6.d.ts +1256 -0
- package/dist/slide-Dx2ZeVZ6.d.ts.map +1 -0
- package/dist/slide-size-BalTjFuv.js +88 -0
- package/dist/slide-size-BalTjFuv.js.map +1 -0
- package/dist/{units-internal-Dg95w_YD.js → table-cell-margins-EVg0EwxT.js} +235 -273
- package/dist/table-cell-margins-EVg0EwxT.js.map +1 -0
- package/dist/table-dom-BTDP3lEP.js +21 -0
- package/dist/table-dom-BTDP3lEP.js.map +1 -0
- package/dist/text-KnLOtEEu.js +3980 -0
- package/dist/text-KnLOtEEu.js.map +1 -0
- package/dist/text-anchor-CrYXAfUu.js +176 -0
- package/dist/text-anchor-CrYXAfUu.js.map +1 -0
- package/dist/transition-speed-kUEWDWTx.js +14 -0
- package/dist/transition-speed-kUEWDWTx.js.map +1 -0
- package/dist/units-internal-XJlf-hOl.js +649 -0
- package/dist/units-internal-XJlf-hOl.js.map +1 -0
- package/dist/zip-C0leZZMj.d.ts +67 -0
- package/dist/zip-C0leZZMj.d.ts.map +1 -0
- package/dist/zip-CKd8ihcf.js +177 -0
- package/dist/zip-CKd8ihcf.js.map +1 -0
- package/dist/zip.d.ts +3 -68
- package/dist/zip.js +3 -163
- package/dist/zoom-cX9sllpH.js +8865 -0
- package/dist/zoom-cX9sllpH.js.map +1 -0
- package/package.json +106 -19
- package/skills/ts-pptx-upstream/SKILL.md +58 -57
- package/dist/autopage-DkjYZUFD.js +0 -423
- package/dist/autopage-DkjYZUFD.js.map +0 -1
- package/dist/diagnostics-Du_s75MT.d.ts +0 -829
- package/dist/diagnostics-Du_s75MT.d.ts.map +0 -1
- package/dist/errors-Bvln0H-7.js.map +0 -1
- package/dist/errors-PflMPWBn.d.ts +0 -182
- package/dist/errors-PflMPWBn.d.ts.map +0 -1
- package/dist/fit-BKs0zxMI.js.map +0 -1
- package/dist/html-dom-B0I0QSbU.js.map +0 -1
- package/dist/namespaces-BVnNu7sg.js +0 -666
- package/dist/namespaces-BVnNu7sg.js.map +0 -1
- package/dist/notes-RLCwdlTE.js +0 -1703
- package/dist/notes-RLCwdlTE.js.map +0 -1
- package/dist/package-CaOLXSNi.d.ts.map +0 -1
- package/dist/pres-C5__xkDh.d.ts +0 -202
- package/dist/pres-C5__xkDh.d.ts.map +0 -1
- package/dist/presentation-Cp7vzlAw.js.map +0 -1
- package/dist/presentation-types-DP_8jog7.d.ts.map +0 -1
- package/dist/shapes-BemroU-z.js.map +0 -1
- package/dist/slide-js0QpRV-.d.ts.map +0 -1
- package/dist/text-CyetbF6p.js +0 -11278
- package/dist/text-CyetbF6p.js.map +0 -1
- package/dist/units-1kRzYShk.js +0 -231
- package/dist/units-1kRzYShk.js.map +0 -1
- package/dist/units-internal-Dg95w_YD.js.map +0 -1
- package/dist/zip.d.ts.map +0 -1
- package/dist/zip.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"presentation-Cp7vzlAw.js","names":["#defaults","#overrides","#dirty","textDecoder","textEncoder","#bytes","#dom","#dirty","#byId","#dirty","textEncoder","#parts","#contentTypesBytes","#relationshipsCache","#flushRelationships","#clrScheme","#themeElements","#cNvPr","#themeContext","#themeContext","#spTree","#byType","textEncoder","textEncoder","childTnLst","#themeColors","#cSld","#spTree","#nextShapeId","#appendShape","textEncoder","#presentationPart","#insertSlidePart","#importContext","#rescaledParts","#importRegistry","#nextSlideId"],"sources":["../src/read/opc/content-types.ts","../src/read/opc/part.ts","../src/read/opc/relationships.ts","../src/read/opc/package.ts","../src/read/api/ops/flatten.ts","../src/read/api/slide-background.ts","../src/read/api/chrome.ts","../src/read/api/notes.ts","../src/read/api/ops/deck-target.ts","../src/read/api/ops/master-registry.ts","../src/read/api/ops/page-owned.ts","../src/read/api/ops/part-reuse.ts","../src/read/api/ops/part-copy.ts","../src/read/api/ops/notes-master.ts","../src/read/api/ops/notes-author.ts","../src/read/api/comments.ts","../src/read/api/tags.ts","../src/read/api/transition.ts","../src/read/api/animation.ts","../src/read/api/slide.ts","../src/read/api/document-properties.ts","../src/read/api/ops/rescale.ts","../src/read/api/ops/table-styles.ts","../src/read/api/ops/carried-rels.ts","../src/read/api/ops/embedded-fonts.ts","../src/read/api/ops/flatten-context.ts","../src/read/api/ops/part-index.ts","../src/read/api/ops/import-slide.ts","../src/read/api/ops/prune.ts","../src/read/api/ops/rescale-import.ts","../src/read/api/presentation.ts"],"sourcesContent":["import { escapeXmlAttribute, getElements, parseXml } from '../oxml/dom.js'\nimport { partNameExtension } from './partnames.js'\nimport { PackageReadError } from '../../errors.js'\n\n/**\n * Overlay over `[Content_Types].xml`, used to resolve part content types at\n * load and to register new ones when parts are added. While clean, the original\n * bytes pass through verbatim on save (byte-identical); once a mutation marks it\n * dirty, `OpcPackage.save()` writes `serialize()` instead.\n */\nexport class ContentTypes {\n\t#defaults = new Map<string, string>()\n\t#overrides = new Map<string, string>()\n\t#dirty = false\n\n\tstatic parse(xml: string): ContentTypes {\n\t\tconst contentTypes = new ContentTypes()\n\t\tconst types = parseXml(xml).documentElement\n\t\tif (!types || types.localName !== 'Types')\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/content-types-invalid-root',\n\t\t\t\t'[Content_Types].xml: expected <Types> root element'\n\t\t\t)\n\t\tfor (const element of getElements(types, 'ct:Default')) {\n\t\t\tconst extension = element.getAttribute('Extension')\n\t\t\tconst contentType = element.getAttribute('ContentType')\n\t\t\tif (!extension || !contentType)\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/content-types-entry-incomplete',\n\t\t\t\t\t'[Content_Types].xml: <Default> missing Extension or ContentType'\n\t\t\t\t)\n\t\t\tcontentTypes.#defaults.set(extension.toLowerCase(), contentType)\n\t\t}\n\t\tfor (const element of getElements(types, 'ct:Override')) {\n\t\t\tconst partName = element.getAttribute('PartName')\n\t\t\tconst contentType = element.getAttribute('ContentType')\n\t\t\tif (!partName || !contentType)\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/content-types-entry-incomplete',\n\t\t\t\t\t'[Content_Types].xml: <Override> missing PartName or ContentType'\n\t\t\t\t)\n\t\t\tcontentTypes.#overrides.set(partName, contentType)\n\t\t}\n\t\treturn contentTypes\n\t}\n\n\t/** Exact `Override` match first, else `Default` by lowercased extension. */\n\tcontentTypeFor(partName: string): string | undefined {\n\t\treturn this.#overrides.get(partName) ?? this.#defaults.get(partNameExtension(partName))\n\t}\n\n\t/** True once a registration changed the overlay; `serialize()` is then authoritative. */\n\tget isDirty(): boolean {\n\t\treturn this.#dirty\n\t}\n\n\t/**\n\t * Ensure `partName` resolves to `contentType`, adding the minimum needed.\n\t * A no-op when an existing `Default`/`Override` already resolves it to the\n\t * same type; otherwise an `Override` is added (always valid, never conflicts\n\t * with a differing `Default`).\n\t */\n\tensureRegistered(partName: string, contentType: string): void {\n\t\tif (this.contentTypeFor(partName) === contentType) return\n\t\tthis.#overrides.set(partName, contentType)\n\t\tthis.#dirty = true\n\t}\n\n\t/**\n\t * Drop the `Override` for `partName` if present (e.g. when a part is removed).\n\t * `Default` rules by extension are left untouched — they may still serve other\n\t * parts. Marks the overlay dirty when something was removed.\n\t */\n\tremoveOverride(partName: string): void {\n\t\tif (this.#overrides.delete(partName)) this.#dirty = true\n\t}\n\n\t/** Register a `Default` content type for a (lowercased) extension if absent. */\n\tensureDefault(extension: string, contentType: string): void {\n\t\tconst ext = extension.toLowerCase()\n\t\tif (this.#defaults.get(ext) === contentType) return\n\t\tthis.#defaults.set(ext, contentType)\n\t\tthis.#dirty = true\n\t}\n\n\tserialize(): string {\n\t\tconst lines: string[] = [\n\t\t\t'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>',\n\t\t\t'<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">',\n\t\t]\n\t\tfor (const [extension, contentType] of this.#defaults) {\n\t\t\tlines.push(\n\t\t\t\t`<Default Extension=\"${escapeXmlAttribute(extension)}\" ContentType=\"${escapeXmlAttribute(contentType)}\"/>`\n\t\t\t)\n\t\t}\n\t\tfor (const [partName, contentType] of this.#overrides) {\n\t\t\tlines.push(\n\t\t\t\t`<Override PartName=\"${escapeXmlAttribute(partName)}\" ContentType=\"${escapeXmlAttribute(contentType)}\"/>`\n\t\t\t)\n\t\t}\n\t\tlines.push('</Types>')\n\t\treturn lines.join('')\n\t}\n}\n","import { parseXml, serializeXml, type Document } from '../oxml/dom.js'\nimport { InvalidOptionError } from '../../errors.js'\n\nconst textDecoder = new TextDecoder('utf-8')\nconst textEncoder = new TextEncoder()\n\nconst XML_DECLARATION_RE = /^\\uFEFF?<\\?xml[^>]*\\?>\\s*/\n\n/**\n * One OPC part. Holds the original bytes from the zip for its whole life;\n * parses to a DOM only on demand; serializes back to the original bytes\n * unless something mutated the DOM and called `markDirty()`.\n *\n * Untouched parts therefore round-trip byte-identically.\n */\nexport class Part {\n\treadonly partName: string\n\treadonly contentType: string\n\t#bytes: Uint8Array\n\t#dom: Document | null = null\n\t#dirty = false\n\n\tconstructor(partName: string, contentType: string, bytes: Uint8Array) {\n\t\tthis.partName = partName\n\t\tthis.contentType = contentType\n\t\tthis.#bytes = bytes\n\t}\n\n\t/** Whether this part's body is XML (by content type). */\n\tget isXmlPart(): boolean {\n\t\treturn (\n\t\t\tthis.contentType.endsWith('+xml') || this.contentType === 'application/xml' || this.contentType === 'text/xml'\n\t\t)\n\t}\n\n\t/** True once the body has been materialized as a DOM. */\n\tget isParsed(): boolean {\n\t\treturn this.#dom !== null\n\t}\n\n\t/** The original bytes from the package. Do not mutate. */\n\tget bytes(): Uint8Array {\n\t\treturn this.#bytes\n\t}\n\n\t/**\n\t * Lazily parsed DOM for XML parts. Parsing alone does not mark the part\n\t * dirty; call `markDirty()` after mutating the tree.\n\t */\n\tget dom(): Document {\n\t\tif (!this.isXmlPart)\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'part/not-xml',\n\t\t\t\t`Part ${this.partName} (${this.contentType}) is not an XML part and has no DOM`\n\t\t\t)\n\t\tif (!this.#dom) this.#dom = parseXml(textDecoder.decode(this.#bytes))\n\t\treturn this.#dom\n\t}\n\n\t/** Call after mutating the DOM so `serialize()` reserializes this part. */\n\tmarkDirty(): void {\n\t\tif (!this.isXmlPart)\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'part/not-xml',\n\t\t\t\t`Part ${this.partName} (${this.contentType}) is not an XML part and cannot be marked dirty`\n\t\t\t)\n\t\tthis.#dirty = true\n\t}\n\n\tget isDirty(): boolean {\n\t\treturn this.#dirty\n\t}\n\n\t/**\n\t * Bytes to write on save: the original bytes when clean (byte-identical),\n\t * the serialized DOM when dirty (semantically equivalent, schema-valid).\n\t */\n\tserialize(): Uint8Array {\n\t\tif (!this.#dirty) return this.#bytes\n\t\tlet xml = serializeXml(this.dom)\n\t\tif (!xml.startsWith('<?xml')) {\n\t\t\tconst declaration = XML_DECLARATION_RE.exec(textDecoder.decode(this.#bytes))?.[0]\n\t\t\txml = (declaration ?? '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\r\\n') + xml\n\t\t}\n\t\treturn textEncoder.encode(xml)\n\t}\n}\n","import { escapeXmlAttribute, getElements, parseXml } from '../oxml/dom.js'\nimport { resolveRelativePartName } from './partnames.js'\nimport { InvalidOptionError, PackageReadError } from '../../errors.js'\n\nexport interface Relationship {\n\tid: string\n\ttype: string\n\ttarget: string\n\ttargetMode?: 'Internal' | 'External'\n}\n\n/**\n * Overlay over one `.rels` part, keyed by relationship id. While clean, the\n * `.rels` bytes pass through verbatim on save (byte-identical); once `add()`\n * (or another mutation) marks it dirty, `OpcPackage.save()` writes\n * `serialize()` into the owning `.rels` part instead.\n */\nexport class Relationships {\n\t/** Partname of the part owning these relationships ('/' for package-level). */\n\treadonly sourcePartName: string\n\t#byId = new Map<string, Relationship>()\n\t#dirty = false\n\n\tprivate constructor(sourcePartName: string) {\n\t\tthis.sourcePartName = sourcePartName\n\t}\n\n\t/**\n\t * @param xml body of the `.rels` part\n\t * @param sourcePartName partname of the owning part ('/' for `/_rels/.rels`)\n\t */\n\tstatic parse(xml: string, sourcePartName: string): Relationships {\n\t\tconst relationships = new Relationships(sourcePartName)\n\t\tconst root = parseXml(xml).documentElement\n\t\tif (!root || root.localName !== 'Relationships')\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/relationships-invalid-root',\n\t\t\t\t`Relationships of ${sourcePartName}: expected <Relationships> root element`\n\t\t\t)\n\t\tfor (const element of getElements(root, 'pr:Relationship')) {\n\t\t\tconst id = element.getAttribute('Id')\n\t\t\tconst type = element.getAttribute('Type')\n\t\t\tconst target = element.getAttribute('Target')\n\t\t\tif (!id || !type || !target)\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/relationship-incomplete',\n\t\t\t\t\t`Relationships of ${sourcePartName}: <Relationship> missing Id, Type, or Target`\n\t\t\t\t)\n\t\t\tconst targetModeAttribute = element.getAttribute('TargetMode')\n\t\t\tconst targetMode =\n\t\t\t\ttargetModeAttribute === 'Internal' || targetModeAttribute === 'External' ? targetModeAttribute : undefined\n\t\t\tif (targetModeAttribute !== null && targetMode === undefined) {\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/relationship-invalid-target-mode',\n\t\t\t\t\t`Relationships of ${sourcePartName}: invalid TargetMode \"${targetModeAttribute}\" on ${id}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst relationship: Relationship = { id, type, target }\n\t\t\tif (targetMode) relationship.targetMode = targetMode\n\t\t\tif (relationships.#byId.has(id))\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/duplicate-relationship-id',\n\t\t\t\t\t`Relationships of ${sourcePartName}: duplicate relationship id ${id}`\n\t\t\t\t)\n\t\t\trelationships.#byId.set(id, relationship)\n\t\t}\n\t\treturn relationships\n\t}\n\n\t/** Empty relationship set (for parts that have no `.rels`). */\n\tstatic empty(sourcePartName: string): Relationships {\n\t\treturn new Relationships(sourcePartName)\n\t}\n\n\tget size(): number {\n\t\treturn this.#byId.size\n\t}\n\n\t/** True once a relationship was added/changed; `serialize()` is then authoritative. */\n\tget isDirty(): boolean {\n\t\treturn this.#dirty\n\t}\n\n\t/**\n\t * Add a relationship and return it. Allocates an id `rId<n>` with `n` one\n\t * past the highest existing numeric id. `target` is relative to the source\n\t * part's directory for internal targets (e.g. `../media/image1.png`), or an\n\t * absolute URI for external ones. Marks this set dirty.\n\t */\n\tadd(type: string, target: string, targetMode?: 'Internal' | 'External'): Relationship {\n\t\tlet max = 0\n\t\tfor (const id of this.#byId.keys()) {\n\t\t\tconst match = /^rId(\\d+)$/.exec(id)\n\t\t\tif (match) max = Math.max(max, Number(match[1]))\n\t\t}\n\t\tconst id = `rId${max + 1}`\n\t\tconst relationship: Relationship = { id, type, target }\n\t\tif (targetMode) relationship.targetMode = targetMode\n\t\tthis.#byId.set(id, relationship)\n\t\tthis.#dirty = true\n\t\treturn relationship\n\t}\n\n\t/**\n\t * Add a relationship under a caller-chosen id and return it. Used when\n\t * rebuilding a copied part's relationships across a package boundary: keeping\n\t * each source id lets the copied part body's `r:id`/`r:embed` references stay\n\t * valid without rewriting the body. Throws if the id is already present.\n\t * Marks this set dirty.\n\t */\n\taddWithId(id: string, type: string, target: string, targetMode?: 'Internal' | 'External'): Relationship {\n\t\tif (this.#byId.has(id))\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'relationship/duplicate-id',\n\t\t\t\t`Relationships of ${this.sourcePartName}: duplicate relationship id ${id}`\n\t\t\t)\n\t\tconst relationship: Relationship = { id, type, target }\n\t\tif (targetMode) relationship.targetMode = targetMode\n\t\tthis.#byId.set(id, relationship)\n\t\tthis.#dirty = true\n\t\treturn relationship\n\t}\n\n\t/**\n\t * Remove the relationship with `id` and return whether one was present. Used\n\t * when a referenced part is deleted (e.g. removing a slide drops the\n\t * presentation→slide relationship). Marks this set dirty when it removes one.\n\t */\n\tremove(id: string): boolean {\n\t\tconst removed = this.#byId.delete(id)\n\t\tif (removed) this.#dirty = true\n\t\treturn removed\n\t}\n\n\tget(id: string): Relationship | undefined {\n\t\treturn this.#byId.get(id)\n\t}\n\n\tbyType(type: string): Relationship[] {\n\t\treturn [...this.#byId.values()].filter((relationship) => relationship.type === type)\n\t}\n\n\t[Symbol.iterator](): IterableIterator<Relationship> {\n\t\treturn this.#byId.values()\n\t}\n\n\t/** Resolve an internal relationship's target to an absolute partname. */\n\tresolveTarget(id: string): string {\n\t\tconst relationship = this.#byId.get(id)\n\t\tif (!relationship)\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'relationship/not-found',\n\t\t\t\t`Relationships of ${this.sourcePartName}: no relationship with id ${id}`\n\t\t\t)\n\t\tif (relationship.targetMode === 'External') {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'relationship/external-has-no-partname',\n\t\t\t\t`Relationships of ${this.sourcePartName}: ${id} is External (${relationship.target}) and has no partname`\n\t\t\t)\n\t\t}\n\t\treturn resolveRelativePartName(this.sourcePartName, relationship.target)\n\t}\n\n\tserialize(): string {\n\t\tconst lines: string[] = [\n\t\t\t'<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>',\n\t\t\t'<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\">',\n\t\t]\n\t\tfor (const { id, type, target, targetMode } of this.#byId.values()) {\n\t\t\tconst mode = targetMode ? ` TargetMode=\"${targetMode}\"` : ''\n\t\t\tlines.push(\n\t\t\t\t`<Relationship Id=\"${escapeXmlAttribute(id)}\" Type=\"${escapeXmlAttribute(type)}\" Target=\"${escapeXmlAttribute(target)}\"${mode}/>`\n\t\t\t)\n\t\t}\n\t\tlines.push('</Relationships>')\n\t\treturn lines.join('')\n\t}\n}\n","import { ZipWriter, readZip } from '../../zip.js'\nimport { ContentTypes } from './content-types.js'\nimport { Part } from './part.js'\nimport { Relationships } from './relationships.js'\nimport { partNameToZipPath, relsPartNameFor, zipPathToPartName } from './partnames.js'\nimport { InvalidOptionError, PackageReadError } from '../../errors.js'\n\n/**\n * Input to {@link OpcPackage.load}. A `string` is a **filesystem path** (Node)\n * read from disk; pass `Uint8Array`/`ArrayBuffer`/`Blob`/`number[]` for an\n * in-memory archive. (A string is a path, not JSZip's latin1 binary content.)\n */\nexport type OpcInput = string | number[] | Uint8Array | ArrayBuffer | Blob\n\nconst CONTENT_TYPES_ZIP_PATH = '[Content_Types].xml'\nconst RELATIONSHIPS_CONTENT_TYPE = 'application/vnd.openxmlformats-package.relationships+xml'\n\nconst textDecoder = new TextDecoder('utf-8')\nconst textEncoder = new TextEncoder()\n\n/**\n * An OPC package loaded from `.pptx` bytes.\n *\n * Fidelity contract: parts that are never mutated (`Part.markDirty()`) are\n * written back byte-identically by `save()`. Whole-zip byte-identity is not\n * promised — zip metadata and compression may differ — but part bodies, the\n * part-name set, and part order are preserved.\n */\nexport class OpcPackage {\n\t/** All parts, keyed by partname (e.g. `/ppt/slides/slide1.xml`), in original zip order. */\n\t#parts: Map<string, Part>\n\t/** Content-type resolution + registration overlay. */\n\treadonly contentTypes: ContentTypes\n\t#contentTypesBytes: Uint8Array\n\t#relationshipsCache = new Map<string, Relationships>()\n\n\tprivate constructor(parts: Map<string, Part>, contentTypes: ContentTypes, contentTypesBytes: Uint8Array) {\n\t\tthis.#parts = parts\n\t\tthis.contentTypes = contentTypes\n\t\tthis.#contentTypesBytes = contentTypesBytes\n\t}\n\n\t/** All parts, keyed by partname, in zip/add order. */\n\tget parts(): ReadonlyMap<string, Part> {\n\t\treturn this.#parts\n\t}\n\n\tstatic async load(input: OpcInput): Promise<OpcPackage> {\n\t\tconst entries = await readZip(input)\n\t\tconst contentTypesBytes = entries.get(CONTENT_TYPES_ZIP_PATH)\n\t\tif (!contentTypesBytes)\n\t\t\tthrow new PackageReadError('package/not-an-opc-package', 'Not an OPC package: missing [Content_Types].xml')\n\t\tconst contentTypes = ContentTypes.parse(textDecoder.decode(contentTypesBytes))\n\n\t\tconst parts = new Map<string, Part>()\n\t\tfor (const [zipPath, bytes] of entries) {\n\t\t\tif (zipPath === CONTENT_TYPES_ZIP_PATH) continue\n\t\t\tconst partName = zipPathToPartName(zipPath)\n\t\t\t// PowerPoint leaves deleted parts in a `[trash]` folder that is not\n\t\t\t// registered in [Content_Types].xml and is referenced by nothing. These\n\t\t\t// are inert artifacts (common in real-world authored decks); drop them on\n\t\t\t// load rather than failing, so the package model holds only live parts.\n\t\t\tif (partName.startsWith('/[trash]/')) continue\n\t\t\tconst contentType = contentTypes.contentTypeFor(partName)\n\t\t\tif (!contentType) {\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/part-content-type-missing',\n\t\t\t\t\t`No content type for part ${partName}: [Content_Types].xml has no matching Override or Default`\n\t\t\t\t)\n\t\t\t}\n\t\t\tparts.set(partName, new Part(partName, contentType, bytes))\n\t\t}\n\t\treturn new OpcPackage(parts, contentTypes, contentTypesBytes)\n\t}\n\n\tpart(partName: string): Part | undefined {\n\t\treturn this.parts.get(partName)\n\t}\n\n\tpartsByContentType(contentType: string): Part[] {\n\t\treturn [...this.parts.values()].filter((part) => part.contentType === contentType)\n\t}\n\n\t/**\n\t * Relationships owned by a part ('/' for the package-level\n\t * `/_rels/.rels`). Parts without a `.rels` part get an empty set.\n\t */\n\trelationshipsFor(sourcePartName = '/'): Relationships {\n\t\tconst cached = this.#relationshipsCache.get(sourcePartName)\n\t\tif (cached) return cached\n\t\tconst relsPart = this.parts.get(relsPartNameFor(sourcePartName))\n\t\tconst relationships = relsPart\n\t\t\t? Relationships.parse(textDecoder.decode(relsPart.bytes), sourcePartName)\n\t\t\t: Relationships.empty(sourcePartName)\n\t\tthis.#relationshipsCache.set(sourcePartName, relationships)\n\t\treturn relationships\n\t}\n\n\t/**\n\t * Add a new part and register its content type (`ensureRegistered`), so the\n\t * package stays consistent. Throws if the partname is already taken.\n\t */\n\taddPart(partName: string, contentType: string, bytes: Uint8Array): Part {\n\t\tif (this.#parts.has(partName))\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'package/duplicate-part-name',\n\t\t\t\t`Cannot add part ${partName}: a part with that name already exists`\n\t\t\t)\n\t\tthis.contentTypes.ensureRegistered(partName, contentType)\n\t\tconst part = new Part(partName, contentType, bytes)\n\t\tthis.#parts.set(partName, part)\n\t\treturn part\n\t}\n\n\t/**\n\t * Remove a part and return whether it existed. Drops its `Override` content-type\n\t * registration and any cached relationship set it owned, so a later `save()`\n\t * neither re-emits it nor flushes a stale `.rels` for it. Low-level: it does not\n\t * touch references *to* this part (dangling rels are the caller's concern) nor\n\t * cascade to parts this one referenced — see {@link Presentation.removeSlide}\n\t * for the slide-aware variant that unwires the presentation and prunes orphans.\n\t */\n\tremovePart(partName: string): boolean {\n\t\tif (!this.#parts.delete(partName)) return false\n\t\tthis.contentTypes.removeOverride(partName)\n\t\t// Cache is keyed by owning part; clearing it stops a stale set being flushed.\n\t\tthis.#relationshipsCache.delete(partName)\n\t\treturn true\n\t}\n\n\t/**\n\t * Reserve an unused media partname `/ppt/media/<base><n>.<ext>` (n one past\n\t * the highest existing index for that base). Does not create the part.\n\t */\n\treserveMediaPartName(extension: string, base = 'image'): string {\n\t\tconst ext = extension.toLowerCase().replace(/^\\./, '')\n\t\tconst re = new RegExp(`^/ppt/media/${base}(\\\\d+)\\\\.${ext}$`, 'i')\n\t\tlet max = 0\n\t\tfor (const partName of this.#parts.keys()) {\n\t\t\tconst match = re.exec(partName)\n\t\t\tif (match) max = Math.max(max, Number(match[1]))\n\t\t}\n\t\treturn `/ppt/media/${base}${max + 1}.${ext}`\n\t}\n\n\t/**\n\t * Reserve an unused partname in the same directory and naming family as\n\t * `templatePartName`, with a fresh index one past the highest existing one.\n\t * The template's filename is split into a base (its stem minus any trailing\n\t * digits) and an extension, e.g. `/ppt/slideLayouts/slideLayout1.xml` →\n\t * `/ppt/slideLayouts/slideLayout<n>.xml`, `/ppt/media/image1.png` →\n\t * `/ppt/media/image<n>.png`. Used when copying a part in from another package.\n\t * Does not create the part.\n\t */\n\treservePartNameLike(templatePartName: string): string {\n\t\tconst slash = templatePartName.lastIndexOf('/')\n\t\tconst dir = templatePartName.slice(0, slash)\n\t\tconst fileName = templatePartName.slice(slash + 1)\n\t\tconst dot = fileName.lastIndexOf('.')\n\t\tconst ext = dot > 0 ? fileName.slice(dot) : '' // includes the leading '.'\n\t\tconst stem = dot > 0 ? fileName.slice(0, dot) : fileName\n\t\tconst base = stem.replace(/\\d+$/, '')\n\t\tconst escape = (s: string): string => s.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n\t\tconst re = new RegExp(`^${escape(`${dir}/${base}`)}(\\\\d+)${escape(ext)}$`)\n\t\tlet max = 0\n\t\tfor (const partName of this.#parts.keys()) {\n\t\t\tconst match = re.exec(partName)\n\t\t\tif (match) max = Math.max(max, Number(match[1]))\n\t\t}\n\t\treturn `${dir}/${base}${max + 1}${ext}`\n\t}\n\n\t/**\n\t * Re-emit the package. Clean parts are written from their original bytes;\n\t * dirty parts from their DOM. Dirty relationship sets and content types are\n\t * flushed first. Part order is preserved from load; added parts append.\n\t */\n\tasync save(): Promise<Uint8Array> {\n\t\tthis.#flushRelationships()\n\t\tconst zip = new ZipWriter()\n\t\tzip.add(CONTENT_TYPES_ZIP_PATH, this.contentTypes.isDirty ? this.contentTypes.serialize() : this.#contentTypesBytes)\n\t\tfor (const part of this.#parts.values()) {\n\t\t\tzip.add(partNameToZipPath(part.partName), part.serialize())\n\t\t}\n\t\treturn zip.toBytes()\n\t}\n\n\t/** Write each dirty `Relationships` set back into its `.rels` part (creating it if new). */\n\t#flushRelationships(): void {\n\t\tfor (const relationships of this.#relationshipsCache.values()) {\n\t\t\tif (!relationships.isDirty) continue\n\t\t\tconst relsPartName = relsPartNameFor(relationships.sourcePartName)\n\t\t\tconst bytes = textEncoder.encode(relationships.serialize())\n\t\t\t// Overwriting an existing key preserves its position in the Map.\n\t\t\tthis.#parts.set(relsPartName, new Part(relsPartName, RELATIONSHIPS_CONTENT_TYPE, bytes))\n\t\t}\n\t}\n}\n","/**\n * Baking a slide's theme dependencies into the slide itself, for `Presentation.importSlide` /\n * `importShape`.\n *\n * A slide imported into another deck is rebound to the *destination* master, so everything it\n * resolved symbolically against its own theme silently re-resolves against a different one — its\n * scheme colours change, its style-matrix fills change, its placeholders snap to different\n * geometry and type sizes. The `theme: 'preserve'` mode exists to stop that: each pass here\n * resolves a dependency against the **source** theme (via `read/oxml/theme.ts` and\n * `read/oxml/placeholder-inherit.ts`) and writes the answer explicitly onto the slide, so after\n * the rebind there is nothing left to re-resolve.\n *\n * What gets flattened, and why each one matters:\n *\n * 1. **`a:schemeClr` tokens** — rewritten to the literal `a:srgbClr` the source `clrMap` +\n * `clrScheme` produce. Child transforms (`lumMod`/`shade`/`alpha`/…) are carried through\n * untouched, so tints and shades render identically; only the *base* reference is swapped,\n * never the transform math.\n * 2. **Style-matrix refs** — a shape's `p:style` (`lnRef`/`fillRef`/`effectRef`) indexes the\n * theme `fmtScheme`; the indexed entry is resolved into an explicit `spPr` fill/line/effect\n * (with its `phClr` substituted) and the ref neutralized so it cannot re-resolve. The\n * `fontRef` is deliberately left intact so its font can re-bind to the destination theme —\n * the \"normalize fonts on attach\" bonus.\n * 3. **Placeholder-inherited run colour, size and weight** — a run that sets none of its own\n * takes them from the source placeholder → layout → master text-style chain. Rebinding\n * replaces that chain, so each is resolved from the source styles and written onto the run.\n * Typeface (`a:latin`) is deliberately *not* baked — it re-binds along with `fontRef`.\n * 4. **Placeholder-inherited geometry** — a placeholder with no own `a:xfrm` takes position and\n * size from the matching source layout/master placeholder; without baking it, a title snaps\n * to the destination default and often clips off-canvas.\n *\n * The `restyle` mode is the deliberate inverse ({@link restyleSlide}): it bakes *nothing*, so\n * everything re-resolves against the destination and the slide takes on the new brand.\n *\n * **Why this lives in `api/ops/` and not in `read/oxml/`.** Everything here *mutates* a live\n * part. The modules it calls into resolve and build detached elements but never write, which is\n * what lets the read model's getters share them; keeping the writes on this side of the line is\n * what keeps that true. Callers own marking the part dirty.\n */\nimport {\n\tOOXML_NS,\n\tattr,\n\tchildElements,\n\tcreateElement,\n\tdescendantsByTag,\n\tfirstChild,\n\tfirstChildElement,\n\tgetElements,\n\tgetOrAddChild,\n\tinsertInOrder,\n\tintValue,\n\townerDocumentOf,\n\tremoveChildrenByQName,\n\treplaceInParent,\n\tsetAttr,\n\ttype Element,\n} from '../../oxml/dom.js'\nimport { FILL_CHOICES } from '../../oxml/fill.js'\nimport {\n\tLST_STYLE_LEVELS,\n\tRUN_PROP_NAMES,\n\tplaceholderInheritedAnchor,\n\tplaceholderInheritedColor,\n\tplaceholderInheritedListStyles,\n\tplaceholderInheritedRunProps,\n\tplaceholderInheritedXfrm,\n\tplaceholderOf,\n\tslideDefinesColor,\n\tslideDefinesProp,\n\ttype RunProps,\n} from '../../oxml/placeholder-inherit.js'\nimport {\n\tSCHEME_SLOTS,\n\tfmtEntry,\n\tintAttr,\n\tisA,\n\tresolveColor,\n\tresolveSchemeToken,\n\tstyleRefFill,\n\tstyleRefLine,\n\tsubstitutePhClr,\n\ttype ColorContext,\n\ttype ResolvedColor,\n\ttype ThemeContext,\n} from '../../oxml/theme.js'\nimport {\n\tRPR_FILL_AFTER,\n\tSHAPE_AFTER_SPPR,\n\tSPPR_AFTER_XFRM,\n\tSPPR_EFFECT_AFTER,\n\tSPPR_FILL_AFTER,\n\tSPPR_LN_AFTER,\n\tSPPR_SCENE3D_AFTER,\n\tSPPR_SP3D_AFTER,\n} from '../../../ooxml/sequence.js'\nimport { cSldOf, nvPrOf } from '../../oxml/slide-dom.js'\n\n/**\n * A {@link ThemeContext} plus the one thing only the flatten pass needs to write from.\n *\n * It is separate from `ThemeContext` because every *other* consumer of a theme context — the\n * read model's colour, font and geometry getters — resolves against a source subgraph without\n * ever carrying a background to apply. Keeping the field here means those callers cannot be\n * handed one and quietly ignore it.\n */\nexport interface FlattenContext extends ThemeContext {\n\t/**\n\t * The slide's effective background inherited from the *source* `slideLayout`/`slideMaster`\n\t * (the raw `p:bg` element), or `null` when the slide carries its own. Applied onto the slide\n\t * before flattening so the background survives rebinding to the destination master.\n\t */\n\tinheritedBackground?: Element | null\n}\n\n/**\n * Flatten one slide's theme dependencies in place:\n *\n * 1. carry the background the slide inherited from its source layout/master onto\n * the slide (so it survives rebinding to a different master);\n * 2. materialize `p:bgRef` and style-matrix refs into explicit fills/lines/effects;\n * 3. bake each placeholder's effective geometry (inherited `a:xfrm`) onto the\n * shape so a rebind cannot move or resize it;\n * 4. bake each placeholder run's effective colour and size/weight (inherited from\n * the source layout/master text styles) explicitly onto the run;\n * 5. rewrite every remaining `a:schemeClr` to its literal `a:srgbClr`.\n *\n * Steps run in this order so the inherited/materialized backgrounds are present\n * before the final scheme-colour sweep resolves the colours they carry. The\n * placeholder geometry/colour/size passes have no data dependency on the others.\n * The caller marks the part dirty.\n */\nexport function flattenSlide(slideRoot: Element, ctx: FlattenContext): void {\n\tapplyInheritedBackground(slideRoot, ctx)\n\tmaterializeBackground(slideRoot, ctx)\n\tmaterializeStyleRefs(slideRoot, ctx)\n\tresolvePlaceholderGeometry(slideRoot, ctx)\n\tresolvePlaceholderRunColors(slideRoot, ctx)\n\tresolvePlaceholderRunSizes(slideRoot, ctx)\n\tresolveSchemeColors(slideRoot, ctx)\n}\n\n/**\n * Flatten a single lifted shape's theme dependencies in place — the shape-scoped\n * subset of {@link flattenSlide} used by `Presentation.importShape` `preserve`\n * mode. It runs every pass that resolves a *shape's* theme references against the\n * source theme (style-matrix refs, placeholder-inherited geometry/colour/size/\n * anchor/list-style, scheme colours) but deliberately **omits** the two\n * slide-scoped background passes (`applyInheritedBackground`/`materializeBackground`):\n * a background belongs to a slide, not to a shape being composed onto a foreign host.\n *\n * Unlike {@link flattenSlide}, this also **demotes** a lifted placeholder to a\n * plain shape ({@link demotePlaceholders}) once everything it inherited is baked.\n * A placeholder makes sense on its own slide, where it resolves against that deck's\n * master/layout; lifted onto a foreign host its surviving `p:ph` would re-resolve\n * against the *host* placeholder of the same type/idx (wrong inheritance, or a\n * fallback when absent) and could collide with the host's own placeholder. The\n * extra bakes here (anchor + list style, on top of the geometry/colour/size the\n * shared passes cover) make the shape self-contained so demotion loses nothing\n * visible. This is why the demotion is scoped to `flattenShape`: `flattenSlide`\n * keeps placeholders as placeholders by design.\n *\n * `shapeRoot` must be an element whose *descendants* include the lifted shape\n * (the passes match via `getElementsByTagNameNS`, which excludes the root element\n * itself) — the caller wraps the imported `p:sp`/`p:pic`/`p:graphicFrame`/`p:grpSp`\n * in a throwaway container before calling. The caller marks the part dirty.\n */\nexport function flattenShape(shapeRoot: Element, ctx: FlattenContext): void {\n\tmaterializeStyleRefs(shapeRoot, ctx)\n\tresolvePlaceholderGeometry(shapeRoot, ctx)\n\tresolvePlaceholderRunColors(shapeRoot, ctx)\n\tresolvePlaceholderRunSizes(shapeRoot, ctx)\n\tresolvePlaceholderBodyPr(shapeRoot, ctx)\n\tresolvePlaceholderListStyle(shapeRoot, ctx) // before resolveSchemeColors: cloned levels carry schemeClr\n\tresolveSchemeColors(shapeRoot, ctx)\n\tdemotePlaceholders(shapeRoot) // last: the passes above key on p:ph\n}\n\n/**\n * Restyle a rebound slide in place (the `theme: 'restyle'` mode): the exact\n * inverse of {@link flattenSlide}. It bakes *nothing* — leaving every\n * `a:schemeClr`/style-matrix ref and `p:bg` `bgRef` symbolic is the whole point,\n * so they re-resolve against the *destination* master's `clrMap` + theme once the\n * slide is rebound. The single mutation is dropping the slide's own colour-map\n * override (`p:clrMapOvr/a:overrideClrMapping`): a source override would keep\n * mapping the slide's scheme-token names the source way and defeat the re-brand,\n * so it must yield to the destination master's `p:clrMap`.\n *\n * Caveat carried from the plan: only *symbolic* colours re-brand. Anything the\n * source authored as a literal `a:srgbClr` has no theme reference to re-resolve\n * and stays exactly that colour. The caller marks the part dirty.\n */\nexport function restyleSlide(slideRoot: Element): void {\n\tremoveChildrenByQName(slideRoot, ['p:clrMapOvr'])\n}\n\n/**\n * The optional inverse of {@link resolveSchemeColors}, for `restyle`'s\n * force-remap-literals mode (the `Presentation.importSlide` `remapLiterals`\n * option). Every literal `a:srgbClr` whose value equals a *source* `clrScheme`\n * slot is rewritten back to a symbolic `a:schemeClr` so it re-resolves against the\n * destination theme; a literal matching no slot (the common case) is left exactly\n * as authored. Transform children (`lumMod`/`shade`/`alpha`/…) are carried across.\n *\n * Plain `restyle` cannot re-brand a literal — it carries no theme reference. This\n * re-introduces one by matching the literal's RGB against the slots the *source*\n * theme defined, emitting the scheme token that routes through the source `clrMap`\n * (so a literal equal to the source `accent1` slot becomes `schemeClr accent1`,\n * which the destination `clrMap`/theme then re-resolve). Slots are matched in\n * `clrScheme` order, so the first slot defining a given RGB wins when several share\n * it. Opt-in because it deliberately reinterprets authored literals as theme\n * colours — visual QA territory, the same caveat as the rest of `restyle`.\n */\nexport function remapLiteralColors(slideRoot: Element, ctx: ColorContext): void {\n\tconst slotByHex = reverseClrScheme(ctx.clrScheme)\n\tif (slotByHex.size === 0) return\n\tconst tokenBySlot = reverseClrMap(ctx.clrMap)\n\tconst doc = ownerDocumentOf(slideRoot)\n\tfor (const srgb of descendantsByTag(slideRoot, OOXML_NS.a, 'srgbClr')) {\n\t\tconst hex = attr(srgb, 'val')\n\t\tconst slot = hex ? slotByHex.get(hex.toUpperCase()) : undefined\n\t\tif (!slot) continue\n\t\tconst scheme = createElement(doc, 'a:schemeClr')\n\t\tsetAttr(scheme, 'val', tokenBySlot.get(slot) ?? slot) // route through the source clrMap; dk1/lt1/… are themselves valid tokens\n\t\twhile (srgb.firstChild) scheme.appendChild(srgb.firstChild) // carry transforms\n\t\treplaceInParent(srgb, scheme)\n\t}\n}\n\n/** Reverse a slot → RGB `clrScheme` into RGB → slot, in `SCHEME_SLOTS` order (first slot wins on a shared RGB). */\nfunction reverseClrScheme(clrScheme: Map<string, string>): Map<string, string> {\n\tconst out = new Map<string, string>()\n\tfor (const slot of SCHEME_SLOTS) {\n\t\tconst hex = clrScheme.get(slot)\n\t\tif (hex && !out.has(hex.toUpperCase())) out.set(hex.toUpperCase(), slot)\n\t}\n\treturn out\n}\n\n/** Reverse a token → slot `clrMap` into slot → token (first token wins on a shared slot). */\nfunction reverseClrMap(clrMap: Map<string, string>): Map<string, string> {\n\tconst out = new Map<string, string>()\n\tfor (const [token, slot] of clrMap) if (!out.has(slot)) out.set(slot, token)\n\treturn out\n}\n\n/**\n * If the slide has no own `p:bg`, insert (a copy of) the background it inherited\n * from its source layout/master as an explicit `p:cSld/p:bg`. The clone is left\n * unresolved here; the later passes flatten its `bgRef`/`schemeClr` in place.\n */\nfunction applyInheritedBackground(slideRoot: Element, ctx: FlattenContext): void {\n\tconst inherited = ctx.inheritedBackground\n\tif (!inherited) return\n\tconst cSld = cSldOf(slideRoot)\n\tif (!cSld || firstChild(cSld, 'p:bg')) return // no cSld, or the slide already owns a background\n\tconst doc = ownerDocumentOf(slideRoot)\n\tconst bg = doc.importNode(inherited, true)\n\tinsertInOrder(cSld, bg, ['p:spTree', 'p:custDataLst', 'p:controls', 'p:extLst'])\n}\n\n/**\n * Resolve every `p:bgRef` (theme-indexed background) under the slide into an\n * explicit `p:bgPr` fill, so the background no longer depends on the destination\n * theme's `fmtScheme`. A `bgPr` background is left for the scheme-colour sweep.\n */\nfunction materializeBackground(slideRoot: Element, ctx: FlattenContext): void {\n\tconst doc = ownerDocumentOf(slideRoot)\n\tfor (const bg of descendantsByTag(slideRoot, OOXML_NS.p, 'bg')) {\n\t\tconst bgRef = firstChild(bg, 'p:bgRef')\n\t\tif (!bgRef) continue\n\t\t// A `p:bgRef` is a `CT_StyleMatrixReference`, the same shape as a shape's\n\t\t// `a:fillRef`, so `styleRefFill` builds its resolved `fmtScheme` fill (phClr\n\t\t// already substituted). `null` (idx 0 / unresolved colour) → transparent.\n\t\tconst fill = styleRefFill(bgRef, ctx)\n\t\tconst bgPr = createElement(doc, 'p:bgPr')\n\t\tbgPr.appendChild(fill ?? createElement(doc, 'a:noFill'))\n\t\tbg.replaceChild(bgPr, bgRef)\n\t}\n}\n\n/** Rewrite every `a:schemeClr` under `root` to a literal `a:srgbClr` when resolvable. */\nfunction resolveSchemeColors(root: Element, ctx: FlattenContext): void {\n\tconst doc = ownerDocumentOf(root)\n\tfor (const schemeClr of descendantsByTag(root, OOXML_NS.a, 'schemeClr')) {\n\t\tconst token = attr(schemeClr, 'val')\n\t\tconst hex = token ? resolveSchemeToken(token, ctx) : null\n\t\tif (!hex) continue // phClr or an unmapped token — leave it for the destination theme.\n\t\tconst srgb = createElement(doc, 'a:srgbClr')\n\t\tsetAttr(srgb, 'val', hex)\n\t\twhile (schemeClr.firstChild) srgb.appendChild(schemeClr.firstChild) // carry transforms\n\t\treplaceInParent(schemeClr, srgb)\n\t}\n}\n\n/**\n * Bake placeholder-inherited run colours onto the slide. For each placeholder run\n * that defines no colour of its own (nor at paragraph/text-body level on the\n * *slide*), resolve the colour it would inherit from the source\n * `slideLayout`/`slideMaster` text styles and write it explicitly onto the run's\n * `a:rPr`. After this the run's colour cannot change when the slide is rebound to\n * the destination master. `a:fld` runs (dates, slide numbers) are treated like\n * `a:r`. Only colour is resolved; other inheritable run properties are left to\n * re-bind to the destination styles.\n */\nfunction resolvePlaceholderRunColors(slideRoot: Element, ctx: FlattenContext): void {\n\tbakePlaceholderRunProperty(slideRoot, ctx, placeholderInheritedColor, (run, color, pPr, slideLst, level) => {\n\t\tif (slideDefinesColor(run, pPr, slideLst, level)) return\n\t\twriteRunColor(run, color)\n\t})\n}\n\n/**\n * The traversal both run-property passes share: every placeholder shape's text body, every\n * paragraph in it, every `a:r` and `a:fld` in that paragraph.\n *\n * `resolve` is asked once per *list level* per shape and memoized, because walking the\n * layout/master style chain is the expensive half and every paragraph at the same level gets\n * the same answer. `write` then runs per run, and owns the decision to skip a run the slide\n * already fixes — the two passes ask that question differently (one colour check versus three\n * independent property checks), so it stays on their side of the boundary rather than becoming\n * a predicate parameter only one caller could use.\n *\n * @param slideRoot - the slide part's root element\n * @param ctx - the flatten context, carrying the source layout/master roots\n * @param resolve - the inherited value for a placeholder type/idx at a list level, or `null`\n * @param write - apply a resolved value to one run\n */\nfunction bakePlaceholderRunProperty<T>(\n\tslideRoot: Element,\n\tctx: FlattenContext,\n\tresolve: (type: string | null, idx: string, level: number, ctx: FlattenContext) => T | null,\n\twrite: (run: Element, value: T, pPr: Element | null, slideLst: Element | null, level: number) => void\n): void {\n\tif (!ctx.layoutRoot && !ctx.masterRoot) return\n\tfor (const sp of descendantsByTag(slideRoot, OOXML_NS.p, 'sp')) {\n\t\tconst ph = placeholderOf(sp)\n\t\tif (!ph) continue\n\t\tconst txBody = firstChild(sp, 'p:txBody')\n\t\tif (!txBody) continue\n\t\tconst type = attr(ph, 'type')\n\t\tconst idx = attr(ph, 'idx') ?? '0'\n\t\tconst slideLst = firstChild(txBody, 'a:lstStyle')\n\t\tconst byLevel = new Map<number, T | null>()\n\t\tfor (const p of getElements(txBody, 'a:p')) {\n\t\t\tconst pPr = firstChild(p, 'a:pPr')\n\t\t\tconst level = (pPr && intValue(attr(pPr, 'lvl'))) ?? 0\n\t\t\tconst runs = [...getElements(p, 'a:r'), ...getElements(p, 'a:fld')]\n\t\t\tif (runs.length === 0) continue\n\t\t\tlet value = byLevel.get(level)\n\t\t\tif (value === undefined) {\n\t\t\t\tvalue = resolve(type, idx, level, ctx)\n\t\t\t\tbyLevel.set(level, value)\n\t\t\t}\n\t\t\tif (!value) continue\n\t\t\tfor (const run of runs) write(run, value, pPr, slideLst, level)\n\t\t}\n\t}\n}\n\n/** Write a resolved colour as an explicit `a:solidFill` (with carried transforms) onto a run's `a:rPr`. */\nfunction writeRunColor(run: Element, color: ResolvedColor): void {\n\tconst doc = ownerDocumentOf(run)\n\tconst rPr = getOrAddChild(run, 'a:rPr', ['a:t'])\n\tconst fill = createElement(doc, 'a:solidFill')\n\tconst srgb = createElement(doc, 'a:srgbClr')\n\tsetAttr(srgb, 'val', color.hex)\n\tfor (const t of color.transforms) srgb.appendChild(t.cloneNode(true))\n\tfill.appendChild(srgb)\n\tinsertInOrder(rPr, fill, RPR_FILL_AFTER)\n}\n\n/**\n * Bake placeholder-inherited geometry onto the slide. A placeholder shape\n * that carries no own `p:spPr/a:xfrm` takes its position/size from the matching\n * source `slideLayout` placeholder, else the `slideMaster` placeholder. Rebinding\n * to the destination master replaces that inheritance, so the placeholder would\n * snap to the destination default (often clipping off-canvas). We deep-clone the\n * effective source `a:xfrm` and write it explicitly onto the shape. Shapes with\n * their own `a:xfrm` are left untouched (explicit geometry is not inherited), and\n * an orphan placeholder with no source match keeps the current fall-back behaviour.\n */\nfunction resolvePlaceholderGeometry(slideRoot: Element, ctx: FlattenContext): void {\n\tif (!ctx.layoutRoot && !ctx.masterRoot) return\n\tfor (const sp of descendantsByTag(slideRoot, OOXML_NS.p, 'sp')) {\n\t\tconst ph = placeholderOf(sp)\n\t\tif (!ph) continue\n\t\tconst spPr = firstChild(sp, 'p:spPr')\n\t\tif (spPr && firstChild(spPr, 'a:xfrm')) continue // explicit geometry is not inherited — leave it\n\t\tconst found = placeholderInheritedXfrm(attr(ph, 'type'), attr(ph, 'idx') ?? '0', ctx)\n\t\tif (!found) continue\n\t\tconst target = getOrAddChild(sp, 'p:spPr', SHAPE_AFTER_SPPR)\n\t\tinsertInOrder(target, found.xfrm.cloneNode(true), SPPR_AFTER_XFRM)\n\t}\n}\n\n/**\n * Bake the placeholder-inherited vertical anchor onto a lifted shape's text body\n * (the {@link flattenShape} placeholder-demotion path). A placeholder whose own\n * `a:bodyPr` sets no `@anchor` inherits it from the source layout/master placeholder;\n * once {@link demotePlaceholders} strips the `p:ph` the shape would lose that\n * inheritance and fall back to top-anchored, so a vertically-centred title jumps.\n * We resolve the effective anchor from the source chain and write it explicitly.\n * Shapes whose `a:bodyPr` already fixes `@anchor`, and placeholders with no\n * resolvable inherited anchor, are left untouched. Other `a:bodyPr` knobs (insets,\n * autofit) are left as authored — they have sane defaults a plain shape keeps.\n */\nfunction resolvePlaceholderBodyPr(shapeRoot: Element, ctx: FlattenContext): void {\n\tif (!ctx.layoutRoot && !ctx.masterRoot) return\n\tfor (const sp of descendantsByTag(shapeRoot, OOXML_NS.p, 'sp')) {\n\t\tconst ph = placeholderOf(sp)\n\t\tif (!ph) continue\n\t\tconst txBody = firstChild(sp, 'p:txBody')\n\t\tif (!txBody) continue\n\t\tconst bodyPr = firstChild(txBody, 'a:bodyPr')\n\t\tif (bodyPr && attr(bodyPr, 'anchor') != null) continue // slide fixes it — not inherited\n\t\tconst anchor = placeholderInheritedAnchor(attr(ph, 'type'), attr(ph, 'idx') ?? '0', ctx)\n\t\tif (!anchor) continue\n\t\tsetAttr(bodyPr ?? getOrAddChild(txBody, 'a:bodyPr', ['a:lstStyle', 'a:p']), 'anchor', anchor)\n\t}\n}\n\n/**\n * Bake the placeholder-inherited list style onto a lifted shape's text body (the\n * {@link flattenShape} placeholder-demotion path). A placeholder's per-level\n * *paragraph* formatting — indent (`marL`/`indent`), bullets (`a:buChar`/\n * `a:buAutoNum`/`a:buNone`), alignment, and the level `a:defRPr` — is inherited\n * from the source layout/master placeholder `a:lstStyle` and the master\n * `p:txStyles` category style. Run colour/size are baked onto each run by the\n * sibling passes, but paragraph-level defaults live here; once\n * {@link demotePlaceholders} strips the `p:ph` the shape stops inheriting them, so\n * bullets and indents would vanish. We materialize the effective list style onto\n * the shape's `p:txBody/a:lstStyle`.\n *\n * Resolution is per *level*, most specific tier wins whole: the slide's own level\n * (if it defines one) is kept verbatim, else the first source tier that defines it\n * (layout placeholder, then master placeholder, then master category style) is\n * cloned. This is a whole-element overlay, not the per-attribute merge PowerPoint\n * does — but explicit paragraph `a:pPr` on the slide's own runs travels with the\n * shape and still wins, so this only supplies defaults for the inherited case\n * (paragraphs that set no `a:pPr` of their own). Scheme colours in the cloned\n * levels are resolved by the later `resolveSchemeColors` pass.\n */\nfunction resolvePlaceholderListStyle(shapeRoot: Element, ctx: FlattenContext): void {\n\tif (!ctx.layoutRoot && !ctx.masterRoot) return\n\tfor (const sp of descendantsByTag(shapeRoot, OOXML_NS.p, 'sp')) {\n\t\tconst ph = placeholderOf(sp)\n\t\tif (!ph) continue\n\t\tconst txBody = firstChild(sp, 'p:txBody')\n\t\tif (!txBody) continue\n\t\tconst tiers = placeholderInheritedListStyles(attr(ph, 'type'), attr(ph, 'idx') ?? '0', ctx)\n\t\tif (tiers.length === 0) continue\n\t\tconst slideLst = firstChild(txBody, 'a:lstStyle')\n\t\tconst merged = createElement(ownerDocumentOf(txBody), 'a:lstStyle')\n\t\tlet any = false\n\t\tfor (const level of LST_STYLE_LEVELS) {\n\t\t\t// Slide's own level wins; otherwise the most-specific source tier that defines it.\n\t\t\tconst own = slideLst && firstChild(slideLst, level)\n\t\t\tconst src = own ?? tiers.map((t) => firstChild(t, level)).find((e): e is Element => !!e) ?? null\n\t\t\tif (!src) continue\n\t\t\tmerged.appendChild(src.cloneNode(true))\n\t\t\tany = true\n\t\t}\n\t\tif (!any) continue\n\t\tif (slideLst) txBody.replaceChild(merged, slideLst)\n\t\telse insertInOrder(txBody, merged, ['a:p'])\n\t}\n}\n\n/**\n * Strip the `p:ph` marker from every placeholder shape in a lifted subtree so it\n * becomes a self-contained ordinary shape (the {@link flattenShape} path only). By\n * the time this runs, the shape's inherited geometry, colour, run size, anchor, and\n * list style are all baked explicitly, so it no longer needs — and must not keep —\n * its placeholder identity: a surviving `p:ph` would re-resolve against the *host*\n * deck's layout/master placeholder of the same type/idx (wrong inheritance, or a\n * fallback when the host has none) and could collide with the host slide's own\n * placeholder of that type. Removing the marker severs both. The `p:nvPr` itself is\n * kept (it can carry media/custom-data children); only the `p:ph` child goes.\n */\nfunction demotePlaceholders(shapeRoot: Element): void {\n\tfor (const sp of descendantsByTag(shapeRoot, OOXML_NS.p, 'sp')) {\n\t\tconst nvPr = nvPrOf(sp)\n\t\tif (nvPr) removeChildrenByQName(nvPr, ['p:ph'])\n\t}\n}\n\n/**\n * Bake placeholder-inherited run size/weight onto the slide. Mirrors\n * {@link resolvePlaceholderRunColors}: for each placeholder run that sets no\n * `sz`/`b`/`i` of its own (nor at paragraph/text-body level on the *slide*),\n * resolve the value it would inherit from the source `slideLayout`/`slideMaster`\n * text styles — per paragraph list level — and write it explicitly onto the run's\n * `a:rPr`. Each property resolves independently up the chain. Typeface (`a:latin`)\n * is left to re-bind to the destination theme, as the colour pass does for the `fontRef`.\n */\nfunction resolvePlaceholderRunSizes(slideRoot: Element, ctx: FlattenContext): void {\n\tbakePlaceholderRunProperty(slideRoot, ctx, placeholderInheritedRunProps, writeRunProps)\n}\n\n/** Write each resolved run property onto a run's `a:rPr`, skipping ones the slide already fixes. */\nfunction writeRunProps(\n\trun: Element,\n\tprops: RunProps,\n\tpPr: Element | null,\n\tslideLst: Element | null,\n\tlevel: number\n): void {\n\tlet rPr: Element | null = null\n\tfor (const name of RUN_PROP_NAMES) {\n\t\tconst value = props[name]\n\t\tif (value == null) continue\n\t\tif (slideDefinesProp(name, run, pPr, slideLst, level)) continue\n\t\trPr ??= getOrAddChild(run, 'a:rPr', ['a:t'])\n\t\tsetAttr(rPr, name, value)\n\t}\n}\n\n/**\n * Resolve each shape's `p:style` `lnRef`/`fillRef`/`effectRef` into explicit\n * `spPr` children (using the theme `fmtScheme`), then neutralize the ref. The\n * `fontRef` is intentionally left for the destination theme to re-resolve.\n */\nfunction materializeStyleRefs(root: Element, ctx: FlattenContext): void {\n\tif (!ctx.fmtScheme) return\n\tfor (const style of descendantsByTag(root, OOXML_NS.p, 'style')) {\n\t\tconst shape = style.parentNode as Element | null\n\t\tif (!shape) continue\n\t\tconst spPr = getOrAddChild(shape, 'p:spPr', SHAPE_AFTER_SPPR)\n\t\tmaterializeFill(spPr, firstChild(style, 'a:fillRef'), ctx)\n\t\tmaterializeLine(spPr, firstChild(style, 'a:lnRef'), ctx)\n\t\tmaterializeEffect(spPr, firstChild(style, 'a:effectRef'), ctx)\n\t}\n}\n\nfunction materializeFill(spPr: Element, fillRef: Element | null, ctx: FlattenContext): void {\n\tif (!fillRef) return\n\tif (!FILL_CHOICES.some((q) => firstChild(spPr, q))) {\n\t\tconst fill = styleRefFill(fillRef, ctx)\n\t\tif (fill) insertInOrder(spPr, fill, SPPR_FILL_AFTER)\n\t}\n\tneutralizeRef(fillRef)\n}\n\nfunction materializeLine(spPr: Element, lnRef: Element | null, ctx: FlattenContext): void {\n\tif (!lnRef) return\n\tif (!firstChild(spPr, 'a:ln')) {\n\t\tconst ln = styleRefLine(lnRef, ctx)\n\t\tif (ln) insertInOrder(spPr, ln, SPPR_LN_AFTER)\n\t}\n\tneutralizeRef(lnRef)\n}\n\nfunction materializeEffect(spPr: Element, effectRef: Element | null, ctx: FlattenContext): void {\n\tif (!effectRef) return\n\tconst idx = intAttr(effectRef, 'idx')\n\tif (idx !== null && idx > 0 && !firstChild(spPr, 'a:effectLst') && !firstChild(spPr, 'a:effectDag')) {\n\t\tconst style = fmtEntry(ctx, 'a:effectStyleLst', idx) // a:effectStyle (effectLst?, scene3d?, sp3d?)\n\t\tconst ref = resolveColor(firstChildElement(effectRef), ctx)\n\t\tif (style && ref) {\n\t\t\tsubstitutePhClr(style, ref)\n\t\t\t// Lift the effectStyle's children (effectLst/scene3d/sp3d) into spPr, in order.\n\t\t\tfor (const child of childElements(style)) {\n\t\t\t\tif (isA(child, 'effectLst') || isA(child, 'effectDag')) insertInOrder(spPr, child, SPPR_EFFECT_AFTER)\n\t\t\t\telse if (isA(child, 'scene3d')) insertInOrder(spPr, child, SPPR_SCENE3D_AFTER)\n\t\t\t\telse if (isA(child, 'sp3d')) insertInOrder(spPr, child, SPPR_SP3D_AFTER)\n\t\t\t}\n\t\t}\n\t}\n\tneutralizeRef(effectRef)\n}\n\n/** Strip a style-matrix ref to `idx=\"0\"` with no colour child so it contributes nothing. */\nfunction neutralizeRef(ref: Element): void {\n\tsetAttr(ref, 'idx', '0')\n\tfor (const child of childElements(ref)) ref.removeChild(child)\n}\n","/**\n * Read a slide's effective background (`p:cSld/p:bg`), decoded into a typed union.\n *\n * A background lives on the slide itself, or is inherited from its slideLayout,\n * else its slideMaster — the {@link SlideBackground.source} field records which.\n * The writer authors solid-colour, gradient, and image backgrounds (all FAITHFUL);\n * pattern and theme-indexed (`p:bgRef`) backgrounds are read-only for imported\n * decks — surface them so a codegen pass can carry the part rather than fake it. A\n * `themeRef` additionally resolves its `idx` through the slide theme's `fmtScheme`\n * to a concrete {@link BackgroundFill} in `resolvedFill`, so a consumer can ask what\n * colour/gradient a theme-indexed background actually renders as.\n */\nimport {\n\tattr,\n\tcreateElement,\n\tfirstChild,\n\tfirstChildElement,\n\tintValue,\n\townerDocumentOf,\n\ttype Element,\n} from '../oxml/dom.js'\nimport { styleRefFill, type ThemeContext } from '../oxml/theme.js'\nimport type { Relationships } from '../opc/relationships.js'\nimport { resolveColorElement, type ResolvedColor } from './theme-context.js'\nimport { readGradientFill, type GradientFill } from './gradient.js'\nimport { readPictureFill, type PictureFill } from './picture-fill.js'\nimport { readPatternFill } from './pattern-fill.js'\nimport { cSldOf } from '../oxml/slide-dom.js'\n\n/** Where a slide's effective background comes from in the slide → layout → master chain. */\nexport type BackgroundSource = 'slide' | 'layout' | 'master'\n\n/**\n * An explicit background fill, decoded from a `p:bgPr` (or from a `p:bgRef`'s\n * resolved `fmtScheme` entry). The source-less core of {@link SlideBackground}: the\n * top-level variants add {@link BackgroundSource}, and it is what a `themeRef`'s\n * {@link SlideBackground.resolvedFill} carries.\n *\n * The `image` variant keeps `relId`/`partName` at the top level — the fields\n * callers already read — and adds the full {@link PictureFill} (stretch/tile\n * geometry, crop, alpha) under `picture`.\n */\nexport type BackgroundFill =\n\t| { type: 'solid'; color: ResolvedColor | null }\n\t| { type: 'gradient'; gradient: GradientFill }\n\t| { type: 'image'; picture: PictureFill; relId: string | null; partName: string | null }\n\t| { type: 'pattern'; preset: string | null; foreground: ResolvedColor | null; background: ResolvedColor | null }\n\t| { type: 'none' }\n\n/**\n * A slide's effective background (`p:cSld/p:bg`), as a discriminated union on\n * `type`. Every variant carries {@link BackgroundSource}. `solid`/`gradient`/`image`\n * are what the writer authors and round-trip faithfully; `pattern`/`themeRef` are\n * read-only (imported decks) and `none` is an explicit `a:noFill`. A `themeRef`\n * keeps its raw `idx` for fidelity and also exposes `resolvedFill` — the concrete\n * fill that `idx` resolves to through the slide theme's `fmtScheme` (`null` when the\n * theme/entry cannot be resolved).\n */\nexport type SlideBackground =\n\t| { type: 'solid'; source: BackgroundSource; color: ResolvedColor | null }\n\t| { type: 'gradient'; source: BackgroundSource; gradient: GradientFill }\n\t| { type: 'image'; source: BackgroundSource; picture: PictureFill; relId: string | null; partName: string | null }\n\t| {\n\t\t\ttype: 'pattern'\n\t\t\tsource: BackgroundSource\n\t\t\tpreset: string | null\n\t\t\tforeground: ResolvedColor | null\n\t\t\tbackground: ResolvedColor | null\n\t }\n\t| {\n\t\t\ttype: 'themeRef'\n\t\t\tsource: BackgroundSource\n\t\t\tidx: number | null\n\t\t\tcolor: ResolvedColor | null\n\t\t\tresolvedFill: BackgroundFill | null\n\t }\n\t| { type: 'none'; source: BackgroundSource }\n\n/** The `p:cSld/p:bg` element of a slide/layout/master root, or `null`. */\nexport function backgroundElementOf(root: Element | null): Element | null {\n\tconst cSld = cSldOf(root)\n\treturn cSld ? firstChild(cSld, 'p:bg') : null\n}\n\n/**\n * Decode a colour-bearing container (`p:bgPr`, or a synthetic wrapper around a\n * `fmtScheme` fill entry) into a {@link BackgroundFill}. `a:noFill`, an empty\n * container, or an unrecognized fill all read as `{ type: 'none' }`.\n */\nfunction decodeBackgroundFill(container: Element, ctx: ThemeContext, rels: Relationships | null): BackgroundFill {\n\tconst solid = firstChild(container, 'a:solidFill')\n\tif (solid) return { type: 'solid', color: resolveColorElement(firstChildElement(solid), ctx) }\n\n\tconst grad = firstChild(container, 'a:gradFill')\n\tif (grad) return { type: 'gradient', gradient: readGradientFill(container, ctx) as GradientFill }\n\n\tconst picture = readPictureFill(container, rels)\n\tif (picture) return { type: 'image', picture, relId: picture.relId, partName: picture.partName }\n\n\tconst patt = readPatternFill(container, ctx)\n\tif (patt) return { type: 'pattern', preset: patt.preset, foreground: patt.foreground, background: patt.background }\n\n\treturn { type: 'none' }\n}\n\n/**\n * Resolve a `p:bgRef`'s `idx` into the concrete {@link BackgroundFill} it renders\n * as, through the slide theme's `fmtScheme`. A `p:bgRef` is a\n * `CT_StyleMatrixReference` — the same shape as a shape's `a:fillRef` — so\n * {@link styleRefFill} builds the indexed `bgFillStyleLst`/`fillStyleLst` entry with\n * its `phClr` substituted by the bgRef's colour, and the resulting fill element is\n * decoded like a `p:bgPr`. `null` when the theme has no `fmtScheme`, the entry is\n * absent, or the colour cannot be resolved.\n *\n * `themeRels` — not the owning slide/layout/master's rels — is what an `a:blipFill`\n * entry's `r:embed` resolves against: the fill element is lifted out of the *theme*\n * part, so its relationship id is scoped to that part. Several stock Office themes\n * (Ion, Facet, …) put a picture in the third `bgFillStyleLst` slot, so a deck using\n * `p:bgRef idx=\"1003\"` hits this.\n */\nfunction resolveThemeRefFill(\n\tbgRef: Element,\n\tctx: ThemeContext,\n\tthemeRels: Relationships | null\n): BackgroundFill | null {\n\tconst fill = styleRefFill(bgRef, ctx)\n\tif (!fill) return null\n\t// Wrap the bare fill element (e.g. `a:gradFill`) in a synthetic container so the\n\t// same child-dispatch decode used for `p:bgPr` applies unchanged.\n\tconst wrapper = createElement(ownerDocumentOf(bgRef), 'p:bgPr')\n\twrapper.appendChild(fill)\n\treturn decodeBackgroundFill(wrapper, ctx, themeRels)\n}\n\n/**\n * Decode a `p:bg` element into a {@link SlideBackground}. `ctx` resolves colour\n * tokens and (for a `themeRef`) the theme `fmtScheme`; `rels` (the *owning* part's\n * relationships) resolves an image background's `r:embed` to an absolute part name.\n *\n * `themeRels` is the theme part's own relationships, used only for a `themeRef`'s\n * {@link SlideBackground.resolvedFill}: that fill comes out of the theme part, so an\n * image entry's `r:embed` is scoped to the theme, not to `rels`.\n */\nexport function readSlideBackground(\n\tbg: Element,\n\tsource: BackgroundSource,\n\tctx: ThemeContext,\n\trels: Relationships | null,\n\tthemeRels: Relationships | null\n): SlideBackground {\n\t// A background is either a `p:bgPr` (explicit fill) or a `p:bgRef` (theme-indexed).\n\tconst bgRef = firstChild(bg, 'p:bgRef')\n\tif (bgRef) {\n\t\treturn {\n\t\t\ttype: 'themeRef',\n\t\t\tsource,\n\t\t\tidx: intValue(attr(bgRef, 'idx')),\n\t\t\tcolor: resolveColorElement(firstChildElement(bgRef), ctx),\n\t\t\tresolvedFill: resolveThemeRefFill(bgRef, ctx, themeRels),\n\t\t}\n\t}\n\n\tconst bgPr = firstChild(bg, 'p:bgPr')\n\tif (!bgPr) return { type: 'none', source }\n\n\t// `a:noFill` (or an empty/unrecognized bgPr) is an explicit transparent background.\n\tconst fill = decodeBackgroundFill(bgPr, ctx, rels)\n\treturn { ...fill, source }\n}\n","/**\n * Read-model proxies for a deck's shared *chrome* — the slide masters, slide\n * layouts, and themes reachable through the presentation → master → layout → theme\n * graph but owned by no single slide. A slide's concrete content is modeled by\n * {@link import('./slide.js').Slide}; this module models the property tiers a slide\n * *inherits* from: the theme's colour scheme and font scheme, the master's colour\n * map, and each master/layout placeholder's own geometry.\n *\n * The three parts form a chain — a {@link SlideLayout} resolves its {@link SlideMaster}\n * (which resolves its {@link Theme}) — and a {@link Slide} enters it through\n * `slide.layout`. Placeholders (master/layout `p:sp` shapes carrying a `p:ph`) are\n * modeled as {@link Placeholder}s: type/idx/name/id, own-`a:xfrm` geometry (EMU),\n * and a navigable {@link TextFrame}. Unlike a notes placeholder — whose geometry is\n * inherited and so reads `null` on an authored deck — a master/layout placeholder\n * carries its geometry explicitly, so position/size round-trip.\n *\n * A master's and a layout's *non*-placeholder content — the bands, rules, logos and\n * decorative furniture a template is recognized by — is reached through\n * {@link SlideMaster.shapes} / {@link SlideLayout.shapes}, which return the same\n * `AnyShape` union `Slide.shapes` does (both classes are {@link ShapeHost}s). Those\n * shapes carry the full paint surface — `resolvedFill`, `resolvedLine`,\n * `presetGeometry`, `rotation`, `absoluteFrame` — so a template renders, not merely\n * positions. `placeholders` remains the filtered convenience view over the same tree.\n *\n * A *slide* placeholder's effective inherited geometry against this chain resolves\n * via `Shape.resolvedFrame` (`shapes.ts`), the geometry sibling of the run\n * colour/size/face resolution already backed by `Slide.themeContext` → `Run.resolved*`.\n */\nimport type { OpcPackage } from '../opc/package.js'\nimport type { Part } from '../opc/part.js'\nimport type { Relationships } from '../opc/relationships.js'\nimport { attr, boolValue, firstChild, getElements, intValue, type Element } from '../oxml/dom.js'\nimport { parseClrMap, parseClrScheme, type ThemeContext } from '../oxml/theme.js'\nimport { resolveLayoutColorContext, resolveMasterColorContext } from './theme-context.js'\nimport { placeholderOf } from '../oxml/placeholder-inherit.js'\nimport { spPrXfrmEmu } from './shapes/oxml.js'\nimport { backgroundElementOf, readSlideBackground, type SlideBackground } from './slide-background.js'\nimport { buildShapes, findShapeByIdDeep, type AnyShape, type ShapeHost } from './shapes.js'\nimport { TextFrame } from './text.js'\nimport { SLIDE_MASTER_REL, THEME_REL } from '../../ooxml/rel-types.js'\nimport { cSldOf, spTreeOf } from '../oxml/slide-dom.js'\nimport { COLOR_MAP_TOKENS, THEME_COLOR_SLOTS, type ColorMapToken, type ThemeColorSlot } from '../../ooxml/st-enums.js'\n\n/**\n * The twelve theme colour slots and the twelve colour-map tokens that point at them, plus\n * the tuples this module iterates. Both are schema vocabulary shared with the write half\n * (`gen/slide/master.ts` emits the identity map, `script/from-read` recognises it), so they\n * are declared in `ooxml/st-enums.ts` and re-exported here to keep `ts-pptx/read`'s surface\n * unchanged.\n */\nexport type { ThemeColorSlot, ColorMapToken }\n\n/**\n * One theme font family (`a:majorFont` or `a:minorFont`): the primary Latin face\n * plus the East-Asian and complex-script faces. Each is `null` when the theme\n * leaves that slot empty (`typeface=\"\"`, PowerPoint's default for `ea`/`cs`). The\n * per-script `<a:font>` fallback list is not decoded here.\n */\nexport interface ThemeFontFace {\n\t/** `<a:latin@typeface>` — the primary face (e.g. `Calibri Light`), or `null` when empty. */\n\tlatin: string | null\n\t/** `<a:ea@typeface>` — the East-Asian face, or `null` when empty. */\n\tea: string | null\n\t/** `<a:cs@typeface>` — the complex-script face, or `null` when empty. */\n\tcs: string | null\n}\n\n/** A theme's `a:fontScheme`: its name plus the major (heading) and minor (body) font families. */\nexport interface ThemeFontScheme {\n\t/** `<a:fontScheme@name>` (e.g. `Office`), or `null` when unnamed. */\n\tname: string | null\n\t/** The `a:majorFont` family — the heading (`+mj-*`) fonts. */\n\tmajor: ThemeFontFace\n\t/** The `a:minorFont` family — the body (`+mn-*`) fonts. */\n\tminor: ThemeFontFace\n}\n\n/** Read `<a:latin>`/`<a:ea>`/`<a:cs>` typefaces of a theme font family; empty string ⇒ `null`. */\nfunction readThemeFontFace(font: Element | null): ThemeFontFace {\n\tconst face = (child: string): string | null => {\n\t\tconst el = font && firstChild(font, child)\n\t\treturn (el && attr(el, 'typeface')) || null\n\t}\n\treturn { latin: face('a:latin'), ea: face('a:ea'), cs: face('a:cs') }\n}\n\n/**\n * A deck's theme part (`theme1.xml`) as a modeled object. Exposes the two property\n * tiers a slide resolves against: the {@link colorScheme} (the 12 `a:clrScheme`\n * slots as literal hex, `a:sysClr` resolved via its `lastClr`) and the\n * {@link fontScheme} (major/minor Latin/EA/CS faces). Reachable from\n * {@link SlideMaster.theme} and `Slide.theme`.\n */\nexport class Theme {\n\tconstructor(\n\t\t/** The theme's OPC part (`/ppt/theme/themeN.xml`). */\n\t\treadonly part: Part\n\t) {}\n\n\t/** Partname of the theme part. */\n\tget partName(): string {\n\t\treturn this.part.partName\n\t}\n\n\t/** Theme name (`a:theme/@name`, e.g. `Office Theme`), or `null` when unnamed. */\n\tget name(): string | null {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn root ? attr(root, 'name') : null\n\t}\n\n\t/** Colour-scheme name (`a:clrScheme/@name`, e.g. `Office`), or `null`. */\n\tget colorSchemeName(): string | null {\n\t\tconst clrScheme = this.#clrScheme()\n\t\treturn clrScheme ? attr(clrScheme, 'name') : null\n\t}\n\n\t/**\n\t * The theme colour scheme: the 12 {@link ThemeColorSlot}s resolved to a 6-hex RGB\n\t * (an `a:sysClr` slot resolves through its `lastClr`). A slot the theme does not\n\t * define reads `null`. Use {@link color} to look one slot up.\n\t */\n\tget colorScheme(): Record<ThemeColorSlot, string | null> {\n\t\tconst parsed = parseClrScheme(this.#clrScheme())\n\t\tconst out = {} as Record<ThemeColorSlot, string | null>\n\t\tfor (const slot of THEME_COLOR_SLOTS) out[slot] = parsed.get(slot) ?? null\n\t\treturn out\n\t}\n\n\t/** The 6-hex RGB of one colour-scheme slot, or `null` when the theme does not define it. */\n\tcolor(slot: ThemeColorSlot): string | null {\n\t\treturn parseClrScheme(this.#clrScheme()).get(slot) ?? null\n\t}\n\n\t/** The theme's `a:fontScheme` (major/minor font families), or `null` when the theme declares none. */\n\tget fontScheme(): ThemeFontScheme | null {\n\t\tconst themeElements = this.#themeElements()\n\t\tconst fontScheme = themeElements && firstChild(themeElements, 'a:fontScheme')\n\t\tif (!fontScheme) return null\n\t\treturn {\n\t\t\tname: attr(fontScheme, 'name'),\n\t\t\tmajor: readThemeFontFace(firstChild(fontScheme, 'a:majorFont')),\n\t\t\tminor: readThemeFontFace(firstChild(fontScheme, 'a:minorFont')),\n\t\t}\n\t}\n\n\t/** Escape hatch: the underlying `a:theme` element. After mutating it call {@link markDirty}, or `save()` writes the original bytes. */\n\tget element_(): Element | null {\n\t\treturn this.part.dom.documentElement\n\t}\n\n\t/** Mark the theme part dirty so `save()` reserializes it. Call after mutating {@link element_}. */\n\tmarkDirty(): void {\n\t\tthis.part.markDirty()\n\t}\n\n\t#themeElements(): Element | null {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn root ? firstChild(root, 'a:themeElements') : null\n\t}\n\n\t#clrScheme(): Element | null {\n\t\tconst themeElements = this.#themeElements()\n\t\treturn themeElements ? firstChild(themeElements, 'a:clrScheme') : null\n\t}\n}\n\n/** The placeholder shapes (`p:sp` carrying a `p:ph`) of a master/layout `p:spTree`, in document order. */\nfunction placeholderShapes(spTree: Element | null): Element[] {\n\tif (!spTree) return []\n\treturn getElements(spTree, 'p:sp').filter((sp) => placeholderOf(sp) !== null)\n}\n\n/**\n * One placeholder shape (`p:sp` with a `p:ph`) of a slide master or slide layout —\n * the definition a slide's placeholder of the same `type`/`idx` inherits geometry\n * and text style from. Geometry getters read the placeholder's *own* `a:xfrm`,\n * which a master/layout placeholder carries explicitly (so it round-trips, unlike a\n * notes placeholder's inherited geometry).\n *\n * This is the identity-and-geometry view. The same `p:sp` also appears in\n * {@link SlideMaster.shapes} / {@link SlideLayout.shapes} as an `AutoShape`, which\n * additionally carries the paint surface (`resolvedFill`, `resolvedLine`,\n * `presetGeometry`, `rotation`, `absoluteFrame`) and reports its `p:ph` through\n * `AutoShape.placeholder`. Read a placeholder here to *place* it; read it there to\n * *draw* it.\n */\nexport class Placeholder {\n\tconstructor(\n\t\t/** The placeholder's `p:sp`. `protected` so {@link NotesPlaceholder} can read it. */\n\t\tprotected readonly sp: Element,\n\t\t/** The part the `p:sp` lives in — a master, a layout, or a notes slide. */\n\t\tprotected readonly part: Part,\n\t\t/** The owning part's theme context, threaded to {@link textFrame}. */\n\t\tprotected readonly themeContext: ThemeContext,\n\t\t/** The owning part's relationships, threaded to {@link textFrame} for hyperlink resolution. */\n\t\tprotected readonly relationships: Relationships\n\t) {}\n\n\t#cNvPr(): Element | null {\n\t\tconst nvSpPr = firstChild(this.sp, 'p:nvSpPr')\n\t\treturn nvSpPr ? firstChild(nvSpPr, 'p:cNvPr') : null\n\t}\n\n\t/** Placeholder type (`p:ph/@type`: `title` | `body` | `sldNum` | …), or `null` when absent (a body placeholder). */\n\tget type(): string | null {\n\t\tconst ph = placeholderOf(this.sp)\n\t\treturn ph ? attr(ph, 'type') : null\n\t}\n\n\t/** Placeholder index (`p:ph/@idx`), or `null` when unset. */\n\tget idx(): string | null {\n\t\tconst ph = placeholderOf(this.sp)\n\t\treturn ph ? attr(ph, 'idx') : null\n\t}\n\n\t/** Shape name (`p:cNvPr/@name`), or `''` when unnamed. */\n\tget name(): string {\n\t\tconst cNvPr = this.#cNvPr()\n\t\treturn (cNvPr && attr(cNvPr, 'name')) ?? ''\n\t}\n\n\t/** Drawing id (`p:cNvPr/@id`), or `null` when absent. */\n\tget id(): number | null {\n\t\tconst cNvPr = this.#cNvPr()\n\t\treturn cNvPr ? intValue(attr(cNvPr, 'id')) : null\n\t}\n\n\t/** Left edge in EMU (`a:off/@x`), or `null` when the placeholder carries no own `a:xfrm`. */\n\tget left(): number | null {\n\t\treturn spPrXfrmEmu(this.sp, 'a:off', 'x')\n\t}\n\n\t/** Top edge in EMU (`a:off/@y`), or `null` when the placeholder carries no own `a:xfrm`. */\n\tget top(): number | null {\n\t\treturn spPrXfrmEmu(this.sp, 'a:off', 'y')\n\t}\n\n\t/** Width in EMU (`a:ext/@cx`), or `null` when the placeholder carries no own `a:xfrm`. */\n\tget width(): number | null {\n\t\treturn spPrXfrmEmu(this.sp, 'a:ext', 'cx')\n\t}\n\n\t/** Height in EMU (`a:ext/@cy`), or `null` when the placeholder carries no own `a:xfrm`. */\n\tget height(): number | null {\n\t\treturn spPrXfrmEmu(this.sp, 'a:ext', 'cy')\n\t}\n\n\t/**\n\t * The placeholder's text as a navigable {@link TextFrame} (`p:txBody`), or `null`\n\t * when it carries no text body. Threaded with the owning master/layout theme\n\t * context so a run's own `schemeClr` resolves through `Run.resolvedColor`.\n\t */\n\tget textFrame(): TextFrame | null {\n\t\tconst txBody = firstChild(this.sp, 'p:txBody')\n\t\treturn txBody ? new TextFrame(txBody, this.part, this.themeContext, undefined, this.relationships) : null\n\t}\n\n\t/** Escape hatch: the underlying `p:sp` element. After mutating it call {@link markDirty}, or `save()` writes the original bytes. */\n\tget element_(): Element {\n\t\treturn this.sp\n\t}\n\n\t/** Mark the owning part dirty so `save()` reserializes it. Call after mutating {@link element_}. */\n\tmarkDirty(): void {\n\t\tthis.part.markDirty()\n\t}\n}\n\n/**\n * The shared body of a slide master and a slide layout — the two template tiers a slide\n * inherits from.\n *\n * Both are an OPC part holding a `p:cSld` with a shape tree and a resolvable theme context, and\n * both were written out in full, member for member: `partName`, `relationships`, `name`,\n * `shapes`, `shapeByIdDeep`, `placeholders`, `themeContext` and the two DOM lookups behind them\n * were character-for-character identical in the two classes. Nothing about that was broken, but\n * it meant every accessor added to a template tier had to be added twice, and the ones meant to\n * agree could quietly stop agreeing.\n *\n * What genuinely differs stays on the subclasses. `theme` differs because a layout has to walk\n * to its master first. `background` differs in the tier label it decodes with and in where it\n * finds the theme part. And the context itself differs, which is why {@link resolveThemeContext}\n * is abstract: a master resolves its own `p:clrMap` + theme, a layout walks layout → master →\n * theme. The caching around it is shared, so a subclass supplies the walk and nothing else.\n *\n * `Slide` deliberately does not extend this. It is a shape host too, but it is constructed from\n * a `Presentation` rather than an `OpcPackage`, reaches its relationships through that, and\n * reports an unnamed slide as `null` where a template tier reports `''` — three differences in\n * the same handful of members, which is more contortion than the sharing is worth.\n */\nabstract class TemplatePart implements ShapeHost {\n\t#themeContext?: ThemeContext\n\n\tconstructor(\n\t\t/** The package this part belongs to, for reaching related parts (theme, master, media). */\n\t\treadonly opc: OpcPackage,\n\t\t/** This tier's OPC part. */\n\t\treadonly part: Part\n\t) {}\n\n\t/** Partname of this part. */\n\tget partName(): string {\n\t\treturn this.part.partName\n\t}\n\n\t/** This part's relationships (its theme or master, image embeds, hyperlinks, …). */\n\tget relationships(): Relationships {\n\t\treturn this.opc.relationshipsFor(this.partName)\n\t}\n\n\t/** The authoring name (`p:cSld/@name`), or `''` when unnamed. */\n\tget name(): string {\n\t\tconst cSld = this.cSld()\n\t\treturn (cSld && attr(cSld, 'name')) ?? ''\n\t}\n\n\t/**\n\t * Every shape in this tier's `p:cSld/p:spTree`, in document order — the same `AnyShape`\n\t * union `Slide.shapes` returns, so shape-walking code applies unchanged.\n\t *\n\t * {@link placeholders} is the filtered view of the same tree.\n\t */\n\tget shapes(): AnyShape[] {\n\t\tconst spTree = this.spTree()\n\t\treturn spTree ? buildShapes(spTree, this) : []\n\t}\n\n\t/** The shape anywhere in this tier's tree with the given drawing id, or `undefined`. */\n\tshapeByIdDeep(id: number): AnyShape | undefined {\n\t\treturn findShapeByIdDeep(this.shapes, id)\n\t}\n\n\t/** This tier's placeholder shapes (`p:sp` carrying a `p:ph`), in document order. */\n\tget placeholders(): Placeholder[] {\n\t\tconst ctx = this.themeContext()\n\t\tconst rels = this.relationships\n\t\treturn placeholderShapes(this.spTree()).map((sp) => new Placeholder(sp, this.part, ctx, rels))\n\t}\n\n\t/** This tier's colour/font context, resolved once and cached. Backs each {@link Placeholder}'s text frame. */\n\tthemeContext(): ThemeContext {\n\t\treturn (this.#themeContext ??= this.resolveThemeContext())\n\t}\n\n\t/** The theme this tier resolves against, or `null` when the chain is incomplete. */\n\tabstract get theme(): Theme | null\n\n\t/** This tier's *own* background (`p:cSld/p:bg`), decoded, or `null` when it defines none. */\n\tabstract get background(): SlideBackground | null\n\n\t/** Walk this tier's colour/font chain. Called once; {@link themeContext} caches the result. */\n\tprotected abstract resolveThemeContext(): ThemeContext\n\n\t/** The `p:cSld` of this part, or `null`. */\n\tprotected cSld(): Element | null {\n\t\treturn cSldOf(this.part.dom.documentElement)\n\t}\n\n\t/** The `p:cSld/p:spTree` of this part, or `null`. */\n\tprotected spTree(): Element | null {\n\t\treturn spTreeOf(this.part.dom.documentElement)\n\t}\n\n\t/** The part this one's first relationship of `type` points at, or `null`. */\n\tprotected relTarget(type: string): Part | null {\n\t\tconst rels = this.relationships\n\t\tconst rel = rels.byType(type)[0]\n\t\treturn rel ? (this.opc.part(rels.resolveTarget(rel.id)) ?? null) : null\n\t}\n}\n\n/**\n * A deck's slide master (`slideMasterN.xml`) as a modeled object. Exposes the\n * property tiers a bound slide inherits: the {@link colorMap} (token → theme slot),\n * its {@link theme}, its `shapes` and the `placeholders` subset of them, its own\n * {@link background}, and the {@link layouts} that build on it. Reachable from\n * {@link SlideLayout.master} and `Slide.master`.\n *\n * `shapes` is where a template's non-placeholder furniture lives: the header band, the\n * rule under the title, the logo. Whether a given slide draws them is\n * `Slide.showMasterSp` (and, for a layout, {@link SlideLayout.showMasterSp}).\n */\nexport class SlideMaster extends TemplatePart {\n\t/** The master's theme (via its `theme` relationship), or `null` when absent. */\n\toverride get theme(): Theme | null {\n\t\tconst themePart = this.relTarget(THEME_REL)\n\t\treturn themePart ? new Theme(themePart) : null\n\t}\n\n\t/**\n\t * The master's colour map (`p:clrMap`): each of the 12 {@link ColorMapToken}s\n\t * mapped to the {@link ThemeColorSlot} it resolves through. This is the indirection\n\t * that lets a slide's `schemeClr val=\"tx1\"` reach a theme slot (e.g. `tx1` → `dk1`).\n\t * A token the map omits reads `null`.\n\t */\n\tget colorMap(): Record<ColorMapToken, string | null> {\n\t\tconst root = this.part.dom.documentElement\n\t\tconst parsed = parseClrMap(root ? firstChild(root, 'p:clrMap') : null)\n\t\tconst out = {} as Record<ColorMapToken, string | null>\n\t\tfor (const token of COLOR_MAP_TOKENS) out[token] = parsed.get(token) ?? null\n\t\treturn out\n\t}\n\n\t/** The layouts built on this master (via `p:sldLayoutIdLst` → its relationships), in list order. */\n\tget layouts(): SlideLayout[] {\n\t\tconst root = this.part.dom.documentElement\n\t\tconst lst = root && firstChild(root, 'p:sldLayoutIdLst')\n\t\tif (!lst) return []\n\t\tconst rels = this.relationships\n\t\tconst out: SlideLayout[] = []\n\t\tfor (const entry of getElements(lst, 'p:sldLayoutId')) {\n\t\t\tconst relId = attr(entry, 'r:id')\n\t\t\tconst part = relId ? this.opc.part(rels.resolveTarget(relId)) : null\n\t\t\tif (part) out.push(new SlideLayout(this.opc, part))\n\t\t}\n\t\treturn out\n\t}\n\n\t/**\n\t * The master's *own* background (`p:cSld/p:bg`), decoded, or `null` when it defines\n\t * none. Scoped to the master's own element — a slide's *effective* background,\n\t * resolved through the slide → layout → master chain, is `Slide.background`.\n\t */\n\toverride get background(): SlideBackground | null {\n\t\tconst bg = backgroundElementOf(this.part.dom.documentElement)\n\t\tif (!bg) return null\n\t\tconst themePart = this.relTarget(THEME_REL)\n\t\treturn readSlideBackground(\n\t\t\tbg,\n\t\t\t'master',\n\t\t\tthis.themeContext(),\n\t\t\tthis.relationships,\n\t\t\tthemePart ? this.opc.relationshipsFor(themePart.partName) : null\n\t\t)\n\t}\n\n\t/** A master's context is its own `p:clrMap` plus its theme — no walk beyond this part. */\n\tprotected override resolveThemeContext(): ThemeContext {\n\t\treturn resolveMasterColorContext(this.opc, this.partName)\n\t}\n}\n\n/**\n * A deck's slide layout (`slideLayoutN.xml`) as a modeled object — the gallery entry\n * a slide binds to. Exposes its {@link name}, its {@link type} (import-only; the\n * writer authors none), its {@link master} (and, through it, the {@link theme}), its\n * `shapes` and the `placeholders` subset of them, and its own {@link background}.\n * Reachable from `Slide.layout` and {@link SlideMaster.layouts}.\n *\n * The write API authors non-placeholder shapes into a layout: every\n * `defineSlideMaster({ objects })` member that is not a `placeholder` — a `rect`, a\n * `line`, an `image`, a `chart`, a `text` box — lands in this tier's tree.\n */\nexport class SlideLayout extends TemplatePart {\n\t/**\n\t * The layout type (`p:sldLayout/@type`, e.g. `title` | `obj` | `blank`), or `null`\n\t * when the layout declares none. Import-only: the writer authors no `@type`, so an\n\t * authored deck reads `null`; an imported deck carries PowerPoint's value.\n\t */\n\tget type(): string | null {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn root ? attr(root, 'type') : null\n\t}\n\n\t/**\n\t * Whether this layout draws the master's non-placeholder shapes\n\t * (`p:sldLayout/@showMasterSp`). `xsd:boolean` defaulting to `true`, so an absent\n\t * attribute means shown — the layout-tier counterpart of `Slide.showMasterSp`,\n\t * and the one PowerPoint actually writes on a section-divider or full-bleed\n\t * layout. A renderer resolving what to paint under a slide's own shapes has to\n\t * consult both: the slide's flag, then its layout's.\n\t */\n\tget showMasterSp(): boolean {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn boolValue(root && attr(root, 'showMasterSp')) !== false\n\t}\n\n\t/** The master this layout is built on (via its `slideMaster` relationship), or `null` when absent. */\n\tget master(): SlideMaster | null {\n\t\tconst rels = this.relationships\n\t\tconst rel = rels.byType(SLIDE_MASTER_REL)[0]\n\t\tconst part = rel ? this.opc.part(rels.resolveTarget(rel.id)) : null\n\t\treturn part ? new SlideMaster(this.opc, part) : null\n\t}\n\n\t/** The theme this layout resolves against, via its {@link master}, or `null`. */\n\toverride get theme(): Theme | null {\n\t\treturn this.master?.theme ?? null\n\t}\n\n\t/**\n\t * The layout's *own* background (`p:cSld/p:bg`), decoded, or `null` when it defines\n\t * none. A layout usually authors one — an explicit fill (`p:bgPr`) or a\n\t * theme-indexed reference (`p:bgRef`). The slide's *effective* background is\n\t * `Slide.background`.\n\t */\n\toverride get background(): SlideBackground | null {\n\t\tconst bg = backgroundElementOf(this.part.dom.documentElement)\n\t\tif (!bg) return null\n\t\tconst themePart = this.master?.theme?.part ?? null\n\t\treturn readSlideBackground(\n\t\t\tbg,\n\t\t\t'layout',\n\t\t\tthis.themeContext(),\n\t\t\tthis.relationships,\n\t\t\tthemePart ? this.opc.relationshipsFor(themePart.partName) : null\n\t\t)\n\t}\n\n\t/** A layout's context is walked layout → master → theme, which is why it is not the master's. */\n\tprotected override resolveThemeContext(): ThemeContext {\n\t\treturn resolveLayoutColorContext(this.opc, this.partName)\n\t}\n}\n","/**\n * Read-model proxies for a slide's speaker-notes slide (`notesSlideN.xml`).\n *\n * A notes slide is a small, fixed surface: a shape tree of exactly three\n * placeholders — the slide thumbnail (`sldImg`), the notes body (`body`), and the\n * slide number (`sldNum`) — and never groups, pictures, connectors, or charts.\n * So it is modeled with a dedicated {@link NotesPlaceholder} rather than the full\n * slide shape hierarchy: each placeholder exposes its `type`/`name`/`id`, its\n * geometry (EMU, `null` when the part carries no `a:xfrm`), and — for the body and\n * the slide-number field — a navigable {@link TextFrame}.\n *\n * The writer authors all three placeholders but leaves the `sldImg`/`sldNum`\n * `p:spPr` empty (no `a:xfrm`), so on an *authored* deck geometry reads `null`; an\n * imported deck carries the notesMaster-derived geometry PowerPoint stamps. The\n * body's text and the `sldNum` field, by contrast, are authored and round-trip.\n *\n * Text frames are threaded with the notes theme context (notesMaster → `theme2.xml`,\n * see {@link resolveNotesColorContext}) so a notes run's own `schemeClr` resolves to\n * a literal hex, and with the notes part's own relationships so a notes hyperlink\n * resolves its url. The body frame is additionally given a placeholder context, so a\n * body run that sets no own size/face/bold resolves its *inherited* value from the\n * notesMaster's `p:notesStyle` — the notes analogue of a slide placeholder's\n * `Run.resolved*` chain.\n */\nimport type { OpcPackage } from '../opc/package.js'\nimport type { Part } from '../opc/part.js'\nimport { firstChild, getElements, type Element } from '../oxml/dom.js'\nimport type { ThemeContext } from '../oxml/theme.js'\nimport { resolveNotesColorContext } from './theme-context.js'\nimport { TextFrame } from './text.js'\nimport { spTreeOf } from '../oxml/slide-dom.js'\nimport { Placeholder } from './chrome.js'\n\n/**\n * One placeholder shape (`p:sp`) of a notes slide. A notes slide holds a fixed set:\n * the slide thumbnail (`type=\"sldImg\"`), the notes body (`type=\"body\"`), and the\n * slide number (`type=\"sldNum\"`). Geometry getters read the placeholder's *own*\n * `a:xfrm` and are `null` when it inherits geometry from the notesMaster (the case\n * on an authored deck, whose `sldImg`/`sldNum` carry an empty `p:spPr`).\n *\n * A notes placeholder IS a {@link Placeholder} — identity, geometry and the escape hatch are\n * the same twelve members read off the same `p:sp`, down to `p:ph` being found the same way —\n * so it extends one rather than repeating it. Two things are its own: the flattened\n * {@link text} convenience, and a {@link textFrame} that threads the notesMaster inheritance\n * context onto the body frame.\n */\nexport class NotesPlaceholder extends Placeholder {\n\t/**\n\t * The placeholder's text as a navigable {@link TextFrame} (`p:txBody`), or `null`\n\t * when it carries no text body (the `sldImg` thumbnail). The body placeholder's\n\t * runs round-trip a slide's authored notes; the `sldNum` placeholder's frame\n\t * holds the slide-number `a:fld`, whose value surfaces through `TextFrame.text`.\n\t *\n\t * Overrides {@link Placeholder.textFrame} for the inheritance context alone — see below.\n\t */\n\toverride get textFrame(): TextFrame | null {\n\t\tconst txBody = firstChild(this.sp, 'p:txBody')\n\t\tif (!txBody) return null\n\t\t// The notes *body* placeholder's runs inherit their effective size/face/bold\n\t\t// (and colour) from the notesMaster's `p:notesStyle`, carried on the notes theme\n\t\t// context (`resolveNotesColorContext`). Give the body frame a placeholder context\n\t\t// so `Run.resolved*` walks that chain; the `sldNum` field frame needs none.\n\t\tconst placeholder =\n\t\t\tthis.type === 'body' ? { ph: { type: this.type, idx: this.idx ?? '0' }, flatten: this.themeContext } : undefined\n\t\treturn new TextFrame(txBody, this.part, this.themeContext, placeholder, this.relationships)\n\t}\n\n\t/** The placeholder's flattened text (paragraphs joined by `\\n`), or `''` when it has no text body. */\n\tget text(): string {\n\t\treturn this.textFrame?.text ?? ''\n\t}\n}\n\n/**\n * A slide's speaker-notes slide (`notesSlideN.xml`) as a modeled object — the deep\n * companion to {@link import('./slide.js').Slide.notesText}. Exposes the notes\n * shape tree as {@link NotesPlaceholder}s ({@link body}/{@link slideImage}/\n * {@link slideNumber}) plus the body {@link textFrame} the older getters flatten.\n *\n * The theme context (notesMaster → `theme2.xml`) is resolved once and shared across\n * every placeholder's text frame.\n */\nexport class NotesSlide {\n\t#themeContext?: ThemeContext\n\n\tconstructor(\n\t\tprivate readonly opc: OpcPackage,\n\t\t/** The notes slide's OPC part (`/ppt/notesSlides/notesSlideN.xml`). */\n\t\treadonly part: Part\n\t) {}\n\n\t/** Partname of the notes slide part. */\n\tget partName(): string {\n\t\treturn this.part.partName\n\t}\n\n\t/**\n\t * The notes theme context, resolved through the notesMaster → `theme2.xml` chain\n\t * and cached. Backs {@link NotesPlaceholder.textFrame}'s `Run.resolvedColor`.\n\t */\n\tthemeContext(): ThemeContext {\n\t\treturn (this.#themeContext ??= resolveNotesColorContext(this.opc, this.partName))\n\t}\n\n\t/** The placeholders (`p:sp`) in the notes shape tree, in document order. */\n\tget placeholders(): NotesPlaceholder[] {\n\t\tconst spTree = this.#spTree()\n\t\tif (!spTree) return []\n\t\tconst ctx = this.themeContext()\n\t\tconst rels = this.opc.relationshipsFor(this.partName)\n\t\treturn getElements(spTree, 'p:sp').map((sp) => new NotesPlaceholder(sp, this.part, ctx, rels))\n\t}\n\n\t/** The notes body placeholder (`p:ph type=\"body\"`), or `null` when the notes slide has none. */\n\tget body(): NotesPlaceholder | null {\n\t\treturn this.#byType('body')\n\t}\n\n\t/** The slide-thumbnail placeholder (`p:ph type=\"sldImg\"`), or `null` when absent. */\n\tget slideImage(): NotesPlaceholder | null {\n\t\treturn this.#byType('sldImg')\n\t}\n\n\t/** The slide-number placeholder (`p:ph type=\"sldNum\"`, carrying the slide-number field), or `null`. */\n\tget slideNumber(): NotesPlaceholder | null {\n\t\treturn this.#byType('sldNum')\n\t}\n\n\t/** The notes body as a navigable {@link TextFrame}, or `null` when there is no body text frame. */\n\tget textFrame(): TextFrame | null {\n\t\treturn this.body?.textFrame ?? null\n\t}\n\n\t/** The notes body text flattened (paragraphs joined by `\\n`), or `''` when the body is empty/absent. */\n\tget text(): string {\n\t\treturn this.body?.text ?? ''\n\t}\n\n\t#byType(type: string): NotesPlaceholder | null {\n\t\treturn this.placeholders.find((ph) => ph.type === type) ?? null\n\t}\n\n\t#spTree(): Element | null {\n\t\treturn spTreeOf(this.part.dom.documentElement)\n\t}\n}\n","/**\n * The structural destination-deck context shared by the modules that mutate a\n * package on `Presentation`'s behalf.\n *\n * Those modules take this rather than the class so they stay independent of their\n * caller; `Presentation` satisfies it structurally, so a call site passes `this`\n * and threads nothing. Pass the instance rather than spreading it into an object\n * literal -- `presentationPart` is a memoizing getter, and a spread resolves it\n * eagerly at the call site instead of on first use.\n */\n\nimport type { OpcPackage } from '../../opc/package.js'\nimport type { Part } from '../../opc/part.js'\nimport type { Relationships } from '../../opc/relationships.js'\n\n/** The destination deck: just the package and its main part. `Presentation` satisfies it. */\nexport interface DeckTarget {\n\treadonly opc: OpcPackage\n\treadonly presentationPart: Part\n}\n\n/**\n * `ppt/_rels/presentation.xml.rels` -- the deck's own relationship part.\n *\n * Every part that masters, layouts, the notes master and embedded fonts hang off\n * is reached through here, so the two-step `dest.presentationPart` ->\n * `dest.opc.relationshipsFor(part.partName)` was written out at every one of\n * those wiring sites. Naming it once means a call site says which rels it wants\n * rather than how to find them.\n * @param {DeckTarget} dest - the destination deck\n * @returns {Relationships} the presentation part's relationships\n */\nexport function presentationRels(dest: DeckTarget): Relationships {\n\treturn dest.opc.relationshipsFor(dest.presentationPart.partName)\n}\n","/**\n * Slide-master bookkeeping in `presentation.xml` and in a master's own\n * `p:sldLayoutIdLst`: registering a master so renderers treat it as active,\n * promoting masters to the front of the id list, allocating ids out of the shared\n * master/layout id space, and emptying a freshly-copied master's layout list.\n *\n * These are the destination-side half of the import machinery -- they read and\n * write only this deck, never a source package and never the copy registry -- so\n * they take a structural {@link DeckTarget} rather than a `Presentation`. The\n * source-side half that drives most of them is `part-copy.ts`.\n */\n\nimport { relativePartName } from '../../opc/partnames.js'\nimport {\n\tattr,\n\tcreateElement,\n\tfirstChild,\n\tgetElements,\n\tgetOrAddChild,\n\tintValue,\n\tremoveChildrenByQName,\n\tsetAttr,\n\ttype Element,\n} from '../../oxml/dom.js'\nimport { presentationRels, type DeckTarget } from './deck-target.js'\nimport { SLIDE_LAYOUT_REL, SLIDE_MASTER_REL } from '../../../ooxml/rel-types.js'\nimport { PackageReadError } from '../../../errors.js'\n\n// ST_SlideMasterId and ST_SlideLayoutId share this floor.\nconst MIN_SLIDE_MASTER_ID = 2147483648\n\n/**\n * Wire a freshly-copied slide master into `presentation.xml`: add a\n * presentation→master relationship and a `p:sldMasterId` entry in\n * `p:sldMasterIdLst`. A master that is reachable only through the\n * slide→layout→master rel chain but absent from `p:sldMasterIdLst` is treated\n * as inactive by renderers, so its background/graphics never paint. No-op when\n * the master is already registered (shared across imports from one source).\n */\nexport function registerMaster(dest: DeckTarget, masterPartName: string): void {\n\tconst presPart = dest.presentationPart\n\tconst presRels = presentationRels(dest)\n\tfor (const rel of presRels.byType(SLIDE_MASTER_REL)) {\n\t\tif (presRels.resolveTarget(rel.id) === masterPartName) return\n\t}\n\tconst relId = presRels.add(SLIDE_MASTER_REL, relativePartName(presPart.partName, masterPartName)).id\n\n\tconst root = presPart.dom.documentElement\n\tif (!root)\n\t\tthrow new PackageReadError(\n\t\t\t'package/part-has-no-root',\n\t\t\t'presentation.xml has no document element to register a master in'\n\t\t)\n\t// `p:sldMasterIdLst` is the first child of CT_Presentation; create it before\n\t// any later sibling if a (degenerate) deck lacks one.\n\tconst lst = getOrAddChild(root, 'p:sldMasterIdLst', [\n\t\t'p:notesMasterIdLst',\n\t\t'p:handoutMasterIdLst',\n\t\t'p:sldIdLst',\n\t\t'p:sldSz',\n\t\t'p:notesSz',\n\t\t'p:embeddedFontLst',\n\t\t'p:custShowLst',\n\t\t'p:photoAlbum',\n\t\t'p:custDataLst',\n\t\t'p:kinsoku',\n\t\t'p:defaultTextStyle',\n\t\t'p:modifyVerifier',\n\t\t'p:extLst',\n\t])\n\tconst entry = createElement(presPart.dom, 'p:sldMasterId')\n\tsetAttr(entry, 'id', String(nextMasterLayoutId(dest)))\n\tsetAttr(entry, 'r:id', relId)\n\tlst.appendChild(entry)\n\tpresPart.markDirty()\n}\n\n/**\n * Move the `p:sldMasterId` entries for `masterPartNames` to the front of\n * `p:sldMasterIdLst`, preserving their existing relative order, so the first of\n * them becomes the deck's `Designs(1)` — the theme PowerPoint's Design tab shows.\n * Reorders the id list only; relationships, ids, and all other parts are left as\n * they are. A no-op when the named masters already lead (idempotent re-call).\n */\nexport function promoteMasters(dest: DeckTarget, masterPartNames: string[]): void {\n\tif (masterPartNames.length === 0) return\n\tconst presPart = dest.presentationPart\n\tconst root = presPart.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldMasterIdLst')\n\tif (!lst) return\n\tconst rels = presentationRels(dest)\n\tconst promote = new Set(masterPartNames)\n\tconst entries = getElements(lst, 'p:sldMasterId')\n\t// Entries whose relationship resolves to a promoted master, kept in their\n\t// current order, then everyone else in theirs — a stable partition.\n\tconst isPromoted = (entry: Element): boolean => {\n\t\tconst relId = attr(entry, 'r:id')\n\t\treturn relId ? promote.has(rels.resolveTarget(relId)) : false\n\t}\n\tconst desired = [...entries.filter(isPromoted), ...entries.filter((e) => !isPromoted(e))]\n\tif (desired.every((entry, i) => entry === entries[i])) return\n\tfor (const entry of desired) lst.appendChild(entry)\n\tpresPart.markDirty()\n}\n\n/**\n * The next free id in the presentation-wide slide-master / slide-layout id space.\n *\n * `p:sldMasterId/@id` and every master's `p:sldLayoutId/@id` draw from ONE shared\n * id space (both ST_SlideMasterId/ST_SlideLayoutId, floor 2147483648) and must be\n * unique across the WHOLE presentation, not just within their own list. A duplicate\n * anywhere in this space makes PowerPoint report the file as corrupt on open\n * (\"found a problem with content\" / 0x80070570), even though LibreOffice silently\n * tolerates it — so an imported master AND each of its layouts must take an id past\n * the max of both the master-id list and every layout-id list. Recomputed per\n * allocation so ids appended earlier in the same import are counted.\n */\nfunction nextMasterLayoutId(dest: DeckTarget): number {\n\tlet max = MIN_SLIDE_MASTER_ID - 1\n\tconst presPart = dest.presentationPart\n\tconst root = presPart.dom.documentElement\n\tconst masterLst = root && firstChild(root, 'p:sldMasterIdLst')\n\tif (masterLst) {\n\t\tfor (const entry of getElements(masterLst, 'p:sldMasterId')) {\n\t\t\tconst id = intValue(attr(entry, 'id'))\n\t\t\tif (id !== null && id > max) max = id\n\t\t}\n\t}\n\t// Every master's layout-id list shares the same id space; scan them all.\n\tconst presRels = presentationRels(dest)\n\tfor (const rel of presRels.byType(SLIDE_MASTER_REL)) {\n\t\tconst masterPart = dest.opc.part(presRels.resolveTarget(rel.id))\n\t\tconst masterRoot = masterPart?.dom.documentElement\n\t\tconst layoutLst = masterRoot && firstChild(masterRoot, 'p:sldLayoutIdLst')\n\t\tif (!layoutLst) continue\n\t\tfor (const entry of getElements(layoutLst, 'p:sldLayoutId')) {\n\t\t\tconst id = intValue(attr(entry, 'id'))\n\t\t\tif (id !== null && id > max) max = id\n\t\t}\n\t}\n\treturn max + 1\n}\n\n/** Empty a freshly-copied master's `p:sldLayoutIdLst`; copied layouts repopulate it. */\nexport function clearLayoutIdList(dest: DeckTarget, masterPartName: string): void {\n\tconst masterPart = dest.opc.part(masterPartName)\n\tconst root = masterPart?.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldLayoutIdLst')\n\tif (!masterPart || !lst) return\n\tremoveChildrenByQName(lst, ['p:sldLayoutId'])\n\tmasterPart.markDirty()\n}\n\n/**\n * Append a `p:sldLayoutId` entry for `layoutPartName` to `masterPartName`'s\n * `p:sldLayoutIdLst`, adding the master→layout relationship it points at. The\n * destination-side half of linking a copied layout into its copied master; the\n * caller resolves which master that is from the source-side rels.\n */\nexport function addLayoutToMaster(dest: DeckTarget, masterPartName: string, layoutPartName: string): void {\n\tconst masterPart = dest.opc.part(masterPartName)\n\tconst root = masterPart?.dom.documentElement\n\tif (!masterPart || !root) return\n\n\tconst masterRels = dest.opc.relationshipsFor(masterPartName)\n\tconst relId = masterRels.add(SLIDE_LAYOUT_REL, relativePartName(masterPartName, layoutPartName)).id\n\tconst lst = getOrAddChild(root, 'p:sldLayoutIdLst', ['p:transition', 'p:timing', 'p:hf', 'p:txStyles', 'p:extLst'])\n\tconst entry = createElement(masterPart.dom, 'p:sldLayoutId')\n\tsetAttr(entry, 'id', String(nextMasterLayoutId(dest)))\n\tsetAttr(entry, 'r:id', relId)\n\tlst.appendChild(entry)\n\tmasterPart.markDirty()\n}\n","/**\n * What a page copy may share with the page it was copied from, and what it must own.\n *\n * Duplicating a page — `cloneSlide`, `importSlide` of the same page twice,\n * `importSlides` naming it twice — copies the page part and then has to decide,\n * for every part hanging off it, whether the copy points at the same part or gets\n * one of its own. Sharing is the cheap answer and is right for most of the graph:\n * a layout, a master, a theme, an image are deck-wide assets PowerPoint itself\n * stores once and points many shapes at.\n *\n * It is not right for the parts a page *owns*. A chart and its embedded workbook,\n * a SmartArt diagram's five parts, an OLE embedding, a notes slide: PowerPoint\n * treats each as belonging to exactly one page, and a package where two slides\n * resolve to one of them is one it refuses to open at all — the \"the file or\n * directory is corrupted and unreadable\" (`0x80070570`) dialog, with the whole\n * deck rejected rather than the duplicate page. The schema validator accepts such\n * a package: nothing in ECMA-376 says a chart part has one referrer, so this rule\n * is only visible against the application.\n *\n * Measured against desktop PowerPoint on the `mixed` fixture (a chart page and a\n * SmartArt page), duplicating a page that owns one of these:\n * - sharing the chart part → refused;\n * - a copy of the chart part sharing its embedded workbook and its\n * `chartUserShapes` drawing → still refused;\n * - the chart subtree copied whole → opens.\n * So ownership is transitive: a part a page owns owns its own subtree in turn,\n * down to the media blobs at the leaves.\n *\n * Hence the list below is of what may be **shared**, and everything else is\n * copied. The asymmetry is deliberate: a wrongly shared part is a deck nobody can\n * open, a wrongly copied one is some duplicated bytes. A new relationship type\n * that nobody has classified therefore lands on the safe side by default.\n */\n\nimport type { OpcPackage } from '../../opc/package.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport {\n\tIMAGE_REL,\n\tNOTES_MASTER_REL,\n\tOFFICE_REL,\n\tSLIDE_LAYOUT_REL,\n\tSLIDE_MASTER_REL,\n\tSLIDE_REL,\n\tTHEME_REL,\n} from '../../../ooxml/rel-types.js'\n\n/** Relationship types whose target two copies of one page may point at together. */\nconst SHARED_BY_PAGE_COPIES: ReadonlySet<string> = new Set([\n\t// Deck furniture: reached through a page, owned by the deck.\n\tSLIDE_LAYOUT_REL,\n\tSLIDE_MASTER_REL,\n\tNOTES_MASTER_REL,\n\tTHEME_REL,\n\tOFFICE_REL + 'themeOverride',\n\tOFFICE_REL + 'handoutMaster',\n\tOFFICE_REL + 'presProps',\n\tOFFICE_REL + 'viewProps',\n\tOFFICE_REL + 'tableStyles',\n\t// Package singletons that a page's own parts point back at — a comments part\n\t// names the deck's author list, which is one list for the whole package.\n\tOFFICE_REL + 'commentAuthors',\n\t'http://schemas.microsoft.com/office/2018/10/relationships/authors',\n\t// Media blobs. PowerPoint stores one copy and points every shape that shows it\n\t// at that copy, so sharing here is what the application does itself.\n\tIMAGE_REL,\n\tOFFICE_REL + 'audio',\n\tOFFICE_REL + 'video',\n\t'http://schemas.microsoft.com/office/2007/relationships/media',\n\t'http://schemas.microsoft.com/office/2017/06/relationships/model3d',\n\tOFFICE_REL + 'font',\n\t// Another page is its own page, never a part this one owns: a jump link points\n\t// at whatever copy of the target page the import decided on.\n\tSLIDE_REL,\n\t// External by nature; an internal one resolves to a page, handled above.\n\tOFFICE_REL + 'hyperlink',\n])\n\n/**\n * Whether a page copy may point at this relationship's target rather than taking\n * a copy of it. Everything not listed is owned by the page and copied — see the\n * module comment for why that is the safe default.\n */\nexport function isSharedByPageCopies(relType: string): boolean {\n\treturn SHARED_BY_PAGE_COPIES.has(relType)\n}\n\n/**\n * Give a just-cloned page its own copy of every part the source page owned,\n * within one package. The clone's relationships start as a byte copy of the\n * source page's, so this walks them and repoints the owned ones at fresh parts;\n * shared targets are left alone.\n *\n * The subtree under each owned part is copied the same way, so a chart's workbook\n * and user-shapes drawing come along while the image inside that drawing stays\n * shared. A relationship *back* to the source page — a notes slide names the\n * slide it annotates — is repointed at the clone, which is what makes the copied\n * notes belong to it.\n *\n * A dangling relationship is left dangling rather than made to throw: cloning a\n * damaged deck is not this function's problem to discover.\n *\n * @param opc the package both pages live in\n * @param sourcePartName partname of the page that was cloned\n * @param clonePartName partname of the clone, whose rels are still the source's\n */\nexport function duplicateOwnedTargets(opc: OpcPackage, sourcePartName: string, clonePartName: string): void {\n\t// Seeded with the page itself, so a back-reference to it lands on the clone.\n\tconst copies = new Map<string, string>([[sourcePartName, clonePartName]])\n\tconst rels = opc.relationshipsFor(clonePartName)\n\t// Snapshot: the loop repoints relationships, which rewrites the live set.\n\tfor (const rel of Array.from(rels)) {\n\t\tif (rel.targetMode === 'External' || isSharedByPageCopies(rel.type)) continue\n\t\tconst target = rels.resolveTarget(rel.id)\n\t\tconst fresh = duplicateSubtree(opc, target, copies)\n\t\tif (fresh === target) continue\n\t\trels.remove(rel.id)\n\t\trels.addWithId(rel.id, rel.type, relativePartName(clonePartName, fresh))\n\t}\n}\n\n/**\n * Copy `partName` and, recursively, every part it owns, into fresh partnames.\n * `copies` dedupes within the one page copy, so a part two of the page's\n * relationships reach is copied once here even though the next page copy gets its\n * own. Returns the copy's partname, or `partName` unchanged when there is no such\n * part to copy.\n */\nfunction duplicateSubtree(opc: OpcPackage, partName: string, copies: Map<string, string>): string {\n\tconst already = copies.get(partName)\n\tif (already !== undefined) return already\n\tconst part = opc.part(partName)\n\tif (!part) return partName\n\n\tconst fresh = opc.reservePartNameLike(partName)\n\topc.addPart(fresh, part.contentType, part.bytes)\n\t// Record before recursing, so a cycle (a notes slide naming its slide) terminates.\n\tcopies.set(partName, fresh)\n\n\tconst sourceRels = opc.relationshipsFor(partName)\n\tconst freshRels = opc.relationshipsFor(fresh)\n\tfor (const rel of sourceRels) {\n\t\tif (rel.targetMode === 'External') {\n\t\t\tfreshRels.addWithId(rel.id, rel.type, rel.target, 'External')\n\t\t\tcontinue\n\t\t}\n\t\tconst target = sourceRels.resolveTarget(rel.id)\n\t\t// A shared target is still routed through `copies`: that is how the notes\n\t\t// slide's `slide` relationship finds the clone instead of the original.\n\t\tconst newTarget = isSharedByPageCopies(rel.type)\n\t\t\t? (copies.get(target) ?? target)\n\t\t\t: duplicateSubtree(opc, target, copies)\n\t\tfreshRels.addWithId(rel.id, rel.type, relativePartName(fresh, newTarget))\n\t}\n\treturn fresh\n}\n","/**\n * Recognising a part the destination deck **already holds**, so an import binds to it\n * instead of copying it in again.\n *\n * The case this exists for is the deck templated from its own source. `fromTemplate`\n * keeps a package's masters, layouts and theme byte-identical and strips only its\n * slides, so a script that then imports a slide back out of that same file hands\n * `copyPart` a `slideLayout -> slideMaster -> theme` subgraph whose every part is\n * already in the destination under its own partname. The copy registry maps *source*\n * partnames to copies this import made and knows nothing about what the destination\n * arrived with, so each of those parts was copied again: the output grew a duplicate\n * layout and master per imported slide, visible in PowerPoint's layout picker and\n * enough to make a later `appendSlides({ layout: <name> })` ambiguous.\n *\n * The test is deliberately strict, because the cost of getting it wrong is a slide\n * bound to chrome that only resembles what it asked for. A part is reusable only when\n * the destination holds it at the *same partname*, with the same content type, the same\n * bytes (as they would be written, so an edited destination part disqualifies itself),\n * the same relationships, and the same rule applied recursively to everything those\n * relationships reach. Byte-equality all the way down means \"reuse\" and \"copy\" produce\n * the same rendering; anything less falls back to the copy, which is always correct and\n * merely wasteful.\n *\n * Two further conditions have nothing to do with identity and everything to do with the\n * destination being a real deck: a reused master must already be registered in\n * `presentation.xml`, and a reused layout must already sit in a registered master's\n * `p:sldLayoutIdLst`. An identical part that is an orphan in the destination is not\n * something to bind a slide to, and the copy path (which registers and links what it\n * copies) is the right answer there.\n *\n * Reuse mutates nothing, which is what lets it hold across repeated imports: the\n * destination's chrome stays byte-identical, so the second import recognises it exactly\n * as the first one did.\n */\n\nimport { attr, firstChild, getElements, type Element } from '../../oxml/dom.js'\nimport type { OpcPackage } from '../../opc/package.js'\nimport { presentationRels, type DeckTarget } from './deck-target.js'\nimport {\n\tNOTES_SLIDE_REL,\n\tSLIDE_CONTENT_TYPE,\n\tSLIDE_LAYOUT_CONTENT_TYPE,\n\tSLIDE_LAYOUT_REL,\n\tSLIDE_MASTER_CONTENT_TYPE,\n} from '../../../ooxml/rel-types.js'\n\n/**\n * Whether the destination already holds `sourcePartName`'s subgraph, part for part and\n * byte for byte, in a state an imported slide can bind to.\n *\n * @param dest the deck being imported into\n * @param source the package being imported out of\n * @param sourcePartName the part the copy is about to make\n * @return `true` when the copy can be skipped and the existing part used\n */\nexport function destinationAlreadyHolds(dest: DeckTarget, source: OpcPackage, sourcePartName: string): boolean {\n\tconst part = dest.opc.part(sourcePartName)\n\t// A page is the one part an import never shares, whatever its bytes say: two\n\t// `p:sldId` entries pointing at one part is a package PowerPoint refuses to open.\n\tif (!part || part.contentType === SLIDE_CONTENT_TYPE) return false\n\tif (!identicalSubgraph(dest.opc, source, sourcePartName, new Set())) return false\n\treturn wiredIntoDeck(dest, sourcePartName)\n}\n\n/**\n * `partName` and everything it reaches are the same in both packages: same content type,\n * same body bytes, same relationships, recursively.\n *\n * The destination side is compared as it would be **written** (`serialize()`), not as it\n * was read, so a part some earlier edit marked dirty is treated as different even when\n * the edit was a no-op. Under-reusing costs a duplicated part; over-reusing binds a slide\n * to something else's chrome.\n *\n * The traversal skips exactly what `copyPart` skips — the notes relationship, and a\n * master's relationships to its layouts — so it asks about the subgraph the copy would\n * actually have made. Skipping the master's layout list is what keeps one edited layout\n * from disqualifying every *other* layout that shares its master.\n */\nfunction identicalSubgraph(dest: OpcPackage, source: OpcPackage, partName: string, visited: Set<string>): boolean {\n\tif (visited.has(partName)) return true\n\tvisited.add(partName)\n\n\tconst sourcePart = source.part(partName)\n\tconst destPart = dest.part(partName)\n\tif (!sourcePart || !destPart) return false\n\tif (sourcePart.contentType !== destPart.contentType) return false\n\tif (!bytesEqual(sourcePart.bytes, destPart.serialize())) return false\n\n\tconst sourceRels = [...source.relationshipsFor(partName)]\n\tconst destRels = [...dest.relationshipsFor(partName)]\n\tif (sourceRels.length !== destRels.length) return false\n\n\tconst isMaster = sourcePart.contentType === SLIDE_MASTER_CONTENT_TYPE\n\tconst destById = new Map(destRels.map((rel) => [rel.id, rel]))\n\tfor (const rel of sourceRels) {\n\t\tconst counterpart = destById.get(rel.id)\n\t\tif (!counterpart) return false\n\t\tif (counterpart.type !== rel.type || counterpart.targetMode !== rel.targetMode) return false\n\t\tif (rel.targetMode === 'External') {\n\t\t\tif (counterpart.target !== rel.target) return false\n\t\t\tcontinue\n\t\t}\n\t\tconst target = source.relationshipsFor(partName).resolveTarget(rel.id)\n\t\tif (dest.relationshipsFor(partName).resolveTarget(rel.id) !== target) return false\n\t\tif (rel.type === NOTES_SLIDE_REL) continue\n\t\tif (isMaster && rel.type === SLIDE_LAYOUT_REL) continue\n\t\tif (!identicalSubgraph(dest, source, target, visited)) return false\n\t}\n\treturn true\n}\n\n/**\n * Whether the destination's copy of this part is wired into the deck, for the two kinds\n * where \"present in the package\" is not the same as \"usable\".\n *\n * A master absent from `p:sldMasterIdLst` is inert: renderers ignore its background and\n * shape tree, so a slide bound through it renders blank. A layout absent from a\n * registered master's `p:sldLayoutIdLst` is not in the deck's gallery, so `layouts()`\n * cannot name it and `appendSlides` cannot bind to it. Every other kind (theme, media,\n * table styles) is reached by relationship alone and needs no registration.\n */\nfunction wiredIntoDeck(dest: DeckTarget, partName: string): boolean {\n\tconst contentType = dest.opc.part(partName)?.contentType\n\tif (contentType === SLIDE_MASTER_CONTENT_TYPE) return registeredMasters(dest).includes(partName)\n\tif (contentType === SLIDE_LAYOUT_CONTENT_TYPE) {\n\t\treturn registeredMasters(dest).some((master) => galleryOf(dest, master).includes(partName))\n\t}\n\treturn true\n}\n\n/** The destination's masters in `p:sldMasterIdLst` order — the ones renderers treat as active. */\nfunction registeredMasters(dest: DeckTarget): string[] {\n\tconst root = dest.presentationPart.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldMasterIdLst')\n\tif (!lst) return []\n\tconst rels = presentationRels(dest)\n\treturn idListTargets(lst, 'p:sldMasterId', (relId) => rels.resolveTarget(relId))\n}\n\n/** One master's layouts in `p:sldLayoutIdLst` order — its slice of the deck's gallery. */\nfunction galleryOf(dest: DeckTarget, masterPartName: string): string[] {\n\tconst root = dest.opc.part(masterPartName)?.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldLayoutIdLst')\n\tif (!lst) return []\n\tconst rels = dest.opc.relationshipsFor(masterPartName)\n\treturn idListTargets(lst, 'p:sldLayoutId', (relId) => rels.resolveTarget(relId))\n}\n\n/** Resolve every `@r:id` in an id list to its partname, skipping entries that carry none. */\nfunction idListTargets(lst: Element, qname: string, resolve: (relId: string) => string): string[] {\n\tconst out: string[] = []\n\tfor (const entry of getElements(lst, qname)) {\n\t\tconst relId = attr(entry, 'r:id')\n\t\tif (relId) out.push(resolve(relId))\n\t}\n\treturn out\n}\n\n/** Byte-for-byte equality of two part bodies. */\nfunction bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n\tif (a === b) return true\n\tif (a.length !== b.length) return false\n\tfor (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false\n\treturn true\n}\n","/**\n * The part-copy traversal: pulling a part -- and, recursively, every internal part\n * it references -- out of a source package into a destination deck, rewriting\n * relationship targets to the freshly-allocated partnames as it goes.\n *\n * This is the source-side half of the import machinery; the destination-side\n * bookkeeping it hands off to lives in `master-registry.ts`. It takes an\n * {@link ImportContext} rather than a `Presentation`, so it stays independent of\n * the class that calls it.\n */\n\nimport type { OpcPackage } from '../../opc/package.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport type { DeckTarget } from './deck-target.js'\nimport { addLayoutToMaster, clearLayoutIdList, registerMaster } from './master-registry.js'\nimport {\n\tNOTES_MASTER_REL,\n\tNOTES_SLIDE_CONTENT_TYPE,\n\tNOTES_SLIDE_REL,\n\tSLIDE_LAYOUT_CONTENT_TYPE,\n\tSLIDE_LAYOUT_REL,\n\tSLIDE_CONTENT_TYPE,\n\tSLIDE_MASTER_CONTENT_TYPE,\n\tSLIDE_MASTER_REL,\n\tSLIDE_REL,\n} from '../../../ooxml/rel-types.js'\nimport { isSharedByPageCopies } from './page-owned.js'\nimport { destinationAlreadyHolds } from './part-reuse.js'\nimport { InvalidOptionError, PackageReadError } from '../../../errors.js'\n\n/**\n * One import in progress: where parts are going, where they are coming from, and\n * what has already come across.\n *\n * `source` and `registry` are one fact, not two — a registry maps partnames *of\n * that package*, so pairing it with any other package silently returns partnames\n * for parts that were never copied. Holding them in a single value makes the\n * pairing a type invariant rather than a call-site convention; mint one with\n * `Presentation`'s factory, which reads through to the per-source registry that\n * outlives any one call (see {@link copyPart}'s idempotence).\n */\nexport interface ImportContext {\n\t/** The deck being copied into. */\n\treadonly dest: DeckTarget\n\t/** The package being copied out of. */\n\treadonly source: OpcPackage\n\t/** Source partname → the partname allocated for it in `dest`. */\n\treadonly registry: Map<string, string>\n\t/**\n\t * The pages this call is materializing, and where each is headed: source slide\n\t * partname → the destination partname pre-allocated for it. A page named here\n\t * gets its own part even when the registry already holds a copy of it, which is\n\t * what lets one source page be imported more than once.\n\t *\n\t * Both import entry points set it — {@link Presentation.importSlides} for the\n\t * whole batch, {@link copySlidePart} for the single page of one\n\t * {@link Presentation.importSlide}. For the batch it carries a second meaning:\n\t * `slide → slide` relationships resolve only within the set, so an imported page\n\t * may link to another *selected* page (rewritten to its fresh partname) but must\n\t * not drag an unselected source page across as a dependency.\n\t *\n\t * One destination per source page is deliberate: a page is a link target as well\n\t * as an output, and a map to *many* destinations would make every jump link\n\t * ambiguous. A batch asked for the same page N times therefore runs the\n\t * traversal N times, each round naming that page's Nth reserved partname and the\n\t * other pages' first — see `importSlides` step 3.\n\t */\n\treadonly selection?: SelectionPlan\n}\n\n/**\n * The parts one page copy has taken for itself: source partname → the copy made\n * for *this* page, never entered in the copy registry. A page owns a chart, a\n * SmartArt diagram, an OLE embedding and their subtrees; sharing one of those\n * with a second copy of the page writes a deck PowerPoint refuses to open, which\n * is what {@link isSharedByPageCopies} draws the line for.\n *\n * One scope per page copy, opened by {@link copyPart} when it reaches a page of\n * the selection plan and by {@link importSlideRebind} for the page it rebinds.\n */\nexport type OwnedScope = Map<string, string>\n\n/** Open an ownership scope for one page copy. */\nexport function newOwnedScope(): OwnedScope {\n\treturn new Map()\n}\n\n/** Which pages of one source package an import is materializing, and where each is headed. */\nexport interface SelectionPlan {\n\t/** Source slide partname → the destination partname reserved for it. */\n\treadonly destinations: ReadonlyMap<string, string>\n}\n\n/**\n * Copy one slide page across as a part of its own, deduping everything under it\n * but never the page itself. This is the `theme: 'copy'` arm of\n * {@link Presentation.importSlide}.\n *\n * The page is the one part an import is *not* allowed to share. `copyPart`'s\n * registry idempotence is right for a theme, master, layout or image, where a\n * second copy is waste; applied to the slide it made a repeated import of the\n * same source page return the first copy's partname, and the caller then wired a\n * second `p:sldId` to a part that already had one — a package PowerPoint refuses\n * to open (0x80070570), with nothing in the read model to show for it. So the\n * page goes into the selection plan `copyPart` already honours for a batch, which\n * re-materializes exactly the named pages and leaves the dedup of their\n * dependencies alone.\n *\n * @param ctx the open import out of the source package\n * @param sourcePartName partname of the source slide to bring across\n * @return partname of the new slide part in `ctx.dest`\n */\nexport function copySlidePart(ctx: ImportContext, sourcePartName: string): string {\n\tconst destinations = new Map([[sourcePartName, ctx.dest.opc.reservePartNameLike(sourcePartName)]])\n\treturn copyPart({ ...ctx, selection: { destinations } }, sourcePartName)\n}\n\n/**\n * Copy `sourcePartName` (and, recursively, every internal part it references)\n * from `ctx.source` into `ctx.dest`, returning the new partname. Idempotent\n * per source package via the copy registry. Relationship ids are preserved so\n * the copied part body's `r:id`/`r:embed` references stay valid; targets are\n * rewritten to the freshly-allocated partnames. Notes relationships are\n * dropped. A copied `slideMaster` does not drag in all its sibling layouts —\n * each imported `slideLayout` wires itself into the master instead (see\n * {@link linkLayoutIntoMaster}).\n *\n * With `ctx.selection`, partnames for the selected slides were already reserved\n * by the caller ({@link Presentation.importSlides}); this traversal wires their\n * relationships to each other instead of re-copying them. The batch's rule that\n * a `slide → slide` link may not leave the selection is enforced ahead of the\n * copy by {@link checkSelectionCopyable}, which also proves every part this\n * traversal will reach exists — so once copying starts there is nothing left to\n * throw, and a rejected batch never leaves a half-copied deck behind.\n *\n * Idempotence stops at the page's own parts. Reaching a page opens an\n * {@link OwnedScope}, and everything under it that {@link isSharedByPageCopies}\n * does not clear for sharing — a chart, a diagram, an OLE embedding, each with\n * its own subtree — is copied into that scope instead of the registry, so the\n * next copy of the page gets parts of its own. Pass `owned` to open the scope\n * from outside, as the rebinding import paths do for the page they build\n * themselves.\n */\nexport function copyPart(\n\tctx: ImportContext,\n\tsourcePartName: string,\n\towned?: OwnedScope,\n\tallowReuse: boolean = false\n): string {\n\t// Inside a page's ownership scope the registry is not consulted at all: the\n\t// point of the scope is that this page copy gets parts of its own, and the\n\t// scope's own map is what keeps a part two of its relationships reach from\n\t// being copied twice within the one copy.\n\tif (owned) {\n\t\tconst alreadyOwned = owned.get(sourcePartName)\n\t\tif (alreadyOwned !== undefined) return alreadyOwned\n\t} else {\n\t\tconst existing = ctx.registry.get(sourcePartName)\n\t\tconst selectedDest = ctx.selection?.destinations.get(sourcePartName)\n\t\t// Registry hit without a selection plan: plain idempotence. With a plan, a\n\t\t// hit on the *selected* destination means this batch already walked the page\n\t\t// (register-before-recurse makes mutually-linked selected pages terminate);\n\t\t// a hit on any OTHER partname is either a shared non-slide dependency from\n\t\t// an earlier traversal or a page a previous import brought across — both are\n\t\t// reused rather than duplicated. Only a selected page whose registered\n\t\t// partname differs (imported by a previous call) is re-materialized fresh:\n\t\t// each batch request owns exactly one output page.\n\t\tif (existing && (selectedDest === undefined || existing === selectedDest)) return existing\n\t}\n\n\t// The destination may already hold this exact part: a deck opened with\n\t// `fromTemplate` from the *same file* carries the source's own layouts, master and\n\t// theme, under their own partnames and byte-identical. Binding to what is there\n\t// beats copying it in again under a fresh name, which is what grew a duplicate\n\t// layout-gallery entry per imported slide. Never inside a page's ownership scope,\n\t// and never for a page the caller is materializing: those must be parts of their own.\n\tif (allowReuse && !owned && !ctx.selection?.destinations.has(sourcePartName)) {\n\t\tif (destinationAlreadyHolds(ctx.dest, ctx.source, sourcePartName)) {\n\t\t\tctx.registry.set(sourcePartName, sourcePartName)\n\t\t\treturn sourcePartName\n\t\t}\n\t}\n\n\tconst sourcePart = ctx.source.part(sourcePartName)\n\tif (!sourcePart)\n\t\tthrow new PackageReadError('package/part-missing', `importSlide: source package has no part ${sourcePartName}`)\n\n\tconst newPartName = owned\n\t\t? ctx.dest.opc.reservePartNameLike(sourcePartName)\n\t\t: (ctx.selection?.destinations.get(sourcePartName) ?? ctx.dest.opc.reservePartNameLike(sourcePartName))\n\t// A selected page's part was already materialized by the batch allocator.\n\tif (!ctx.dest.opc.part(newPartName)) ctx.dest.opc.addPart(newPartName, sourcePart.contentType, sourcePart.bytes)\n\t// Record before recursing so the master↔layout cycle terminates.\n\tif (owned) owned.set(sourcePartName, newPartName)\n\telse ctx.registry.set(sourcePartName, newPartName)\n\n\t// A page opens an ownership scope for everything under it; parts inside one\n\t// stay inside it. See `page-owned.ts` for what that scope covers and why.\n\tconst scope = owned ?? (ctx.selection?.destinations.has(sourcePartName) ? newOwnedScope() : undefined)\n\n\tconst isMaster = sourcePart.contentType === SLIDE_MASTER_CONTENT_TYPE\n\tconst isPage = sourcePart.contentType === SLIDE_CONTENT_TYPE\n\tconst sourceRels = ctx.source.relationshipsFor(sourcePartName)\n\tconst targetRels = ctx.dest.opc.relationshipsFor(newPartName)\n\tfor (const rel of sourceRels) {\n\t\t// Notes pull in a notesMaster + its own theme; an imported slide does not need them.\n\t\tif (rel.type === NOTES_SLIDE_REL) continue\n\t\t// Lean master: skip its layout rels; copied layouts re-link themselves.\n\t\tif (isMaster && rel.type === SLIDE_LAYOUT_REL) continue\n\t\tif (rel.targetMode === 'External') {\n\t\t\ttargetRels.addWithId(rel.id, rel.type, rel.target, 'External')\n\t\t\tcontinue\n\t\t}\n\t\t// A batch import's slide→slide rule is enforced by checkSelectionCopyable\n\t\t// before this traversal starts, so the recursion below cannot reach an\n\t\t// unselected page: by here every target is selected, already copied, or\n\t\t// not a slide at all.\n\t\tconst newTargetPartName = copyPart(\n\t\t\tctx,\n\t\t\tsourceRels.resolveTarget(rel.id),\n\t\t\tisSharedByPageCopies(rel.type) ? undefined : scope,\n\t\t\t// Reuse decides at the page boundary and never below it. A part reached from\n\t\t\t// the page can be answered with the destination's own identical copy; a part\n\t\t\t// reached from something this import *copied* is copied too, so a copied\n\t\t\t// subgraph stays self-contained rather than half-linking into deck chrome\n\t\t\t// that merely happens to match.\n\t\t\tisPage\n\t\t)\n\t\ttargetRels.addWithId(rel.id, rel.type, relativePartName(newPartName, newTargetPartName))\n\t}\n\n\tif (isMaster) {\n\t\tclearLayoutIdList(ctx.dest, newPartName)\n\t\t// Register the copied master in presentation.xml. Without a\n\t\t// `p:sldMasterId` entry (and a presentation→master relationship) the\n\t\t// master is inert: PowerPoint/LibreOffice ignore its background and shape\n\t\t// tree, so a `copy`-imported slide whose look lives on its master (a\n\t\t// cover/closer) renders blank. Idempotent, so masters shared across\n\t\t// repeated imports are registered exactly once.\n\t\tregisterMaster(ctx.dest, newPartName)\n\t}\n\tif (sourcePart.contentType === SLIDE_LAYOUT_CONTENT_TYPE) {\n\t\tlinkLayoutIntoMaster(ctx, sourceRels, newPartName)\n\t}\n\n\treturn newPartName\n}\n\n/**\n * Which of a batch's selected pages are also carrying their speaker notes across,\n * and whether the notes subgraph will pull a `notesMaster` with it. Handed to\n * {@link checkSelectionCopyable} so the dry run walks what `carryNotes` will walk.\n */\nexport interface NotesSelection {\n\t/** Source partnames of the selected pages whose request asked for `importNotes`. */\n\treadonly pages: ReadonlySet<string>\n\t/**\n\t * Whether a source `notesMaster` would be copied. False once the destination\n\t * has one of its own, since `p:notesMasterIdLst` is `0..1` and `carryNotes`\n\t * then binds to the destination's master instead of copying the source's.\n\t */\n\treadonly copyMaster: boolean\n}\n\nconst NO_NOTES: NotesSelection = { pages: new Set(), copyMaster: false }\n\n/**\n * Dry-run {@link copyPart} over one source's batch selection, reading only the\n * *source* package: walk the graph the copy will walk, under the same\n * relationship-skipping rules, and throw what the copy would throw — a source\n * part that is missing, XML that will not parse, or a `slide → slide` link that\n * escapes the selection.\n *\n * This is what makes a rejected batch leave the destination byte-identical.\n * `importSlides` reserves partnames and mutates the destination only after this\n * passes, at which point the copy has no reachable failure left; a check that\n * lived inside the traversal instead would fire with parts already added, a\n * master already registered in `presentation.xml`, and no way back.\n *\n * Keep this in step with `copyPart`: the two must skip the same relationships\n * and stop at the same registry hits, or the guarantee is only as good as the\n * drift between them. With `notes` the same obligation extends to `carryNotes`,\n * which runs after the copy and is the batch's other way to reach a source part.\n *\n * @param source the package the pages are coming from\n * @param registry the copy registry for that source (parts already in `dest`)\n * @param selected source partnames of the pages this batch selected\n * @param notes the pages of `selected` whose notes travel too; none by default\n */\nexport function checkSelectionCopyable(\n\tsource: OpcPackage,\n\tregistry: ReadonlyMap<string, string>,\n\tselected: ReadonlySet<string>,\n\tnotes: NotesSelection = NO_NOTES\n): void {\n\tconst visited = new Set<string>()\n\n\tconst walk = (partName: string): void => {\n\t\tif (visited.has(partName)) return\n\t\t// `copyPart` reuses an already-copied part rather than recursing into it,\n\t\t// and its subgraph was validated when that copy happened. A *selected*\n\t\t// page is the exception the batch re-materializes, so it is always walked.\n\t\tif (registry.has(partName) && !selected.has(partName)) return\n\t\tvisited.add(partName)\n\n\t\tconst part = source.part(partName)\n\t\tif (!part)\n\t\t\tthrow new PackageReadError('package/part-missing', `importSlides: source package has no part ${partName}`)\n\n\t\tconst isMaster = part.contentType === SLIDE_MASTER_CONTENT_TYPE\n\t\tconst isNotesSlide = part.contentType === NOTES_SLIDE_CONTENT_TYPE\n\t\t// The copy re-parses a master/layout to rebuild its layout id list; force\n\t\t// the same parse here so unparseable XML fails before anything moves.\n\t\tif (isMaster || part.contentType === SLIDE_LAYOUT_CONTENT_TYPE) void part.dom\n\n\t\tconst rels = source.relationshipsFor(partName)\n\t\tfor (const rel of rels) {\n\t\t\t// `copyPart` always drops the notes rel; `carryNotes` picks it up\n\t\t\t// afterwards for the pages that asked, so those subgraphs are walked here\n\t\t\t// and no other.\n\t\t\tif (rel.type === NOTES_SLIDE_REL) {\n\t\t\t\tif (notes.pages.has(partName)) walk(rels.resolveTarget(rel.id))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif (isNotesSlide) {\n\t\t\t\t// The notes' back-rel to the page it annotates is repointed at the new\n\t\t\t\t// slide, not copied — walking it would re-enter the page graph.\n\t\t\t\tif (rel.type === SLIDE_REL) continue\n\t\t\t\t// A deck already holding a notesMaster keeps it; the source's is then\n\t\t\t\t// never read, so a dry run that walked it would reject a batch the copy\n\t\t\t\t// would have accepted.\n\t\t\t\tif (rel.type === NOTES_MASTER_REL && !notes.copyMaster) continue\n\t\t\t}\n\t\t\tif (isMaster && rel.type === SLIDE_LAYOUT_REL) continue\n\t\t\tif (rel.targetMode === 'External') continue\n\t\t\tconst targetPartName = rels.resolveTarget(rel.id)\n\t\t\t// A jump link must land on another selected page, or on one an earlier\n\t\t\t// import from this source already brought across. Anything else would\n\t\t\t// drag a page nobody asked for into the deck, or strand the link.\n\t\t\tif (rel.type === SLIDE_REL && !selected.has(targetPartName) && !registry.has(targetPartName)) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/unresolved-slide-link',\n\t\t\t\t\t`importSlides: source slide ${partName} links to ${targetPartName}, which is not among the selected imported pages`\n\t\t\t\t)\n\t\t\t}\n\t\t\twalk(targetPartName)\n\t\t}\n\t}\n\n\tfor (const partName of selected) walk(partName)\n}\n\n/**\n * Wire a just-copied layout into its (already-copied) master. Resolves which\n * destination master that is by running the layout's *source* master rel through\n * the copy registry, then hands the destination-side wiring to\n * {@link addLayoutToMaster}. Called once per copied layout, so the master\n * accumulates exactly the imported layouts.\n */\nfunction linkLayoutIntoMaster(\n\tctx: ImportContext,\n\tlayoutSourceRels: ReturnType<OpcPackage['relationshipsFor']>,\n\tlayoutPartName: string\n): void {\n\tconst masterRel = layoutSourceRels.byType(SLIDE_MASTER_REL)[0]\n\tif (!masterRel) return\n\tconst masterPartName = ctx.registry.get(layoutSourceRels.resolveTarget(masterRel.id))\n\tif (!masterPartName) return\n\taddLayoutToMaster(ctx.dest, masterPartName, layoutPartName)\n}\n","/**\n * Carrying speaker notes and the deck's single notes master across an import or an append.\n *\n * A `notesSlide` is not self-contained: it back-references the slide it annotates and forward-\n * references the deck's notes master. `CT_NotesMasterIdList` allows at most one master per\n * presentation, so a deck that already has one keeps it — the destination's notes styling wins —\n * and a source master is copied only into a deck that has none. That single rule is why both the\n * `Presentation`-to-`Presentation` path and the generator-XML path funnel through\n * `registerNotesMaster`: they differ only in how the *part* comes into being.\n */\n\nimport { createElement, getOrAddChild, removeChildrenByQName, setAttr } from '../../oxml/dom.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { copyPart, newOwnedScope, type ImportContext } from './part-copy.js'\nimport { isSharedByPageCopies } from './page-owned.js'\nimport type { Presentation } from '../presentation.js'\nimport {\n\tNOTES_MASTER_CONTENT_TYPE,\n\tNOTES_MASTER_REL,\n\tNOTES_SLIDE_REL,\n\tSLIDE_REL,\n\tTHEME_CONTENT_TYPE,\n\tTHEME_REL,\n} from '../../../ooxml/rel-types.js'\nimport { PackageReadError } from '../../../errors.js'\nimport { makeXmlNotesMaster } from '../../../gen/slide/notes.js'\nimport { resolveSlideThemeParts } from '../theme-context.js'\nimport { presentationRels } from './deck-target.js'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * Carry the source slide's speaker notes onto the just-imported slide (the\n * `importNotes` option). The slide copy itself dropped the `notesSlide` rel, so\n * this copies the source `notesSlide` part into a fresh partname, wires a\n * `slide → notesSlide` rel on the new slide, and rebuilds the copied notesSlide's\n * own relationships:\n *\n * - its `slide` back-rel is repointed at the new slide (`newSlidePartName`) — the\n * source slide is *not* copied (that would be circular);\n * - its `notesMaster` rel is resolved through {@link ensureNotesMaster}, which\n * reuses this deck's notesMaster when it has one and copies the source's only\n * when it has none (a deck may have at most one notesMaster);\n * - any other internal target (media, etc.) is copied via {@link copyPart}, under an\n * ownership scope so a second copy of the page gets notes parts of its own.\n *\n * No-op when the source slide has no notes. Content-type registration for the\n * copied parts is handled by `addPart`/{@link copyPart}.\n */\nexport function carryNotes(\n\tdest: Presentation,\n\tsource: Presentation,\n\tctx: ImportContext,\n\tsourceSlidePartName: string,\n\tnewSlidePartName: string\n): void {\n\tconst sourceSlideRels = source.opc.relationshipsFor(sourceSlidePartName)\n\tconst notesRel = sourceSlideRels.byType(NOTES_SLIDE_REL)[0]\n\tif (!notesRel) return // slide has no speaker notes\n\tconst sourceNotesPartName = sourceSlideRels.resolveTarget(notesRel.id)\n\tconst sourceNotesPart = source.opc.part(sourceNotesPartName)\n\tif (!sourceNotesPart) return\n\n\t// Copy the notesSlide bytes into a fresh partname, then wire slide → notesSlide.\n\tconst newNotesPartName = dest.opc.reservePartNameLike(sourceNotesPartName)\n\tdest.opc.addPart(newNotesPartName, sourceNotesPart.contentType, sourceNotesPart.bytes)\n\tdest.opc.relationshipsFor(newSlidePartName).add(NOTES_SLIDE_REL, relativePartName(newSlidePartName, newNotesPartName))\n\n\t// A notes slide is a part its page *owns* (see `page-owned.ts`), and so is\n\t// whatever it owns in turn. Two copies of one source page — `importSlide`\n\t// called twice, or one `importSlides` batch naming the page twice — each get\n\t// notes of their own here; without a scope the second copy would share the\n\t// first's OLE embedding or chart through the registry, which is a package\n\t// PowerPoint refuses to open. Media stays shared, as everywhere else.\n\tconst owned = newOwnedScope()\n\towned.set(sourceNotesPartName, newNotesPartName)\n\n\t// Rebuild the copied notesSlide's relationships. Preserve each source rel id so\n\t// the notesSlide body's r:id references stay valid; only the targets are rewritten.\n\tconst notesSourceRels = source.opc.relationshipsFor(sourceNotesPartName)\n\tconst notesTargetRels = dest.opc.relationshipsFor(newNotesPartName)\n\tfor (const rel of notesSourceRels) {\n\t\tif (rel.type === SLIDE_REL) {\n\t\t\t// Back-reference to the annotated slide → repoint at the new slide (don't copy it).\n\t\t\tnotesTargetRels.addWithId(rel.id, SLIDE_REL, relativePartName(newNotesPartName, newSlidePartName))\n\t\t\tcontinue\n\t\t}\n\t\tif (rel.type === NOTES_MASTER_REL) {\n\t\t\tconst notesMaster = ensureNotesMaster(dest, ctx, notesSourceRels.resolveTarget(rel.id))\n\t\t\tnotesTargetRels.addWithId(rel.id, NOTES_MASTER_REL, relativePartName(newNotesPartName, notesMaster))\n\t\t\tcontinue\n\t\t}\n\t\tif (rel.targetMode === 'External') {\n\t\t\tnotesTargetRels.addWithId(rel.id, rel.type, rel.target, 'External')\n\t\t\tcontinue\n\t\t}\n\t\tconst newTarget = copyPart(\n\t\t\tctx,\n\t\t\tnotesSourceRels.resolveTarget(rel.id),\n\t\t\tisSharedByPageCopies(rel.type) ? undefined : owned\n\t\t)\n\t\tnotesTargetRels.addWithId(rel.id, rel.type, relativePartName(newNotesPartName, newTarget))\n\t}\n}\n\n/**\n * Resolve the notesMaster an imported `notesSlide` should bind to, honouring the\n * single-notesMaster-per-presentation rule (`p:notesMasterIdLst` holds 0..1\n * `p:notesMasterId`). If this deck already has a notesMaster it is reused and the\n * source's is *not* copied (the destination's notes styling wins); otherwise the\n * source notesMaster (and, via {@link copyPart}, its theme) is copied and\n * registered in `presentation.xml`. Returns the destination notesMaster partname.\n */\nfunction ensureNotesMaster(dest: Presentation, ctx: ImportContext, sourceNotesMasterPartName: string): string {\n\tconst presRels = presentationRels(dest)\n\tconst existing = presRels.byType(NOTES_MASTER_REL)[0]\n\tif (existing) return presRels.resolveTarget(existing.id)\n\n\t// No notesMaster yet: copy the source's (pulls its theme) and register it.\n\treturn registerNotesMaster(dest, copyPart(ctx, sourceNotesMasterPartName))\n}\n\n/**\n * Wire an already-added notesMaster part into `presentation.xml`: a `notesMaster`\n * relationship plus the single `p:notesMasterId` entry that `CT_NotesMasterIdList`\n * allows. Returns the partname, so callers can use it as a rel target.\n *\n * Split out of {@link ensureNotesMaster} because the two ways a notesMaster arrives\n * — copied from another `Presentation`, or authored by a generator and injected by\n * {@link Presentation.appendSlides} — differ only in how the *part* is created, not in how it is\n * registered.\n */\nfunction registerNotesMaster(dest: Presentation, notesMasterPartName: string): string {\n\tconst presPart = dest.presentationPart\n\tconst presRels = presentationRels(dest)\n\tconst relId = presRels.add(NOTES_MASTER_REL, relativePartName(presPart.partName, notesMasterPartName)).id\n\n\tconst root = presPart.dom.documentElement\n\tif (!root)\n\t\tthrow new PackageReadError(\n\t\t\t'package/part-has-no-root',\n\t\t\t'presentation.xml has no document element to register a notes master in'\n\t\t)\n\t// `p:notesMasterIdLst` follows `p:sldMasterIdLst` in CT_Presentation order.\n\tconst lst = getOrAddChild(root, 'p:notesMasterIdLst', [\n\t\t'p:handoutMasterIdLst',\n\t\t'p:sldIdLst',\n\t\t'p:sldSz',\n\t\t'p:notesSz',\n\t\t'p:embeddedFontLst',\n\t\t'p:custShowLst',\n\t\t'p:photoAlbum',\n\t\t'p:custDataLst',\n\t\t'p:kinsoku',\n\t\t'p:defaultTextStyle',\n\t\t'p:modifyVerifier',\n\t\t'p:extLst',\n\t])\n\t// CT_NotesMasterIdList holds a single p:notesMasterId; replace any stray entry.\n\tremoveChildrenByQName(lst, ['p:notesMasterId'])\n\tconst entry = createElement(presPart.dom, 'p:notesMasterId')\n\tsetAttr(entry, 'r:id', relId)\n\tlst.appendChild(entry)\n\tpresPart.markDirty()\n\treturn notesMasterPartName\n}\n\n/**\n * Resolve the notesMaster an *appended* slide's notes should bind to. Same\n * single-notesMaster rule as {@link ensureNotesMaster}: this deck's own wins when it\n * has one, so the destination's notes styling is preserved and `master.xml` is\n * discarded. Otherwise the generator's notes master is installed, together with the\n * theme its `.rels` requires (the normal write path emits that as `theme2.xml`).\n */\nexport function ensureNotesMasterFromXml(dest: Presentation, master: { xml: string; themeXml: string }): string {\n\tconst presRels = presentationRels(dest)\n\tconst existing = presRels.byType(NOTES_MASTER_REL)[0]\n\tif (existing) return presRels.resolveTarget(existing.id)\n\n\tconst masterPartName = dest.opc.reservePartNameLike('/ppt/notesMasters/notesMaster1.xml')\n\tdest.opc.addPart(masterPartName, NOTES_MASTER_CONTENT_TYPE, textEncoder.encode(master.xml))\n\n\t// A notesMaster's .rels must resolve a theme; reserve alongside any theme the\n\t// destination already owns rather than assuming theme2.xml is free.\n\tconst themePartName = dest.opc.reservePartNameLike('/ppt/theme/theme1.xml')\n\tdest.opc.addPart(themePartName, THEME_CONTENT_TYPE, textEncoder.encode(master.themeXml))\n\tdest.opc.relationshipsFor(masterPartName).add(THEME_REL, relativePartName(masterPartName, themePartName))\n\n\treturn registerNotesMaster(dest, masterPartName)\n}\n\n/**\n * Resolve the notesMaster a *newly authored* notes slide should bind to\n * ({@link Slide.addNotes} on a loaded deck). Same single-notesMaster rule as\n * {@link ensureNotesMaster} and {@link ensureNotesMasterFromXml}: this deck's own\n * wins when it has one. The third way a notesMaster arrives, and the only one with\n * no source deck and no generator instance behind it, so it has to build both parts\n * itself.\n *\n * The *theme* is where it differs from the append path. `ensureNotesMasterFromXml`\n * installs the generator's `theme2.xml` because a generator deck's notes were\n * authored against it; there is no such theme here, so the deck's **own** theme\n * (reached through the annotated slide's layout → master → theme chain) is cloned\n * into a fresh part instead. That is both the closer match to \"the destination's\n * notes styling wins\" and the safer package: the notesMaster gets a theme part of\n * its own rather than a second relationship onto the slide master's, which is the\n * arrangement PowerPoint writes (`theme1.xml` for the master, `theme2.xml` for the\n * notes master).\n *\n * Throws when the deck has no theme to clone — a package that malformed cannot be\n * given a valid notesMaster, and silently emitting one without a resolvable theme\n * is what PowerPoint reports as a repair prompt rather than a bad edit.\n * @param {Presentation} dest - the deck being authored onto\n * @param {string} slidePartName - the slide whose notes are being authored, used to find the theme\n * @return {string} the destination notesMaster partname\n */\nexport function ensureNotesMasterForAuthoring(dest: Presentation, slidePartName: string): string {\n\tconst presRels = presentationRels(dest)\n\tconst existing = presRels.byType(NOTES_MASTER_REL)[0]\n\tif (existing) return presRels.resolveTarget(existing.id)\n\n\tconst themePartName = resolveSlideThemeParts(dest.opc, slidePartName).themePartName\n\tconst themePart = themePartName ? dest.opc.part(themePartName) : undefined\n\tif (!themePart)\n\t\tthrow new PackageReadError(\n\t\t\t'package/part-missing',\n\t\t\t`addNotes: no theme reachable from ${slidePartName} to bind a new notes master to`\n\t\t)\n\n\tconst masterPartName = dest.opc.reservePartNameLike('/ppt/notesMasters/notesMaster1.xml')\n\tdest.opc.addPart(masterPartName, NOTES_MASTER_CONTENT_TYPE, textEncoder.encode(makeXmlNotesMaster()))\n\n\t// A notesMaster's .rels must resolve a theme; clone the deck's rather than share\n\t// the slide master's part. Reserved alongside any theme this deck already owns.\n\tconst notesThemePartName = dest.opc.reservePartNameLike('/ppt/theme/theme1.xml')\n\tdest.opc.addPart(notesThemePartName, themePart.contentType, themePart.bytes)\n\tdest.opc.relationshipsFor(masterPartName).add(THEME_REL, relativePartName(masterPartName, notesThemePartName))\n\n\treturn registerNotesMaster(dest, masterPartName)\n}\n","/**\n * Authoring speaker notes onto a slide of a *loaded* deck ({@link Slide.addNotes}).\n *\n * The third way a notes slide comes into being, after the two in `notes-master.ts`\n * (carried from another `Presentation` by `importSlide({ importNotes: true })`, or\n * emitted by the generator and spliced on by `appendSlides`). Those two both *move*\n * an existing part; this one has no source part to move, so it builds one.\n *\n * The part it builds is the generator's, not a second design: the fixed three-\n * placeholder frame comes from {@link makeXmlNotesSlideSkeleton}, and the body\n * paragraphs carry the same elements and attributes the write path emits for a plain\n * `pptx.addSlide().addNotes(text)`. `test/read/add-notes.test.js` asserts that\n * equivalence, so the two cannot drift apart unnoticed — the same guarantee\n * `src/ooxml/` gives the constants both halves share.\n *\n * The one difference is empty-element *spelling*: the write path emits `a:rPr` as an\n * open/close pair and this emits it self-closed, because a part the read model\n * authors is reserialized through `read/oxml/dom.ts`, which self-closes every empty\n * element. Writing the open/close form here would not survive the first save, so the\n * form that does is written in the first place and the test normalizes the spelling\n * rather than pretending the bytes match.\n *\n * Notes text is split on `\\n` into paragraphs, matching the write-side `addNotes`;\n * runs carry no formatting of their own. Per-run formatting, hyperlinks, and\n * multi-run paragraphs are reached afterwards through `slide.notesTextFrame`, which\n * is the read model's normal text-editing surface.\n */\n\nimport { el, raw, voidEl } from '../../../gen/oxml/el.js'\nimport { makeXmlNotesSlideSkeleton } from '../../../gen/slide/notes.js'\nimport { attr, firstChild, getElements, parseXml, removeChildrenByQName, type Element } from '../../oxml/dom.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { NOTES_MASTER_REL, NOTES_SLIDE_CONTENT_TYPE, NOTES_SLIDE_REL, SLIDE_REL } from '../../../ooxml/rel-types.js'\nimport { InternalError, PackageReadError } from '../../../errors.js'\nimport { ensureNotesMasterForAuthoring } from './notes-master.js'\nimport type { Slide } from '../slide.js'\nimport { OOXML_NS } from '../../../ooxml/namespaces.js'\nimport { nvPrOf, spTreeOf } from '../../oxml/slide-dom.js'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * The `a:p` children of a notes body, one per `\\n`-separated line: the write path's\n * output for an unformatted note, modulo the empty-element spelling described above.\n * An empty line yields a paragraph with no run, exactly as `genXmlNotesParagraphs`\n * does.\n * @param {string} text - the note, `\\n` separating paragraphs\n * @return {string} concatenated `a:p` XML\n */\nfunction notesParagraphsXml(text: string): string {\n\treturn text\n\t\t.split('\\n')\n\t\t.map((line) => line.replace(/\\r/g, ''))\n\t\t.map((line) =>\n\t\t\tel('a:p', null, [\n\t\t\t\traw(\n\t\t\t\t\tline === ''\n\t\t\t\t\t\t? ''\n\t\t\t\t\t\t: el('a:r', null, [raw(voidEl('a:rPr', { lang: 'en-US', dirty: 0 })), raw(el('a:t', null, line))])\n\t\t\t\t),\n\t\t\t\traw(voidEl('a:endParaRPr', { lang: 'en-US', dirty: 0 })),\n\t\t\t])\n\t\t)\n\t\t.join('')\n}\n\n/**\n * Replace a notes body's paragraphs with `text`, in the body's own document.\n *\n * The path taken when the slide *already* has a notes part — an imported one, or one\n * an earlier `addNotes` wrote. Only the `a:p` children are replaced, so the part's\n * geometry, its `a:bodyPr`/`a:lstStyle`, and its other two placeholders survive. The\n * body's hyperlink relationships are deliberately *not* pruned: a caller replacing\n * text has not asked for its rels to be rewritten, and a now-unreferenced notes\n * hyperlink rel is inert (nothing resolves it on save).\n * @param {Element} txBody - the body placeholder's `p:txBody`\n * @param {string} text - the note, `\\n` separating paragraphs\n */\nfunction replaceNotesParagraphs(txBody: Element, text: string): void {\n\tconst doc = txBody.ownerDocument\n\tif (!doc) throw new InternalError('oxml/node-has-no-document', 'Notes body has no owner document')\n\tremoveChildrenByQName(txBody, ['a:p'])\n\t// Parsed inside a namespace-declaring wrapper, then imported: the same move\n\t// `animation.ts` makes to bring authored XML into a loaded part's document.\n\tconst wrapper = parseXml(`<w xmlns:a=\"${OOXML_NS.a}\">${notesParagraphsXml(text)}</w>`).documentElement\n\tif (!wrapper)\n\t\tthrow new InternalError('oxml/node-has-no-document', 'Authored notes paragraphs did not parse to a root')\n\tfor (const paragraph of Array.from(wrapper.childNodes)) txBody.appendChild(doc.importNode(paragraph, true))\n}\n\n/**\n * The `p:txBody` of a notes slide's body placeholder (`p:ph type=\"body\"`), or `null`\n * when the part carries none. A raw walk rather than a `NotesSlide`/`TextFrame` hop,\n * because the caller needs the element itself to rewrite and the modeled surface\n * would resolve a notes theme context it has no use for.\n * @param {Element | null} root - the notes slide's `p:notes` root\n * @return {Element | null} the body placeholder's text body\n */\nfunction notesBodyTxBody(root: Element | null): Element | null {\n\tconst spTree = spTreeOf(root)\n\tif (!spTree) return null\n\tfor (const sp of getElements(spTree, 'p:sp')) {\n\t\tconst nvPr = nvPrOf(sp)\n\t\tconst ph = nvPr && firstChild(nvPr, 'p:ph')\n\t\tif (ph && attr(ph, 'type') === 'body') return firstChild(sp, 'p:txBody')\n\t}\n\treturn null\n}\n\n/**\n * Give `slide` the speaker notes `text`, creating its notes slide part when it has\n * none, and return the notes part's name.\n *\n * When the slide already has a notes part, only the body paragraphs are rewritten\n * (see {@link replaceNotesParagraphs}). When it has none, the part is built and\n * wired: `slide → notesSlide`, and on the new part the two relationships a notes\n * slide always carries — `notesMaster` as rId1 and a `slide` back-reference as rId2,\n * the ids and order the write path reserves.\n *\n * The notes master is resolved through {@link ensureNotesMasterForAuthoring}: this\n * deck's own when it has one, otherwise a fresh one bound to a clone of the deck's\n * theme. That is the single-notesMaster-per-presentation rule the import and append\n * paths already follow, so the three cannot produce a second master between them.\n * @param {Slide} slide - the slide to annotate\n * @param {string} text - the note, `\\n` separating paragraphs\n * @return {string} the notes slide's partname\n */\nexport function authorNotes(slide: Slide, text: string): string {\n\tconst opc = slide.presentation.opc\n\n\tconst existingRel = slide.relationships.byType(NOTES_SLIDE_REL)[0]\n\tif (existingRel) {\n\t\tconst partName = slide.relationships.resolveTarget(existingRel.id)\n\t\tconst part = opc.part(partName)\n\t\tif (!part)\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/part-missing',\n\t\t\t\t`addNotes: slide ${slide.partName} has a notesSlide rel to a missing part ${partName}`\n\t\t\t)\n\t\tconst txBody = notesBodyTxBody(part.dom.documentElement)\n\t\tif (!txBody)\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/part-has-no-root',\n\t\t\t\t`addNotes: notes slide ${partName} has no body placeholder to write into`\n\t\t\t)\n\t\treplaceNotesParagraphs(txBody, text)\n\t\tpart.markDirty()\n\t\treturn partName\n\t}\n\n\t// No notes part yet: build one. The slide-number field caches this slide's\n\t// 1-based position, the value the write path stamps; PowerPoint recomputes it.\n\tconst slideNum = slide.index + 1\n\tconst partName = opc.reservePartNameLike('/ppt/notesSlides/notesSlide1.xml')\n\topc.addPart(\n\t\tpartName,\n\t\tNOTES_SLIDE_CONTENT_TYPE,\n\t\ttextEncoder.encode(makeXmlNotesSlideSkeleton(notesParagraphsXml(text), slideNum))\n\t)\n\n\tslide.relationships.add(NOTES_SLIDE_REL, relativePartName(slide.partName, partName))\n\n\tconst notesRels = opc.relationshipsFor(partName)\n\tconst masterPartName = ensureNotesMasterForAuthoring(slide.presentation, slide.partName)\n\tnotesRels.addWithId('rId1', NOTES_MASTER_REL, relativePartName(partName, masterPartName))\n\tnotesRels.addWithId('rId2', SLIDE_REL, relativePartName(partName, slide.partName))\n\n\treturn partName\n}\n","/**\n * Read a slide's **legacy** review comments (`p:cmLst/p:cm` in\n * `ppt/comments/commentN.xml`) plus the deck-wide comment-author registry\n * (`p:cmAuthorLst/p:cmAuthor` in `ppt/commentAuthors.xml`), the read counterparts\n * of the write-side `slide.addComment(...)` / `commentAuthors.xml` emitter.\n *\n * This models the ISO/IEC 29500 §13 *legacy* comment schema — the one the writer\n * authors and older PowerPoint decks carry. The 2018 **modern** comment parts\n * (`p188:cm` / `ppt/comments/modernComment_*` + `authors.xml`) are a separate,\n * GUID-keyed, thread-capable schema; they are decoded read-only by the\n * `readModern*` functions below, and have no writer (preserved byte-perfect on\n * round-trip). The two schemas do not coexist in a single deck in practice —\n * {@link commentSchema} reports which one a deck uses.\n */\nimport { OpcPackage } from '../opc/package.js'\nimport type { Part } from '../opc/part.js'\nimport { attr, firstChild, getElements, intValue, type Element } from '../oxml/dom.js'\n\n/** The slide → comments-part relationship type (legacy comments). */\nconst COMMENTS_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/comments'\n/** The presentation → commentAuthors-part relationship type. */\nconst COMMENT_AUTHORS_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/commentAuthors'\n\n/** Content type of a legacy per-slide comments part (`ppt/comments/commentN.xml`). */\nconst LEGACY_COMMENTS_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.presentationml.comments+xml'\n/** The slide → modern-comments-part relationship type (2018 schema). */\nconst MODERN_COMMENTS_REL_TYPE = 'http://schemas.microsoft.com/office/2018/10/relationships/comments'\n/** The presentation → modern-authors-part relationship type (2018 schema). */\nconst MODERN_AUTHORS_REL_TYPE = 'http://schemas.microsoft.com/office/2018/10/relationships/authors'\n/** Content type of the modern per-slide comments part (`ppt/comments/modernComment_*.xml`). */\nconst MODERN_COMMENTS_CONTENT_TYPE = 'application/vnd.ms-powerpoint.comments+xml'\n\n/** One entry of the deck-wide comment-author registry (`p:cmAuthor`). */\nexport interface CommentAuthor {\n\t/** Author id (`@id`), referenced by each comment's `@authorId`. */\n\tid: number | null\n\t/** Display name (`@name`). */\n\tname: string\n\t/** Initials shown in the comment marker (`@initials`). */\n\tinitials: string\n\t/** Highest per-author comment index used (`@lastIdx`). */\n\tlastIdx: number | null\n\t/** Author colour slot (`@clrIdx`). */\n\tclrIdx: number | null\n}\n\n/** One legacy review comment (`p:cm`), with its author resolved via the registry. */\nexport interface Comment {\n\t/** Resolved author display name (via `@authorId` → `commentAuthors.xml`), or `null` when unresolved. */\n\tauthor: string | null\n\t/** Resolved author initials, or `null` when unresolved. */\n\tauthorInitials: string | null\n\t/** The comment's `@authorId`, or `null` when absent/unparseable. */\n\tauthorId: number | null\n\t/** The comment's per-author 1-based index (`@idx`), or `null` when absent. */\n\tidx: number | null\n\t/** The comment body text (`p:text`). */\n\ttext: string\n\t/** Marker X position in EMU (`p:pos/@x`), or `null` when absent. */\n\tx: number | null\n\t/** Marker Y position in EMU (`p:pos/@y`), or `null` when absent. */\n\ty: number | null\n\t/** Authored timestamp (`@dt`, ISO-8601 as written), or `null` when absent. */\n\tdate: string | null\n}\n\n/** Parse a `p:cmAuthorLst` root element into the author registry. */\nfunction parseCommentAuthors(root: Element | null): CommentAuthor[] {\n\tif (!root) return []\n\treturn getElements(root, 'p:cmAuthor').map((el) => ({\n\t\tid: intValue(attr(el, 'id')),\n\t\tname: attr(el, 'name') ?? '',\n\t\tinitials: attr(el, 'initials') ?? '',\n\t\tlastIdx: intValue(attr(el, 'lastIdx')),\n\t\tclrIdx: intValue(attr(el, 'clrIdx')),\n\t}))\n}\n\n/**\n * Read the deck-wide comment authors from `ppt/commentAuthors.xml`, resolved via the\n * presentation part's `commentAuthors` relationship. `[]` when the deck has no comments.\n */\nexport function readCommentAuthors(opc: OpcPackage, presentationPartName: string): CommentAuthor[] {\n\tconst rels = opc.relationshipsFor(presentationPartName)\n\tconst rel = rels.byType(COMMENT_AUTHORS_REL_TYPE)[0]\n\tif (!rel) return []\n\tconst part = opc.part(rels.resolveTarget(rel.id))\n\treturn parseCommentAuthors(part?.dom.documentElement ?? null)\n}\n\n/**\n * Read one slide's legacy comments from its `comments/commentN.xml` part (resolved\n * via the slide's `comments` relationship), resolving each comment's `@authorId`\n * against `authors` (typically {@link readCommentAuthors}). `[]` when the slide has\n * no comments part.\n */\nexport function readSlideComments(opc: OpcPackage, slidePart: Part, authors: CommentAuthor[]): Comment[] {\n\tconst rels = opc.relationshipsFor(slidePart.partName)\n\tconst rel = rels.byType(COMMENTS_REL_TYPE)[0]\n\tif (!rel) return []\n\tconst part = opc.part(rels.resolveTarget(rel.id))\n\tconst root = part?.dom.documentElement\n\tif (!root) return []\n\n\tconst byId = new Map(authors.map((a) => [a.id, a]))\n\treturn getElements(root, 'p:cm').map((cm) => {\n\t\tconst authorId = intValue(attr(cm, 'authorId'))\n\t\tconst author = authorId !== null ? (byId.get(authorId) ?? null) : null\n\t\tconst pos = firstChild(cm, 'p:pos')\n\t\tconst textEl = firstChild(cm, 'p:text')\n\t\treturn {\n\t\t\tauthor: author ? author.name : null,\n\t\t\tauthorInitials: author ? author.initials : null,\n\t\t\tauthorId,\n\t\t\tidx: intValue(attr(cm, 'idx')),\n\t\t\ttext: textEl?.textContent ?? '',\n\t\t\tx: pos ? intValue(attr(pos, 'x')) : null,\n\t\t\ty: pos ? intValue(attr(pos, 'y')) : null,\n\t\t\tdate: attr(cm, 'dt') ?? null,\n\t\t}\n\t})\n}\n\n// --- Modern (2018) comments ------------------------------------------------\n//\n// PowerPoint's post-2018 comment schema (`p188`, uri\n// `http://schemas.microsoft.com/office/powerpoint/2018/8/main`). Authors move to\n// their own deck-wide `ppt/authors.xml` keyed by **GUID**, and each slide's\n// comments live in a `ppt/comments/modernComment_*.xml` part that supports reply\n// threads. This is read-only; the writer never emits these, and a modern part is\n// preserved byte-for-byte on round-trip.\n\n/** One entry of the modern deck-wide author registry (`p188:author`). */\nexport interface ModernCommentAuthor {\n\t/** Author id (`@id`) — a GUID string like `{E8A64ABA-…}`, referenced by each comment's `@authorId`. */\n\tid: string | null\n\t/** Display name (`@name`). */\n\tname: string\n\t/** Initials (`@initials`). */\n\tinitials: string\n\t/** Account identifier (`@userId`, e.g. an email), or `null`. */\n\tuserId: string | null\n\t/** Identity provider (`@providerId`, e.g. `Windows Live`), or `null`. */\n\tproviderId: string | null\n}\n\n/** One modern comment or reply (`p188:cm` / `p188:reply`), with its author resolved via the registry. */\nexport interface ModernComment {\n\t/** The comment's own GUID id (`@id`), or `null` when absent. */\n\tid: string | null\n\t/** Resolved author display name (via `@authorId` → `authors.xml`), or `null` when unresolved. */\n\tauthor: string | null\n\t/** Resolved author initials, or `null` when unresolved. */\n\tauthorInitials: string | null\n\t/** The comment's `@authorId` GUID, or `null` when absent. */\n\tauthorId: string | null\n\t/** Creation timestamp (`@created`, ISO-8601 as written), or `null` when absent. */\n\tcreated: string | null\n\t/** The comment body text; multiple paragraphs are joined with `\\n`. */\n\ttext: string\n\t/** Marker X position in EMU (`p188:pos/@x`), or `null` (replies carry no position). */\n\tx: number | null\n\t/** Marker Y position in EMU (`p188:pos/@y`), or `null` (replies carry no position). */\n\ty: number | null\n\t/** Nested replies in thread order; each is itself a {@link ModernComment} with no further replies. */\n\treplies: ModernComment[]\n}\n\n/** Which comment schema a deck carries. `'none'` when it has neither part. */\nexport type CommentSchema = 'legacy' | 'modern' | 'none'\n\n/** Concatenate a `p188:txBody`'s paragraphs into plain text, joining paragraphs with `\\n`. */\nfunction modernCommentText(el: Element): string {\n\tconst txBody = firstChild(el, 'p188:txBody')\n\tif (!txBody) return ''\n\tconst paras = getElements(txBody, 'a:p')\n\tif (paras.length === 0) return txBody.textContent ?? ''\n\treturn paras.map((p) => p.textContent ?? '').join('\\n')\n}\n\n/**\n * Decode one `p188:cm` (or `p188:reply`) element. Only the top-level comment\n * carries a position and a reply list; replies pass `withThread: false` so they\n * report `x`/`y` as `null` and never recurse (the schema forbids nested replies).\n */\nfunction parseModernComment(\n\tel: Element,\n\tbyId: Map<string | null, ModernCommentAuthor>,\n\twithThread: boolean\n): ModernComment {\n\tconst authorId = attr(el, 'authorId')\n\tconst author = authorId !== null ? (byId.get(authorId) ?? null) : null\n\tconst pos = withThread ? firstChild(el, 'p188:pos') : null\n\tconst replyLst = withThread ? firstChild(el, 'p188:replyLst') : null\n\treturn {\n\t\tid: attr(el, 'id'),\n\t\tauthor: author ? author.name : null,\n\t\tauthorInitials: author ? author.initials : null,\n\t\tauthorId,\n\t\tcreated: attr(el, 'created'),\n\t\ttext: modernCommentText(el),\n\t\tx: pos ? intValue(attr(pos, 'x')) : null,\n\t\ty: pos ? intValue(attr(pos, 'y')) : null,\n\t\treplies: replyLst ? getElements(replyLst, 'p188:reply').map((r) => parseModernComment(r, byId, false)) : [],\n\t}\n}\n\n/**\n * Read the deck-wide modern comment authors from `ppt/authors.xml`, resolved via\n * the presentation part's 2018 `authors` relationship. `[]` when the deck has no\n * modern authors part.\n */\nexport function readModernCommentAuthors(opc: OpcPackage, presentationPartName: string): ModernCommentAuthor[] {\n\tconst rels = opc.relationshipsFor(presentationPartName)\n\tconst rel = rels.byType(MODERN_AUTHORS_REL_TYPE)[0]\n\tif (!rel) return []\n\tconst part = opc.part(rels.resolveTarget(rel.id))\n\tconst root = part?.dom.documentElement\n\tif (!root) return []\n\treturn getElements(root, 'p188:author').map((el) => ({\n\t\tid: attr(el, 'id'),\n\t\tname: attr(el, 'name') ?? '',\n\t\tinitials: attr(el, 'initials') ?? '',\n\t\tuserId: attr(el, 'userId'),\n\t\tproviderId: attr(el, 'providerId'),\n\t}))\n}\n\n/**\n * Read one slide's modern comments from its `modernComment_*.xml` part (resolved\n * via the slide's 2018 `comments` relationship), resolving each comment's and\n * reply's `@authorId` GUID against `authors` (typically\n * {@link readModernCommentAuthors}). Replies are nested, not flattened. `[]` when\n * the slide has no modern comments part.\n */\nexport function readModernSlideComments(\n\topc: OpcPackage,\n\tslidePart: Part,\n\tauthors: ModernCommentAuthor[]\n): ModernComment[] {\n\tconst rels = opc.relationshipsFor(slidePart.partName)\n\tconst rel = rels.byType(MODERN_COMMENTS_REL_TYPE)[0]\n\tif (!rel) return []\n\tconst root = opc.part(rels.resolveTarget(rel.id))?.dom.documentElement\n\tif (!root) return []\n\tconst byId = new Map(authors.map((a) => [a.id, a]))\n\treturn getElements(root, 'p188:cm').map((cm) => parseModernComment(cm, byId, true))\n}\n\n/**\n * Report which comment schema a deck uses: `'modern'` when it carries any 2018\n * `modernComment_*` part, else `'legacy'` when it carries any classic\n * `commentN.xml` part, else `'none'`. Lets a consumer pick the right accessor\n * ({@link readModernSlideComments} vs {@link readSlideComments}) without probing\n * both.\n */\nexport function commentSchema(opc: OpcPackage): CommentSchema {\n\tif (opc.partsByContentType(MODERN_COMMENTS_CONTENT_TYPE).length > 0) return 'modern'\n\tif (opc.partsByContentType(LEGACY_COMMENTS_CONTENT_TYPE).length > 0) return 'legacy'\n\treturn 'none'\n}\n","/**\n * Read the programmatic **tags** attached to an owner part — a slide or the\n * presentation itself. A tag is a simple `@name`/`@val` string pair PowerPoint\n * (or an add-in) stores out-of-band from the visible content, referenced from the\n * owner via `p:custDataLst/p:tags@r:id` and materialized in a `ppt/tags/tagN.xml`\n * part (`p:tagLst` → `p:tag`, CT_StringTag).\n *\n * There is no writer for tags, so this is a read-only accessor; a deck's tag parts\n * are preserved byte-for-byte on round-trip. An owner may reference more than one\n * tag part (rare but legal); {@link readTagsForPart} concatenates them in\n * relationship order.\n */\nimport { OpcPackage } from '../opc/package.js'\nimport { attr, getElements } from '../oxml/dom.js'\n\n/** The owner → tags-part relationship type. */\nconst TAGS_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/tags'\n\n/** One programmatic tag (`p:tag`) — a name/value string pair. */\nexport interface Tag {\n\t/** The tag's `@name`. */\n\tname: string\n\t/** The tag's `@val`. */\n\tval: string\n}\n\n/**\n * Read every tag referenced by `ownerPartName` (a slide part or the presentation\n * part), resolving the owner's `tags` relationship(s) to their `ppt/tags/tagN.xml`\n * part(s) and flattening each part's `p:tag` children into `{ name, val }`. `[]`\n * when the owner references no tag part. Rel-driven rather than walking\n * `p:custDataLst`, so it is robust to element ordering in the owner.\n */\nexport function readTagsForPart(opc: OpcPackage, ownerPartName: string): Tag[] {\n\tconst rels = opc.relationshipsFor(ownerPartName)\n\tconst out: Tag[] = []\n\tfor (const rel of rels.byType(TAGS_REL_TYPE)) {\n\t\tconst root = opc.part(rels.resolveTarget(rel.id))?.dom.documentElement\n\t\tif (!root) continue\n\t\tfor (const tag of getElements(root, 'p:tag')) {\n\t\t\tout.push({ name: attr(tag, 'name') ?? '', val: attr(tag, 'val') ?? '' })\n\t\t}\n\t}\n\treturn out\n}\n","/**\n * Typed read/edit model for a slide's `p:transition` (slide-show transition).\n *\n * The element sits in `CT_Slide` between `p:clrMapOvr` and `p:timing` and comes\n * in two shapes PowerPoint emits:\n *\n * - **bare** `<p:transition spd=… advClick=… advTm=…><p:TYPE …/></p:transition>`\n * when the duration matches a coarse `spd` speed bucket; and\n * - **wrapped** `<mc:AlternateContent>` carrying a `<mc:Choice Requires=\"p14\">`\n * whose `p:transition` adds the precise `p14:dur` (milliseconds), plus a base\n * `<mc:Fallback>` without it — emitted for an off-bucket exact duration.\n *\n * The getter prefers the `p14` Choice (so `durationMs` is recovered); the setter\n * emits the `mc:AlternateContent` form when `durationMs` is set and the bare form\n * otherwise. See `docs/animations-and-transitions.md`.\n */\nimport {\n\tOOXML_NS,\n\tattr,\n\tboolValue,\n\tchildElements,\n\tcreateElement,\n\tfirstChild,\n\tintValue,\n\tsetAttr,\n\ttype Document,\n\ttype Element,\n} from '../oxml/dom.js'\n\n/** `ST_TransitionSpeed` — the coarse speed bucket (`spd`), default `fast`. */\nexport type TransitionSpeed = 'slow' | 'med' | 'fast'\n\n/** Decoded slide transition (`p:transition`), as returned by {@link Slide.transition}. */\nexport interface TransitionInfo {\n\t/**\n\t * The transition-type element's local name (e.g. `fade`, `push`, `wipe`,\n\t * `cut`, `dissolve`). Base ECMA-376 types use the `p` namespace; modern\n\t * PowerPoint types live in `p14`/`p15`/`p159` (see {@link namespace}).\n\t */\n\ttype: string\n\t/** The transition element's namespace prefix (`p` for base, else `p14`/`p15`/`p159`). */\n\tnamespace: string\n\t/** Coarse speed bucket; `fast` when `spd` is absent (its schema default). */\n\tspeed: TransitionSpeed\n\t/** Exact duration in milliseconds (`p14:dur`), or `null` when only a speed bucket is set. */\n\tdurationMs: number | null\n\t/** Whether the slide advances on click (`advClick`, default `true`). */\n\tadvanceOnClick: boolean\n\t/** Auto-advance delay in milliseconds (`advTm`), or `null` when not timed. */\n\tadvanceAfterMs: number | null\n\t/** Type-specific variant attributes (e.g. `{ dir: 'd' }` for push, `{ spokes: '2' }` for wheel). */\n\tvariant: Record<string, string>\n\t/** Transition sound (`p:sndAc`), or `null` when the transition is silent. */\n\tsound: TransitionSoundInfo | null\n}\n\n/** Decoded transition sound (`p:sndAc`). A start sound (`p:stSnd`) or the stop-previous form (`p:endSnd`). */\nexport interface TransitionSoundInfo {\n\t/** `start` for an embedded start sound (`p:stSnd`), `stop` for the stop-previous form (`p:endSnd`). */\n\tform: 'start' | 'stop'\n\t/** Whether the start sound loops until the next sound (`p:stSnd @loop`). Always `false` for `stop`. */\n\tloop: boolean\n\t/** Relationship id of the embedded WAV (`p:snd @r:embed`), or `null` (stop form / missing). */\n\tembedRid: string | null\n\t/** Display name on `p:snd @name`, or `null`. */\n\tname: string | null\n}\n\n/** Transition fields accepted by the {@link Slide.transition} setter. `speed` defaults are derived from `durationMs`. */\nexport interface TransitionInput {\n\ttype: string\n\t/** Namespace prefix for the type element; defaults to `p` (base ECMA-376). */\n\tnamespace?: string\n\tspeed?: TransitionSpeed\n\tdurationMs?: number | null\n\tadvanceOnClick?: boolean\n\tadvanceAfterMs?: number | null\n\tvariant?: Record<string, string>\n}\n\n/** Child element names of `p:transition` that are not the transition-type choice. */\nconst NON_TYPE_CHILDREN = new Set(['sndAc', 'extLst'])\n\n/** The single transition-type child element (the choice), or `null`. */\nfunction typeElement(transition: Element): Element | null {\n\tfor (const child of childElements(transition)) {\n\t\tif (!NON_TYPE_CHILDREN.has(child.localName ?? '')) return child\n\t}\n\treturn null\n}\n\n/** Namespace prefix for a URI, defaulting to `p` for the base presentationml namespace. */\nfunction prefixFor(uri: string | null): string {\n\tif (!uri) return 'p'\n\tfor (const [prefix, ns] of Object.entries(OOXML_NS)) {\n\t\tif (ns === uri) return prefix\n\t}\n\t// Modern transition namespaces not in the canonical registry.\n\tif (uri === 'http://schemas.microsoft.com/office/powerpoint/2012/main') return 'p15'\n\tif (uri === 'http://schemas.microsoft.com/office/powerpoint/2015/9/main') return 'p159'\n\treturn 'p'\n}\n\n/** Collect a transition-type element's non-namespace attributes by local name. */\nfunction variantAttrs(element: Element): Record<string, string> {\n\tconst out: Record<string, string> = {}\n\tconst attrs = element.attributes\n\tfor (let i = 0; i < attrs.length; i++) {\n\t\tconst a = attrs[i]\n\t\tif (!a || a.prefix === 'xmlns' || a.name === 'xmlns') continue\n\t\tout[a.localName ?? a.name] = a.value\n\t}\n\treturn out\n}\n\n/**\n * Locate the slide's transition under the root `p:sld`, returning the\n * `p:transition` element to decode (the `p14` Choice when wrapped) and the\n * outermost node that represents it (the bare element or the `mc:AlternateContent`\n * wrapper), or `null` when the slide has no transition.\n */\nexport function findTransition(root: Element): { transition: Element; outer: Element } | null {\n\tconst bare = firstChild(root, 'p:transition')\n\tif (bare) return { transition: bare, outer: bare }\n\n\tconst altContent = firstChild(root, 'mc:AlternateContent')\n\tif (altContent) {\n\t\tconst choice = firstChild(altContent, 'mc:Choice')\n\t\tconst transition = choice ? firstChild(choice, 'p:transition') : null\n\t\tif (transition) return { transition, outer: altContent }\n\t\t// Degenerate AlternateContent with only a Fallback — still surface it.\n\t\tconst fallback = firstChild(altContent, 'mc:Fallback')\n\t\tconst fbTransition = fallback ? firstChild(fallback, 'p:transition') : null\n\t\tif (fbTransition) return { transition: fbTransition, outer: altContent }\n\t}\n\treturn null\n}\n\n/** Decode a `p:transition` element into a {@link TransitionInfo}, or `null` when malformed. */\nexport function parseTransition(root: Element): TransitionInfo | null {\n\tconst found = findTransition(root)\n\tif (!found) return null\n\tconst { transition } = found\n\tconst type = typeElement(transition)\n\tif (!type) return null\n\n\tconst advClick = boolValue(attr(transition, 'advClick'))\n\tconst advTm = intValue(attr(transition, 'advTm'))\n\tconst spd = attr(transition, 'spd')\n\treturn {\n\t\ttype: type.localName ?? '',\n\t\tnamespace: prefixFor(type.namespaceURI),\n\t\tspeed: spd === 'slow' || spd === 'med' || spd === 'fast' ? spd : 'fast',\n\t\tdurationMs: intValue(attr(transition, 'p14:dur')),\n\t\tadvanceOnClick: advClick ?? true,\n\t\tadvanceAfterMs: advTm,\n\t\tvariant: variantAttrs(type),\n\t\tsound: parseSound(transition),\n\t}\n}\n\n/** Decode the `p:sndAc` sound-action child of a transition into a {@link TransitionSoundInfo}, or `null`. */\nfunction parseSound(transition: Element): TransitionSoundInfo | null {\n\tconst sndAc = firstChild(transition, 'p:sndAc')\n\tif (!sndAc) return null\n\tconst stSnd = firstChild(sndAc, 'p:stSnd')\n\tif (stSnd) {\n\t\tconst snd = firstChild(stSnd, 'p:snd')\n\t\treturn {\n\t\t\tform: 'start',\n\t\t\tloop: boolValue(attr(stSnd, 'loop')) ?? false,\n\t\t\tembedRid: snd ? attr(snd, 'r:embed') : null,\n\t\t\tname: snd ? attr(snd, 'name') : null,\n\t\t}\n\t}\n\tif (firstChild(sndAc, 'p:endSnd')) return { form: 'stop', loop: false, embedRid: null, name: null }\n\treturn null\n}\n\n/** Map an exact duration (ms) to PowerPoint's coarse speed bucket. */\nfunction speedForDuration(durationMs: number): TransitionSpeed {\n\tif (durationMs <= 500) return 'fast'\n\tif (durationMs <= 1000) return 'med'\n\treturn 'slow'\n}\n\n/** Build a `p:transition` element (without the `p14:dur` attribute) from an input. */\nfunction buildTransitionElement(\n\tdoc: Document,\n\tinput: TransitionInput,\n\tspeed: TransitionSpeed | null,\n\twithDur: boolean\n): Element {\n\tconst transition = createElement(doc, 'p:transition')\n\tif (speed) setAttr(transition, 'spd', speed)\n\tif (withDur && typeof input.durationMs === 'number')\n\t\tsetAttr(transition, 'p14:dur', String(Math.round(input.durationMs)))\n\tif (input.advanceOnClick === false) setAttr(transition, 'advClick', '0')\n\tif (typeof input.advanceAfterMs === 'number') setAttr(transition, 'advTm', String(Math.round(input.advanceAfterMs)))\n\n\tconst prefix = input.namespace ?? 'p'\n\tconst type = createElement(doc, `${prefix}:${input.type}`)\n\tfor (const [name, value] of Object.entries(input.variant ?? {})) setAttr(type, name, value)\n\ttransition.appendChild(type)\n\treturn transition\n}\n\n/**\n * Build the DOM node for a transition: the bare `p:transition` when no exact\n * duration is requested, or an `mc:AlternateContent` wrapper (a `p14` Choice\n * carrying `p14:dur` plus a base `mc:Fallback`) when `durationMs` is set.\n */\nexport function buildTransition(doc: Document, input: TransitionInput): Element {\n\tconst hasDuration = typeof input.durationMs === 'number'\n\tconst speed = input.speed ?? (hasDuration ? speedForDuration(input.durationMs as number) : null)\n\n\tif (!hasDuration) return buildTransitionElement(doc, input, speed, false)\n\n\tconst alt = createElement(doc, 'mc:AlternateContent')\n\tconst choice = createElement(doc, 'mc:Choice')\n\tsetAttr(choice, 'Requires', 'p14')\n\tchoice.appendChild(buildTransitionElement(doc, input, speed, true))\n\talt.appendChild(choice)\n\tconst fallback = createElement(doc, 'mc:Fallback')\n\tfallback.appendChild(buildTransitionElement(doc, input, speed, false))\n\talt.appendChild(fallback)\n\treturn alt\n}\n\n/** Remove any existing transition node (bare or wrapped) from the slide root. */\nexport function removeTransition(root: Element): void {\n\tconst found = findTransition(root)\n\tif (found) root.removeChild(found.outer)\n}\n","/**\n * Spid-aware, otherwise-opaque handling of a slide's build-animation tree\n * (`p:timing` / `p:bldLst`).\n *\n * The `p:timing` subtree is `CT_TimeNodeList` — deeply recursive and modeled\n * here as opaque DOM (an unmodified slide round-trips it byte-identically for\n * free). The only structured data we extract or rewrite is the set of `spid`\n * references — `<p:spTgt spid>` inside the timing tree and `<p:bldP spid>` in the\n * build list — so animations stay coherent when shape ids change. Three purely\n * structural operations: **enumerate**, **remap**, and **prune**. See\n * `docs/animations-and-transitions.md` (\"spid-awareness\").\n */\nimport {\n\tOOXML_NS,\n\tattr,\n\tchildElements,\n\tcreateElement,\n\tfirstChild,\n\tinsertInOrder,\n\tintValue,\n\tparseXml,\n\tsetAttr,\n\ttype Document,\n\ttype Element,\n} from '../oxml/dom.js'\nimport { InternalError } from '../../errors.js'\n\nconst P_NS = OOXML_NS.p\n\n/** Every element carrying an animation `spid` reference, across the timing tree and build list. */\nfunction spidElements(root: Element): Element[] {\n\tconst out: Element[] = []\n\tfor (const el of root.getElementsByTagNameNS(OOXML_NS.p, 'spTgt')) out.push(el)\n\tfor (const el of root.getElementsByTagNameNS(OOXML_NS.p, 'bldP')) out.push(el)\n\treturn out\n}\n\n/**\n * Whether the slide carries build animations — a `<p:bldP>` entry or any timing\n * node with a `presetID` (distinguishing animation timing from the media-loop\n * timing that has neither).\n */\nexport function hasAnimations(root: Element): boolean {\n\tif (root.getElementsByTagNameNS(OOXML_NS.p, 'bldP').length > 0) return true\n\tfor (const cTn of root.getElementsByTagNameNS(OOXML_NS.p, 'cTn')) {\n\t\tif (attr(cTn, 'presetID') !== null) return true\n\t}\n\treturn false\n}\n\n/** The sorted, de-duplicated set of `spid`s referenced by the slide's animations. */\nexport function enumerateSpids(root: Element): number[] {\n\tconst seen = new Set<number>()\n\tfor (const element of spidElements(root)) {\n\t\tconst spid = intValue(attr(element, 'spid'))\n\t\tif (spid !== null) seen.add(spid)\n\t}\n\treturn [...seen].sort((a, b) => a - b)\n}\n\n/**\n * Rewrite every animation `spid` according to `mapping` (old → new). Returns\n * `true` when at least one reference changed, so callers can `markDirty()` only\n * when needed.\n */\nexport function remapSpids(root: Element, mapping: Map<number, number>): boolean {\n\tlet changed = false\n\tfor (const element of spidElements(root)) {\n\t\tconst spid = intValue(attr(element, 'spid'))\n\t\tif (spid === null) continue\n\t\tconst next = mapping.get(spid)\n\t\tif (next !== undefined && next !== spid) {\n\t\t\tsetAttr(element, 'spid', String(next))\n\t\t\tchanged = true\n\t\t}\n\t}\n\treturn changed\n}\n\n/** The nearest ancestor `<p:par>` whose `<p:cTn>` carries a `presetID` (the effect node), or `null`. */\nfunction effectParFor(spTgt: Element): Element | null {\n\tfor (let node: Element | null = spTgt.parentNode as Element | null; node; node = node.parentNode as Element | null) {\n\t\tif (node.localName === 'par' && node.namespaceURI === OOXML_NS.p) {\n\t\t\tconst cTn = firstChild(node, 'p:cTn')\n\t\t\tif (cTn && attr(cTn, 'presetID') !== null) return node\n\t\t}\n\t}\n\treturn null\n}\n\n/** Whether a `<p:par>` wrapper node has become empty (its `p:cTn/p:childTnLst` has no element children). */\nfunction isEmptyWrapperPar(par: Element): boolean {\n\tif (par.localName !== 'par' || par.namespaceURI !== OOXML_NS.p) return false\n\tconst cTn = firstChild(par, 'p:cTn')\n\tif (!cTn || attr(cTn, 'presetID') !== null) return false // an effect par, not a wrapper\n\tconst childTnLst = firstChild(cTn, 'p:childTnLst')\n\treturn !childTnLst || childElements(childTnLst).length === 0\n}\n\n/**\n * Remove all animation traces of the given `spid`s: each shape's `<p:bldP>` and\n * the effect-level `<p:par>` nodes whose `<p:spTgt>` targets it, then any wrapper\n * `<p:par>` left empty by the removal. Keeps the opaque timing tree free of\n * dangling references when shapes are deleted. Returns `true` when anything was\n * removed.\n */\nexport function pruneSpids(root: Element, spids: Iterable<number>): boolean {\n\tconst drop = new Set<number>()\n\tfor (const s of spids) drop.add(s)\n\tif (drop.size === 0) return false\n\n\tlet changed = false\n\tconst wrappersToCheck = new Set<Element>()\n\n\t// Remove effect pars whose spTgt targets a pruned shape.\n\tconst spTgts = Array.from(root.getElementsByTagNameNS(OOXML_NS.p, 'spTgt'))\n\tconst effectPars = new Set<Element>()\n\tfor (const spTgt of spTgts) {\n\t\tconst spid = intValue(attr(spTgt, 'spid'))\n\t\tif (spid === null || !drop.has(spid)) continue\n\t\tconst effectPar = effectParFor(spTgt)\n\t\tif (effectPar) effectPars.add(effectPar)\n\t}\n\tfor (const effectPar of effectPars) {\n\t\tconst parent = effectPar.parentNode as Element | null\n\t\teffectPar.parentNode?.removeChild(effectPar)\n\t\tchanged = true\n\t\t// The wrapper par is two levels up: childTnLst → par.\n\t\tconst childTnLst = parent\n\t\tconst wrapperPar = childTnLst?.parentNode?.parentNode as Element | null\n\t\tif (wrapperPar) wrappersToCheck.add(wrapperPar)\n\t}\n\n\t// Remove now-empty wrapper pars, climbing while they keep collapsing.\n\tlet progress = true\n\twhile (progress) {\n\t\tprogress = false\n\t\t// The spread is a snapshot, not a redundant copy: the body both deletes the\n\t\t// current wrapper and adds its grandparent, and iterating a Set while mutating\n\t\t// it would visit entries added during this pass.\n\t\t// oxlint-disable-next-line unicorn/no-useless-spread\n\t\tfor (const wrapper of [...wrappersToCheck]) {\n\t\t\tif (isEmptyWrapperPar(wrapper)) {\n\t\t\t\tconst grandWrapper = wrapper.parentNode?.parentNode?.parentNode as Element | null\n\t\t\t\twrapper.parentNode?.removeChild(wrapper)\n\t\t\t\twrappersToCheck.delete(wrapper)\n\t\t\t\tif (grandWrapper) wrappersToCheck.add(grandWrapper)\n\t\t\t\tprogress = true\n\t\t\t\tchanged = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Remove the build-list entries.\n\tconst bldPs = Array.from(root.getElementsByTagNameNS(OOXML_NS.p, 'bldP'))\n\tfor (const bldP of bldPs) {\n\t\tconst spid = intValue(attr(bldP, 'spid'))\n\t\tif (spid !== null && drop.has(spid)) {\n\t\t\tbldP.parentNode?.removeChild(bldP)\n\t\t\tchanged = true\n\t\t}\n\t}\n\n\t// Drop an emptied <p:bldLst>.\n\tconst bldLsts = Array.from(root.getElementsByTagNameNS(OOXML_NS.p, 'bldLst'))\n\tfor (const bldLst of bldLsts) {\n\t\tif (childElements(bldLst).length === 0) bldLst.parentNode?.removeChild(bldLst)\n\t}\n\n\treturn changed\n}\n\n/**\n * Flatten the whole slide to its final static state by removing the build\n * animation timeline: drop the `<p:timing>` block (which carries the `<p:bldLst>`\n * and the effect tree) so every shape renders at once with no click-through\n * staging. Gated on {@link hasAnimations}: a `<p:timing>` that is purely a\n * media loop (no `<p:bldP>` and no `presetID`-bearing node) is left untouched so\n * media playback survives. Returns `true` when a timing block was removed.\n *\n * This is the whole-slide counterpart to {@link pruneSpids} (which drops the\n * builds of specific shapes). It only removes staging; it never deletes shapes,\n * so a slide that animated alternating states over the same region will show\n * them all at once after flattening — that is \"drop animations\", distinct from\n * \"remove staged/duplicate shapes\".\n */\nexport function flattenAnimations(root: Element): boolean {\n\tif (!hasAnimations(root)) return false\n\tconst timing = firstChild(root, 'p:timing')\n\tif (!timing) return false\n\ttiming.parentNode?.removeChild(timing)\n\treturn true\n}\n\n// --- carry: bring a copied shape's build animation into a destination slide ---\n\nconst P_XMLNS = `xmlns:p=\"${P_NS}\"`\n/** A fresh `p:timing` carrying only an empty `tmRoot` (no effects yet). */\nconst TIMING_SCAFFOLD = `<p:timing ${P_XMLNS}><p:tnLst><p:par><p:cTn id=\"1\" dur=\"indefinite\" restart=\"never\" nodeType=\"tmRoot\"><p:childTnLst/></p:cTn></p:par></p:tnLst></p:timing>`\n/** A fresh `mainSeq` `p:seq` (its `cTn@id` is filled in by the caller). */\nconst MAIN_SEQ_SCAFFOLD =\n\t`<p:seq ${P_XMLNS} concurrent=\"1\" nextAc=\"seek\"><p:cTn id=\"0\" dur=\"indefinite\" nodeType=\"mainSeq\"><p:childTnLst/></p:cTn>` +\n\t'<p:prevCondLst><p:cond evt=\"onPrev\" delay=\"0\"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:prevCondLst>' +\n\t'<p:nextCondLst><p:cond evt=\"onNext\" delay=\"0\"><p:tgtEl><p:sldTgt/></p:tgtEl></p:cond></p:nextCondLst></p:seq>'\n\n/** Largest `<p:cTn @id>` in a subtree (0 when none). */\nfunction maxCTnId(scope: Element): number {\n\tlet max = 0\n\tfor (const cTn of scope.getElementsByTagNameNS(P_NS, 'cTn')) {\n\t\tconst id = intValue(attr(cTn, 'id'))\n\t\tif (id !== null && id > max) max = id\n\t}\n\treturn max\n}\n\n/** Renumber every `<p:cTn @id>` in `node` (document order) starting at `start`; returns the next free id. */\nfunction renumberCTnIds(node: Element, start: number): number {\n\tlet id = start\n\tfor (const cTn of node.getElementsByTagNameNS(P_NS, 'cTn')) setAttr(cTn, 'id', String(id++))\n\treturn id\n}\n\n/** Whether `par`'s subtree targets any of `spids` via a `<p:spTgt>`. */\nfunction targetsAnySpid(par: Element, spids: Set<number>): boolean {\n\tfor (const spTgt of par.getElementsByTagNameNS(P_NS, 'spTgt')) {\n\t\tconst spid = intValue(attr(spTgt, 'spid'))\n\t\tif (spid !== null && spids.has(spid)) return true\n\t}\n\treturn false\n}\n\n/** Parse a namespaced scaffold string and import its root into `doc`. */\nfunction importScaffold(doc: Document, xml: string): Element {\n\treturn doc.importNode(parseXml(xml).documentElement as Element, true)\n}\n\n/** The destination `mainSeq` `p:childTnLst` to append click groups into, creating the timing/seq scaffold as needed. */\nfunction getOrCreateMainSeqChildTnLst(root: Element, doc: Document): Element {\n\tlet timing = firstChild(root, 'p:timing')\n\tif (!timing) {\n\t\ttiming = importScaffold(doc, TIMING_SCAFFOLD)\n\t\tinsertInOrder(root, timing, ['p:extLst'])\n\t}\n\t// Reuse an existing mainSeq if present.\n\tconst existingSeq = timing.getElementsByTagNameNS(P_NS, 'seq')[0]\n\tif (existingSeq) {\n\t\tconst seqCTn = firstChild(existingSeq, 'p:cTn')\n\t\tif (seqCTn) {\n\t\t\tlet childLst = firstChild(seqCTn, 'p:childTnLst')\n\t\t\tif (!childLst) {\n\t\t\t\tchildLst = createElement(doc, 'p:childTnLst')\n\t\t\t\tseqCTn.appendChild(childLst)\n\t\t\t}\n\t\t\treturn childLst\n\t\t}\n\t}\n\t// Otherwise insert a fresh mainSeq into the tmRoot child list (before any media nodes).\n\tlet tmRootChildLst = timing.getElementsByTagNameNS(P_NS, 'childTnLst')[0]\n\tif (!tmRootChildLst) {\n\t\t// Degenerate timing with no tmRoot child list — graft the full scaffold's tnLst.\n\t\tconst fresh = importScaffold(doc, TIMING_SCAFFOLD)\n\t\tconst freshTnLst = firstChild(fresh, 'p:tnLst')\n\t\tif (freshTnLst) insertInOrder(timing, freshTnLst, ['p:bldLst', 'p:extLst'])\n\t\ttmRootChildLst = timing.getElementsByTagNameNS(P_NS, 'childTnLst')[0]\n\t}\n\tif (!tmRootChildLst)\n\t\tthrow new InternalError(\n\t\t\t'animation/timing-scaffold-failed',\n\t\t\t'getOrCreateMainSeqChildTnLst: failed to resolve or create the tmRoot child list'\n\t\t)\n\tconst seq = importScaffold(doc, MAIN_SEQ_SCAFFOLD)\n\tsetAttr(firstChild(seq, 'p:cTn') as Element, 'id', String(maxCTnId(timing) + 1))\n\ttmRootChildLst.insertBefore(seq, tmRootChildLst.firstChild)\n\treturn firstChild(firstChild(seq, 'p:cTn') as Element, 'p:childTnLst') as Element\n}\n\n/** The destination `p:bldLst` (under `p:timing`), creating it before any `p:extLst`. */\nfunction getOrCreateBldLst(timing: Element, doc: Document): Element {\n\tlet bldLst = firstChild(timing, 'p:bldLst')\n\tif (!bldLst) {\n\t\tbldLst = createElement(doc, 'p:bldLst')\n\t\tinsertInOrder(timing, bldLst, ['p:extLst'])\n\t}\n\treturn bldLst\n}\n\n/**\n * Carry the build animation of one or more copied shapes from `sourceRoot`'s\n * timing into `targetRoot`'s, remapping shape ids via `spidMap` (source id → new\n * id on the destination). For each mapped shape: its mainSeq click-group `<p:par>`\n * (the whole click step) and `<p:bldP>` are cloned, their `spid`s remapped, their\n * `<p:cTn>` ids renumbered to stay collision-free in the destination, and appended\n * after any existing build — matching how PowerPoint merges a pasted shape's\n * animation. Returns `true` when anything was carried (so the caller can\n * `markDirty()`), `false` when the source shapes have no animation.\n */\nexport function carryShapeAnimations(sourceRoot: Element, targetRoot: Element, spidMap: Map<number, number>): boolean {\n\tconst sourceTiming = firstChild(sourceRoot, 'p:timing')\n\tif (!sourceTiming) return false\n\tconst carriedSpids = new Set(spidMap.keys())\n\n\t// Source click groups (direct children of the mainSeq child list) that target a carried shape.\n\tconst sourceSeq = sourceTiming.getElementsByTagNameNS(P_NS, 'seq')[0]\n\tconst groups: Element[] = []\n\tif (sourceSeq) {\n\t\tconst seqCTn = firstChild(sourceSeq, 'p:cTn')\n\t\tconst seqChildLst = seqCTn ? firstChild(seqCTn, 'p:childTnLst') : null\n\t\tif (seqChildLst) {\n\t\t\tfor (const par of childElements(seqChildLst)) {\n\t\t\t\tif (targetsAnySpid(par, carriedSpids)) groups.push(par)\n\t\t\t}\n\t\t}\n\t}\n\t// Source build-list entries for the carried shapes.\n\tconst sourceBldLst = firstChild(sourceTiming, 'p:bldLst')\n\tconst bldPs: Element[] = []\n\tif (sourceBldLst) {\n\t\tfor (const bldP of childElements(sourceBldLst)) {\n\t\t\tconst spid = intValue(attr(bldP, 'spid'))\n\t\t\tif (spid !== null && carriedSpids.has(spid)) bldPs.push(bldP)\n\t\t}\n\t}\n\tif (groups.length === 0 && bldPs.length === 0) return false\n\n\tconst doc = targetRoot.ownerDocument as Document\n\tconst destChildLst = getOrCreateMainSeqChildTnLst(targetRoot, doc)\n\tconst destTiming = firstChild(targetRoot, 'p:timing') as Element\n\tlet nextId = maxCTnId(destTiming) + 1\n\n\tfor (const par of groups) {\n\t\tconst clone = doc.importNode(par, true)\n\t\tremapSpids(clone, spidMap)\n\t\tnextId = renumberCTnIds(clone, nextId)\n\t\tdestChildLst.appendChild(clone)\n\t}\n\tif (bldPs.length > 0) {\n\t\tconst destBldLst = getOrCreateBldLst(destTiming, doc)\n\t\tfor (const bldP of bldPs) {\n\t\t\tconst clone = doc.importNode(bldP, true)\n\t\t\tconst spid = intValue(attr(clone, 'spid'))\n\t\t\tif (spid !== null && spidMap.has(spid)) setAttr(clone, 'spid', String(spidMap.get(spid)))\n\t\t\tdestBldLst.appendChild(clone)\n\t\t}\n\t}\n\treturn true\n}\n","/**\n * Read-model proxy for one slide (`p:sld`), backed by its live part DOM.\n */\nimport type { OpcPackage } from '../opc/package.js'\nimport type { Part } from '../opc/part.js'\nimport { relativePartName } from '../opc/partnames.js'\nimport type { Relationships } from '../opc/relationships.js'\nimport {\n\tOOXML_NS,\n\tattr,\n\tboolValue,\n\tcreateElement,\n\tfirstChild,\n\tinsertInOrder,\n\tintValue,\n\townerDocumentOf,\n\tremoveAttr,\n\tsetAttr,\n\ttype Document,\n\ttype Element,\n} from '../oxml/dom.js'\nimport type { ThemeContext } from '../oxml/theme.js'\nimport { resolveSlideColorContext, resolveSlideThemeParts } from './theme-context.js'\nimport { backgroundElementOf, readSlideBackground, type SlideBackground } from './slide-background.js'\nimport type { Presentation } from './presentation.js'\nimport {\n\tAutoShape,\n\tGraphicFrame,\n\tGroupShape,\n\tPicture,\n\tbuildShapes,\n\tfindShapeByIdDeep,\n\ttype AnyShape,\n\ttype ShapeHost,\n} from './shapes.js'\nimport { NotesSlide } from './notes.js'\nimport { authorNotes } from './ops/notes-author.js'\nimport { readModernSlideComments, readSlideComments, type Comment, type ModernComment } from './comments.js'\nimport { readTagsForPart, type Tag } from './tags.js'\nimport { SlideLayout, type SlideMaster, type Theme } from './chrome.js'\nimport type { TextFrame } from './text.js'\nimport {\n\tbuildTransition,\n\tparseTransition,\n\tremoveTransition,\n\ttype TransitionInfo,\n\ttype TransitionInput,\n} from './transition.js'\nimport { enumerateSpids, flattenAnimations, hasAnimations, pruneSpids, remapSpids } from './animation.js'\nimport { IMAGE_REL, NOTES_SLIDE_REL, SLIDE_LAYOUT_REL } from '../../ooxml/rel-types.js'\nimport { InternalError, InvalidOptionError, PackageReadError } from '../../errors.js'\nimport { cSldOf, spTreeOf } from '../oxml/slide-dom.js'\n\n/** Options for {@link Slide.addTextBox}. Geometry is in EMU. */\nexport interface AddTextBoxOptions {\n\t/** Left edge in EMU (`a:off/@x`). */\n\tleft: number\n\t/** Top edge in EMU (`a:off/@y`). */\n\ttop: number\n\t/** Width in EMU (`a:ext/@cx`); must be positive. */\n\twidth: number\n\t/** Height in EMU (`a:ext/@cy`); must be positive. */\n\theight: number\n\t/** Initial text; omitted/empty yields an empty paragraph. */\n\ttext?: string\n\t/** Shape name (`p:cNvPr/@name`); defaults to `TextBox <id>`. */\n\tname?: string\n}\n\n/** Options for {@link Slide.addPicture}. Geometry is in EMU. */\nexport interface AddPictureOptions {\n\t/** Left edge in EMU (`a:off/@x`). */\n\tleft: number\n\t/** Top edge in EMU (`a:off/@y`). */\n\ttop: number\n\t/** Width in EMU (`a:ext/@cx`); must be positive. */\n\twidth: number\n\t/** Height in EMU (`a:ext/@cy`); must be positive. */\n\theight: number\n\t/** Shape name (`p:cNvPr/@name`); defaults to `Picture <id>`. */\n\tname?: string\n\t/**\n\t * Image file extension (e.g. `png`). When omitted it is sniffed from the\n\t * image's magic bytes; supply it (with `contentType`) for formats the\n\t * sniffer does not recognize.\n\t */\n\textension?: string\n\t/** MIME content type (e.g. `image/png`); sniffed alongside `extension` when omitted. */\n\tcontentType?: string\n}\n\ninterface ImageType {\n\textension: string\n\tcontentType: string\n}\n\n/** Recognize a handful of common raster formats from their leading bytes. */\nfunction sniffImageType(bytes: Uint8Array): ImageType | null {\n\tconst b = bytes\n\tif (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47)\n\t\treturn { extension: 'png', contentType: 'image/png' }\n\tif (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff)\n\t\treturn { extension: 'jpeg', contentType: 'image/jpeg' }\n\tif (b.length >= 4 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38)\n\t\treturn { extension: 'gif', contentType: 'image/gif' }\n\tif (b.length >= 2 && b[0] === 0x42 && b[1] === 0x4d) return { extension: 'bmp', contentType: 'image/bmp' }\n\tif (\n\t\tb.length >= 4 &&\n\t\t((b[0] === 0x49 && b[1] === 0x49 && b[2] === 0x2a && b[3] === 0x00) ||\n\t\t\t(b[0] === 0x4d && b[1] === 0x4d && b[2] === 0x00 && b[3] === 0x2a))\n\t)\n\t\treturn { extension: 'tiff', contentType: 'image/tiff' }\n\tif (\n\t\tb.length >= 12 &&\n\t\tb[0] === 0x52 &&\n\t\tb[1] === 0x49 &&\n\t\tb[2] === 0x46 &&\n\t\tb[3] === 0x46 &&\n\t\tb[8] === 0x57 &&\n\t\tb[9] === 0x45 &&\n\t\tb[10] === 0x42 &&\n\t\tb[11] === 0x50\n\t)\n\t\treturn { extension: 'webp', contentType: 'image/webp' }\n\treturn null\n}\n\nexport class Slide implements ShapeHost {\n\tconstructor(\n\t\treadonly presentation: Presentation,\n\t\t/** The slide's OPC part (`/ppt/slides/slideN.xml`). */\n\t\treadonly part: Part,\n\t\t/** The slide id from `p:sldIdLst` (`p:sldId/@id`). */\n\t\treadonly slideId: number,\n\t\t/** Zero-based position in presentation order. */\n\t\treadonly index: number\n\t) {}\n\n\t/** Partname of this slide's part. */\n\tget partName(): string {\n\t\treturn this.part.partName\n\t}\n\n\t/**\n\t * Escape hatch: the underlying `p:sld` element. After mutating it call\n\t * {@link markDirty}, or `save()` writes the original bytes. Slide-level DOM\n\t * access is also reachable as `slide.part.dom`; this getter is the same node,\n\t * on the same rung of the ladder as `Shape.element_` and the rest.\n\t */\n\tget element_(): Element {\n\t\tconst root = this.part.dom.documentElement\n\t\tif (!root)\n\t\t\tthrow new PackageReadError('package/part-has-no-root', `Slide ${this.partName} has no root <p:sld> element`)\n\t\treturn root\n\t}\n\n\t/** Mark this slide's part dirty so `save()` reserializes it. Call after mutating {@link element_}. */\n\tmarkDirty(): void {\n\t\tthis.part.markDirty()\n\t}\n\n\t/** This slide part's relationships (image embeds, layout, hyperlinks, …). */\n\tget relationships(): Relationships {\n\t\treturn this.presentation.opc.relationshipsFor(this.partName)\n\t}\n\n\t/**\n\t * The deck's OPC package. Convenience for `presentation.opc`, and the member\n\t * {@link ShapeHost} names so a shape can reach a referenced part (an image, a\n\t * chart) the same way whether it lives on a slide, a layout, or a master.\n\t */\n\tget opc(): OpcPackage {\n\t\treturn this.presentation.opc\n\t}\n\n\t#themeColors?: ThemeContext\n\n\t/**\n\t * The slide's resolved theme context (`clrMap` + `clrScheme` + the theme\n\t * `fmtScheme` + `fontScheme`, plus the layout/master roots), walked once from\n\t * slide → layout → master → theme and cached on this proxy. Backs the read-model\n\t * resolved getters ({@link Shape.resolvedFill}, `Run.resolvedColor`,\n\t * `Run.resolvedSizePt`, `Run.resolvedFontFace`) so a `schemeClr` token — including\n\t * one delivered through a shape's `p:style` `fillRef`/`lnRef` — resolves to a\n\t * literal hex, and a placeholder run's inherited size/typeface (a `+mj-*`/`+mn-*`\n\t * font token included) resolves to a literal value. The maps/roots are empty when\n\t * the theme chain is incomplete, in which case tokens simply stay unresolved.\n\t */\n\tthemeContext(): ThemeContext {\n\t\treturn (this.#themeColors ??= resolveSlideColorContext(this.presentation.opc, this.partName))\n\t}\n\n\t/** Authoring name of the slide (`p:cSld/@name`), or `null` if unnamed. */\n\tget name(): string | null {\n\t\tconst cSld = this.#cSld()\n\t\treturn cSld ? attr(cSld, 'name') : null\n\t}\n\n\t/**\n\t * Whether this slide is hidden (`p:sld/@show=\"0\"`). The attribute is\n\t * `xsd:boolean` defaulting to `true`, so an absent attribute means shown.\n\t * Hidden slides are dropped from PowerPoint/LibreOffice presentations and\n\t * exported PDFs, so render order diverges from model order when any earlier\n\t * slide is hidden.\n\t */\n\tget hidden(): boolean {\n\t\tconst root = this.part.dom.documentElement\n\t\tconst show = root ? attr(root, 'show') : null\n\t\treturn show === '0' || show === 'false'\n\t}\n\n\t/**\n\t * Hide or show this slide. Hiding writes `p:sld/@show=\"0\"`; showing removes\n\t * the attribute, restoring PowerPoint's canonical shown form (absent ⇒ shown).\n\t * Marks the slide part dirty.\n\t */\n\tset hidden(value: boolean) {\n\t\tconst root = this.part.dom.documentElement\n\t\tif (!root)\n\t\t\tthrow new PackageReadError('package/part-has-no-root', `Slide ${this.partName} has no root <p:sld> element`)\n\t\tif (value) setAttr(root, 'show', '0')\n\t\telse removeAttr(root, 'show')\n\t\tthis.part.markDirty()\n\t}\n\n\t/**\n\t * Whether this slide draws the master's non-placeholder shapes\n\t * (`p:sld/@showMasterSp`). `xsd:boolean` defaulting to `true`, so an absent\n\t * attribute means shown — the same shape as {@link hidden}.\n\t *\n\t * This is the switch that decides whether {@link SlideMaster.shapes} belongs on\n\t * *this* slide. A slide the author gave a full-bleed image or a section divider\n\t * usually sets it to `0`, and a renderer that paints the master's band and logo\n\t * anyway puts the template's furniture on top of a slide that deliberately hid\n\t * it. Placeholders are unaffected: the flag suppresses only the master's\n\t * decorative shapes.\n\t */\n\tget showMasterSp(): boolean {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn boolValue(root && attr(root, 'showMasterSp')) !== false\n\t}\n\n\t/**\n\t * The slide's show transition (`p:transition`), decoded into a typed model, or\n\t * `null` when the slide has none. Handles both PowerPoint forms: the bare\n\t * `<p:transition>` and the `mc:AlternateContent` wrapper that carries the exact\n\t * `p14:dur` duration (the `p14` Choice is preferred so `durationMs` is recovered).\n\t */\n\tget transition(): TransitionInfo | null {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn root ? parseTransition(root) : null\n\t}\n\n\t/**\n\t * Set or clear the slide's show transition. Assigning `null` removes it.\n\t * Writing a transition with `durationMs` emits the `mc:AlternateContent` form\n\t * (a `p14` Choice carrying `p14:dur` plus a base `mc:Fallback`); otherwise the\n\t * bare `<p:transition>` is written. The node is inserted at its schema slot —\n\t * after `p:clrMapOvr`, before `p:timing`/`p:extLst`. Marks the slide part dirty.\n\t */\n\tset transition(value: TransitionInput | null) {\n\t\tconst root = this.part.dom.documentElement\n\t\tif (!root)\n\t\t\tthrow new PackageReadError('package/part-has-no-root', `Slide ${this.partName} has no root <p:sld> element`)\n\t\tremoveTransition(root)\n\t\tif (value) {\n\t\t\tconst doc = this.part.dom\n\t\t\tinsertInOrder(root, buildTransition(doc, value), ['p:timing', 'p:extLst'])\n\t\t}\n\t\tthis.part.markDirty()\n\t}\n\n\t/**\n\t * Whether the slide carries build animations (`p:timing` with a `<p:bldP>` or a\n\t * `presetID`-bearing time node). The animation tree itself is preserved opaquely;\n\t * see {@link animationSpids}.\n\t */\n\tget hasAnimations(): boolean {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn root ? hasAnimations(root) : false\n\t}\n\n\t/**\n\t * @internal The sorted, de-duplicated set of shape ids (`spid`) referenced by\n\t * the slide's animations (`<p:spTgt spid>` and `<p:bldP spid>`). Exposed for the\n\t * import paths' spid-coherence checks.\n\t */\n\tanimationSpids(): number[] {\n\t\tconst root = this.part.dom.documentElement\n\t\treturn root ? enumerateSpids(root) : []\n\t}\n\n\t/**\n\t * @internal Rewrite every animation `spid` per `mapping` (old → new), keeping\n\t * the opaque timing tree coherent when shape ids are reassigned. Marks the slide\n\t * part dirty only when a reference changed.\n\t */\n\tremapAnimationSpids(mapping: Map<number, number>): void {\n\t\tconst root = this.part.dom.documentElement\n\t\tif (root && remapSpids(root, mapping)) this.part.markDirty()\n\t}\n\n\t/**\n\t * @internal Remove the build animations targeting the given shape ids (their\n\t * `<p:bldP>` and effect nodes), so deleting a shape never leaves a dangling\n\t * `spid` reference. Marks the slide part dirty only when something was removed.\n\t */\n\tpruneAnimationSpids(spids: Iterable<number>): void {\n\t\tconst root = this.part.dom.documentElement\n\t\tif (root && pruneSpids(root, spids)) this.part.markDirty()\n\t}\n\n\t/**\n\t * Flatten the slide's build animations: remove the `<p:timing>` block so the\n\t * slide renders and edits as its final static state, with every shape shown at\n\t * once. Gated like {@link hasAnimations} — a `<p:timing>` that is purely a media\n\t * loop (no `<p:bldP>` or `presetID`) is preserved so media playback survives.\n\t * Marks the slide part dirty and returns `true` only when a timing block was\n\t * removed.\n\t *\n\t * This removes click-through staging only; it does not delete shapes. If a slide\n\t * animated alternating states over the same region, the flattened render shows\n\t * them all at once — keep that distinct from removing staged/duplicate shapes.\n\t */\n\tflattenAnimations(): boolean {\n\t\tconst root = this.part.dom.documentElement\n\t\tif (root && flattenAnimations(root)) {\n\t\t\tthis.part.markDirty()\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t}\n\n\t/** Top-level shapes in the slide's shape tree, in document order. */\n\tget shapes(): AnyShape[] {\n\t\tconst spTree = this.#spTree()\n\t\treturn spTree ? buildShapes(spTree, this) : []\n\t}\n\n\t/**\n\t * All text on the slide, flattened in document order — the read-model\n\t * counterpart to {@link TextFrame.text} one level up. Every text-bearing shape\n\t * contributes its text, recursing into groups ({@link GroupShape}) and reading\n\t * table cells ({@link GraphicFrame.table}) and SmartArt node text\n\t * ({@link GraphicFrame.diagram}); text-free shapes (pictures, connectors, empty\n\t * boxes) contribute nothing. Blocks are joined by `\\n`; within a table, cells in\n\t * a row are joined by `\\t` and rows by `\\n`.\n\t *\n\t * A diagram contributes for the same reason a table does: its nodes are body text\n\t * PowerPoint itself searches and spell-checks, so a slide whose whole message is a\n\t * SmartArt graphic would otherwise flatten to the empty string.\n\t *\n\t * This is deliberately scoped to the slide's own shape tree. It does **not**\n\t * include speaker notes (read those via {@link notesText}) or chart data labels\n\t * (read those via {@link GraphicFrame.chart}); folding those in would force\n\t * ordering and separator choices a caller is better placed to make. Extract a\n\t * whole deck with `deck.slides.map((s) => s.text)`.\n\t */\n\tget text(): string {\n\t\tconst blocks: string[] = []\n\t\tconst walk = (shapes: AnyShape[]): void => {\n\t\t\tfor (const shape of shapes) {\n\t\t\t\tif (shape instanceof GroupShape) {\n\t\t\t\t\twalk(shape.shapes)\n\t\t\t\t} else if (shape instanceof GraphicFrame) {\n\t\t\t\t\tconst table = shape.table\n\t\t\t\t\tif (table) {\n\t\t\t\t\t\tfor (const row of table.rows) {\n\t\t\t\t\t\t\tconst cells = row.cells.map((cell) => cell.text)\n\t\t\t\t\t\t\tif (cells.some((cell) => cell.length > 0)) blocks.push(cells.join('\\t'))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tconst diagram = shape.diagram\n\t\t\t\t\tconst diagramText = diagram ? diagram.text : ''\n\t\t\t\t\tif (diagramText.length > 0) blocks.push(diagramText)\n\t\t\t\t} else {\n\t\t\t\t\tconst text = shape.text\n\t\t\t\t\tif (text.length > 0) blocks.push(text)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\twalk(this.shapes)\n\t\treturn blocks.join('\\n')\n\t}\n\n\t/**\n\t * The slide's speaker-note text — the companion to {@link text} for the notes\n\t * that {@link text} deliberately excludes. Delegates to {@link notesSlide}: finds\n\t * the notes body placeholder (`p:ph` `type=\"body\"`) and flattens its text frame\n\t * the same way {@link TextFrame.text} does (paragraphs joined by `\\n`).\n\t *\n\t * Returns `null` when the slide has **no notes slide part at all** — distinct\n\t * from `''`, which means a notes slide exists but its body is empty (PowerPoint\n\t * often attaches an empty notes slide to every slide). Only the body placeholder\n\t * is read; the slide-thumbnail (`sldImg`) and slide-number (`sldNum`)\n\t * placeholders a notes slide also carries are read via {@link notesSlide}.\n\t */\n\tget notesText(): string | null {\n\t\tconst notes = this.notesSlide\n\t\treturn notes ? notes.text : null\n\t}\n\n\t/**\n\t * The slide's speaker-note body as a navigable {@link TextFrame} — the rich\n\t * companion to {@link notesText}, which flattens the same body to a plain string.\n\t * Walk `paragraphs → runs` to recover per-run formatting (bold/italic/underline,\n\t * colour, size, face) and any notes hyperlink that {@link notesText} discards.\n\t *\n\t * `null` when the slide has **no notes slide part** (the same boundary\n\t * {@link notesText} returns `null` at), and also when a notes part exists but\n\t * carries no body-placeholder text frame — there is then no frame to hand back\n\t * (whereas {@link notesText} reports `''` for that empty-body case). Convenience\n\t * for `notesSlide.textFrame`; see {@link notesSlide} for the whole modeled notes\n\t * slide (its `sldImg`/`sldNum` placeholders and their geometry).\n\t */\n\tget notesTextFrame(): TextFrame | null {\n\t\treturn this.notesSlide?.textFrame ?? null\n\t}\n\n\t/**\n\t * The slide's speaker-notes slide (`notesSlideN.xml`) as a modeled\n\t * {@link NotesSlide}, or `null` when the slide has no notes slide part. Beyond the\n\t * body text {@link notesText}/{@link notesTextFrame} surface, this exposes the\n\t * notes slide's three placeholders — the slide thumbnail (`slideImage`), the notes\n\t * body, and the slide-number field (`slideNumber`) — each with its geometry and\n\t * (where present) a navigable text frame.\n\t *\n\t * The writer authors all three placeholders but leaves `sldImg`/`sldNum` with an\n\t * empty `p:spPr`, so on an authored deck their geometry reads `null` while an\n\t * imported deck carries the notesMaster-derived geometry. The body text and the\n\t * slide-number field round-trip either way.\n\t */\n\tget notesSlide(): NotesSlide | null {\n\t\tconst notesRel = this.relationships.byType(NOTES_SLIDE_REL)[0]\n\t\tif (!notesRel) return null\n\t\tconst notesPart = this.presentation.opc.part(this.relationships.resolveTarget(notesRel.id))\n\t\tif (!notesPart) return null\n\t\treturn new NotesSlide(this.presentation.opc, notesPart)\n\t}\n\n\t/**\n\t * The slide layout this slide is bound to (`slideLayout` relationship), as a\n\t * modeled {@link SlideLayout}, or `null` when the slide has no layout. The layout\n\t * carries the placeholder geometry and background a slide inherits; walk on to\n\t * {@link master} and {@link theme} through it (`slide.layout.master.theme`).\n\t */\n\tget layout(): SlideLayout | null {\n\t\tconst rel = this.relationships.byType(SLIDE_LAYOUT_REL)[0]\n\t\tif (!rel) return null\n\t\tconst part = this.presentation.opc.part(this.relationships.resolveTarget(rel.id))\n\t\treturn part ? new SlideLayout(this.presentation.opc, part) : null\n\t}\n\n\t/**\n\t * The slide master this slide resolves against, via its {@link layout}, as a\n\t * modeled {@link SlideMaster}, or `null` when the layout/master chain is broken.\n\t * The master owns the colour map (`schemeClr` token → theme slot) and the default\n\t * text styles a placeholder inherits.\n\t */\n\tget master(): SlideMaster | null {\n\t\treturn this.layout?.master ?? null\n\t}\n\n\t/**\n\t * The theme this slide resolves colour and font tokens against, via its\n\t * {@link layout} → {@link master} → theme, as a modeled {@link Theme}, or `null`.\n\t * Read its {@link Theme.colorScheme}/{@link Theme.fontScheme} to see the literal\n\t * palette and faces a `schemeClr`/`+mj-*` token resolves to.\n\t */\n\tget theme(): Theme | null {\n\t\treturn this.layout?.master?.theme ?? null\n\t}\n\n\t/**\n\t * The slide's **legacy** review comments (`p:cm` in its `comments/commentN.xml`\n\t * part), `[]` when it has none. Each {@link Comment} carries its body text, marker\n\t * position (EMU), timestamp, and its author resolved through the deck-wide\n\t * {@link Presentation.commentAuthors} registry (`@authorId` → name/initials). These\n\t * are the comments the writer authors via `slide.addComment(...)`; the 2018 modern\n\t * comment parts (`p188:cm`) are a separate schema, preserved but not decoded.\n\t */\n\tget comments(): Comment[] {\n\t\treturn readSlideComments(this.presentation.opc, this.part, this.presentation.commentAuthors)\n\t}\n\n\t/**\n\t * The slide's **modern** (2018) review comments (`p188:cm` in its\n\t * `modernComment_*.xml` part), `[]` when it has none. Each {@link ModernComment}\n\t * carries its body text, `created` timestamp, marker position (EMU), its author\n\t * resolved through the deck-wide {@link Presentation.modernCommentAuthors}\n\t * registry (`@authorId` GUID → name/initials), and its reply thread nested under\n\t * `replies`. Read-only — the writer authors the legacy schema; see\n\t * {@link Presentation.commentSchema} to tell which schema a deck uses.\n\t */\n\tget modernComments(): ModernComment[] {\n\t\treturn readModernSlideComments(this.presentation.opc, this.part, this.presentation.modernCommentAuthors)\n\t}\n\n\t/**\n\t * The slide's programmatic tags (`p:custDataLst/p:tags` on the slide part,\n\t * resolved to `ppt/tags/tagN.xml`) as `{ name, val }` string pairs, `[]` when it\n\t * has none. Host/add-in metadata with no visible rendering and no writer —\n\t * read-only, preserved byte-for-byte on round-trip. Deck-level tags are\n\t * {@link Presentation.tags}.\n\t */\n\tget tags(): Tag[] {\n\t\treturn readTagsForPart(this.presentation.opc, this.partName)\n\t}\n\n\t/**\n\t * The slide's effective background (`p:cSld/p:bg`), decoded into a typed\n\t * {@link SlideBackground}. Resolved through the inheritance chain: the slide's\n\t * own `p:bg` wins; failing that the slideLayout's, then the slideMaster's — the\n\t * result's `source` records which supplied it. `null` when nothing in the chain\n\t * defines a background.\n\t *\n\t * Colour tokens resolve against this slide's theme; an image background's\n\t * `r:embed` resolves to an absolute part name through the *owning* part's\n\t * relationships (the layout's rels for a layout-inherited image, etc.). Solid,\n\t * gradient, and image backgrounds are the three the writer authors and so\n\t * round-trip faithfully; `pattern`/`themeRef` are read-only for imported decks.\n\t */\n\tget background(): SlideBackground | null {\n\t\tconst opc = this.presentation.opc\n\t\tconst parts = resolveSlideThemeParts(opc, this.partName)\n\t\tconst ctx = this.themeContext()\n\t\tconst candidates: { root: Element | null; source: 'slide' | 'layout' | 'master'; partName: string | null }[] = [\n\t\t\t{ root: parts.slideRoot, source: 'slide', partName: this.partName },\n\t\t\t{ root: parts.layoutRoot, source: 'layout', partName: parts.layoutPartName },\n\t\t\t{ root: parts.masterRoot, source: 'master', partName: parts.masterPartName },\n\t\t]\n\t\tconst themeRels = parts.themePartName ? opc.relationshipsFor(parts.themePartName) : null\n\t\tfor (const { root, source, partName } of candidates) {\n\t\t\tconst bg = backgroundElementOf(root)\n\t\t\tif (!bg) continue\n\t\t\tconst rels = partName ? opc.relationshipsFor(partName) : null\n\t\t\treturn readSlideBackground(bg, source, ctx, rels, themeRels)\n\t\t}\n\t\treturn null\n\t}\n\n\t/**\n\t * The slide's own slide-number placeholder (`p:sp` with `p:ph type=\"sldNum\"`,\n\t * carrying an `<a:fld type=\"slidenum\">`), or `null` when the slide shows no slide\n\t * number of its own. This is the concrete shape the writer emits for\n\t * `pptx.setSlideNumber(...)` on a slide's layout; its geometry and run formatting\n\t * read off the returned {@link AutoShape} the same as any placeholder.\n\t *\n\t * Scoped to the slide's *own* shape tree — a slide number inherited purely from\n\t * the master's `p:hf`/placeholder (with no shape on the slide) is a master-level\n\t * concern this getter does not resolve.\n\t */\n\tget slideNumberPlaceholder(): AutoShape | null {\n\t\treturn this.placeholder('sldNum') ?? null\n\t}\n\n\t/** The first top-level shape with the given drawing id (`p:cNvPr/@id`), or `undefined`. */\n\tshapeById(id: number): AnyShape | undefined {\n\t\treturn this.shapes.find((shape) => shape.id === id)\n\t}\n\n\t/**\n\t * The first shape *anywhere* in the slide's shape tree with the given drawing id\n\t * (`p:cNvPr/@id`), descending into groups — unlike {@link shapeById}, which scans\n\t * only top-level shapes. Walked pre-order (a group is visited before its children),\n\t * matching how the writer allocates ids. `undefined` when no shape carries that id.\n\t *\n\t * Drawing ids are unique within a slide, so the first match is the only match; the\n\t * pre-order walk just fixes a deterministic order. This backs the connector-binding\n\t * resolution ({@link import('./shapes.js').Connector.startConnection}), which must\n\t * resolve a binding into a group that top-level {@link shapeById} cannot see.\n\t */\n\tshapeByIdDeep(id: number): AnyShape | undefined {\n\t\treturn findShapeByIdDeep(this.shapes, id)\n\t}\n\n\t/** The first top-level shape with the given name (`p:cNvPr/@name`), or `undefined`. */\n\tshapeByName(name: string): AnyShape | undefined {\n\t\treturn this.shapes.find((shape) => shape.name === name)\n\t}\n\n\t/**\n\t * The first placeholder of the given type (`p:ph/@type`, e.g. `title`,\n\t * `ctrTitle`, `subTitle`, `body`), optionally narrowed by `idx`. Returns\n\t * `undefined` when none match. Only `p:sp` shapes can be placeholders, so the\n\t * result is an {@link AutoShape}.\n\t */\n\tplaceholder(type: string, idx?: string): AutoShape | undefined {\n\t\treturn this.shapes.find((shape): shape is AutoShape => {\n\t\t\tconst ph = shape instanceof AutoShape ? shape.placeholder : null\n\t\t\treturn ph !== null && ph.type === type && (idx === undefined || ph.idx === idx)\n\t\t})\n\t}\n\n\t/**\n\t * Append a text box (`p:sp` with `txBox=\"1\"`) to the slide's shape tree and\n\t * return it. Geometry is required (EMU); width and height must be positive.\n\t * Allocates a drawing id unique within the slide. Marks the slide part dirty.\n\t */\n\taddTextBox(options: AddTextBoxOptions): AutoShape {\n\t\tconst { left, top, width, height } = options\n\t\trequireFinite(left, 'left')\n\t\trequireFinite(top, 'top')\n\t\trequirePositive(width, 'width')\n\t\trequirePositive(height, 'height')\n\n\t\tconst spTree = this.#spTree()\n\t\tif (!spTree)\n\t\t\tthrow new PackageReadError('slide/no-shape-tree', `Slide ${this.partName} has no spTree to add a shape to`)\n\t\tconst doc = spTree.ownerDocument\n\t\tif (!doc) throw new InternalError('oxml/node-has-no-document', 'Slide DOM has no owner document')\n\n\t\tconst id = this.#nextShapeId()\n\t\tconst sp = buildTextBox(doc, {\n\t\t\tid,\n\t\t\tname: options.name ?? `TextBox ${id}`,\n\t\t\ttext: options.text ?? '',\n\t\t\tleft: Math.round(left),\n\t\t\ttop: Math.round(top),\n\t\t\twidth: Math.round(width),\n\t\t\theight: Math.round(height),\n\t\t})\n\t\tthis.#appendShape(spTree, sp)\n\t\treturn new AutoShape(sp, this)\n\t}\n\n\t/**\n\t * Add a picture (`p:pic`) from raw image bytes and return it. Creates a media\n\t * part under `/ppt/media/`, registers its content type, wires an `image`\n\t * relationship from this slide, and appends the picture to the shape tree.\n\t * Geometry is required (EMU); width and height must be positive. The image\n\t * format is sniffed from the bytes unless `extension`/`contentType` are given.\n\t */\n\taddPicture(image: Uint8Array, options: AddPictureOptions): Picture {\n\t\tconst { left, top, width, height } = options\n\t\trequireFinite(left, 'left')\n\t\trequireFinite(top, 'top')\n\t\trequirePositive(width, 'width')\n\t\trequirePositive(height, 'height')\n\n\t\tconst sniffed = sniffImageType(image)\n\t\tconst extension = (options.extension ?? sniffed?.extension)?.toLowerCase().replace(/^\\./, '')\n\t\tconst contentType = options.contentType ?? sniffed?.contentType\n\t\tif (!extension || !contentType) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'image/undeterminable-type',\n\t\t\t\t'Could not determine image type; pass { extension, contentType } to addPicture'\n\t\t\t)\n\t\t}\n\n\t\tconst spTree = this.#spTree()\n\t\tif (!spTree)\n\t\t\tthrow new PackageReadError('slide/no-shape-tree', `Slide ${this.partName} has no spTree to add a picture to`)\n\t\tconst doc = spTree.ownerDocument\n\t\tif (!doc) throw new InternalError('oxml/node-has-no-document', 'Slide DOM has no owner document')\n\n\t\tconst opc = this.presentation.opc\n\t\tconst mediaPartName = opc.reserveMediaPartName(extension)\n\t\topc.addPart(mediaPartName, contentType, image)\n\t\tconst relId = this.relationships.add(IMAGE_REL, relativePartName(this.partName, mediaPartName)).id\n\n\t\tconst id = this.#nextShapeId()\n\t\tconst pic = buildPicture(doc, {\n\t\t\tid,\n\t\t\tname: options.name ?? `Picture ${id}`,\n\t\t\trelId,\n\t\t\tleft: Math.round(left),\n\t\t\ttop: Math.round(top),\n\t\t\twidth: Math.round(width),\n\t\t\theight: Math.round(height),\n\t\t})\n\t\tthis.#appendShape(spTree, pic)\n\t\treturn new Picture(pic, this)\n\t}\n\n\t/**\n\t * Give this slide the speaker notes `text`, and return the resulting\n\t * {@link NotesSlide}. A `\n` starts a new paragraph, matching the write-side\n\t * `addNotes`; the runs carry no formatting of their own, so style them\n\t * afterwards through {@link notesTextFrame}.\n\t *\n\t * The counterpart to the read side's `notesText`/`notesTextFrame`/`notesSlide`\n\t * getters, and the way to annotate a slide that has **no notes part at all** —\n\t * the state an `importSlide` without `{ importNotes: true }` leaves behind, and\n\t * the one a `notesTextFrame` edit cannot reach because there is no frame to\n\t * hand back. Calling it on a slide that already has notes replaces the body\n\t * text and leaves the rest of the part (its geometry, its other two\n\t * placeholders) alone.\n\t *\n\t * Creating the part pulls in what a notes slide must bind to: a `notesMaster`,\n\t * of which a presentation may hold at most one. This deck's own is reused when\n\t * it has one; otherwise one is installed, bound to a clone of this deck's theme\n\t * so it resolves against the destination palette. That is the same\n\t * single-master rule `importSlide({ importNotes: true })` and `appendSlides`\n\t * follow, so mixing the three cannot produce a second notes master.\n\t */\n\taddNotes(text: string): NotesSlide {\n\t\tconst partName = authorNotes(this, text)\n\t\tconst part = this.presentation.opc.part(partName)\n\t\tif (!part) throw new InternalError('import/part-went-missing', `Authored notes part went missing: ${partName}`)\n\t\treturn new NotesSlide(this.presentation.opc, part)\n\t}\n\n\t/**\n\t * @internal The slide's shape tree (`p:cSld/p:spTree`), or `null` if absent.\n\t * Exposed for cross-slide composition (`Presentation.importShape`).\n\t */\n\tshapeTree(): Element | null {\n\t\treturn this.#spTree()\n\t}\n\n\t/**\n\t * @internal The smallest drawing id (`p:cNvPr/@id`) not already used on this\n\t * slide. Exposed so `Presentation.importShape` can give a lifted shape (and its\n\t * group children) collision-free ids on the host.\n\t */\n\tnextShapeId(): number {\n\t\treturn this.#nextShapeId()\n\t}\n\n\t/** Insert a shape after grpSpPr and before any trailing p:extLst on the tree; mark dirty. */\n\t#appendShape(spTree: Element, shape: Element): void {\n\t\tspTree.insertBefore(shape, firstChild(spTree, 'p:extLst'))\n\t\tthis.part.markDirty()\n\t}\n\n\t/** The smallest drawing id (`p:cNvPr/@id`) not already used on the slide. */\n\t#nextShapeId(): number {\n\t\tconst root = this.part.dom.documentElement\n\t\tlet max = 1\n\t\tif (root) {\n\t\t\tfor (const cNvPr of root.getElementsByTagNameNS(OOXML_NS.p, 'cNvPr')) {\n\t\t\t\tconst id = intValue(attr(cNvPr, 'id'))\n\t\t\t\tif (id !== null && id > max) max = id\n\t\t\t}\n\t\t}\n\t\treturn max + 1\n\t}\n\n\t#cSld(): Element | null {\n\t\treturn cSldOf(this.part.dom.documentElement)\n\t}\n\n\t#spTree(): Element | null {\n\t\treturn spTreeOf(this.part.dom.documentElement)\n\t}\n}\n\nfunction requireFinite(value: number, name: string): void {\n\tif (!Number.isFinite(value))\n\t\tthrow new InvalidOptionError('coord/non-finite', `${name} must be a finite number of EMU, got ${value}`)\n}\n\nfunction requirePositive(value: number, name: string): void {\n\trequireFinite(value, name)\n\tif (value <= 0) throw new InvalidOptionError('coord/not-positive', `${name} must be positive, got ${value}`)\n}\n\n/** The box a built shape sits in, in EMU. */\ninterface BoxSpec {\n\tleft: number\n\ttop: number\n\twidth: number\n\theight: number\n}\n\n/**\n * Create `qname` in the parent's document and append it.\n *\n * The builders below are uniformly parent-then-child, so this is the only shape\n * of element creation they need; `ownerDocumentOf` is what lets it take the\n * parent alone rather than threading a `Document` through every call.\n */\nfunction appendEl(parent: Element, qname: string): Element {\n\tconst child = createElement(ownerDocumentOf(parent), qname)\n\tparent.appendChild(child)\n\treturn child\n}\n\n/**\n * Append the `p:spPr` a built `p:sp` and `p:pic` share: the spec's box as an\n * `a:xfrm`, then a rect `prstGeom` with the empty `a:avLst` the schema requires.\n */\nfunction appendSpPr(parent: Element, spec: BoxSpec): Element {\n\tconst spPr = appendEl(parent, 'p:spPr')\n\tconst xfrm = appendEl(spPr, 'a:xfrm')\n\tconst off = appendEl(xfrm, 'a:off')\n\tsetAttr(off, 'x', String(spec.left))\n\tsetAttr(off, 'y', String(spec.top))\n\tconst ext = appendEl(xfrm, 'a:ext')\n\tsetAttr(ext, 'cx', String(spec.width))\n\tsetAttr(ext, 'cy', String(spec.height))\n\tconst prstGeom = appendEl(spPr, 'a:prstGeom')\n\tsetAttr(prstGeom, 'prst', 'rect')\n\tappendEl(prstGeom, 'a:avLst')\n\treturn spPr\n}\n\ninterface TextBoxSpec extends BoxSpec {\n\tid: number\n\tname: string\n\ttext: string\n}\n\n/** Build a minimal, schema-valid text-box `p:sp` element (not yet attached). */\nfunction buildTextBox(doc: Document, spec: TextBoxSpec): Element {\n\tconst sp = createElement(doc, 'p:sp')\n\n\tconst nvSpPr = appendEl(sp, 'p:nvSpPr')\n\tconst cNvPr = appendEl(nvSpPr, 'p:cNvPr')\n\tsetAttr(cNvPr, 'id', String(spec.id))\n\tsetAttr(cNvPr, 'name', spec.name)\n\tconst cNvSpPr = appendEl(nvSpPr, 'p:cNvSpPr')\n\tsetAttr(cNvSpPr, 'txBox', '1')\n\tappendEl(nvSpPr, 'p:nvPr')\n\n\tappendSpPr(sp, spec)\n\n\tconst txBody = appendEl(sp, 'p:txBody')\n\tappendEl(txBody, 'a:bodyPr')\n\tappendEl(txBody, 'a:lstStyle')\n\tconst p = appendEl(txBody, 'a:p')\n\tif (spec.text !== '') {\n\t\tconst r = appendEl(p, 'a:r')\n\t\tconst t = appendEl(r, 'a:t')\n\t\tt.textContent = spec.text\n\t\tif (spec.text !== spec.text.trim()) setAttr(t, 'xml:space', 'preserve')\n\t}\n\n\treturn sp\n}\n\ninterface PictureSpec extends BoxSpec {\n\tid: number\n\tname: string\n\trelId: string\n}\n\n/** Build a minimal, schema-valid `p:pic` element (not yet attached). */\nfunction buildPicture(doc: Document, spec: PictureSpec): Element {\n\tconst pic = createElement(doc, 'p:pic')\n\n\tconst nvPicPr = appendEl(pic, 'p:nvPicPr')\n\tconst cNvPr = appendEl(nvPicPr, 'p:cNvPr')\n\tsetAttr(cNvPr, 'id', String(spec.id))\n\tsetAttr(cNvPr, 'name', spec.name)\n\tconst cNvPicPr = appendEl(nvPicPr, 'p:cNvPicPr')\n\tconst picLocks = appendEl(cNvPicPr, 'a:picLocks')\n\tsetAttr(picLocks, 'noChangeAspect', '1')\n\tappendEl(nvPicPr, 'p:nvPr')\n\n\tconst blipFill = appendEl(pic, 'p:blipFill')\n\tconst blip = appendEl(blipFill, 'a:blip')\n\tsetAttr(blip, 'r:embed', spec.relId)\n\tconst stretch = appendEl(blipFill, 'a:stretch')\n\tappendEl(stretch, 'a:fillRect')\n\n\tappendSpPr(pic, spec)\n\n\treturn pic\n}\n","/**\n * Read a deck's document properties — the `docProps/core.xml` core properties\n * (Dublin Core title/subject/creator + OPC keywords/revision/timestamps) and the\n * `docProps/custom.xml` user-defined name/value pairs. These are the read\n * counterparts of the write-side `pptx.title`/`subject`/`author`/`revision`\n * setters (`makeXmlCore`) and `pptx.setCustomProperty(...)` (`makeXmlCustomProperties`),\n * so a reader is verified by a genuine write→read round-trip.\n *\n * Both parts are declared at the package root (`/_rels/.rels`): core-properties\n * via the OPC `metadata/core-properties` rel, custom-properties via the\n * officeDocument `custom-properties` rel.\n */\nimport type { CustomPropertyValue } from '../../types/index.js'\nimport { OpcPackage } from '../opc/package.js'\nimport { attr, childElements, firstChild, firstChildElement, intValue, type Element } from '../oxml/dom.js'\n\n/** Package-root rel to `/docProps/core.xml`. */\nconst CORE_PROPS_REL_TYPE = 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties'\n/** Content type of the core-properties part (fallback lookup when the rel is absent). */\nconst CORE_PROPS_CONTENT_TYPE = 'application/vnd.openxmlformats-package.core-properties+xml'\n/** Package-root rel to `/docProps/custom.xml`. */\nconst CUSTOM_PROPS_REL_TYPE = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties'\n/** Content type of the custom-properties part (fallback lookup when the rel is absent). */\nconst CUSTOM_PROPS_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.custom-properties+xml'\n\n/**\n * Decoded `docProps/core.xml`. Every field is optional (present only when the\n * element is). `created`/`modified`/`lastPrinted` are kept as the **raw W3CDTF\n * string** rather than parsed to `Date`, avoiding timezone round-trip loss and\n * matching the byte-preserve ethos of the read model.\n */\nexport interface CoreProperties {\n\t/** `dc:title`. */\n\ttitle?: string\n\t/** `dc:subject`. */\n\tsubject?: string\n\t/** `dc:creator` (the write-side `pptx.author`). */\n\tcreator?: string\n\t/** `cp:keywords`. */\n\tkeywords?: string\n\t/** `dc:description`. */\n\tdescription?: string\n\t/** `cp:lastModifiedBy`. */\n\tlastModifiedBy?: string\n\t/** `cp:revision`. */\n\trevision?: string\n\t/** `cp:category`. */\n\tcategory?: string\n\t/** `cp:contentStatus`. */\n\tcontentStatus?: string\n\t/** `dcterms:created`, raw W3CDTF string. */\n\tcreated?: string\n\t/** `dcterms:modified`, raw W3CDTF string. */\n\tmodified?: string\n\t/** `cp:lastPrinted`, raw W3CDTF string. */\n\tlastPrinted?: string\n}\n\n/** One user-defined custom document property (`docProps/custom.xml`). */\nexport interface CustomProperty {\n\t/** The property's `@name`. */\n\tname: string\n\t/** The decoded value, typed from its `vt:` child element. */\n\tvalue: CustomPropertyValue\n}\n\n/** `dc:title`-style core-property fields, keyed by output field → element qname. */\nconst CORE_FIELDS: ReadonlyArray<[keyof CoreProperties, string]> = [\n\t['title', 'dc:title'],\n\t['subject', 'dc:subject'],\n\t['creator', 'dc:creator'],\n\t['keywords', 'cp:keywords'],\n\t['description', 'dc:description'],\n\t['lastModifiedBy', 'cp:lastModifiedBy'],\n\t['revision', 'cp:revision'],\n\t['category', 'cp:category'],\n\t['contentStatus', 'cp:contentStatus'],\n\t['created', 'dcterms:created'],\n\t['modified', 'dcterms:modified'],\n\t['lastPrinted', 'cp:lastPrinted'],\n]\n\n/**\n * Read the deck's core document properties from `/docProps/core.xml`, resolved\n * via the package-root `core-properties` relationship (fallback: the part's\n * content type). Missing part → `{}` (all fields undefined). Present-but-empty\n * elements decode to the empty string.\n */\nexport function readCoreProperties(opc: OpcPackage): CoreProperties {\n\tconst rels = opc.relationshipsFor('/')\n\tconst rel = rels.byType(CORE_PROPS_REL_TYPE)[0]\n\tconst part = rel ? opc.part(rels.resolveTarget(rel.id)) : opc.partsByContentType(CORE_PROPS_CONTENT_TYPE)[0]\n\tconst root = part?.dom.documentElement\n\tif (!root) return {}\n\tconst out: CoreProperties = {}\n\tfor (const [field, qname] of CORE_FIELDS) {\n\t\tconst el = firstChild(root, qname)\n\t\tif (el) out[field] = el.textContent ?? ''\n\t}\n\treturn out\n}\n\n/**\n * Decode one `<property>`'s single `vt:` child into a typed value. String types\n * (`lpwstr`/`lpstr`/`bstr`) → string; integer types (`i1`..`i8`/`int`/`ui*`) →\n * number; real types (`r4`/`r8`/`decimal`) → number; `bool` → boolean;\n * `filetime`/`date` → the **raw string** (see {@link CoreProperties} on\n * timestamps). Any unrecognized `vt:` element falls back to its text content as a\n * string — lossy but never throws.\n */\nfunction decodeValue(vt: Element): CustomPropertyValue {\n\tconst text = vt.textContent ?? ''\n\tswitch (vt.localName) {\n\t\tcase 'lpwstr':\n\t\tcase 'lpstr':\n\t\tcase 'bstr':\n\t\t\treturn text\n\t\tcase 'i1':\n\t\tcase 'i2':\n\t\tcase 'i4':\n\t\tcase 'i8':\n\t\tcase 'int':\n\t\tcase 'ui1':\n\t\tcase 'ui2':\n\t\tcase 'ui4':\n\t\tcase 'ui8':\n\t\tcase 'uint':\n\t\t\treturn intValue(text) ?? text\n\t\tcase 'r4':\n\t\tcase 'r8':\n\t\tcase 'decimal': {\n\t\t\tconst n = Number.parseFloat(text)\n\t\t\treturn Number.isFinite(n) ? n : text\n\t\t}\n\t\tcase 'bool':\n\t\t\treturn text.trim().toLowerCase() === 'true' || text.trim() === '1'\n\t\tcase 'filetime':\n\t\tcase 'date':\n\t\t\treturn text\n\t\tdefault:\n\t\t\t// Unknown vt type (vt:array, vt:cy, …): keep the raw text, lossy but safe.\n\t\t\treturn text\n\t}\n}\n\n/**\n * Read the deck's user-defined custom properties from `/docProps/custom.xml`,\n * resolved via the package-root `custom-properties` relationship (fallback: the\n * part's content type). Each `<property name=...>` maps to `{ name, value }`,\n * with `value` typed from its single `vt:` child. Missing part → `[]`. A\n * `<property>` without a `@name` or without a `vt:` child is skipped.\n *\n * The `vt:` child and `<property>` element sit in namespaces outside the read\n * model's qname registry, so children are matched by local name rather than the\n * `firstChild`/`getElements` helpers.\n */\nexport function readCustomProperties(opc: OpcPackage): CustomProperty[] {\n\tconst rels = opc.relationshipsFor('/')\n\tconst rel = rels.byType(CUSTOM_PROPS_REL_TYPE)[0]\n\tconst part = rel ? opc.part(rels.resolveTarget(rel.id)) : opc.partsByContentType(CUSTOM_PROPS_CONTENT_TYPE)[0]\n\tconst root = part?.dom.documentElement\n\tif (!root) return []\n\tconst out: CustomProperty[] = []\n\tfor (const property of childElements(root)) {\n\t\tif (property.localName !== 'property') continue\n\t\tconst name = attr(property, 'name')\n\t\tconst vt = firstChildElement(property)\n\t\tif (name === null || !vt) continue\n\t\tout.push({ name, value: decodeValue(vt) })\n\t}\n\treturn out\n}\n","/**\n * EMU geometry rescaling for slides imported across differing canvas sizes.\n *\n * {@link computeRescale} turns a source/target {@link SlideSize} pair into an affine\n * transform; the `rescale*` functions apply it in place to a live `p:spTree` and to the\n * table grids inside it. Pure DOM mutation -- the caller decides which parts to visit\n * and tracks which have already been rewritten.\n */\n\nimport type { SlideSize } from '../presentation-types.js'\nimport {\n\tELEMENT_NODE,\n\tOOXML_NS,\n\tattr,\n\tfirstChild,\n\tgetElements,\n\tintValue,\n\tsetAttr,\n\ttype Element,\n} from '../../oxml/dom.js'\n\n/** An EMU coordinate remap: `newX = x*sx + dx`, `newY = y*sy + dy`; sizes scale by `sx`/`sy` only. */\nexport interface RescaleTransform {\n\tsx: number\n\tsy: number\n\tdx: number\n\tdy: number\n}\n\n/** Build the EMU transform mapping source-canvas coordinates onto the target canvas (see {@link ImportSlideOptions.rescale}). */\nexport function computeRescale(source: SlideSize, target: SlideSize, mode: 'fit' | 'stretch'): RescaleTransform {\n\tif (mode === 'stretch') {\n\t\treturn { sx: target.widthEmu / source.widthEmu, sy: target.heightEmu / source.heightEmu, dx: 0, dy: 0 }\n\t}\n\t// 'fit': uniform scale (no distortion), centering the slack on the longer axis.\n\tconst scale = Math.min(target.widthEmu / source.widthEmu, target.heightEmu / source.heightEmu)\n\treturn {\n\t\tsx: scale,\n\t\tsy: scale,\n\t\tdx: (target.widthEmu - source.widthEmu * scale) / 2,\n\t\tdy: (target.heightEmu - source.heightEmu * scale) / 2,\n\t}\n}\n\n/**\n * Rescale every top-level transform on a `p:spTree`: shapes/pictures/connectors\n * (`p:spPr/a:xfrm`), groups (`p:grpSpPr/a:xfrm` — only the group's own off/ext, so\n * its children remap via the unchanged `chOff`/`chExt` rather than being recursed\n * into), and graphic frames (`p:graphicFrame/p:xfrm`, plus any inner table grid).\n * Placeholders that inherit geometry carry no `a:xfrm` and are left to inherit from\n * the (separately rescaled) layout/master.\n */\nexport function rescaleSpTree(spTree: Element, t: RescaleTransform): void {\n\tfor (let node = spTree.firstChild; node; node = node.nextSibling) {\n\t\tif (node.nodeType !== ELEMENT_NODE) continue\n\t\tconst el = node as Element\n\t\tif (el.namespaceURI !== OOXML_NS.p) continue\n\t\tswitch (el.localName) {\n\t\t\tcase 'sp':\n\t\t\tcase 'pic':\n\t\t\tcase 'cxnSp': {\n\t\t\t\tconst spPr = firstChild(el, 'p:spPr')\n\t\t\t\trescaleXfrm(spPr && firstChild(spPr, 'a:xfrm'), t)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'grpSp': {\n\t\t\t\tconst grpSpPr = firstChild(el, 'p:grpSpPr')\n\t\t\t\trescaleXfrm(grpSpPr && firstChild(grpSpPr, 'a:xfrm'), t)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tcase 'graphicFrame': {\n\t\t\t\trescaleXfrm(firstChild(el, 'p:xfrm'), t)\n\t\t\t\trescaleTableGrid(el, t)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n}\n\n/** Rewrite an `a:xfrm`/`p:xfrm`: `a:off` is repositioned (scale + translate); `a:ext` is resized (scale only). */\nfunction rescaleXfrm(xfrm: Element | null, t: RescaleTransform): void {\n\tif (!xfrm) return\n\tconst off = firstChild(xfrm, 'a:off')\n\tif (off) {\n\t\tconst x = intValue(attr(off, 'x'))\n\t\tconst y = intValue(attr(off, 'y'))\n\t\tif (x !== null) setAttr(off, 'x', String(Math.round(x * t.sx + t.dx)))\n\t\tif (y !== null) setAttr(off, 'y', String(Math.round(y * t.sy + t.dy)))\n\t}\n\tconst ext = firstChild(xfrm, 'a:ext')\n\tif (ext) {\n\t\tconst cx = intValue(attr(ext, 'cx'))\n\t\tconst cy = intValue(attr(ext, 'cy'))\n\t\tif (cx !== null) setAttr(ext, 'cx', String(Math.max(0, Math.round(cx * t.sx))))\n\t\tif (cy !== null) setAttr(ext, 'cy', String(Math.max(0, Math.round(cy * t.sy))))\n\t}\n}\n\n/**\n * Scale a graphic-frame table's intrinsic dimensions — column widths by `sx`, row\n * heights by `sy` — so the table resizes with the slide (PowerPoint derives table\n * geometry from the grid, not the frame `a:ext`). No-op for non-table frames.\n */\nfunction rescaleTableGrid(graphicFrame: Element, t: RescaleTransform): void {\n\tconst graphic = firstChild(graphicFrame, 'a:graphic')\n\tconst graphicData = graphic && firstChild(graphic, 'a:graphicData')\n\tconst tbl = graphicData && firstChild(graphicData, 'a:tbl')\n\tif (!tbl) return\n\tconst grid = firstChild(tbl, 'a:tblGrid')\n\tif (grid) {\n\t\tfor (const col of getElements(grid, 'a:gridCol')) {\n\t\t\tconst w = intValue(attr(col, 'w'))\n\t\t\tif (w !== null) setAttr(col, 'w', String(Math.max(0, Math.round(w * t.sx))))\n\t\t}\n\t}\n\tfor (const tr of getElements(tbl, 'a:tr')) {\n\t\tconst h = intValue(attr(tr, 'h'))\n\t\tif (h !== null) setAttr(tr, 'h', String(Math.max(0, Math.round(h * t.sy))))\n\t}\n}\n","/**\n * Presentation-level `tableStyles.xml` merging for imported slides and masters.\n *\n * `tableStyles.xml` is a single deck-wide part that records no ownership -- it does not\n * say which style belongs to which master -- so copying styles across decks is its own\n * traversal rather than part of the master/layout copy chain. Both entry points union\n * `<a:tblStyle>` by `styleId` and are idempotent.\n *\n * The functions take a structural {@link DeckTarget} rather than a `Presentation`,\n * so this module stays independent of the class that calls it.\n */\n\nimport type { OpcPackage } from '../../opc/package.js'\nimport type { Part } from '../../opc/part.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { OOXML_NS, attr, getElements, ownerDocumentOf, type Element } from '../../oxml/dom.js'\nimport type { DeckTarget } from './deck-target.js'\n\nconst TABLE_STYLES_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/tableStyles'\nconst TABLE_STYLES_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml'\n// The well-known \"no style / table grid\" GUID PowerPoint uses as a tblStyleLst @def.\nconst TABLE_STYLES_DEFAULT_GUID = '{5C22544A-7EE6-4342-B048-85BDC9FD1C3A}'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * Copy any table style the restyled slide references from the source\n * `tableStyles.xml` into this deck's (the `remapLiterals` table leg). A restyled\n * table resolves its `@tableStyleId` against the *destination* `tableStyles` and\n * silently falls back when that id is absent; the source `<a:tblStyle>` is itself\n * symbolic (scheme colours), so copying it verbatim under the **same** id lets the\n * table keep its structure while re-branding to this deck's theme — no table-XML\n * rewrite needed. Idempotent: an id this deck already defines is left as-is, and a\n * referenced id with no source definition is skipped. Creates and wires a\n * `tableStyles.xml` part if this deck has none.\n */\nexport function copySourceTableStyles(dest: DeckTarget, sourceOpc: OpcPackage, slideRoot: Element): void {\n\tconst ids = new Set<string>()\n\tfor (const idEl of slideRoot.getElementsByTagNameNS(OOXML_NS.a, 'tableStyleId')) {\n\t\tconst id = idEl.textContent?.trim()\n\t\tif (id) ids.add(id)\n\t}\n\tif (ids.size === 0) return\n\n\tconst sourceList = tableStyleList(sourceOpc)\n\tif (!sourceList) return\n\tconst sourceStyles = new Map(getElements(sourceList, 'a:tblStyle').map((st) => [attr(st, 'styleId'), st] as const))\n\n\tconst destPart = ensureTableStylesPart(dest)\n\tconst destList = destPart.dom.documentElement\n\tif (!destList) return\n\n\tconst referenced: Element[] = []\n\tfor (const id of ids) {\n\t\tconst src = sourceStyles.get(id)\n\t\tif (src) referenced.push(src)\n\t}\n\tif (addTableStyles(destList, referenced)) destPart.markDirty()\n}\n\n/**\n * Append each source `<a:tblStyle>` this deck does not already define, keyed by\n * `styleId` — the shared core of {@link copySourceTableStyles} (which offers only\n * the styles a restyled slide references) and {@link carryTableStyles} (which\n * offers the source's whole list). Destination-wins per id: a style this deck\n * already defines is left untouched, so a re-call adds nothing. Returns whether\n * anything was added.\n */\nfunction addTableStyles(destList: Element, styles: Iterable<Element>): boolean {\n\tconst present = new Set(getElements(destList, 'a:tblStyle').map((st) => attr(st, 'styleId')))\n\tlet added = false\n\tfor (const style of styles) {\n\t\tconst id = attr(style, 'styleId')\n\t\tif (!id || present.has(id)) continue\n\t\tdestList.appendChild(ownerDocumentOf(destList).importNode(style, true))\n\t\tpresent.add(id)\n\t\tadded = true\n\t}\n\treturn added\n}\n\n/**\n * Copy the source deck's **whole** `tableStyles.xml` into this deck: every\n * `<a:tblStyle>` it defines, plus its `a:tblStyleLst@def` (the default table\n * style). Presentation-level, so a separate traversal from the master/layout copy\n * chain — and whole-deck, since `tableStyles.xml` does not record which style\n * belongs to which master. See `ImportSlideMastersOptions.tableStyles`.\n *\n * Styles union by `styleId` (destination-wins per id, via {@link addTableStyles}),\n * but `def` is **source-wins**: a caller asking for the source's table styling\n * wants its default too, and the destination's `def` is typically a generator stub\n * rather than a deliberate choice. Carrying the styles without the `def` would be\n * the worse half-measure — the standard default GUID is one most templates also\n * define, so a new table would silently resolve to the wrong style rather than\n * visibly to none. Idempotent: a re-call re-adds nothing and re-sets `def` to the\n * same value.\n */\nexport function carryTableStyles(dest: DeckTarget, sourceOpc: OpcPackage): void {\n\tconst sourceList = tableStyleList(sourceOpc)\n\tif (!sourceList) return\n\n\tconst destPart = ensureTableStylesPart(dest)\n\tconst destList = destPart.dom.documentElement\n\tif (!destList) return\n\n\tlet changed = addTableStyles(destList, getElements(sourceList, 'a:tblStyle'))\n\n\tconst sourceDef = attr(sourceList, 'def')\n\tif (sourceDef && attr(destList, 'def') !== sourceDef) {\n\t\tdestList.setAttribute('def', sourceDef)\n\t\tchanged = true\n\t}\n\tif (changed) destPart.markDirty()\n}\n\n/** The `a:tblStyleLst` root of a package's `tableStyles.xml`, or `null` when it has none. */\nfunction tableStyleList(opc: OpcPackage): Element | null {\n\tconst part = opc.partsByContentType(TABLE_STYLES_CONTENT_TYPE)[0]\n\treturn part ? part.dom.documentElement : null\n}\n\n/**\n * The deck's `tableStyles.xml` part, creating an empty one (and wiring its\n * `presentation.xml` relationship + content type) when the deck has none.\n */\nfunction ensureTableStylesPart(dest: DeckTarget): Part {\n\tconst existing = dest.opc.partsByContentType(TABLE_STYLES_CONTENT_TYPE)[0]\n\tif (existing) return existing\n\tconst partName = dest.opc.reservePartNameLike('/ppt/tableStyles.xml')\n\tconst xml = `<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\\r\\n<a:tblStyleLst xmlns:a=\"${OOXML_NS.a}\" def=\"${TABLE_STYLES_DEFAULT_GUID}\"/>`\n\tconst part = dest.opc.addPart(partName, TABLE_STYLES_CONTENT_TYPE, textEncoder.encode(xml))\n\tconst presRels = dest.opc.relationshipsFor(dest.presentationPart.partName)\n\tpresRels.add(TABLE_STYLES_REL, relativePartName(dest.presentationPart.partName, partName))\n\treturn part\n}\n","/**\n * Relationship rewriting for content carried between packages.\n *\n * When a shape or decoration is deep-copied out of a source deck, every relationship\n * reference it carries (`r:embed` on a picture fill, `r:id` on a chart frame, `r:link` on a\n * linked image, …) still names an id in the *source* part's relationship list. Left alone\n * those ids either dangle or — worse — silently resolve to whatever the destination part\n * happens to have under the same id. This rewrites each one to a fresh relationship on the\n * destination part, copying the referenced part into the destination package on first sight.\n *\n * Both functions are pure with respect to the deck: everything they touch arrives as an\n * argument. They were private methods on `Presentation` and used no instance state, which\n * made the import subsystem look more entangled with the read model than it is.\n */\n\nimport { OOXML_NS, setAttr, type Element } from '../../oxml/dom.js'\nimport type { Relationships } from '../../opc/relationships.js'\nimport { InvalidOptionError } from '../../../errors.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { collectElements } from '../../oxml/slide-dom.js'\nimport { copyPart, type ImportContext, type OwnedScope } from './part-copy.js'\nimport { isSharedByPageCopies } from './page-owned.js'\n\n/**\n * Rewrite every relationship reference inside a carried subtree to a fresh destination-local id.\n * @param {Element} node - root of the carried subtree (rewritten in place)\n * @param {ImportContext} ctx - the open import (destination deck + source package + copy registry)\n * @param {Relationships} sourceRels - relationships of the source part the subtree came from\n * @param {string} destPartName - partname of the destination part the subtree is being placed in\n * @param {Relationships} destRels - relationships of that destination part\n * @param {Map<string, string>} relIdMap - per-call cache (source part + source id → new id) deduping references shared within one import\n * @param {OwnedScope} [owned] - ownership scope of the thing being carried, so the chart or diagram under a carried shape is copied for it rather than shared with an earlier copy\n */\nexport function rewriteCarriedRels(\n\tnode: Element,\n\tctx: ImportContext,\n\tsourceRels: Relationships,\n\tdestPartName: string,\n\tdestRels: Relationships,\n\trelIdMap: Map<string, string>,\n\towned?: OwnedScope\n): void {\n\tconst elements: Element[] = []\n\tcollectElements(node, elements)\n\tfor (const el of elements) {\n\t\tconst refs: { local: string; id: string }[] = []\n\t\tconst attrs = el.attributes\n\t\tfor (let i = 0; i < attrs.length; i++) {\n\t\t\tconst a = attrs.item(i)\n\t\t\tif (!a || a.namespaceURI !== OOXML_NS.r || !a.value) continue\n\t\t\tif (!sourceRels.get(a.value)) continue // an r-namespaced attribute that isn't a relationship id\n\t\t\trefs.push({ local: a.localName ?? a.name, id: a.value })\n\t\t}\n\t\tfor (const { local, id } of refs) {\n\t\t\tsetAttr(el, `r:${local}`, carryRel(ctx, sourceRels, id, destPartName, destRels, relIdMap, owned))\n\t\t}\n\t}\n}\n\n/**\n * Resolve one carried relationship to a fresh destination-local id, copying its internal target.\n * @param {ImportContext} ctx - the open import\n * @param {Relationships} sourceRels - relationships of the source part\n * @param {string} id - the source relationship id to carry\n * @param {string} destPartName - partname of the destination part\n * @param {Relationships} destRels - relationships of that destination part\n * @param {Map<string, string>} relIdMap - per-call dedupe cache\n * @param {OwnedScope} [owned] - ownership scope of the carried content, for the parts it owns\n * @return {string} the new relationship id on the destination part\n */\nfunction carryRel(\n\tctx: ImportContext,\n\tsourceRels: Relationships,\n\tid: string,\n\tdestPartName: string,\n\tdestRels: Relationships,\n\trelIdMap: Map<string, string>,\n\towned?: OwnedScope\n): string {\n\tconst rel = sourceRels.get(id)\n\tif (!rel)\n\t\tthrow new InvalidOptionError(\n\t\t\t'relationship/not-found',\n\t\t\t`Relationships of ${sourceRels.sourcePartName}: no relationship with id ${id}`\n\t\t)\n\t// The dedupe cache is for what may be shared. A part the carried content owns —\n\t// the chart under a copied frame, the diagram under a copied SmartArt — is copied\n\t// into its scope instead, so carrying the same shape twice does not hand two\n\t// frames one chart part, which is a deck PowerPoint refuses to open.\n\tconst ownsIt = owned !== undefined && rel.targetMode !== 'External' && !isSharedByPageCopies(rel.type)\n\tconst key = `${sourceRels.sourcePartName}|${id}`\n\tif (!ownsIt) {\n\t\tconst cached = relIdMap.get(key)\n\t\tif (cached) return cached\n\t}\n\tconst newId =\n\t\trel.targetMode === 'External'\n\t\t\t? destRels.add(rel.type, rel.target, 'External').id\n\t\t\t: destRels.add(\n\t\t\t\t\trel.type,\n\t\t\t\t\trelativePartName(destPartName, copyPart(ctx, sourceRels.resolveTarget(id), ownsIt ? owned : undefined))\n\t\t\t\t).id\n\tif (!ownsIt) relIdMap.set(key, newId)\n\treturn newId\n}\n","/**\n * Merging embedded font faces into a deck's `p:embeddedFontLst`.\n *\n * Fonts arrive two ways — copied out of another `Presentation`, or handed over as raw bytes by a\n * generator during an append — and the two differ only in how the binary part comes into being.\n * That difference is confined to a per-face thunk, so both paths share one merge core: entries\n * join by typeface, faces de-dupe by slot, and the thunk runs only for a face actually being\n * added, so a face the deck already embeds never mints an orphan part.\n */\n\nimport {\n\tattr,\n\tcreateElement,\n\tfirstChild,\n\tgetElements,\n\tgetOrAddChild,\n\tinsertInOrder,\n\tsetAttr,\n\ttype Element,\n} from '../../oxml/dom.js'\nimport {\n\tEMBEDDED_FONT_SLOTS,\n\tFONT_DATA_CONTENT_TYPE,\n\tFONT_DATA_EXTENSION,\n\tFONT_REL_TYPE,\n\ttype EmbeddedFont,\n\ttype EmbeddedFontSlot,\n} from '../../../embedded-fonts.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { copyPart, type ImportContext } from './part-copy.js'\nimport type { Presentation } from '../presentation.js'\nimport { PackageReadError } from '../../../errors.js'\nimport { presentationRels } from './deck-target.js'\n\n/**\n * `p:embeddedFontLst`'s document-order successors in `CT_Presentation` (index 7,\n * after `smartTags`): everything that may legally follow it, so a created list\n * lands in the right slot when the deck has none yet.\n */\nconst PRESENTATION_EMBEDDED_FONT_LST_SUCCESSORS = [\n\t'p:custShowLst',\n\t'p:photoAlbum',\n\t'p:custDataLst',\n\t'p:kinsoku',\n\t'p:defaultTextStyle',\n\t'p:modifyVerifier',\n\t'p:extLst',\n]\n\n/**\n * A face slot's document-order successors in `CT_EmbeddedFontListEntry`\n * (`font`, `regular`, `bold`, `italic`, `boldItalic`), so a newly-inserted face\n * keeps the schema's child order regardless of which slots already exist.\n */\nconst EMBEDDED_FONT_FACE_SUCCESSORS: Record<EmbeddedFontSlot, string[]> = {\n\tregular: ['p:bold', 'p:italic', 'p:boldItalic'],\n\tbold: ['p:italic', 'p:boldItalic'],\n\titalic: ['p:boldItalic'],\n\tboldItalic: [],\n}\n\n/**\n * One typeface's faces normalized for the embedded-font merge core (`#mergeEmbeddedFontEntries`):\n * the `p:font` identity attributes plus, per face slot, a thunk that creates the\n * binary font part on demand and returns its partname. The thunk runs only for a\n * face actually being added (after the typeface+slot de-dupe), so no orphan part is\n * created for a face the deck already embeds. Lets the import-side (copy a part out\n * of a source package) and append-side (write raw generator bytes) callers share one\n * merge core while differing only in how the binary part is produced.\n */\ninterface IncomingEmbeddedFont {\n\ttypeface: string\n\t/** `p:font` identity attrs other than `typeface` (panose/pitchFamily/charset), in document order. */\n\tidentity: Array<{ name: string; value: string }>\n\tfaces: Array<{ slot: EmbeddedFontSlot; createPart: () => string }>\n}\n\n/**\n * Copy `source`'s embedded fonts into this deck and merge them into our\n * `p:embeddedFontLst`. Font binaries come across via {@link copyPart} (so the\n * per-source registry dedupes faces shared across repeated imports); entries are\n * merged by `typeface` + face slot, so a face this deck already embeds is reused\n * rather than duplicated. No-op when the source embeds no fonts. See\n * {@link ImportSlideOptions.embedFonts}.\n */\nexport function carryEmbeddedFonts(dest: Presentation, source: Presentation, ctx: ImportContext): void {\n\tconst sourceRoot = source.presentationPart.dom.documentElement\n\tconst sourceLst = sourceRoot && firstChild(sourceRoot, 'p:embeddedFontLst')\n\tconst sourceEntries = sourceLst ? getElements(sourceLst, 'p:embeddedFont') : []\n\tif (sourceEntries.length === 0) return\n\n\tconst sourcePresRels = source.opc.relationshipsFor(source.presentationPart.partName)\n\tconst incoming: IncomingEmbeddedFont[] = []\n\tfor (const srcEntry of sourceEntries) {\n\t\tconst srcFont = firstChild(srcEntry, 'p:font')\n\t\tconst typeface = srcFont ? attr(srcFont, 'typeface') : null\n\t\tif (!srcFont || !typeface) continue\n\n\t\t// Copy the source p:font identity attributes (panose/pitchFamily/charset).\n\t\tconst identity: IncomingEmbeddedFont['identity'] = []\n\t\tfor (const name of ['panose', 'pitchFamily', 'charset']) {\n\t\t\tconst value = attr(srcFont, name)\n\t\t\tif (value !== null) identity.push({ name, value })\n\t\t}\n\n\t\tconst faces: IncomingEmbeddedFont['faces'] = []\n\t\tfor (const slot of EMBEDDED_FONT_SLOTS) {\n\t\t\tconst srcFace = firstChild(srcEntry, `p:${slot}`)\n\t\t\tconst srcRid = srcFace && attr(srcFace, 'r:id')\n\t\t\tif (!srcFace || !srcRid) continue\n\t\t\t// Binary comes across via copyPart, so the per-source registry dedupes faces\n\t\t\t// shared across repeated imports; the thunk runs only when the face is added.\n\t\t\tfaces.push({ slot, createPart: () => copyPart(ctx, sourcePresRels.resolveTarget(srcRid)) })\n\t\t}\n\t\tincoming.push({ typeface, identity, faces })\n\t}\n\tmergeEmbeddedFontEntries(dest, incoming)\n}\n\n/**\n * Carry a generator's presentation-level embedded fonts ({@link ExtractedSlides.embeddedFonts},\n * from `pptx.embedFont`) into this deck during {@link Presentation.appendSlides}. Each face's raw bytes are\n * written as a fresh `/ppt/fonts/fontN.fntdata` part; merge/de-dupe by typeface + slot is shared\n * with {@link carryEmbeddedFonts} via {@link mergeEmbeddedFontEntries}, so appending the same\n * generator twice (or onto a deck that already embeds the face) carries each face once.\n */\nexport function carryGeneratedEmbeddedFonts(dest: Presentation, fonts: EmbeddedFont[]): void {\n\tconst incoming: IncomingEmbeddedFont[] = []\n\tfor (const font of fonts) {\n\t\tif (!font.typeface) continue\n\t\tconst identity: IncomingEmbeddedFont['identity'] = []\n\t\tif (font.panose !== undefined) identity.push({ name: 'panose', value: font.panose })\n\t\tif (font.pitchFamily !== undefined) identity.push({ name: 'pitchFamily', value: String(font.pitchFamily) })\n\t\tif (font.charset !== undefined) identity.push({ name: 'charset', value: String(font.charset) })\n\n\t\tconst faces: IncomingEmbeddedFont['faces'] = []\n\t\tfor (const slot of EMBEDDED_FONT_SLOTS) {\n\t\t\tconst face = font.faces.find((f) => f.slot === slot)\n\t\t\tif (!face?.bytes) continue\n\t\t\tconst bytes = face.bytes\n\t\t\tfaces.push({\n\t\t\t\tslot,\n\t\t\t\tcreatePart: () => {\n\t\t\t\t\tconst partName = dest.opc.reservePartNameLike('/ppt/fonts/font1.fntdata')\n\t\t\t\t\tdest.opc.addPart(partName, FONT_DATA_CONTENT_TYPE, bytes)\n\t\t\t\t\treturn partName\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tif (faces.length > 0) incoming.push({ typeface: font.typeface, identity, faces })\n\t}\n\tmergeEmbeddedFontEntries(dest, incoming)\n}\n\n/**\n * Merge normalized {@link IncomingEmbeddedFont} entries into this deck's\n * `p:embeddedFontLst` — the shared core of {@link carryEmbeddedFonts} (import-side)\n * and {@link carryGeneratedEmbeddedFonts} (append-side). Entries merge by `typeface`,\n * faces de-dupe by slot (a face this deck already embeds is left as is). For each newly\n * added face the `fntdata` Default is ensured, the binary part is created via the face's\n * `createPart` thunk, a `font` rel is added to presentation.xml, and the `p:<slot>` element\n * is inserted in schema child order. The list is created at CT_Presentation index 7 when\n * the deck has none yet. No-op for empty input.\n */\nfunction mergeEmbeddedFontEntries(dest: Presentation, entries: IncomingEmbeddedFont[]): void {\n\tif (entries.length === 0) return\n\n\tconst presPart = dest.presentationPart\n\tconst presRoot = presPart.dom.documentElement\n\tif (!presRoot)\n\t\tthrow new PackageReadError(\n\t\t\t'package/part-has-no-root',\n\t\t\t'presentation.xml has no document element to carry embedded fonts into'\n\t\t)\n\tconst presRels = presentationRels(dest)\n\n\tconst targetLst = getOrAddChild(presRoot, 'p:embeddedFontLst', PRESENTATION_EMBEDDED_FONT_LST_SUCCESSORS)\n\tconst targetByTypeface = new Map<string, Element>()\n\tfor (const entry of getElements(targetLst, 'p:embeddedFont')) {\n\t\tconst font = firstChild(entry, 'p:font')\n\t\tconst typeface = font && attr(font, 'typeface')\n\t\tif (typeface) targetByTypeface.set(typeface, entry)\n\t}\n\n\tlet copiedAny = false\n\tfor (const incoming of entries) {\n\t\t// Find or create the target entry for this typeface, carrying its\n\t\t// p:font identity attributes (typeface + optional panose/pitchFamily/charset).\n\t\tlet targetEntry = targetByTypeface.get(incoming.typeface)\n\t\tif (!targetEntry) {\n\t\t\ttargetEntry = createElement(presPart.dom, 'p:embeddedFont')\n\t\t\tconst targetFont = createElement(presPart.dom, 'p:font')\n\t\t\tsetAttr(targetFont, 'typeface', incoming.typeface)\n\t\t\tfor (const { name, value } of incoming.identity) setAttr(targetFont, name, value)\n\t\t\ttargetEntry.appendChild(targetFont)\n\t\t\ttargetLst.appendChild(targetEntry)\n\t\t\ttargetByTypeface.set(incoming.typeface, targetEntry)\n\t\t}\n\n\t\tfor (const face of incoming.faces) {\n\t\t\tif (firstChild(targetEntry, `p:${face.slot}`)) continue // de-dupe: face already present\n\n\t\t\t// Ensure the fntdata Default exists *before* creating the part, so addPart\n\t\t\t// resolves the content type via the Default (no per-part Override).\n\t\t\tdest.opc.contentTypes.ensureDefault(FONT_DATA_EXTENSION, FONT_DATA_CONTENT_TYPE)\n\t\t\tconst newFontPart = face.createPart()\n\t\t\tconst relId = presRels.add(FONT_REL_TYPE, relativePartName(presPart.partName, newFontPart)).id\n\n\t\t\tconst targetFace = createElement(presPart.dom, `p:${face.slot}`)\n\t\t\tsetAttr(targetFace, 'r:id', relId)\n\t\t\tinsertInOrder(targetEntry, targetFace, EMBEDDED_FONT_FACE_SUCCESSORS[face.slot])\n\t\t\tcopiedAny = true\n\t\t}\n\t}\n\n\tif (copiedAny) presPart.markDirty()\n}\n","/**\n * The theme context a source slide is flattened against.\n *\n * `preserve`-mode import bakes a slide's *source* look into its XML — scheme colours and\n * style-matrix fills resolved to literals — so it keeps that look after being attached to a\n * different deck's master. Doing so needs the source subgraph's colour map, colour scheme,\n * format scheme, and the background the slide inherits but does not itself carry. This\n * gathers exactly that.\n *\n * Pure with respect to the destination deck: it reads only the source package. It was a\n * private method on `Presentation` that used no instance state.\n */\n\nimport { firstChild, type Element } from '../../oxml/dom.js'\nimport type { OpcPackage } from '../../opc/package.js'\nimport type { FlattenContext } from './flatten.js'\nimport { resolveSlideThemeParts } from '../theme-context.js'\nimport { backgroundElementOf } from '../slide-background.js'\n\n/**\n * The background the slide effectively inherits from its source subgraph: the layout's\n * `p:bg`, else the master's. Returns `null` when the slide carries its own `p:bg` (it stays\n * on the slide and is flattened directly) or when none exists.\n */\nfunction effectiveBackground(\n\tsourceOpc: OpcPackage,\n\tslideRoot: Element | null,\n\tlayoutPartName: string | null,\n\tmasterPartName: string | null\n): Element | null {\n\tif (slideRoot && backgroundElementOf(slideRoot)) return null\n\tconst layoutRoot = layoutPartName ? (sourceOpc.part(layoutPartName)?.dom.documentElement ?? null) : null\n\tconst masterRoot = masterPartName ? (sourceOpc.part(masterPartName)?.dom.documentElement ?? null) : null\n\treturn (layoutRoot && backgroundElementOf(layoutRoot)) ?? (masterRoot && backgroundElementOf(masterRoot)) ?? null\n}\n\n/**\n * Gather the flatten context for a source slide: walk slide → layout → master → theme,\n * reading the effective colour map (the slide's `clrMapOvr` override, or the master\n * `clrMap`), the theme `clrScheme`, and the theme `fmtScheme`.\n * @param {OpcPackage} sourceOpc - the source package to read\n * @param {string} slidePartName - partname of the source slide\n * @return {FlattenContext} the context {@link flattenSlide} / {@link flattenShape} resolve against\n */\nexport function sourceFlattenContext(sourceOpc: OpcPackage, slidePartName: string): FlattenContext {\n\t// Reuse the shared slide → layout → master → theme walk (also backing the read-model\n\t// colour getters), then layer the flatten-only needs on top.\n\tconst parts = resolveSlideThemeParts(sourceOpc, slidePartName)\n\tconst themeElements = parts.themeElements\n\treturn {\n\t\tclrMap: parts.clrMap,\n\t\tclrScheme: parts.clrScheme,\n\t\tfmtScheme: themeElements ? firstChild(themeElements, 'a:fmtScheme') : null,\n\t\tinheritedBackground: effectiveBackground(sourceOpc, parts.slideRoot, parts.layoutPartName, parts.masterPartName),\n\t\tlayoutRoot: parts.layoutRoot,\n\t\tmasterRoot: parts.masterRoot,\n\t}\n}\n","/**\n * Walking a deck's master/layout spine by partname.\n *\n * The `p:sldMasterIdLst` / `p:sldLayoutIdLst` entries hold relationship ids, not partnames, so\n * every traversal has to resolve through the owning part's relationships. These are the\n * source-side reads that do it — used against a *foreign* presentation as often as against this\n * one, which is why they take the deck rather than living on it.\n */\n\nimport { attr, firstChild, getElements } from '../../oxml/dom.js'\nimport type { Presentation } from '../presentation.js'\n\n// Resolving a single-of-a-kind relationship is an OPC concern, not a spine-walking one; it is\n// re-exported here because the spine walkers were its first callers.\nexport { resolveSingleRel } from '../../opc/partnames.js'\n\n/** Master partnames in `p:sldMasterIdLst` order. */\nexport function slideMasterPartNames(pres: Presentation): string[] {\n\tconst root = pres.presentationPart.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldMasterIdLst')\n\tif (!lst) return []\n\tconst rels = pres.opc.relationshipsFor(pres.presentationPart.partName)\n\tconst out: string[] = []\n\tfor (const entry of getElements(lst, 'p:sldMasterId')) {\n\t\tconst relId = attr(entry, 'r:id')\n\t\tif (relId) out.push(rels.resolveTarget(relId))\n\t}\n\treturn out\n}\n\n/** A master's layout partnames in `p:sldLayoutIdLst` order. */\nexport function layoutPartNamesOf(pres: Presentation, masterPartName: string): string[] {\n\tconst root = pres.opc.part(masterPartName)?.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldLayoutIdLst')\n\tif (!lst) return []\n\tconst rels = pres.opc.relationshipsFor(masterPartName)\n\tconst out: string[] = []\n\tfor (const entry of getElements(lst, 'p:sldLayoutId')) {\n\t\tconst relId = attr(entry, 'r:id')\n\t\tif (relId) out.push(rels.resolveTarget(relId))\n\t}\n\treturn out\n}\n","/**\n * The three ways a slide can be brought across from another deck.\n *\n * {@link Presentation.importSlide} picks one by `options.theme`, and the difference between\n * them is entirely about what happens to the slide's *look*:\n *\n * - **`copy`** — not here. It copies the source theme subgraph wholesale via `copyPart`, so\n * the slide keeps its look by keeping its own theme; nothing needs rewriting.\n * - **`preserve`** ({@link importSlidePreserve}) — rebind to this deck's master, then bake\n * the source theme into the slide XML. The slide looks the same as it did; it just no\n * longer depends on the theme it came from.\n * - **`restyle`** ({@link importSlideRestyle}) — rebind and bake *nothing*, so the slide's\n * symbolic theme references re-resolve against the destination theme and it re-brands.\n *\n * The two share {@link importSlideRebind} and are exact inverses on top of it: preserve\n * resolves every reference it can, restyle resolves none. Any baking added to the shared\n * rebind would break restyle by pinning the slide to its source look, which is why the\n * rebind carries no theme handling of its own — not even the inherited background.\n *\n * These were private methods on `Presentation`, where they made the read model's own surface\n * (open a deck, walk slides, read shapes) hard to see: the import machinery was roughly two\n * thirds of the class. They live here as free functions taking the destination deck, matching\n * the other `ops/` modules.\n */\n\nimport { ownerDocumentOf, type Element } from '../../oxml/dom.js'\nimport type { Part } from '../../opc/part.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { PackageReadError, InvalidOptionError } from '../../../errors.js'\nimport { flattenSlide, remapLiteralColors, restyleSlide } from './flatten.js'\nimport { resolveSlideThemeParts } from '../theme-context.js'\nimport { carriedDecorations, firstShapeChild, spTreeOf } from '../../oxml/slide-dom.js'\nimport { copySourceTableStyles } from './table-styles.js'\nimport { copyPart, newOwnedScope, type ImportContext, type OwnedScope } from './part-copy.js'\nimport { isSharedByPageCopies } from './page-owned.js'\nimport type { Presentation } from '../presentation.js'\nimport type { Slide } from '../slide.js'\nimport { NOTES_SLIDE_REL, SLIDE_LAYOUT_REL, SLIDE_MASTER_REL } from '../../../ooxml/rel-types.js'\nimport { resolveSingleRel } from './part-index.js'\nimport { rewriteCarriedRels } from './carried-rels.js'\nimport { sourceFlattenContext } from './flatten-context.js'\n\n/** What {@link importSlideRebind} hands back for the caller's mode-specific pass. */\ninterface RebindResult {\n\tnewPartName: string\n\tslideRoot: Element\n\tnewPart: Part\n}\n\n/**\n * Import a slide in `preserve` mode: rebind it to this deck's master/layout, then flatten its\n * source theme into the slide XML (scheme colours + style-matrix fills baked to literals).\n *\n * The flatten context is gathered from the *source* subgraph, so it can be read before or\n * after the rebind; the rebind injects any carried decorations before we flatten, so a single\n * sweep resolves the theme references on the slide's own content and on the carried\n * decorations together.\n * @param {Presentation} dest - the destination deck\n * @param {ImportContext} ctx - the open import out of the source package\n * @param {Presentation} source - the source deck\n * @param {Slide} sourceSlide - the slide being imported\n * @param {boolean} carryGraphics - bake the source master/layout decorations onto the slide\n * @return {string} partname of the new slide part in the destination package\n */\nexport function importSlidePreserve(\n\tdest: Presentation,\n\tctx: ImportContext,\n\tsource: Presentation,\n\tsourceSlide: Slide,\n\tcarryGraphics: boolean\n): string {\n\tconst flattenCtx = sourceFlattenContext(source.opc, sourceSlide.partName)\n\tconst { newPartName, slideRoot, newPart } = importSlideRebind(dest, ctx, source, sourceSlide, carryGraphics)\n\tflattenSlide(slideRoot, flattenCtx)\n\tnewPart.markDirty()\n\treturn newPartName\n}\n\n/**\n * Import a slide in `restyle` mode: rebind it to this deck's master/layout and then\n * {@link restyleSlide} it — drop its colour map override but bake *nothing*, so its symbolic\n * theme references re-resolve against the destination theme and the slide re-brands.\n *\n * The deliberate inverse of `preserve`: no flatten, no inherited-background bake, no\n * placeholder colour/size/geometry bake — every one of those would pin the slide to its\n * source look, the opposite of re-branding. Carried decorations are left symbolic too, so\n * they re-brand along with the slide.\n *\n * With `remapLiterals` it additionally force-remaps the slide's source-theme literal colours\n * back to symbolic scheme colours and copies any referenced source table style into this deck\n * — the two things plain `restyle` cannot re-brand.\n * @param {Presentation} dest - the destination deck\n * @param {ImportContext} ctx - the open import out of the source package\n * @param {Presentation} source - the source deck\n * @param {Slide} sourceSlide - the slide being imported\n * @param {boolean} carryGraphics - bake the source master/layout decorations onto the slide\n * @param {boolean} remapLiterals - additionally remap source-theme literal colours to scheme tokens\n * @return {string} partname of the new slide part in the destination package\n */\nexport function importSlideRestyle(\n\tdest: Presentation,\n\tctx: ImportContext,\n\tsource: Presentation,\n\tsourceSlide: Slide,\n\tcarryGraphics: boolean,\n\tremapLiterals: boolean\n): string {\n\tconst { newPartName, slideRoot, newPart } = importSlideRebind(dest, ctx, source, sourceSlide, carryGraphics)\n\trestyleSlide(slideRoot)\n\tif (remapLiterals) {\n\t\t// The source colour context (slot ↔ RGB ↔ token) the literals are matched against.\n\t\tconst parts = resolveSlideThemeParts(source.opc, sourceSlide.partName)\n\t\tremapLiteralColors(slideRoot, { clrMap: parts.clrMap, clrScheme: parts.clrScheme })\n\t\tcopySourceTableStyles(dest, source.opc, slideRoot)\n\t}\n\tnewPart.markDirty()\n\treturn newPartName\n}\n\n/**\n * The rebind shared by `preserve` and `restyle`: copy the slide bytes into a fresh part,\n * rebuild its relationships (drop notes, repoint the `slideLayout` rel at this deck's\n * existing layout, copy every other internal target — media/charts — and pass externals\n * through), and optionally bake the source master/layout decorations onto the slide. Returns\n * the new part, its name, and its live root element for the caller's mode-specific pass.\n *\n * This carries *no* theme baking of its own — not even the inherited background.\n * `preserve` adds that via {@link flattenSlide}'s context; `restyle` must not, so the\n * background stays symbolic and re-brands.\n * @param {Presentation} dest - the destination deck\n * @param {ImportContext} ctx - the open import out of the source package\n * @param {Presentation} source - the source deck\n * @param {Slide} sourceSlide - the slide being imported\n * @param {boolean} carryGraphics - bake the source master/layout decorations onto the slide\n * @return {RebindResult} the new part, its partname, and its live root element\n */\nexport function importSlideRebind(\n\tdest: Presentation,\n\tctx: ImportContext,\n\tsource: Presentation,\n\tsourceSlide: Slide,\n\tcarryGraphics: boolean\n): RebindResult {\n\tconst destLayout = destinationLayoutPartName(dest)\n\n\t// Copy the slide bytes into a fresh partname; we then mutate that copy's DOM\n\t// (a distinct document, so the source package is never touched).\n\tconst sourcePart = source.opc.part(sourceSlide.partName)\n\tif (!sourcePart)\n\t\tthrow new PackageReadError(\n\t\t\t'package/part-missing',\n\t\t\t`importSlide: source package has no part ${sourceSlide.partName}`\n\t\t)\n\tconst newPartName = dest.opc.reservePartNameLike(sourceSlide.partName)\n\tconst newPart = dest.opc.addPart(newPartName, sourcePart.contentType, sourcePart.bytes)\n\tconst slideRoot = newPart.dom.documentElement\n\tif (!slideRoot)\n\t\tthrow new PackageReadError('package/part-has-no-root', `Imported slide ${newPartName} has no root element`)\n\n\t// Rebuild the slide's relationships: drop notes, repoint slideLayout at the\n\t// destination layout, and copy every other internal target (media/charts).\n\tconst sourceRels = source.opc.relationshipsFor(sourceSlide.partName)\n\tconst targetRels = dest.opc.relationshipsFor(newPartName)\n\t// This page is built here rather than by `copyPart`, so its ownership scope is\n\t// opened here too: the chart or diagram under a page rebound twice must not be\n\t// the same part twice (see `page-owned.ts`).\n\tconst owned = newOwnedScope()\n\tfor (const rel of sourceRels) {\n\t\tif (rel.type === NOTES_SLIDE_REL) continue\n\t\tif (rel.type === SLIDE_LAYOUT_REL) {\n\t\t\ttargetRels.addWithId(rel.id, SLIDE_LAYOUT_REL, relativePartName(newPartName, destLayout))\n\t\t\tcontinue\n\t\t}\n\t\tif (rel.targetMode === 'External') {\n\t\t\ttargetRels.addWithId(rel.id, rel.type, rel.target, 'External')\n\t\t\tcontinue\n\t\t}\n\t\tconst newTarget = copyPart(\n\t\t\tctx,\n\t\t\tsourceRels.resolveTarget(rel.id),\n\t\t\tisSharedByPageCopies(rel.type) ? undefined : owned,\n\t\t\t// These are the page's own relationships, so a target the destination already\n\t\t\t// holds byte-for-byte is bound to rather than copied (see `part-reuse.ts`).\n\t\t\ttrue\n\t\t)\n\t\ttargetRels.addWithId(rel.id, rel.type, relativePartName(newPartName, newTarget))\n\t}\n\n\t// Optionally bake the source master/layout decorations (logos, accent shapes) onto the\n\t// slide behind its own content. Done after the slide's own rels are in place (so carried\n\t// media get fresh, non-colliding ids) but before the caller's flatten/restyle pass acts\n\t// on the carried shapes.\n\tif (carryGraphics) carryMasterGraphics(dest, ctx, slideRoot, newPartName, sourceSlide.partName, owned)\n\n\treturn { newPartName, slideRoot, newPart }\n}\n\n/**\n * Bake the source `slideLayout`/`slideMaster` shape-tree decorations onto the imported slide\n * (the `carryMasterGraphics` path). Every shape on those trees *except* placeholders is\n * deep-copied into the slide's `p:spTree` ahead of its own content — master decorations\n * first, then layout, then the slide's shapes — so document (z-)order keeps the master\n * furthest back. Each decoration's media and other relationship targets are copied into this\n * package and its `r:embed`/`r:id`/… references rewritten to fresh slide-local ids. The\n * injected shapes are left for the caller's {@link flattenSlide} pass to resolve any theme\n * references they carry.\n * @param {Presentation} dest - the destination deck\n * @param {ImportContext} ctx - the open import out of the source package\n * @param {Element} slideRoot - root element of the new slide part (mutated in place)\n * @param {string} newPartName - partname of the new slide part\n * @param {string} slidePartName - partname of the source slide, for resolving its layout/master\n * @param {OwnedScope} owned - the page's ownership scope, so a decoration's own parts land in it\n */\nfunction carryMasterGraphics(\n\tdest: Presentation,\n\tctx: ImportContext,\n\tslideRoot: Element,\n\tnewPartName: string,\n\tslidePartName: string,\n\towned: OwnedScope\n): void {\n\tconst sourceOpc = ctx.source\n\tconst layoutPartName = resolveSingleRel(sourceOpc, slidePartName, SLIDE_LAYOUT_REL)\n\tconst masterPartName = layoutPartName ? resolveSingleRel(sourceOpc, layoutPartName, SLIDE_MASTER_REL) : null\n\tconst spTree = spTreeOf(slideRoot)\n\tif (!spTree) return\n\n\tconst doc = ownerDocumentOf(slideRoot)\n\tconst slideRels = dest.opc.relationshipsFor(newPartName)\n\tconst relIdMap = new Map<string, string>()\n\t// Insert ahead of the slide's own first shape so decorations render behind it.\n\tconst anchor = firstShapeChild(spTree)\n\t// Master behind layout behind the slide (document order == z-order).\n\tfor (const partName of [masterPartName, layoutPartName]) {\n\t\tif (!partName) continue\n\t\tconst decorations = carriedDecorations(sourceOpc.part(partName)?.dom.documentElement ?? null)\n\t\tif (decorations.length === 0) continue\n\t\tconst sourceRels = sourceOpc.relationshipsFor(partName)\n\t\tfor (const deco of decorations) {\n\t\t\tconst imported = doc.importNode(deco, true)\n\t\t\trewriteCarriedRels(imported, ctx, sourceRels, newPartName, slideRels, relIdMap, owned)\n\t\t\tspTree.insertBefore(imported, anchor)\n\t\t}\n\t}\n}\n\n/**\n * The partname of the layout this deck's slides should attach to in `preserve` mode: the\n * first layout of the first slide master. Throws when the deck has no master/layout to attach\n * to (a deck ts-pptx always provides).\n * @param {Presentation} dest - the destination deck\n * @return {string} partname of the destination layout\n */\nfunction destinationLayoutPartName(dest: Presentation): string {\n\tconst presRels = dest.opc.relationshipsFor(dest.presentationPart.partName)\n\tconst masterRel = presRels.byType(SLIDE_MASTER_REL)[0]\n\tif (!masterRel)\n\t\tthrow new InvalidOptionError(\n\t\t\t'import/destination-missing-master',\n\t\t\t'importSlide preserve mode requires a slide master in the destination deck'\n\t\t)\n\tconst masterPartName = presRels.resolveTarget(masterRel.id)\n\tconst masterRels = dest.opc.relationshipsFor(masterPartName)\n\tconst layoutRel = masterRels.byType(SLIDE_LAYOUT_REL)[0]\n\tif (!layoutRel)\n\t\tthrow new InvalidOptionError(\n\t\t\t'import/destination-missing-layout',\n\t\t\t'importSlide preserve mode requires a slide layout in the destination deck'\n\t\t)\n\treturn masterRels.resolveTarget(layoutRel.id)\n}\n","/**\n * Orphan pruning after a part stops being referenced.\n *\n * Removing a slide can strand the parts only it used — its notes slide, media, chart parts. This\n * walks that fringe: a part is dropped when nothing left in the package (or the package root)\n * still resolves an internal relationship to it, and the parts *it* referenced are then examined\n * the same way. Shared chrome (masters, layouts, themes, the notes master) is exempt, so a deck\n * that momentarily has no slides does not lose its design.\n */\n\nimport { relsPartNameFor } from '../../opc/partnames.js'\nimport type { Presentation } from '../presentation.js'\nimport {\n\tNOTES_MASTER_CONTENT_TYPE,\n\tSLIDE_LAYOUT_CONTENT_TYPE,\n\tSLIDE_MASTER_CONTENT_TYPE,\n\tTHEME_CONTENT_TYPE,\n} from '../../../ooxml/rel-types.js'\n\nconst PRESENTATION_MAIN_CONTENT_TYPE =\n\t'application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml'\n\n/**\n * Content types that are shared deck chrome: reachable through the\n * presentation → master → layout → theme graph, not owned by any one slide.\n * {@link Presentation.removeSlide} never prunes these as a removed slide's\n * orphan, even while momentarily unreferenced.\n */\nconst SHARED_CHROME_CONTENT_TYPES = new Set([\n\tSLIDE_MASTER_CONTENT_TYPE,\n\tSLIDE_LAYOUT_CONTENT_TYPE,\n\tTHEME_CONTENT_TYPE,\n\t'application/vnd.openxmlformats-officedocument.themeOverride+xml',\n\tNOTES_MASTER_CONTENT_TYPE,\n\t'application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml',\n\t'application/vnd.openxmlformats-officedocument.presentationml.presProps+xml',\n\t'application/vnd.openxmlformats-officedocument.presentationml.viewProps+xml',\n\t'application/vnd.openxmlformats-officedocument.presentationml.tableStyles+xml',\n\tPRESENTATION_MAIN_CONTENT_TYPE,\n])\n\n/**\n * Remove `partName` if it is neither shared chrome nor still referenced by any\n * remaining part, then recurse into the parts it referenced. The pruning a\n * removed slide triggers (notes/media/charts the slide alone used).\n */\nexport function pruneIfOrphan(pres: Presentation, partName: string): void {\n\tconst part = pres.opc.part(partName)\n\tif (!part || SHARED_CHROME_CONTENT_TYPES.has(part.contentType)) return\n\tif (isReferenced(pres, partName)) return\n\tconst rels = pres.opc.relationshipsFor(partName)\n\tconst childTargets = [...rels].filter((rel) => rel.targetMode !== 'External').map((rel) => rels.resolveTarget(rel.id))\n\tpres.opc.removePart(relsPartNameFor(partName))\n\tpres.opc.removePart(partName)\n\tfor (const child of childTargets) pruneIfOrphan(pres, child)\n}\n\n/** Whether any remaining part (or the package root) resolves an internal relationship to `partName`. */\nfunction isReferenced(pres: Presentation, partName: string): boolean {\n\tfor (const owner of [...pres.opc.parts.keys(), '/']) {\n\t\tif (owner.endsWith('.rels')) continue\n\t\tconst rels = pres.opc.relationshipsFor(owner)\n\t\tfor (const rel of rels) {\n\t\t\tif (rel.targetMode === 'External') continue\n\t\t\tif (rels.resolveTarget(rel.id) === partName) return true\n\t\t}\n\t}\n\treturn false\n}\n","/**\n * Rescaling an imported slide's geometry onto the destination canvas.\n *\n * The memo of already-rescaled parts is the load-bearing part: a layout or master shared by\n * several imports from one source deck must be rescaled exactly once, or the second import\n * scales it again on top of the first. It is owned by the calling `Presentation` and threaded\n * through here, so it lives as long as the deck does rather than as long as one call.\n */\n\nimport { computeRescale, rescaleSpTree, type RescaleTransform } from './rescale.js'\nimport { resolveSingleRel } from './part-index.js'\nimport type { ImportSlideOptions, SlideSize } from '../presentation-types.js'\nimport type { Presentation } from '../presentation.js'\nimport { SLIDE_LAYOUT_REL, SLIDE_MASTER_REL } from '../../../ooxml/rel-types.js'\nimport { spTreeOf } from '../../oxml/slide-dom.js'\n\n/**\n * Rescale an imported slide's geometry onto this deck's canvas (the `rescale`\n * option of {@link Presentation.importSlide}). Rewrites every top-level shape/group/\n * graphicFrame transform and table grid on the slide; in `copy` mode also\n * rescales the imported layout and master shape trees (resolved via the\n * slide → layout → master rel chain) so inherited placeholder/background geometry\n * stays aligned. `preserve`/`restyle` rebind to this deck's own master/layout —\n * already the destination size — so only the slide is touched. Geometry only:\n * font sizes and line widths are left as authored.\n */\nexport function rescaleImportedGeometry(\n\tdest: Presentation,\n\trescaledParts: Set<string>,\n\tslidePartName: string,\n\ttheme: ImportSlideOptions['theme'],\n\tsource: SlideSize,\n\ttarget: SlideSize,\n\tmode: 'fit' | 'stretch'\n): void {\n\tconst transform = computeRescale(source, target, mode)\n\trescalePartGeometry(dest, rescaledParts, slidePartName, transform)\n\tif (theme === undefined || theme === 'copy') {\n\t\tconst layout = resolveSingleRel(dest.opc, slidePartName, SLIDE_LAYOUT_REL)\n\t\tconst master = layout ? resolveSingleRel(dest.opc, layout, SLIDE_MASTER_REL) : null\n\t\tif (layout) rescalePartGeometry(dest, rescaledParts, layout, transform)\n\t\tif (master) rescalePartGeometry(dest, rescaledParts, master, transform)\n\t}\n}\n\n/**\n * Rescale one part's `p:spTree` geometry in place. Idempotent per part\n * (`rescaledParts`), so a layout/master shared across repeated imports from one\n * source is rescaled exactly once.\n */\nfunction rescalePartGeometry(\n\tdest: Presentation,\n\trescaledParts: Set<string>,\n\tpartName: string,\n\ttransform: RescaleTransform\n): void {\n\tif (rescaledParts.has(partName)) return\n\trescaledParts.add(partName)\n\tconst part = dest.opc.part(partName)\n\tconst spTree = spTreeOf(part?.dom.documentElement)\n\tif (!part || !spTree) return\n\trescaleSpTree(spTree, transform)\n\tpart.markDirty()\n}\n","/**\n * Read-model entry point: `Presentation` wraps an `OpcPackage` and exposes a\n * navigable, typed view of the deck (slides → shapes → text), backed by the\n * live DOM so the same nodes can later be mutated.\n *\n * The class holds the model and the deck-level plumbing every operation needs — the part\n * index, the slide list, the copy registry that lets repeated imports from one source share\n * what they already copied, and the `p:sldIdLst` wiring. The operations themselves live in\n * `ops/`, one job per module, taking this deck as an argument. The slide-import machinery\n * used to sit here as ~280 lines of private methods and made that split hard to see: the\n * read model's own surface was outnumbered by one feature's internals.\n */\nimport { emuToInches } from '../../units.js'\nimport { OpcPackage, type OpcInput } from '../opc/package.js'\nimport type { Part } from '../opc/part.js'\nimport { relativePartName, relsPartNameFor } from '../opc/partnames.js'\nimport {\n\tOOXML_NS,\n\tattr,\n\tcreateElement,\n\tfirstChild,\n\tgetElements,\n\tgetOrAddChild,\n\tintValue,\n\tsetAttr,\n} from '../oxml/dom.js'\nimport { EMBEDDED_FONT_SLOTS } from '../../embedded-fonts.js'\nimport { flattenShape } from './ops/flatten.js'\nimport { Slide } from './slide.js'\nimport { SlideMaster } from './chrome.js'\nimport { wrapShapeElement, type AnyShape } from './shapes.js'\nimport { carryShapeAnimations } from './animation.js'\nimport {\n\tcommentSchema,\n\treadCommentAuthors,\n\treadModernCommentAuthors,\n\ttype CommentAuthor,\n\ttype CommentSchema,\n\ttype ModernCommentAuthor,\n} from './comments.js'\nimport {\n\treadCoreProperties,\n\treadCustomProperties,\n\ttype CoreProperties,\n\ttype CustomProperty,\n} from './document-properties.js'\nimport { readTagsForPart, type Tag } from './tags.js'\nimport type {\n\tAppendSlidesOptions,\n\tFromTemplateOptions,\n\tImportShapeOptions,\n\tEmbeddedFontInfo,\n\tImportSlideMastersOptions,\n\tImportSlideOptions,\n\tImportSlidesRequest,\n\tImportedSlideMaster,\n\tLayoutHandle,\n\tSlideSize,\n\tSlideSource,\n} from './presentation-types.js'\nimport { cSldName, nthShapeChild } from '../oxml/slide-dom.js'\nimport { computeRescale, rescaleSpTree, type RescaleTransform } from './ops/rescale.js'\nimport { carryTableStyles } from './ops/table-styles.js'\nimport { promoteMasters } from './ops/master-registry.js'\nimport { checkSelectionCopyable, copyPart, copySlidePart, newOwnedScope, type ImportContext } from './ops/part-copy.js'\n// Deck-mutation operations. They live beside the model rather than on it: each is a whole job\n// (prune a part fringe, carry notes, merge embedded fonts, rescale onto a new canvas) that reads\n// and writes the package through the deck's public surface, and none of them is something a\n// caller navigates *to*.\nimport { rewriteCarriedRels } from './ops/carried-rels.js'\nimport { carryEmbeddedFonts, carryGeneratedEmbeddedFonts } from './ops/embedded-fonts.js'\nimport { sourceFlattenContext } from './ops/flatten-context.js'\nimport { importSlidePreserve, importSlideRestyle } from './ops/import-slide.js'\nimport { carryNotes, ensureNotesMasterFromXml } from './ops/notes-master.js'\nimport { layoutPartNamesOf, slideMasterPartNames } from './ops/part-index.js'\nimport { duplicateOwnedTargets } from './ops/page-owned.js'\nimport { pruneIfOrphan } from './ops/prune.js'\nimport { rescaleImportedGeometry } from './ops/rescale-import.js'\nimport {\n\tIMAGE_REL,\n\tNOTES_MASTER_REL,\n\tNOTES_SLIDE_CONTENT_TYPE,\n\tNOTES_SLIDE_REL,\n\tOFFICE_DOCUMENT_REL,\n\tSLIDE_CONTENT_TYPE,\n\tSLIDE_LAYOUT_REL,\n\tSLIDE_REL,\n} from '../../ooxml/rel-types.js'\nimport { InternalError, InvalidOptionError, PackageReadError, UnsupportedFeatureError } from '../../errors.js'\nimport { presentationRels } from './ops/deck-target.js'\n\nconst HYPERLINK_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink'\nconst CHART_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart'\n// chartEx (Office 2016) charts are reached through a Microsoft rel, not the ECMA `chart` one,\n// and their two mandatory style sidecars through a third pair — see `gen/chart/chartex-style.ts`.\nconst CHARTEX_REL = 'http://schemas.microsoft.com/office/2014/relationships/chartEx'\nconst CHART_STYLE_REL = 'http://schemas.microsoft.com/office/2011/relationships/chartStyle'\nconst CHART_COLOR_STYLE_REL = 'http://schemas.microsoft.com/office/2011/relationships/chartColorStyle'\nconst PACKAGE_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/package'\nconst AUDIO_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/audio'\nconst VIDEO_REL = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/video'\n// Microsoft 2007 `media` rel: paired with the ECMA audio/video rel (same Target),\n// referenced by the slide body's <p14:media r:embed>.\nconst MS_MEDIA_REL = 'http://schemas.microsoft.com/office/2007/relationships/media'\n\nconst CHART_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.drawingml.chart+xml'\n// chartEx parts carry Microsoft content types, not the `openxmlformats` ones.\nconst CHARTEX_CONTENT_TYPE = 'application/vnd.ms-office.chartex+xml'\nconst CHART_STYLE_CONTENT_TYPE = 'application/vnd.ms-office.chartstyle+xml'\nconst CHART_COLOR_STYLE_CONTENT_TYPE = 'application/vnd.ms-office.chartcolorstyle+xml'\nconst XLSX_CONTENT_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\n/** Content type of the main part in an editable `.pptx` package. */\nconst PRESENTATION_MAIN_CONTENT_TYPE =\n\t'application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml'\n/** Content type of the main part in a `.potx` template package — flipped to {@link PRESENTATION_MAIN_CONTENT_TYPE} by {@link Presentation.fromTemplate}. */\nconst PRESENTATION_TEMPLATE_MAIN_CONTENT_TYPE =\n\t'application/vnd.openxmlformats-officedocument.presentationml.template.main+xml'\n\nconst textEncoder = new TextEncoder()\n\n/**\n * `p:sldIdLst`'s document-order successors in `CT_Presentation` (ECMA-376):\n * everything that may legally follow it, so an inserted `p:sldIdLst` lands in the\n * right position when a template omitted it (zero slides).\n */\nconst PRESENTATION_SLD_ID_LST_SUCCESSORS = [\n\t'p:sldSz',\n\t'p:notesSz',\n\t'p:smartTags',\n\t'p:embeddedFontLst',\n\t'p:custShowLst',\n\t'p:photoAlbum',\n\t'p:custDataLst',\n\t'p:kinsoku',\n\t'p:defaultTextStyle',\n\t'p:modifyVerifier',\n\t'p:extLst',\n]\n/** ST_SlideId minimum (ECMA-376): slide ids live in [256, 2147483647]. */\nconst MIN_SLIDE_ID = 256\n\nexport class Presentation {\n\t#presentationPart: Part | undefined\n\t/**\n\t * Per-source copy registry for {@link importSlide}: source `OpcPackage` →\n\t * (source partname → partname allocated in this package). Lets parts shared\n\t * across imports from the same source deck (layout, master, theme, media) be\n\t * copied once and reused on later calls.\n\t */\n\t#importRegistry = new Map<OpcPackage, Map<string, string>>()\n\t/**\n\t * Parts whose geometry {@link importSlide}'s `rescale` has already rewritten, so a\n\t * layout/master shared across repeated imports from one source is not scaled twice.\n\t */\n\t#rescaledParts = new Set<string>()\n\n\tprivate constructor(readonly opc: OpcPackage) {}\n\n\t/** Open a `.pptx` from bytes and wrap it as a navigable `Presentation`. */\n\tstatic async load(input: OpcInput): Promise<Presentation> {\n\t\treturn new Presentation(await OpcPackage.load(input))\n\t}\n\n\t/** Wrap an already-loaded OPC package (e.g. from the lower-level API). */\n\tstatic fromPackage(opc: OpcPackage): Presentation {\n\t\treturn new Presentation(opc)\n\t}\n\n\t/**\n\t * Open a PowerPoint template (`.pptx` or `.potx`) and return it as an empty\n\t * deck shell ready to author onto: its slide masters, layouts, and theme are\n\t * kept **byte-identical**, while any sample slides the template carried are\n\t * stripped so only the shared chrome remains.\n\t *\n\t * Use it to build a fresh deck on a corporate template without rebuilding the\n\t * masters in code: discover the bindable layouts with {@link layouts}, then\n\t * author slides with a generator sized to match the template and graft them in\n\t * with {@link appendSlides} (which enforces an equal slide size). Saving yields\n\t * an editable `.pptx` that reuses the template's authored chrome verbatim.\n\t *\n\t * ```ts\n\t * const deck = await Presentation.fromTemplate(templateBytes) // .pptx or .potx\n\t * deck.layouts().map(l => l.name) // discover layouts\n\t * await deck.appendSlides(pptx, { layout: 'Title and Content' })\n\t * const out = await deck.save() // editable .pptx\n\t * ```\n\t *\n\t * A `.potx` package declares its main part with the template content type; by\n\t * default that override is flipped to the editable presentation type so the\n\t * saved output opens as a normal deck. Pass `keepTemplateContentType: true` to\n\t * preserve the template type. A `.pptx` input needs no flip, and a template\n\t * that already carries zero slides makes the strip a no-op.\n\t */\n\tstatic async fromTemplate(input: OpcInput, options: FromTemplateOptions = {}): Promise<Presentation> {\n\t\tconst pres = new Presentation(await OpcPackage.load(input))\n\n\t\t// Normalize a .potx main part to the editable presentation content type so\n\t\t// the saved package opens as a deck, not a template. The officeDocument\n\t\t// relationship resolves the main part regardless of its content type, so a\n\t\t// .potx already loads; only the [Content_Types].xml override needs flipping.\n\t\tif (!options.keepTemplateContentType) {\n\t\t\tconst mainPart = pres.presentationPart\n\t\t\tif (mainPart.contentType === PRESENTATION_TEMPLATE_MAIN_CONTENT_TYPE) {\n\t\t\t\tpres.opc.contentTypes.ensureRegistered(mainPart.partName, PRESENTATION_MAIN_CONTENT_TYPE)\n\t\t\t}\n\t\t}\n\n\t\t// Strip any sample slides to a master/layout-only shell. removeSlide never\n\t\t// prunes shared chrome, so masters/layouts/theme stay byte-identical.\n\t\twhile (pres.slides.length > 0) pres.removeSlide(0)\n\n\t\treturn pres\n\t}\n\n\t/** The main presentation part (`/ppt/presentation.xml`), resolved via the package `officeDocument` relationship. */\n\tget presentationPart(): Part {\n\t\tif (this.#presentationPart) return this.#presentationPart\n\t\tconst packageRels = this.opc.relationshipsFor('/')\n\t\tconst officeDocument = packageRels.byType(OFFICE_DOCUMENT_REL)\n\t\tconst officeDocumentRel = officeDocument[0]\n\t\tif (officeDocument.length !== 1 || !officeDocumentRel) {\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/office-document-relationship-invalid',\n\t\t\t\t`Expected exactly one officeDocument relationship, found ${officeDocument.length}`\n\t\t\t)\n\t\t}\n\t\tconst partName = packageRels.resolveTarget(officeDocumentRel.id)\n\t\tconst part = this.opc.part(partName)\n\t\tif (!part)\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/relationship-target-missing',\n\t\t\t\t`officeDocument relationship targets a missing part: ${partName}`\n\t\t\t)\n\t\tthis.#presentationPart = part\n\t\treturn part\n\t}\n\n\t/** The slides in presentation order (resolved from `p:sldIdLst` + the presentation's relationships). */\n\tget slides(): Slide[] {\n\t\tconst root = this.presentationPart.dom.documentElement\n\t\tconst sldIdLst = root && firstChild(root, 'p:sldIdLst')\n\t\tif (!sldIdLst) return []\n\t\tconst rels = this.opc.relationshipsFor(this.presentationPart.partName)\n\t\tconst slides: Slide[] = []\n\t\tlet index = 0\n\t\tfor (const sldId of getElements(sldIdLst, 'p:sldId')) {\n\t\t\tconst relId = attr(sldId, 'r:id')\n\t\t\tif (!relId) continue\n\t\t\tconst partName = rels.resolveTarget(relId)\n\t\t\tconst part = this.opc.part(partName)\n\t\t\tif (!part)\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/relationship-target-missing',\n\t\t\t\t\t`Slide relationship ${relId} targets a missing part: ${partName}`\n\t\t\t\t)\n\t\t\tslides.push(new Slide(this, part, intValue(attr(sldId, 'id')) ?? 0, index++))\n\t\t}\n\t\treturn slides\n\t}\n\n\t/** Slide dimensions (`p:sldSz`), or `null` if the presentation declares none. */\n\tget slideSize(): SlideSize | null {\n\t\tconst root = this.presentationPart.dom.documentElement\n\t\tconst sldSz = root && firstChild(root, 'p:sldSz')\n\t\tif (!sldSz) return null\n\t\tconst widthEmu = intValue(attr(sldSz, 'cx'))\n\t\tconst heightEmu = intValue(attr(sldSz, 'cy'))\n\t\tif (widthEmu === null || heightEmu === null) return null\n\t\treturn { widthEmu, heightEmu, widthIn: emuToInches(widthEmu), heightIn: emuToInches(heightEmu) }\n\t}\n\n\t/**\n\t * The deck's embedded font families (`p:embeddedFontLst` in `presentation.xml`),\n\t * `[]` when it embeds none. Each entry names the typeface and resolves every\n\t * embedded face's `r:id` to the absolute partname of its `.fntdata` binary — the\n\t * read counterpart to the write-side `pptx.embedFont` / `importSlide({ embedFonts })`\n\t * carry. An entry whose `p:font` has no `@typeface`, or a face whose `r:id` is\n\t * missing or dangling, is skipped (faithful degradation, no throw). Read-only.\n\t */\n\tget embeddedFonts(): EmbeddedFontInfo[] {\n\t\tconst root = this.presentationPart.dom.documentElement\n\t\tconst lst = root && firstChild(root, 'p:embeddedFontLst')\n\t\tif (!lst) return []\n\t\tconst rels = this.opc.relationshipsFor(this.presentationPart.partName)\n\t\tconst fonts: EmbeddedFontInfo[] = []\n\t\tfor (const entry of getElements(lst, 'p:embeddedFont')) {\n\t\t\tconst font = firstChild(entry, 'p:font')\n\t\t\tconst typeface = font && attr(font, 'typeface')\n\t\t\tif (!typeface) continue\n\t\t\tconst faces: EmbeddedFontInfo['faces'] = []\n\t\t\tfor (const slot of EMBEDDED_FONT_SLOTS) {\n\t\t\t\tconst face = firstChild(entry, `p:${slot}`)\n\t\t\t\tconst relId = face && attr(face, 'r:id')\n\t\t\t\tif (!relId || !rels.get(relId)) continue\n\t\t\t\tfaces.push({ slot, partName: rels.resolveTarget(relId) })\n\t\t\t}\n\t\t\tfonts.push({ typeface, panose: font ? attr(font, 'panose') : null, faces })\n\t\t}\n\t\treturn fonts\n\t}\n\n\t/**\n\t * The deck-wide **legacy** comment-author registry (`p:cmAuthorLst` in\n\t * `ppt/commentAuthors.xml`), `[]` when the deck has no comments. Each slide's\n\t * {@link Slide.comments} resolves its `@authorId` against this list. The 2018\n\t * modern comment authors (`ppt/authors.xml`) are a separate part, not decoded here.\n\t */\n\tget commentAuthors(): CommentAuthor[] {\n\t\treturn readCommentAuthors(this.opc, this.presentationPart.partName)\n\t}\n\n\t/**\n\t * The deck-wide **modern** (2018) comment-author registry (`p188:authorLst` in\n\t * `ppt/authors.xml`), `[]` when the deck carries no modern comments. Unlike the\n\t * legacy {@link commentAuthors}, each entry is keyed by a GUID `id` (plus\n\t * `userId`/`providerId`); each slide's {@link Slide.modernComments} resolves its\n\t * `@authorId` against this list. Read-only — the writer emits legacy comments.\n\t */\n\tget modernCommentAuthors(): ModernCommentAuthor[] {\n\t\treturn readModernCommentAuthors(this.opc, this.presentationPart.partName)\n\t}\n\n\t/**\n\t * Which comment schema this deck uses: `'modern'` when it carries any 2018\n\t * `modernComment_*` part (read via {@link Slide.modernComments} /\n\t * {@link modernCommentAuthors}), `'legacy'` when it carries classic\n\t * `commentN.xml` parts (read via {@link Slide.comments} / {@link commentAuthors}),\n\t * or `'none'`. The two schemas do not coexist in practice, so this tells a\n\t * consumer which accessor to read without probing both.\n\t */\n\tget commentSchema(): CommentSchema {\n\t\treturn commentSchema(this.opc)\n\t}\n\n\t/**\n\t * The deck's core document properties (`docProps/core.xml`): title, subject,\n\t * creator, keywords, revision, and the created/modified/lastPrinted timestamps\n\t * (kept as raw W3CDTF strings). `{}` when the deck carries no core-properties\n\t * part. The read counterpart of the write-side `pptx.title`/`subject`/`author`\n\t * (→ `creator`)/`revision` setters.\n\t */\n\tget coreProperties(): CoreProperties {\n\t\treturn readCoreProperties(this.opc)\n\t}\n\n\t/**\n\t * The deck's user-defined custom document properties (`docProps/custom.xml`) as\n\t * `{ name, value }` pairs, each value typed from its `vt:` element (string,\n\t * number, boolean, or a raw filetime string). `[]` when the deck carries no\n\t * custom-properties part. The read counterpart of `pptx.setCustomProperty(...)`.\n\t */\n\tget customProperties(): CustomProperty[] {\n\t\treturn readCustomProperties(this.opc)\n\t}\n\n\t/**\n\t * The deck-level programmatic tags (`p:custDataLst/p:tags` on `presentation.xml`,\n\t * resolved to `ppt/tags/tagN.xml`) as `{ name, val }` string pairs, `[]` when the\n\t * deck carries none. These are add-in/host metadata with no visible rendering and\n\t * no writer — read-only, preserved byte-for-byte on round-trip. Per-slide tags are\n\t * {@link Slide.tags}.\n\t */\n\tget tags(): Tag[] {\n\t\treturn readTagsForPart(this.opc, this.presentationPart.partName)\n\t}\n\n\t/**\n\t * Duplicate the slide at `index` and insert the copy at `options.at` (deck\n\t * order; `0` = first), defaulting to appending at the end when `at` is omitted\n\t * or out of range. Returns the new slide. The new slide part copies the source\n\t * bytes verbatim and shares the source's deck-wide relationship targets\n\t * (layout, images, media) by copying its `.rels`; a new presentation→slide\n\t * relationship and a `p:sldId` entry are wired up. Marks the presentation part\n\t * dirty.\n\t *\n\t * What the source page *owns* is copied rather than shared: its notes slide,\n\t * charts, SmartArt diagrams and OLE embeddings, each with the subtree under it\n\t * (a chart's embedded workbook comes along; the image inside its user-shapes\n\t * drawing stays shared). PowerPoint refuses to open a deck where two slides\n\t * resolve to one chart or diagram, so this is not tidiness — see\n\t * `page-owned.ts` for the rule and the evidence behind it.\n\t */\n\tcloneSlide(index: number, options: { at?: number } = {}): Slide {\n\t\tconst source = this.slides[index]\n\t\tif (!source) throw new InvalidOptionError('slide/index-out-of-range', `No slide at index ${index} to clone`)\n\t\tconst opc = this.opc\n\t\tconst sourcePart = source.part\n\n\t\t// 1. Copy the slide part bytes verbatim into a fresh slide partname.\n\t\tconst newPartName = opc.reservePartNameLike(sourcePart.partName)\n\t\tconst newPart = opc.addPart(newPartName, sourcePart.contentType, sourcePart.bytes)\n\n\t\t// 2. Copy the slide's relationships (targets resolve identically — same dir).\n\t\t// Through the live relationship set, not the `.rels` part bytes: a page\n\t\t// this session imported or edited holds its rels in memory until the deck\n\t\t// is saved, and copying the bytes gave such a clone no relationships at\n\t\t// all — a slide whose `r:id`s resolved to nothing.\n\t\tconst sourceRels = opc.relationshipsFor(sourcePart.partName)\n\t\tconst cloneRels = opc.relationshipsFor(newPartName)\n\t\tfor (const rel of sourceRels) cloneRels.addWithId(rel.id, rel.type, rel.target, rel.targetMode)\n\n\t\t// 3. Take copies of the parts the page owned, leaving the shared ones shared.\n\t\tduplicateOwnedTargets(opc, sourcePart.partName, newPartName)\n\n\t\t// 4. Wire the new slide into the presentation (rel + p:sldId entry) at `at`.\n\t\treturn this.#insertSlidePart(newPart, options.at)\n\t}\n\n\t/**\n\t * Remove the slide at `index` (deck order) and return its former partname. The\n\t * `p:sldId` entry and the presentation→slide relationship are dropped, the slide\n\t * part and its `.rels` are deleted, and any part the slide *privately* owned\n\t * (its notes slide, slide-only media, charts/embeddings) that no remaining part\n\t * references is pruned too — recursively. Shared deck chrome (layout, master,\n\t * theme, …) is never pruned, so the deck stays renderable; removing every slide\n\t * leaves a valid master/layout-only package (a template shell).\n\t *\n\t * Untouched parts stay byte-identical, matching the package fidelity contract.\n\t * Throws when there is no slide at `index`.\n\t */\n\tremoveSlide(index: number): string {\n\t\tconst slide = this.slides[index]\n\t\tif (!slide) throw new InvalidOptionError('slide/index-out-of-range', `No slide at index ${index} to remove`)\n\t\tconst partName = slide.partName\n\n\t\t// The slide's internal targets, captured before its rels are dropped, so the\n\t\t// parts it privately owned can be pruned afterwards.\n\t\tconst slideRels = this.opc.relationshipsFor(partName)\n\t\tconst formerTargets = [...slideRels]\n\t\t\t.filter((rel) => rel.targetMode !== 'External')\n\t\t\t.map((rel) => slideRels.resolveTarget(rel.id))\n\n\t\t// Unwire from presentation.xml: remove the matching p:sldId and the rel.\n\t\tconst presPart = this.presentationPart\n\t\tconst presRels = presentationRels(this)\n\t\tconst root = presPart.dom.documentElement\n\t\tconst sldIdLst = root && firstChild(root, 'p:sldIdLst')\n\t\tif (sldIdLst) {\n\t\t\tfor (const sldId of getElements(sldIdLst, 'p:sldId')) {\n\t\t\t\tconst relId = attr(sldId, 'r:id')\n\t\t\t\tif (relId && presRels.get(relId) && presRels.resolveTarget(relId) === partName) {\n\t\t\t\t\tsldIdLst.removeChild(sldId)\n\t\t\t\t\tpresRels.remove(relId)\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tpresPart.markDirty()\n\n\t\t// Drop the slide part and its .rels, then prune the parts it privately owned.\n\t\tthis.opc.removePart(relsPartNameFor(partName))\n\t\tthis.opc.removePart(partName)\n\t\tfor (const target of formerTargets) pruneIfOrphan(this, target)\n\n\t\treturn partName\n\t}\n\n\t/**\n\t * Append a copy of `source.slides[index]` to this presentation and return it.\n\t *\n\t * Unlike {@link cloneSlide} (same-deck duplicate), this copies a slide across\n\t * a package boundary: it brings the connected sub-graph the slide depends on —\n\t * its `slideLayout` → `slideMaster` → `theme`, plus any media, charts, and\n\t * embeddings — into this package under fresh partnames, rewriting every\n\t * partname, relationship id, and content-type registration so the result is a\n\t * self-consistent OPC package. Parts of this (target) package that are not\n\t * touched stay byte-identical, matching `cloneSlide`'s fidelity contract.\n\t *\n\t * Only the layout(s) actually used by imported slides are copied; the imported\n\t * master's `p:sldLayoutIdLst` is pruned to exactly those, mirroring how\n\t * PowerPoint's \"Reuse Slides\" brings a slide across. Parts shared by repeated\n\t * imports from the same source deck are copied once and reused — every part\n\t * except the page itself. Importing the same source slide twice yields two\n\t * independent copies over one shared layout/master/theme, which is what lets a\n\t * deck show one page twice (verbatim, then edited).\n\t *\n\t * With `{ theme: 'preserve' }` the slide's source theme is instead *flattened*\n\t * into the slide XML and the slide is bound to this deck's existing\n\t * master/layout; with `{ theme: 'restyle' }` the slide is bound to this deck's\n\t * master/layout with its theme references left symbolic, so it re-brands to the\n\t * destination palette — see {@link ImportSlideOptions}.\n\t *\n\t * v1 limitations: by default the source slide size must equal this\n\t * presentation's — pass `{ rescale: 'fit' | 'stretch' }` to rescale the imported\n\t * geometry onto this deck's canvas instead (geometry only, not fonts/line\n\t * widths). Source notes are dropped unless you pass `{ importNotes: true }`.\n\t */\n\timportSlide(source: Presentation, index: number, options: ImportSlideOptions = {}): Slide {\n\t\tconst sourceSlide = source.slides[index]\n\t\tif (!sourceSlide) throw new InvalidOptionError('slide/index-out-of-range', `No slide at index ${index} to import`)\n\n\t\t// 1. Pre-flight: slide sizes must match unless the caller opts into a rescale.\n\t\tconst target = this.slideSize\n\t\tconst incoming = source.slideSize\n\t\tconst sizesDiffer =\n\t\t\t!target || !incoming || target.widthEmu !== incoming.widthEmu || target.heightEmu !== incoming.heightEmu\n\t\tif (sizesDiffer && !options.rescale) {\n\t\t\tconst fmt = (s: SlideSize | null): string => (s ? `${s.widthEmu}×${s.heightEmu} EMU` : 'unknown')\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/slide-size-mismatch',\n\t\t\t\t`importSlide requires equal slide sizes (pass { rescale: 'fit' | 'stretch' } to rescale); target is ${fmt(target)}, source is ${fmt(incoming)}`\n\t\t\t)\n\t\t}\n\t\tif (sizesDiffer && options.rescale && (!target || !incoming)) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/slide-size-unknown',\n\t\t\t\t'importSlide rescale requires both decks to declare a slide size (p:sldSz)'\n\t\t\t)\n\t\t}\n\n\t\t// 2. Copy the slide and its dependencies. 'preserve' flattens the theme into\n\t\t// the slide and attaches it to this deck's master; 'restyle' attaches it\n\t\t// to this deck's master with theme refs left symbolic (re-brand); 'copy'\n\t\t// brings the source theme subgraph across wholesale.\n\t\tconst importCtx = this.#importContext(source.opc)\n\t\tconst newPartName =\n\t\t\toptions.theme === 'preserve'\n\t\t\t\t? importSlidePreserve(this, importCtx, source, sourceSlide, options.carryMasterGraphics === true)\n\t\t\t\t: options.theme === 'restyle'\n\t\t\t\t\t? importSlideRestyle(\n\t\t\t\t\t\t\tthis,\n\t\t\t\t\t\t\timportCtx,\n\t\t\t\t\t\t\tsource,\n\t\t\t\t\t\t\tsourceSlide,\n\t\t\t\t\t\t\toptions.carryMasterGraphics === true,\n\t\t\t\t\t\t\toptions.remapLiterals === true\n\t\t\t\t\t\t)\n\t\t\t\t\t: copySlidePart(importCtx, sourceSlide.partName)\n\t\tconst newPart = this.opc.part(newPartName)\n\t\tif (!newPart)\n\t\t\tthrow new InternalError('import/part-went-missing', `Imported slide part went missing: ${newPartName}`)\n\n\t\t// 2b. Rescale the imported geometry to this deck's canvas when sizes differ.\n\t\tif (sizesDiffer && options.rescale && target && incoming) {\n\t\t\trescaleImportedGeometry(\n\t\t\t\tthis,\n\t\t\t\tthis.#rescaledParts,\n\t\t\t\tnewPartName,\n\t\t\t\toptions.theme,\n\t\t\t\tincoming,\n\t\t\t\ttarget,\n\t\t\t\toptions.rescale === true ? 'fit' : options.rescale\n\t\t\t)\n\t\t}\n\n\t\t// 3. Wire the new slide into the presentation (rel + p:sldId entry) at `at`.\n\t\tconst slide = this.#insertSlidePart(newPart, options.at)\n\n\t\t// 4. Optionally carry the source slide's speaker notes. The slide copy above\n\t\t// drops the notesSlide rel (both copyPart and importSlideRebind do); this\n\t\t// re-adds it wired to the new slide and merged onto a single notesMaster.\n\t\tif (options.importNotes) carryNotes(this, source, importCtx, sourceSlide.partName, newPartName)\n\n\t\t// 5. Optionally carry the source deck's embedded fonts (presentation-level, so\n\t\t// a separate traversal from the slide-part copy chain above).\n\t\tif (options.embedFonts) carryEmbeddedFonts(this, source, importCtx)\n\n\t\treturn slide\n\t}\n\n\t/**\n\t * Import selected pages from one or more loaded source presentations as one\n\t * batch. Each imported page lands at its `outputIndex` in the complete\n\t * destination slide list after the batch, and the returned array is parallel\n\t * to `requests` — `result[i]` is the page `requests[i]` asked for, whatever\n\t * order the output positions were given in.\n\t *\n\t * Everything is checked before a single byte of this deck moves: every request\n\t * names an existing source page, final output positions are unique, each source\n\t * has this deck's slide size, and a read-only dry run of the copy proves every\n\t * part it would reach is present. A batch therefore either applies in full or\n\t * leaves this deck byte-identical, where a per-page loop of\n\t * {@link importSlide} can leave a half-stitched deck behind.\n\t *\n\t * The batch also decides what a `slide → slide` link means: an internal link\n\t * on a selected page must target another **selected** page (or one this deck\n\t * already contains via an earlier import from that source), and is rewritten\n\t * to the fresh partname — importing page 3 of 10 does not drag pages 1–2\n\t * across as dependencies, and never strands the link. This mirrors\n\t * `appendSlides`' `import/unresolved-slide-link`, which the write side already\n\t * enforces for generator decks.\n\t *\n\t * One request is one output page, so naming the same source page in several\n\t * requests is how you ask for several independent copies of it — the page part\n\t * is the one thing an import never shares, exactly as in {@link importSlide}.\n\t * Everything under it (layout, master, theme, media) is still copied once and\n\t * shared. Where such a page is the target of a `slide → slide` link, the link\n\t * resolves to one of its copies: pages duplicated together are copied in\n\t * lockstep and link to their round-mates, and a link into a page requested only\n\t * once always lands on that single copy.\n\t *\n\t * Speaker notes travel per request: `{ importNotes: true }` carries that page's\n\t * `notesSlide` part across, wired to the new page and bound to a single\n\t * `notesMaster` under the same 0..1 rule {@link importSlide} and\n\t * {@link appendSlides} follow — the destination's own master wins when it has\n\t * one. Notes are part of the up-front dry run too, so a batch that would fail\n\t * carrying them is refused with the deck still byte-identical. A page named in\n\t * several requests gets its own copy of its notes each time, as of everything\n\t * else that page owns.\n\t *\n\t * Scope: pages come across under `'copy'` theme semantics (their own layout →\n\t * master → theme subgraph, shared parts deduped via the copy registry).\n\t * Embedded fonts are not carried, and sizes must match, since there is no batch\n\t * spelling for `embedFonts` or `rescale`. Use {@link importSlide} when you need\n\t * either of those.\n\t */\n\timportSlides(requests: readonly ImportSlidesRequest[]): Slide[] {\n\t\t// 1. Validate everything up front: indexes exist, selections and output\n\t\t// positions are unique, sizes match. No part is touched until all pass.\n\t\tconst resolved = requests.map((request, requestIndex) => {\n\t\t\tif (!Number.isInteger(request.sourceIndex) || request.sourceIndex < 0) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'slide/index-out-of-range',\n\t\t\t\t\t`importSlides: sourceIndex must be a non-negative integer; received ${request.sourceIndex}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (!Number.isInteger(request.outputIndex) || request.outputIndex < 0) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/output-index-out-of-range',\n\t\t\t\t\t`importSlides: outputIndex must be a non-negative integer; received ${request.outputIndex}`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst sourceSlide = request.source.slides[request.sourceIndex]\n\t\t\tif (!sourceSlide) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'slide/index-out-of-range',\n\t\t\t\t\t`importSlides: no slide at index ${request.sourceIndex} to import`\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn { ...request, requestIndex, sourceSlide }\n\t\t})\n\t\tif (resolved.length === 0) return []\n\n\t\t// Step 4 inserts into this element; failing on it here rather than there\n\t\t// keeps the wiring loop, like the copy, unable to stop half-way.\n\t\tif (!this.presentationPart.dom.documentElement) {\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/part-has-no-root',\n\t\t\t\t'presentation.xml has no document element to insert slides into'\n\t\t\t)\n\t\t}\n\n\t\tconst finalSlideCount = this.slides.length + resolved.length\n\t\t// Which pages each source is being asked for. A page may appear in several\n\t\t// requests: the set is what the dry run walks, and the per-request output\n\t\t// parts are allocated in step 2. `notesPages` is the subset whose notes are\n\t\t// coming too, which the dry run has to walk past the dropped notes rel.\n\t\tconst selectedPages = new Map<OpcPackage, Set<string>>()\n\t\tconst notesPages = new Map<OpcPackage, Set<string>>()\n\t\tfor (const request of resolved) {\n\t\t\tlet pages = selectedPages.get(request.source.opc)\n\t\t\tif (!pages) {\n\t\t\t\tpages = new Set()\n\t\t\t\tselectedPages.set(request.source.opc, pages)\n\t\t\t}\n\t\t\tpages.add(request.sourceSlide.partName)\n\t\t\tif (!request.importNotes) continue\n\t\t\tlet withNotes = notesPages.get(request.source.opc)\n\t\t\tif (!withNotes) {\n\t\t\t\twithNotes = new Set()\n\t\t\t\tnotesPages.set(request.source.opc, withNotes)\n\t\t\t}\n\t\t\twithNotes.add(request.sourceSlide.partName)\n\t\t}\n\n\t\tconst target = this.slideSize\n\t\tconst outputIndexes = new Set<number>()\n\t\tfor (const request of resolved) {\n\t\t\tif (request.outputIndex >= finalSlideCount) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/output-index-out-of-range',\n\t\t\t\t\t`importSlides: outputIndex ${request.outputIndex} is outside the final slide list of ${finalSlideCount} slides`\n\t\t\t\t)\n\t\t\t}\n\t\t\tif (outputIndexes.has(request.outputIndex)) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/output-index-conflict',\n\t\t\t\t\t`importSlides: outputIndex ${request.outputIndex} is requested more than once`\n\t\t\t\t)\n\t\t\t}\n\t\t\toutputIndexes.add(request.outputIndex)\n\t\t\tconst incoming = request.source.slideSize\n\t\t\tif (!target || !incoming || target.widthEmu !== incoming.widthEmu || target.heightEmu !== incoming.heightEmu) {\n\t\t\t\tconst fmt = (size: SlideSize | null): string => (size ? `${size.widthEmu}×${size.heightEmu} EMU` : 'unknown')\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/slide-size-mismatch',\n\t\t\t\t\t`importSlides requires equal slide sizes; target is ${fmt(target)}, source is ${fmt(incoming)}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\t// 1b. Dry-run the copy against each source, still reading only source\n\t\t// packages: every part the traversal will reach exists and parses, and\n\t\t// no selected page links outside the selection. Once this passes the\n\t\t// copy below has no reachable throw, which is what lets a rejected\n\t\t// batch leave this deck byte-identical instead of half-stitched.\n\t\t// `copyMaster` is read once, before anything moves: a destination that\n\t\t// already has a notesMaster keeps it, so no source master is copied at\n\t\t// all, and one that has none takes the first carried master — after which\n\t\t// the rest bind to it. Walking every source's master when the deck has\n\t\t// none is deliberately the strict side of that: it can only reject a\n\t\t// source deck whose own notes master is already broken.\n\t\tconst copyMaster = this.opc.relationshipsFor(this.presentationPart.partName).byType(NOTES_MASTER_REL).length === 0\n\t\tfor (const [sourceOpc, pages] of selectedPages) {\n\t\t\tcheckSelectionCopyable(sourceOpc, this.#importContext(sourceOpc).registry, pages, {\n\t\t\t\tpages: notesPages.get(sourceOpc) ?? new Set(),\n\t\t\t\tcopyMaster,\n\t\t\t})\n\t\t}\n\n\t\t// 2. Materialize each request's output page now, so the copy traversals can\n\t\t// wire slide→slide relationships to their pre-allocated destinations.\n\t\t// One request is one output page, so a source page asked for twice gets\n\t\t// two reservations, in request order.\n\t\t// The reservation list is typed non-empty, so round 0 needs no fallback.\n\t\tconst destinationsBySource = new Map<OpcPackage, Map<string, [string, ...string[]]>>()\n\t\tconst planned = resolved.map((request) => {\n\t\t\tlet destinations = destinationsBySource.get(request.source.opc)\n\t\t\tif (!destinations) {\n\t\t\t\tdestinations = new Map()\n\t\t\t\tdestinationsBySource.set(request.source.opc, destinations)\n\t\t\t}\n\t\t\tconst sourcePart = request.sourceSlide.part\n\t\t\tconst newPartName = this.opc.reservePartNameLike(request.sourceSlide.partName)\n\t\t\tconst destPart = this.opc.addPart(newPartName, sourcePart.contentType, sourcePart.bytes)\n\t\t\tconst reserved = destinations.get(request.sourceSlide.partName)\n\t\t\tif (reserved) reserved.push(newPartName)\n\t\t\telse destinations.set(request.sourceSlide.partName, [newPartName])\n\t\t\treturn { ...request, destPart }\n\t\t})\n\n\t\t// 3. Copy each selected page and its dependency subgraph (theme/master/\n\t\t// layout/media/…), with links constrained to the selection.\n\t\t//\n\t\t// `copyPart`'s plan holds one destination per source page, so a page\n\t\t// requested N times is copied in N rounds: round K materializes every\n\t\t// page that has a Kth reservation, and names each other page's *first*\n\t\t// copy so a jump link out of the round still lands on a page of this\n\t\t// batch. A page duplicated alongside another therefore links to its\n\t\t// round-mate, and a link into a single-copy page resolves to that one\n\t\t// copy from every round. Rounds after the first re-materialize only the\n\t\t// pages they name: everything else is a registry hit `copyPart` returns\n\t\t// unchanged.\n\t\tfor (const [sourceOpc, destinations] of destinationsBySource) {\n\t\t\tconst base = this.#importContext(sourceOpc)\n\t\t\tconst rounds = Math.max(...[...destinations.values()].map((reserved) => reserved.length))\n\t\t\tfor (let round = 0; round < rounds; round++) {\n\t\t\t\tconst plan = new Map<string, string>()\n\t\t\t\tfor (const [sourcePartName, reserved] of destinations) plan.set(sourcePartName, reserved[round] ?? reserved[0])\n\t\t\t\tconst ctx: ImportContext = { ...base, selection: { destinations: plan } }\n\t\t\t\tfor (const [sourcePartName, reserved] of destinations) {\n\t\t\t\t\tif (round < reserved.length) void copyPart(ctx, sourcePartName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// 3b. Carry the notes of the pages that asked for them, in request order, so\n\t\t// the deck's single notesMaster comes from the first such page — the same\n\t\t// order the dry run assumed. The copy above dropped every notesSlide rel,\n\t\t// so this is the only thing that re-adds one, and a page named twice gets\n\t\t// a notes part per copy.\n\t\tfor (const request of planned) {\n\t\t\tif (!request.importNotes) continue\n\t\t\tcarryNotes(\n\t\t\t\tthis,\n\t\t\t\trequest.source,\n\t\t\t\tthis.#importContext(request.source.opc),\n\t\t\t\trequest.sourceSlide.partName,\n\t\t\t\trequest.destPart.partName\n\t\t\t)\n\t\t}\n\n\t\t// 4. Wire into p:sldIdLst at each requested final position. Ascending order\n\t\t// makes the raw final index the correct insertion point at every step:\n\t\t// earlier inserts all sit before it, so they shift it by exactly the\n\t\t// number of entries the final position already counts. The result is\n\t\t// written back by request index, so `result[i]` is `requests[i]`'s page\n\t\t// whatever order the positions were given in.\n\t\tconst added: Slide[] = []\n\t\tfor (const request of [...planned].sort((left, right) => left.outputIndex - right.outputIndex)) {\n\t\t\tadded[request.requestIndex] = this.#insertSlidePart(request.destPart, request.outputIndex)\n\t\t}\n\t\treturn added\n\t}\n\n\t/**\n\t * Graft slide master(s) from another open package into this one and return what\n\t * was copied. Unlike {@link importSlide} — which brings a master across only as\n\t * the dependency of an imported *slide* and prunes it to the one layout that\n\t * slide uses — this copies a master together with its **whole** layout family\n\t * and attaches it to no slide: the master and its layouts land in this deck's\n\t * layout gallery (PowerPoint's *Insert ▸ New Slide* / *Layout* picker) without\n\t * changing any existing slide.\n\t *\n\t * It is the \"ship a brand template's layouts into a generated deck\" capability,\n\t * kept brand-agnostic here: the caller supplies the source `.pptx`. Each grafted\n\t * master is wired into `p:sldMasterIdLst` (so renderers treat it as active) and\n\t * its `p:sldLayoutIdLst` is rebuilt to list exactly the copied layouts; the\n\t * connected theme/media/tag parts come across under fresh partnames, and parts\n\t * shared with earlier imports from the same source are reused (the copy\n\t * registry), so a re-call is idempotent. Untouched parts of this package stay\n\t * byte-identical, matching {@link importSlide}'s fidelity contract.\n\t *\n\t * `options.masters` / `options.layouts` narrow what is grafted; by default every\n\t * master and every layout comes across. The source and destination slide sizes\n\t * must match unless `options.requireEqualSize` is `false` (see\n\t * {@link ImportSlideMastersOptions}).\n\t *\n\t * Presentation-level parts are carried only on request: embedded fonts via\n\t * `options.embedFonts` and table styles via `options.tableStyles`. By default a\n\t * grafted master is appended after the deck's existing masters; `options.primary`\n\t * moves the grafted masters to the front so the deck presents as their theme (see\n\t * {@link ImportSlideMastersOptions}). The v1 limitation mirroring\n\t * {@link importSlide} is that geometry is not rescaled.\n\t */\n\timportSlideMasters(source: Presentation, options: ImportSlideMastersOptions = {}): ImportedSlideMaster[] {\n\t\tif (options.requireEqualSize !== false) {\n\t\t\tconst target = this.slideSize\n\t\t\tconst incoming = source.slideSize\n\t\t\tif (!target || !incoming || target.widthEmu !== incoming.widthEmu || target.heightEmu !== incoming.heightEmu) {\n\t\t\t\tconst fmt = (s: SlideSize | null): string => (s ? `${s.widthEmu}×${s.heightEmu} EMU` : 'unknown')\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/slide-size-mismatch',\n\t\t\t\t\t`importSlideMasters requires equal slide sizes (pass { requireEqualSize: false } to override); target is ${fmt(target)}, source is ${fmt(incoming)}`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\n\t\tconst pickMaster = options.masters ?? (() => true)\n\t\tconst pickLayout = options.layouts ?? (() => true)\n\n\t\tconst ctx = this.#importContext(source.opc)\n\t\tconst imported: ImportedSlideMaster[] = []\n\t\tslideMasterPartNames(source).forEach((masterPartName, masterIndex) => {\n\t\t\tif (!pickMaster(cSldName(source.opc.part(masterPartName)), masterIndex)) return\n\n\t\t\t// Copy the (lean) master first: copyPart registers it in p:sldMasterIdLst\n\t\t\t// and clears its layout list, then each copied layout re-links itself in.\n\t\t\tconst newMasterPartName = copyPart(ctx, masterPartName)\n\n\t\t\tconst layoutPartNames: string[] = []\n\t\t\tlayoutPartNamesOf(source, masterPartName).forEach((layoutPartName, layoutIndex) => {\n\t\t\t\tif (!pickLayout(cSldName(source.opc.part(layoutPartName)), layoutIndex)) return\n\t\t\t\tlayoutPartNames.push(copyPart(ctx, layoutPartName))\n\t\t\t})\n\n\t\t\timported.push({ partName: newMasterPartName, layoutPartNames })\n\t\t})\n\n\t\t// Optionally carry the source deck's presentation-level styling parts. Both are\n\t\t// separate traversals from the master/layout copy chain above, and both are\n\t\t// whole-deck: neither part records which font/style belongs to which master.\n\t\tif (options.embedFonts) carryEmbeddedFonts(this, source, this.#importContext(source.opc))\n\t\tif (options.tableStyles) carryTableStyles(this, source.opc)\n\t\tif (options.primary)\n\t\t\tpromoteMasters(\n\t\t\t\tthis,\n\t\t\t\timported.map((m) => m.partName)\n\t\t\t)\n\n\t\treturn imported\n\t}\n\n\t/**\n\t * The deck's slide masters, in `p:sldMasterIdLst` order, as modeled\n\t * {@link SlideMaster}s — the typed read model over the shared chrome (each\n\t * master's colour map, theme, placeholders, and the layouts built on it). Walk\n\t * `pres.masters()[i].layouts` for the rich layout model, or use {@link layouts}\n\t * for the flat {@link LayoutHandle} gallery {@link appendSlides} binds to.\n\t * Read-only: it copies nothing and leaves the package byte-identical.\n\t */\n\tmasters(): SlideMaster[] {\n\t\treturn slideMasterPartNames(this)\n\t\t\t.map((partName) => this.opc.part(partName))\n\t\t\t.filter((part): part is Part => part !== undefined)\n\t\t\t.map((part) => new SlideMaster(this.opc, part))\n\t}\n\n\t/**\n\t * The deck's slide layouts, in master then layout order — the gallery a new\n\t * slide can bind to. Each {@link LayoutHandle} addresses one layout for\n\t * {@link appendSlides}; the `name` is its `p:cSld@name`. Read-only enumeration:\n\t * it copies nothing and leaves the package byte-identical.\n\t */\n\tlayouts(): LayoutHandle[] {\n\t\tconst out: LayoutHandle[] = []\n\t\tslideMasterPartNames(this).forEach((masterPartName, masterIndex) => {\n\t\t\tlayoutPartNamesOf(this, masterPartName).forEach((layoutPartName, layoutIndex) => {\n\t\t\t\tout.push({\n\t\t\t\t\tpartName: layoutPartName,\n\t\t\t\t\tname: cSldName(this.opc.part(layoutPartName)),\n\t\t\t\t\tmasterPartName,\n\t\t\t\t\tmasterIndex,\n\t\t\t\t\tlayoutIndex,\n\t\t\t\t})\n\t\t\t})\n\t\t})\n\t\treturn out\n\t}\n\n\t/**\n\t * Append generator-produced slides onto this deck, binding each to an existing\n\t * layout, and return the new {@link Slide}s. This is the hybrid\n\t * \"generate-onto-existing\" path: the deck's masters, layouts, theme — and every\n\t * other untouched part — stay **byte-identical** (only `presentation.xml`, its\n\t * `.rels`, `[Content_Types].xml`, and the freshly-added slide/media parts\n\t * change), because the existing chrome is never regenerated.\n\t *\n\t * `source` is any slide producer (a `TsPptx` instance); its authored slides\n\t * are serialized via {@link SlideSource.extractSlides} and spliced in under\n\t * fresh partnames, with each slide's `slideLayout` relationship pointed at the\n\t * layout named by `options.layout` and its image/hyperlink relationships rebuilt\n\t * (preserving the body's relationship ids). Insert position follows\n\t * `options.at` (see {@link AppendSlidesOptions}).\n\t *\n\t * Charts and internal slide-to-slide hyperlinks are carried across: chart parts\n\t * (chart XML + `.rels` + embedded workbook) are injected under fresh names, and a\n\t * `slide:N` link is repointed at the Nth appended slide's new partname. A chartEx\n\t * (Office 2016 — waterfall, funnel, treemap, ...) chart carries too, as its own\n\t * `chartEx{N}.xml` part behind the MS chartEx rel, with the style and color-style\n\t * sidecars PowerPoint requires alongside it.\n\t *\n\t * The generator's presentation-level embedded fonts (`pptx.embedFont`) are also\n\t * carried into this deck and merged into its `p:embeddedFontLst`, de-duped by\n\t * typeface + face slot — so author-side embedded fonts survive the append onto a\n\t * template that may itself already embed fonts.\n\t *\n\t * Embedded audio/video is carried too: the media part backs the ECMA audio/video rel\n\t * and the MS-2007 `media` rel sharing one Target, plus a separate preview image part,\n\t * with the media content type registered as a Default extension entry (what PowerPoint\n\t * authors). Online (external-link) video rides as two External rels over the link.\n\t *\n\t * Speaker notes ride across too: a slide authored with `addNotes` gets a `notesSlide`\n\t * part wired back to it, with its hyperlink rels preserved. A notes slide must bind to\n\t * a notes master, and a template commonly has none, so the generator's is installed\n\t * (with the theme its `.rels` needs) — but only when this deck has none of its own, so\n\t * an existing notes master and its styling always win.\n\t *\n\t * Limitations:\n\t * - An internal link to a source slide outside the appended batch throws (its\n\t * target has no counterpart in the destination).\n\t * - Appended slides are concrete absolute-positioned content with no placeholder\n\t * inheritance from the bound layout; the binding governs theme/`clrMap`\n\t * resolution and the \"based on\" link, not placeholder geometry. Author with\n\t * concrete colours — any `schemeClr` re-resolves against the destination theme.\n\t * - Source and destination slide sizes must match (no geometry rescale).\n\t */\n\tasync appendSlides(source: SlideSource, options: AppendSlidesOptions): Promise<Slide[]> {\n\t\t// 1. Resolve the target layout partname (explicit; no silent fallback).\n\t\tconst gallery = this.layouts()\n\t\tlet target: LayoutHandle\n\t\tif (typeof options.layout === 'string') {\n\t\t\tconst matches = gallery.filter((l) => l.name === options.layout)\n\t\t\tif (matches.length > 1) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'layout/ambiguous-name',\n\t\t\t\t\t`appendSlides: layout name ${JSON.stringify(options.layout)} is ambiguous (${matches.length} layouts share it); pass a LayoutHandle from layouts() instead`\n\t\t\t\t)\n\t\t\t}\n\t\t\tconst [only] = matches\n\t\t\tif (!only) {\n\t\t\t\tconst names = gallery.map((l) => JSON.stringify(l.name)).join(', ')\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'layout/not-found',\n\t\t\t\t\t`appendSlides: no layout named ${JSON.stringify(options.layout)}; available: ${names || '(none)'}`\n\t\t\t\t)\n\t\t\t}\n\t\t\ttarget = only\n\t\t} else {\n\t\t\tconst handle = options.layout\n\t\t\tif (!gallery.some((l) => l.partName === handle.partName)) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'layout/foreign-handle',\n\t\t\t\t\t`appendSlides: layout ${handle.partName} does not belong to this presentation`\n\t\t\t\t)\n\t\t\t}\n\t\t\ttarget = handle\n\t\t}\n\n\t\t// 2. Author + extract; enforce equal slide size (no geometry rescale in v1).\n\t\tconst extracted = await source.extractSlides({ onMediaError: options.onMediaError })\n\t\tconst size = this.slideSize\n\t\tif (!size || size.widthEmu !== extracted.widthEmu || size.heightEmu !== extracted.heightEmu) {\n\t\t\tconst fmt = (w: number, h: number): string => `${w}×${h} EMU`\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/slide-size-mismatch',\n\t\t\t\t`appendSlides requires equal slide sizes; target is ${size ? fmt(size.widthEmu, size.heightEmu) : 'unknown'}, source is ${fmt(extracted.widthEmu, extracted.heightEmu)}`\n\t\t\t)\n\t\t}\n\n\t\t// Any existing slide partname seeds the fresh-partname family; fall back to a\n\t\t// literal seed for a slide-less template shell (reservePartNameLike parses the\n\t\t// string, it does not require the part to exist).\n\t\tconst slideTemplate = this.slides[0]?.partName ?? '/ppt/slides/slide1.xml'\n\n\t\t// Pass 1: reserve + add every slide body first, so internal slide-to-slide\n\t\t// links (which may point forward) can resolve to any appended slide. Adding\n\t\t// each part immediately claims its name — reservePartNameLike returns max+1\n\t\t// from the existing parts, so the next reservation sees it. (addPart registers\n\t\t// the slide's Override content type.)\n\t\tconst placed = extracted.slides.map((slide) => {\n\t\t\tconst partName = this.opc.reservePartNameLike(slideTemplate)\n\t\t\tconst part = this.opc.addPart(partName, SLIDE_CONTENT_TYPE, textEncoder.encode(slide.xml))\n\t\t\treturn { slide, part, partName }\n\t\t})\n\n\t\t// 1-based source slide number -> the appended slide's new partname.\n\t\tconst partBySourceNumber = new Map<number, string>(placed.map((p, i) => [i + 1, p.partName]))\n\n\t\t// Pass 2: build each slide's .rels and wire it into presentation.xml. Media,\n\t\t// hyperlinks, charts, and slide-links keep the body's rId (addWithId); the\n\t\t// layout rel is added last via add() so its auto-id cannot collide.\n\t\tconst added: Slide[] = []\n\t\tplaced.forEach(({ slide, part, partName }, i) => {\n\t\t\tconst rels = this.opc.relationshipsFor(partName)\n\t\t\tfor (const m of slide.media) {\n\t\t\t\tconst mediaPartName = this.opc.reserveMediaPartName(m.extn)\n\t\t\t\tthis.opc.addPart(mediaPartName, m.contentType, m.bytes)\n\t\t\t\trels.addWithId(`rId${m.rId}`, IMAGE_REL, relativePartName(partName, mediaPartName))\n\t\t\t}\n\t\t\tfor (const av of slide.avMedia) {\n\t\t\t\t// One media part backs two rels (ECMA audio/video + MS-2007 media) sharing\n\t\t\t\t// its Target; the preview poster is a separate image part. ensureDefault\n\t\t\t\t// runs before addPart so the content type resolves via a Default extension\n\t\t\t\t// entry (what PowerPoint authors) rather than a per-part Override.\n\t\t\t\tconst mediaPartName = this.opc.reserveMediaPartName(av.mediaExtn, 'media')\n\t\t\t\tthis.opc.contentTypes.ensureDefault(av.mediaExtn, av.mediaContentType)\n\t\t\t\tthis.opc.addPart(mediaPartName, av.mediaContentType, av.mediaBytes)\n\t\t\t\tconst mediaTarget = relativePartName(partName, mediaPartName)\n\t\t\t\trels.addWithId(`rId${av.mediaRid}`, av.mtype === 'audio' ? AUDIO_REL : VIDEO_REL, mediaTarget)\n\t\t\t\trels.addWithId(`rId${av.msMediaRid}`, MS_MEDIA_REL, mediaTarget)\n\n\t\t\t\tconst previewPartName = this.opc.reserveMediaPartName(av.previewExtn)\n\t\t\t\tthis.opc.contentTypes.ensureDefault(av.previewExtn, av.previewContentType)\n\t\t\t\tthis.opc.addPart(previewPartName, av.previewContentType, av.previewBytes)\n\t\t\t\trels.addWithId(`rId${av.previewRid}`, IMAGE_REL, relativePartName(partName, previewPartName))\n\t\t\t}\n\t\t\tfor (const ov of slide.onlineMedia) {\n\t\t\t\t// Online (external-link) video: two External rels share the link Target — the\n\t\t\t\t// ECMA video rel and the MS-2007 media rel — with no media binary part and no\n\t\t\t\t// content-type entry. The poster image is wired by the `slide.media` loop above.\n\t\t\t\trels.addWithId(`rId${ov.mediaRid}`, VIDEO_REL, ov.link, 'External')\n\t\t\t\trels.addWithId(`rId${ov.msMediaRid}`, MS_MEDIA_REL, ov.link, 'External')\n\t\t\t}\n\t\t\tfor (const h of slide.hyperlinks) {\n\t\t\t\trels.addWithId(`rId${h.rId}`, HYPERLINK_REL, h.target, 'External')\n\t\t\t}\n\t\t\tif (slide.notes) {\n\t\t\t\t// Speaker notes. The notes part carries its own rel namespace, independent of\n\t\t\t\t// the slide's: rId1 = notesMaster, rId2 = the slide it annotates, hyperlinks\n\t\t\t\t// from rId3 — the order the generator's body was serialized against, so these\n\t\t\t\t// are added by explicit id rather than left to auto-numbering.\n\t\t\t\tconst notesPartName = this.opc.reservePartNameLike('/ppt/notesSlides/notesSlide1.xml')\n\t\t\t\tthis.opc.addPart(notesPartName, NOTES_SLIDE_CONTENT_TYPE, textEncoder.encode(slide.notes.xml))\n\t\t\t\trels.add(NOTES_SLIDE_REL, relativePartName(partName, notesPartName))\n\n\t\t\t\tconst notesRels = this.opc.relationshipsFor(notesPartName)\n\t\t\t\tconst notesMasterPartName = extracted.notesMaster ? ensureNotesMasterFromXml(this, extracted.notesMaster) : null\n\t\t\t\tif (notesMasterPartName) {\n\t\t\t\t\tnotesRels.addWithId('rId1', NOTES_MASTER_REL, relativePartName(notesPartName, notesMasterPartName))\n\t\t\t\t}\n\t\t\t\tnotesRels.addWithId('rId2', SLIDE_REL, relativePartName(notesPartName, partName))\n\t\t\t\tfor (const h of slide.notes.hyperlinks) {\n\t\t\t\t\tnotesRels.addWithId(`rId${h.rId}`, HYPERLINK_REL, h.target, 'External')\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor (const c of slide.charts) {\n\t\t\t\t// Chart part + its embedded workbook, each under a fresh name. Both chart\n\t\t\t\t// flavours reference the workbook through the chart part's own rId1, so the\n\t\t\t\t// chart .rels is rebuilt here against the reserved workbook partname.\n\t\t\t\t//\n\t\t\t\t// A chartEx chart differs in every other coordinate: the `chartEx{N}.xml` name\n\t\t\t\t// family, the MS chartex content type, the MS `chartEx` rel off the slide, and two\n\t\t\t\t// mandatory sidecars at rId2/rId3 — without which PowerPoint reports the deck as\n\t\t\t\t// corrupt (schema-valid but unopenable). `c.chartEx` carries both sidecar bodies;\n\t\t\t\t// the generator built them, so nothing here reaches into the emitters.\n\t\t\t\tconst isChartEx = c.chartEx !== undefined\n\t\t\t\tconst chartPartName = this.opc.reservePartNameLike(\n\t\t\t\t\tisChartEx ? '/ppt/charts/chartEx1.xml' : '/ppt/charts/chart1.xml'\n\t\t\t\t)\n\t\t\t\tthis.opc.addPart(\n\t\t\t\t\tchartPartName,\n\t\t\t\t\tisChartEx ? CHARTEX_CONTENT_TYPE : CHART_CONTENT_TYPE,\n\t\t\t\t\ttextEncoder.encode(c.chartXml)\n\t\t\t\t)\n\t\t\t\tconst embeddingPartName = this.opc.reservePartNameLike('/ppt/embeddings/Microsoft_Excel_Worksheet1.xlsx')\n\t\t\t\tthis.opc.contentTypes.ensureDefault('xlsx', XLSX_CONTENT_TYPE)\n\t\t\t\tthis.opc.addPart(embeddingPartName, XLSX_CONTENT_TYPE, c.embeddingBytes)\n\t\t\t\tconst chartRels = this.opc.relationshipsFor(chartPartName)\n\t\t\t\tchartRels.addWithId('rId1', PACKAGE_REL, relativePartName(chartPartName, embeddingPartName))\n\t\t\t\tif (c.chartEx) {\n\t\t\t\t\t// rId2 = colors, rId3 = style: the order the write path authors\n\t\t\t\t\t// (`buildChartExRelsXml` in gen/chart/embed-xlsx.ts).\n\t\t\t\t\tconst colorsPartName = this.opc.reservePartNameLike('/ppt/charts/colors1.xml')\n\t\t\t\t\tthis.opc.addPart(colorsPartName, CHART_COLOR_STYLE_CONTENT_TYPE, textEncoder.encode(c.chartEx.colorsXml))\n\t\t\t\t\tchartRels.addWithId('rId2', CHART_COLOR_STYLE_REL, relativePartName(chartPartName, colorsPartName))\n\n\t\t\t\t\tconst stylePartName = this.opc.reservePartNameLike('/ppt/charts/style1.xml')\n\t\t\t\t\tthis.opc.addPart(stylePartName, CHART_STYLE_CONTENT_TYPE, textEncoder.encode(c.chartEx.styleXml))\n\t\t\t\t\tchartRels.addWithId('rId3', CHART_STYLE_REL, relativePartName(chartPartName, stylePartName))\n\t\t\t\t}\n\t\t\t\trels.addWithId(`rId${c.rId}`, isChartEx ? CHARTEX_REL : CHART_REL, relativePartName(partName, chartPartName))\n\t\t\t}\n\t\t\tfor (const link of slide.slideLinks) {\n\t\t\t\tconst targetPartName = partBySourceNumber.get(link.sourceSlideNumber)\n\t\t\t\tif (!targetPartName) {\n\t\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t\t'import/unresolved-slide-link',\n\t\t\t\t\t\t`appendSlides: slide ${i} links to source slide ${link.sourceSlideNumber}, which is not among the appended slides`\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\trels.addWithId(`rId${link.rId}`, SLIDE_REL, relativePartName(partName, targetPartName))\n\t\t\t}\n\t\t\trels.add(SLIDE_LAYOUT_REL, relativePartName(partName, target.partName))\n\n\t\t\t// Wire into presentation.xml (rel + p:sldId) at the requested position.\n\t\t\tconst at = options.at === undefined ? undefined : options.at + i\n\t\t\tadded.push(this.#insertSlidePart(part, at))\n\t\t})\n\n\t\t// Carry the generator's presentation-level embedded fonts (pptx.embedFont) into\n\t\t// this deck, so author-side embedded fonts survive the append onto a template.\n\t\tcarryGeneratedEmbeddedFonts(this, extracted.embeddedFonts || [])\n\n\t\treturn added\n\t}\n\n\t/**\n\t * Copy one shape — an autoshape, picture, table/chart graphic frame, connector,\n\t * or group — from `source.shapes[shapeIndex]` onto `target`, returning the new\n\t * {@link Shape}. `target` must be a slide of *this* presentation; `source` may\n\t * belong to any open presentation.\n\t *\n\t * The lifted subtree is copied self-consistently: every media/chart/embedding it\n\t * depends on is dragged into this package (deduped against earlier imports from\n\t * the same source), its `r:embed`/`r:id`/… are rewritten to fresh host-slide\n\t * relationships, and its drawing ids (including a group's children) are reassigned\n\t * so they cannot collide with the host. With `theme: 'preserve'` (default) the\n\t * shape's theme references are baked to literals against the *source* theme so it\n\t * renders the same on a foreign host; `restyle` leaves them symbolic to re-brand;\n\t * `copy` brings the XML across untouched — see {@link ImportShapeOptions}.\n\t *\n\t * Differing slide sizes need `{ rescale }` (see {@link ImportShapeOptions.rescale});\n\t * a lifted `preserve` placeholder is baked self-contained and demoted to a plain\n\t * shape (see {@link ImportShapeOptions.theme}), so it neither re-inherits from nor\n\t * collides with the host. A shape's build animation lives in the slide-scoped\n\t * `p:timing`, not in its subtree, so the shape lands static unless\n\t * `{ carryAnimation: true }` opts in (see {@link ImportShapeOptions.carryAnimation}).\n\t */\n\timportShape(target: Slide, source: Slide, shapeIndex: number, options: ImportShapeOptions = {}): AnyShape {\n\t\tconst [shape] = this.importShapes(target, source, [shapeIndex], options)\n\t\tif (!shape)\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'shape/index-out-of-range',\n\t\t\t\t`importShape: source slide has no shape at index ${shapeIndex}`\n\t\t\t)\n\t\treturn shape\n\t}\n\n\t/**\n\t * Batch form of {@link importShape}: copy several shapes from one source slide\n\t * onto `target` in the given order. Media/chart/embedding parts shared by the\n\t * lifted shapes (and by earlier imports from the same source deck) are copied\n\t * once via the copy registry, and shared images resolve to a single host-slide\n\t * relationship. Returns the new {@link Shape}s in `shapeIndices` order.\n\t */\n\timportShapes(target: Slide, source: Slide, shapeIndices: number[], options: ImportShapeOptions = {}): AnyShape[] {\n\t\tif (target.presentation !== this)\n\t\t\tthrow new InvalidOptionError('slide/foreign-target', 'importShape: target slide must belong to this presentation')\n\n\t\t// Pre-flight: slide sizes must match unless { rescale } opts into scaling the\n\t\t// lifted geometry onto this canvas (computed once, applied per shape below).\n\t\tconst targetSize = this.slideSize\n\t\tconst sourceSize = source.presentation.slideSize\n\t\tconst sizesMatch =\n\t\t\t!!targetSize &&\n\t\t\t!!sourceSize &&\n\t\t\ttargetSize.widthEmu === sourceSize.widthEmu &&\n\t\t\ttargetSize.heightEmu === sourceSize.heightEmu\n\t\tlet transform: RescaleTransform | null = null\n\t\tif (!sizesMatch) {\n\t\t\tif (!options.rescale || !targetSize || !sourceSize) {\n\t\t\t\tconst fmt = (s: SlideSize | null): string => (s ? `${s.widthEmu}×${s.heightEmu} EMU` : 'unknown')\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/slide-size-mismatch',\n\t\t\t\t\t`importShape requires equal slide sizes (or { rescale }); target is ${fmt(targetSize)}, source is ${fmt(sourceSize)}`\n\t\t\t\t)\n\t\t\t}\n\t\t\ttransform = computeRescale(sourceSize, targetSize, options.rescale === 'stretch' ? 'stretch' : 'fit')\n\t\t}\n\n\t\t// Resolve + validate every index up front so a bad batch throws before mutating.\n\t\tconst sourceShapes = source.shapes\n\t\tconst sourceElements = shapeIndices.map((i) => {\n\t\t\tconst shape = sourceShapes[i]\n\t\t\tif (!shape)\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'shape/index-out-of-range',\n\t\t\t\t\t`No shape at index ${i} on the source slide (it has ${sourceShapes.length})`\n\t\t\t\t)\n\t\t\treturn shape.element_\n\t\t})\n\n\t\tconst spTree = target.shapeTree()\n\t\tif (!spTree)\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'slide/no-shape-tree',\n\t\t\t\t`importShape: target slide ${target.partName} has no shape tree`\n\t\t\t)\n\t\tconst targetDoc = spTree.ownerDocument\n\t\tif (!targetDoc)\n\t\t\tthrow new InternalError('oxml/node-has-no-document', 'importShape: target slide DOM has no owner document')\n\n\t\tconst theme = options.theme ?? 'preserve'\n\t\tconst sourceOpc = source.presentation.opc\n\t\tconst sourceRels = sourceOpc.relationshipsFor(source.partName)\n\t\tconst targetRels = this.opc.relationshipsFor(target.partName)\n\t\t// One rel-id map across the batch so shapes sharing a source image share a rel.\n\t\tconst relIdMap = new Map<string, string>()\n\t\t// preserve: build the source theme context once; copy/restyle need none.\n\t\tconst ctx = theme === 'preserve' ? sourceFlattenContext(sourceOpc, source.partName) : null\n\t\tconst importCtx = this.#importContext(sourceOpc)\n\n\t\t// Anchor for z-order: the existing shape currently at `at` (insert before it,\n\t\t// preserving batch order), else append before any trailing p:extLst.\n\t\tconst extLst = firstChild(spTree, 'p:extLst')\n\t\tconst anchor = options.at == null ? extLst : (nthShapeChild(spTree, options.at) ?? extLst)\n\n\t\tconst result: AnyShape[] = []\n\t\tfor (const shapeEl of sourceElements) {\n\t\t\tconst imported = targetDoc.importNode(shapeEl, true)\n\n\t\t\t// Drag media/charts/embeddings across and rewrite refs to fresh host rels.\n\t\t\t// A scope per shape: media are shared through `relIdMap`, but the chart or\n\t\t\t// diagram under this frame is its own — importing one chart shape twice must\n\t\t\t// not point both frames at one chart part (see `page-owned.ts`).\n\t\t\trewriteCarriedRels(imported, importCtx, sourceRels, target.partName, targetRels, relIdMap, newOwnedScope())\n\n\t\t\t// preserve: bake the source theme onto the subtree. The flatten passes match\n\t\t\t// descendants (not the root), so wrap the shape in a throwaway container.\n\t\t\tif (ctx) {\n\t\t\t\tconst holder = createElement(targetDoc, 'p:spTree')\n\t\t\t\tholder.appendChild(imported)\n\t\t\t\tflattenShape(holder, ctx)\n\t\t\t}\n\n\t\t\t// Rescale geometry onto this canvas (after flatten, so a placeholder's just-baked\n\t\t\t// inherited a:xfrm is scaled too). rescaleSpTree wants a p:spTree, so wrap the shape.\n\t\t\tif (transform) {\n\t\t\t\tconst holder = createElement(targetDoc, 'p:spTree')\n\t\t\t\tholder.appendChild(imported)\n\t\t\t\trescaleSpTree(holder, transform)\n\t\t\t}\n\n\t\t\t// Give the shape and any group children collision-free host ids, recording the\n\t\t\t// source id → new id map so a carried build animation can be remapped onto it.\n\t\t\tlet nextId = target.nextShapeId()\n\t\t\tconst spidMap = new Map<number, number>()\n\t\t\tfor (const cNvPr of imported.getElementsByTagNameNS(OOXML_NS.p, 'cNvPr')) {\n\t\t\t\tconst oldId = intValue(attr(cNvPr, 'id'))\n\t\t\t\tif (oldId !== null) spidMap.set(oldId, nextId)\n\t\t\t\tsetAttr(cNvPr, 'id', String(nextId++))\n\t\t\t}\n\n\t\t\t// Insert into the host tree (this reparents it out of any holder).\n\t\t\tspTree.insertBefore(imported, anchor)\n\n\t\t\t// Carry the shape's slide-scoped build animation (opt-in): append its effect\n\t\t\t// click-group(s) + <p:bldP> into the destination timing, remapped to the new id.\n\t\t\tif (options.carryAnimation) {\n\t\t\t\tconst sourceRoot = source.part.dom.documentElement\n\t\t\t\tconst targetRoot = target.part.dom.documentElement\n\t\t\t\tif (sourceRoot && targetRoot) carryShapeAnimations(sourceRoot, targetRoot, spidMap)\n\t\t\t}\n\n\t\t\tconst shape = wrapShapeElement(imported, target)\n\t\t\tif (!shape)\n\t\t\t\tthrow new UnsupportedFeatureError(\n\t\t\t\t\t'shape/element-unsupported',\n\t\t\t\t\t`importShape: unsupported shape element <${imported.localName}>`\n\t\t\t\t)\n\t\t\tif (options.left != null) shape.left = options.left\n\t\t\tif (options.top != null) shape.top = options.top\n\t\t\tif (options.width != null) shape.width = options.width\n\t\t\tif (options.height != null) shape.height = options.height\n\t\t\tresult.push(shape)\n\t\t}\n\n\t\ttarget.part.markDirty()\n\t\treturn result\n\t}\n\n\t/**\n\t * Open an import out of `source`: this deck as the destination, paired with the\n\t * copy registry for that package (created on first use). The registry is held on\n\t * the class rather than in the context because it must outlive any one call —\n\t * that is what makes a second import from the same source reuse the layout,\n\t * master, theme, and media it already copied instead of duplicating them.\n\t */\n\t#importContext(source: OpcPackage): ImportContext {\n\t\tlet registry = this.#importRegistry.get(source)\n\t\tif (!registry) {\n\t\t\tregistry = new Map()\n\t\t\tthis.#importRegistry.set(source, registry)\n\t\t}\n\t\treturn { dest: this, source, registry }\n\t}\n\n\t/**\n\t * Wire a new slide part into `p:sldIdLst` (rel + `p:sldId`) at zero-based\n\t * position `at` and return it. `p:sldIdLst` order *is* deck order, so the\n\t * insertion point is the only bookkeeping needed. An `at` that is omitted,\n\t * negative, or `>=` the current slide count appends (the prior behaviour).\n\t */\n\t#insertSlidePart(newPart: Part, at?: number): Slide {\n\t\tconst presPart = this.presentationPart\n\t\tconst presRels = presentationRels(this)\n\n\t\t// A slide part belongs to `p:sldIdLst` exactly once. Two `p:sldId` entries\n\t\t// naming one part is a package PowerPoint refuses to open (0x80070570) and\n\t\t// the read model cannot see: `slides` counts the list, so the deck reports\n\t\t// the slide it does not have and the failure surfaces only when someone\n\t\t// opens the file. Every caller here hands over a part it just materialized,\n\t\t// so this cannot fire on caller input — only on the import machinery\n\t\t// handing back a part it should have copied (issue #18). Refusing at the\n\t\t// call is the difference between a thrown error and a bad deliverable.\n\t\tfor (const rel of presRels) {\n\t\t\tif (rel.type !== SLIDE_REL || rel.targetMode === 'External') continue\n\t\t\tif (presRels.resolveTarget(rel.id) !== newPart.partName) continue\n\t\t\tthrow new InternalError(\n\t\t\t\t'slide/part-already-in-deck',\n\t\t\t\t`Slide part ${newPart.partName} is already in this deck's slide list; a second p:sldId entry for it would make the package unopenable`\n\t\t\t)\n\t\t}\n\n\t\tconst relId = presRels.add(SLIDE_REL, relativePartName(presPart.partName, newPart.partName)).id\n\n\t\tconst root = presPart.dom.documentElement\n\t\tif (!root)\n\t\t\tthrow new PackageReadError(\n\t\t\t\t'package/part-has-no-root',\n\t\t\t\t'presentation.xml has no document element to append a slide to'\n\t\t\t)\n\t\t// A template with zero slides omits p:sldIdLst entirely; create it in\n\t\t// CT_Presentation document order (after the *IdLst children, before p:sldSz).\n\t\tconst sldIdLst = getOrAddChild(root, 'p:sldIdLst', PRESENTATION_SLD_ID_LST_SUCCESSORS)\n\t\tconst existing = getElements(sldIdLst, 'p:sldId')\n\t\tconst newSlideId = this.#nextSlideId(existing)\n\t\tconst sldId = createElement(presPart.dom, 'p:sldId')\n\t\tsetAttr(sldId, 'id', String(newSlideId))\n\t\tsetAttr(sldId, 'r:id', relId)\n\n\t\tconst inRange = at !== undefined && at >= 0 && at < existing.length\n\t\tconst newIndex = inRange ? at : existing.length\n\t\tconst before = inRange ? existing[at] : null\n\t\tif (before) sldIdLst.insertBefore(sldId, before)\n\t\telse sldIdLst.appendChild(sldId)\n\t\tpresPart.markDirty()\n\n\t\treturn new Slide(this, newPart, newSlideId, newIndex)\n\t}\n\n\t/** A slide id one past the highest existing, but at least ST_SlideId's minimum. */\n\t#nextSlideId(sldIds: ReturnType<typeof getElements>): number {\n\t\tlet max = MIN_SLIDE_ID - 1\n\t\tfor (const sldId of sldIds) {\n\t\t\tconst id = intValue(attr(sldId, 'id'))\n\t\t\tif (id !== null && id > max) max = id\n\t\t}\n\t\treturn max + 1\n\t}\n\n\t/** Re-emit the package; untouched parts stay byte-identical (see `OpcPackage.save`). */\n\tasync save(): Promise<Uint8Array> {\n\t\treturn this.opc.save()\n\t}\n}\n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