pptx-ts 4.0.1 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +147 -114
  2. package/dist/{autopage-odPz7zZO.js → autopage-D4kyVp11.js} +5 -5
  3. package/dist/{autopage-odPz7zZO.js.map → autopage-D4kyVp11.js.map} +1 -1
  4. package/dist/{body-insets-Dw_BeWD_.js → body-insets-kVHmjGc6.js} +2 -2
  5. package/dist/{body-insets-Dw_BeWD_.js.map → body-insets-kVHmjGc6.js.map} +1 -1
  6. package/dist/browser.d.ts +7 -7
  7. package/dist/browser.js +5 -5
  8. package/dist/{clip-Bl01BPcN.d.ts → clip-DHDlnHUq.d.ts} +2 -2
  9. package/dist/{clip-Bl01BPcN.d.ts.map → clip-DHDlnHUq.d.ts.map} +1 -1
  10. package/dist/{diagnostics-D8ot4Ei7.d.ts → diagnostics-DiMmBU8P.d.ts} +6 -6
  11. package/dist/{diagnostics-D8ot4Ei7.d.ts.map → diagnostics-DiMmBU8P.d.ts.map} +1 -1
  12. package/dist/{embedded-fonts-DarT9aoa.d.ts → embedded-fonts-CI_YGW2d.d.ts} +2 -2
  13. package/dist/{embedded-fonts-DarT9aoa.d.ts.map → embedded-fonts-CI_YGW2d.d.ts.map} +1 -1
  14. package/dist/{entry-compose-DCnvBZz2.d.ts → entry-compose-6hF9aTmT.d.ts} +19 -17
  15. package/dist/{entry-compose-DCnvBZz2.d.ts.map → entry-compose-6hF9aTmT.d.ts.map} +1 -1
  16. package/dist/{enums-BUKTUB6V.d.ts → enums-DQRpVOLh.d.ts} +3 -3
  17. package/dist/{enums-BUKTUB6V.d.ts.map → enums-DQRpVOLh.d.ts.map} +1 -1
  18. package/dist/{errors-C4oENPcu.js → errors-Da2nXCJm.js} +6 -6
  19. package/dist/{errors-C4oENPcu.js.map → errors-Da2nXCJm.js.map} +1 -1
  20. package/dist/families.d.ts +6 -6
  21. package/dist/families.js +2 -2
  22. package/dist/{fit-Cb7naFj6.js → fit-CcXbg__l.js} +10 -10
  23. package/dist/{fit-Cb7naFj6.js.map → fit-CcXbg__l.js.map} +1 -1
  24. package/dist/{font-metrics-v5fn7s7e.d.ts → font-metrics-CBGmhLo0.d.ts} +6 -6
  25. package/dist/{font-metrics-v5fn7s7e.d.ts.map → font-metrics-CBGmhLo0.d.ts.map} +1 -1
  26. package/dist/{grid-DikTjFey.js → grid-9B2w5EaY.js} +2 -2
  27. package/dist/{grid-DikTjFey.js.map → grid-9B2w5EaY.js.map} +1 -1
  28. package/dist/{html-dom-Iuog2wdK.js → html-dom-DvJmuHt2.js} +10 -10
  29. package/dist/html-dom-DvJmuHt2.js.map +1 -0
  30. package/dist/html.d.ts +3 -3
  31. package/dist/html.js +2 -2
  32. package/dist/{image-size-CvN2iCA4.js → image-size-DwDbakcl.js} +64 -5
  33. package/dist/image-size-DwDbakcl.js.map +1 -0
  34. package/dist/index.d.ts +7 -7
  35. package/dist/index.js +3 -3
  36. package/dist/inspect.d.ts +4 -4
  37. package/dist/inspect.js +4 -4
  38. package/dist/inspect.js.map +1 -1
  39. package/dist/math.d.ts +1 -1
  40. package/dist/math.js +1 -1
  41. package/dist/measure.d.ts +3 -3
  42. package/dist/measure.js +2 -2
  43. package/dist/node.d.ts +7 -7
  44. package/dist/node.js +3 -3
  45. package/dist/{notes-Dh12JAbn.js → notes-BcT571R4.js} +19 -18
  46. package/dist/notes-BcT571R4.js.map +1 -0
  47. package/dist/options-internal-WqgMf720.js.map +1 -1
  48. package/dist/{package-J49Ck6S2.d.ts → package-KoEgVwII.d.ts} +6 -2
  49. package/dist/{package-J49Ck6S2.d.ts.map → package-KoEgVwII.d.ts.map} +1 -1
  50. package/dist/{pres-C6qgOFAa.d.ts → pres-BA9_lJbY.d.ts} +32 -12
  51. package/dist/pres-BA9_lJbY.d.ts.map +1 -0
  52. package/dist/{presentation-DGYlAWhl.js → presentation-Cyl74rq2.js} +70 -35
  53. package/dist/presentation-Cyl74rq2.js.map +1 -0
  54. package/dist/{presentation-types-8jLQHI4M.d.ts → presentation-types-B3VQH4Bz.d.ts} +19 -15
  55. package/dist/presentation-types-B3VQH4Bz.d.ts.map +1 -0
  56. package/dist/read.d.ts +6 -6
  57. package/dist/read.js +3 -3
  58. package/dist/script.d.ts +2 -2
  59. package/dist/script.d.ts.map +1 -1
  60. package/dist/script.js +11 -11
  61. package/dist/script.js.map +1 -1
  62. package/dist/{shapes-re0KyQk_.js → shapes-BcyFdZpp.js} +14 -10
  63. package/dist/shapes-BcyFdZpp.js.map +1 -0
  64. package/dist/{slide-Dx2ZeVZ6.d.ts → slide-BqPtyKmb.d.ts} +12 -7
  65. package/dist/slide-BqPtyKmb.d.ts.map +1 -0
  66. package/dist/{table-cell-margins-EVg0EwxT.js → table-cell-margins-PDshga8T.js} +4 -4
  67. package/dist/{table-cell-margins-EVg0EwxT.js.map → table-cell-margins-PDshga8T.js.map} +1 -1
  68. package/dist/{table-dom-BTDP3lEP.js → table-dom-CVbvUfgh.js} +3 -3
  69. package/dist/{table-dom-BTDP3lEP.js.map → table-dom-CVbvUfgh.js.map} +1 -1
  70. package/dist/{text-sN64Otf_.js → text-BvFFMMFQ.js} +38 -36
  71. package/dist/{text-sN64Otf_.js.map → text-BvFFMMFQ.js.map} +1 -1
  72. package/dist/{text-anchor-CrYXAfUu.js → text-anchor-BgLPbwbL.js} +2 -2
  73. package/dist/{text-anchor-CrYXAfUu.js.map → text-anchor-BgLPbwbL.js.map} +1 -1
  74. package/dist/{units-internal-XJlf-hOl.js → units-internal-DFcUYjh3.js} +11 -6
  75. package/dist/units-internal-DFcUYjh3.js.map +1 -0
  76. package/dist/{zip-C0leZZMj.d.ts → zip-CTll_dr0.d.ts} +2 -2
  77. package/dist/{zip-C0leZZMj.d.ts.map → zip-CTll_dr0.d.ts.map} +1 -1
  78. package/dist/{zip-CKd8ihcf.js → zip-CYZ0F6BV.js} +2 -2
  79. package/dist/{zip-CKd8ihcf.js.map → zip-CYZ0F6BV.js.map} +1 -1
  80. package/dist/zip.d.ts +2 -2
  81. package/dist/zip.js +2 -2
  82. package/dist/{zoom-DPUHh85d.js → zoom-BoNyOlPm.js} +65 -51
  83. package/dist/zoom-BoNyOlPm.js.map +1 -0
  84. package/package.json +39 -31
  85. package/skills/ts-pptx-upstream/SKILL.md +18 -18
  86. package/dist/html-dom-Iuog2wdK.js.map +0 -1
  87. package/dist/image-size-CvN2iCA4.js.map +0 -1
  88. package/dist/notes-Dh12JAbn.js.map +0 -1
  89. package/dist/pres-C6qgOFAa.d.ts.map +0 -1
  90. package/dist/presentation-DGYlAWhl.js.map +0 -1
  91. package/dist/presentation-types-8jLQHI4M.d.ts.map +0 -1
  92. package/dist/shapes-re0KyQk_.js.map +0 -1
  93. package/dist/slide-Dx2ZeVZ6.d.ts.map +0 -1
  94. package/dist/units-internal-XJlf-hOl.js.map +0 -1
  95. package/dist/zoom-DPUHh85d.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"presentation-DGYlAWhl.js","names":["textDecoder","textEncoder","textEncoder","textEncoder","textEncoder","importSlideInto","importSlidesInto","importSlideMastersInto","appendSlidesInto","importShapeInto","importShapesInto"],"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/slide-background.ts","../src/read/api/ops/part-index.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/copy-traversal.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/slide-build.ts","../src/read/api/slide.ts","../src/read/api/document-properties.ts","../src/read/api/ops/embedded-fonts.ts","../src/read/api/ops/slide-size.ts","../src/read/api/ops/append-slides.ts","../src/read/api/ops/prune.ts","../src/read/api/ops/import-memo.ts","../src/read/api/ops/flatten.ts","../src/read/api/ops/carried-rels.ts","../src/read/api/ops/flatten-context.ts","../src/read/api/ops/table-styles.ts","../src/read/api/ops/import-slide.ts","../src/read/api/ops/rescale.ts","../src/read/api/ops/rescale-import.ts","../src/read/api/presentation-imports.ts","../src/read/api/presentation.ts"],"sourcesContent":["import { getElements, parseXml } from '../oxml/dom.js'\nimport { encodeXmlAttrValue } from '../../xml-escape.js'\nimport { partNameExtension } from './partnames.js'\nimport { PackageReadError } from '../../errors.js'\nimport { OOXML_NS } from '../../ooxml/namespaces.js'\nimport { XML_DECL } from '../../ooxml/xml-decl.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[] = [XML_DECL, `<Types xmlns=\"${OOXML_NS.ct}\">`]\n\t\tfor (const [extension, contentType] of this.#defaults) {\n\t\t\tlines.push(\n\t\t\t\t`<Default Extension=\"${encodeXmlAttrValue(extension)}\" ContentType=\"${encodeXmlAttrValue(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=\"${encodeXmlAttrValue(partName)}\" ContentType=\"${encodeXmlAttrValue(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'\nimport { XML_DECL } from '../../ooxml/xml-decl.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/**\n\t * The bytes the part was loaded or created with. Do not mutate.\n\t *\n\t * **Not the part's current body.** An edit made through {@link dom} and\n\t * {@link markDirty} is visible only through {@link serialize}. Anything that copies,\n\t * compares or reads a part's content wants `serialize()`: every slide copy and import\n\t * used to read this instead, and silently dropped each edit made earlier in the session.\n\t * Named so a call site has to say which of the two it means.\n\t */\n\tget originalBytes(): 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 * The part's current body, which is also what `save()` writes: the original bytes when\n\t * clean (byte-identical), the serialized DOM when dirty (semantically equivalent,\n\t * schema-valid). Copy a part through this, not {@link originalBytes}.\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_DECL + '\\r\\n') + xml\n\t\t}\n\t\treturn textEncoder.encode(xml)\n\t}\n}\n","import { getElements, parseXml } from '../oxml/dom.js'\nimport { encodeXmlAttrValue } from '../../xml-escape.js'\nimport { resolveRelativePartName } from './partnames.js'\nimport { InvalidOptionError, PackageReadError } from '../../errors.js'\nimport { OOXML_NS } from '../../ooxml/namespaces.js'\nimport { XML_DECL } from '../../ooxml/xml-decl.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\treturn this.#put(`rId${max + 1}`, type, target, targetMode)\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\treturn this.#put(id, type, target, targetMode)\n\t}\n\n\t/**\n\t * Build the relationship record, store it under `id`, and mark the set dirty.\n\t *\n\t * `targetMode` is written only when stated: `Internal` is the schema default, and a key\n\t * holding `undefined` is not the same as an absent one to the serializer. {@link add} and\n\t * {@link addWithId} differ only in where the id comes from.\n\t */\n\t#put(id: string, type: string, target: string, targetMode?: 'Internal' | 'External'): Relationship {\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.#resolvedTargets.clear()\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) {\n\t\t\tthis.#resolvedTargets.clear()\n\t\t\tthis.#dirty = true\n\t\t}\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/**\n\t * Partnames already resolved, keyed by relationship id.\n\t *\n\t * A target resolves to the same partname every time -- it is a pure function of this set's\n\t * source part and the relationship's `Target` -- and the orphan prune asks for every\n\t * relationship of every remaining part once per candidate part, so stripping a 60-slide\n\t * template resolved the same few hundred targets tens of thousands of times. Dropped\n\t * whenever a relationship is added or removed, which are the only two ways a target here\n\t * can change.\n\t */\n\t#resolvedTargets = new Map<string, string>()\n\n\t/** Resolve an internal relationship's target to an absolute partname. */\n\tresolveTarget(id: string): string {\n\t\tconst memo = this.#resolvedTargets.get(id)\n\t\tif (memo !== undefined) return memo\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\tconst resolved = resolveRelativePartName(this.sourcePartName, relationship.target)\n\t\tthis.#resolvedTargets.set(id, resolved)\n\t\treturn resolved\n\t}\n\n\tserialize(): string {\n\t\tconst lines: string[] = [XML_DECL, `<Relationships xmlns=\"${OOXML_NS.pr}\">`]\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=\"${encodeXmlAttrValue(id)}\" Type=\"${encodeXmlAttrValue(type)}\" Target=\"${encodeXmlAttrValue(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'\nimport { RELATIONSHIPS_CONTENT_TYPE } from '../../ooxml/rel-types.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'\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\t/**\n\t * Parts grouped by content type, built on first ask and dropped whenever the part set\n\t * changes.\n\t *\n\t * {@link partsByContentType} answers a question the read model asks constantly -- every\n\t * table style resolution, every theme lookup, every comment-schema check -- and answering\n\t * it by materialising and filtering the whole part list made those linear in the size of\n\t * the deck each time. A 20x8 table read cell by cell asked it 160 times.\n\t */\n\t#partsByContentType: Map<string, Part[]> | null = null\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\tif (!this.#partsByContentType) {\n\t\t\tconst index = new Map<string, Part[]>()\n\t\t\tfor (const part of this.#parts.values()) {\n\t\t\t\tconst group = index.get(part.contentType)\n\t\t\t\tif (group) group.push(part)\n\t\t\t\telse index.set(part.contentType, [part])\n\t\t\t}\n\t\t\tthis.#partsByContentType = index\n\t\t}\n\t\t// A fresh array per call: the group is the index's own, and a caller that sorted or\n\t\t// spliced the result would corrupt every later answer.\n\t\tconst found = this.#partsByContentType.get(contentType)\n\t\treturn found ? [...found] : []\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.serialize()), 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\tthis.#partsByContentType = null\n\t\treturn part\n\t}\n\n\t/**\n\t * Remove a part and return whether it existed. Its `.rels` part goes with it, along with\n\t * its `Override` content-type registration and any cached relationship set it owned, so a\n\t * later `save()` neither re-emits it nor flushes a stale `.rels` for it. A relationship set\n\t * belongs to its part: one left behind would come back as the relationships of the next part\n\t * added under the same name. Low-level: it does not touch references *to* this part\n\t * (dangling rels are the caller's concern) nor cascade to parts this one referenced — see\n\t * {@link Presentation.removeSlide} for the slide-aware variant that unwires the presentation\n\t * and prunes orphans.\n\t */\n\tremovePart(partName: string): boolean {\n\t\tif (!this.#parts.delete(partName)) return false\n\t\tconst relsPartName = relsPartNameFor(partName)\n\t\tthis.#parts.delete(relsPartName)\n\t\tthis.#partsByContentType = null\n\t\tthis.contentTypes.removeOverride(partName)\n\t\tthis.contentTypes.removeOverride(relsPartName)\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\t// Case-insensitive, unlike `reservePartNameLike`: a package holding `image1.PNG` must not\n\t\t// hand out `image1.png` as free.\n\t\tconst next = this.#nextPartIndex(new RegExp(`^/ppt/media/${base}(\\\\d+)\\\\.${ext}$`, 'i'))\n\t\treturn `/ppt/media/${base}${next}.${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\t * `taken` names partnames to count as existing although the package does not hold them yet:\n\t * an import plan's names for the parts it would add, so the names it predicts are the ones the\n\t * copy itself is then given.\n\t */\n\treservePartNameLike(templatePartName: string, taken?: ReadonlySet<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 next = this.#nextPartIndex(new RegExp(`^${escape(`${dir}/${base}`)}(\\\\d+)${escape(ext)}$`), taken)\n\t\treturn `${dir}/${base}${next}${ext}`\n\t}\n\n\t/**\n\t * One past the highest numeric index any existing partname matches, or `1` when none does.\n\t * `re` must capture the index as its first group.\n\t */\n\t#nextPartIndex(re: RegExp, taken: Iterable<string> = []): number {\n\t\tlet max = 0\n\t\tfor (const names of [this.#parts.keys(), taken]) {\n\t\t\tfor (const partName of names) {\n\t\t\t\tconst match = re.exec(partName)\n\t\t\t\tif (match) max = Math.max(max, Number(match[1]))\n\t\t\t}\n\t\t}\n\t\treturn max + 1\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\tthis.#partsByContentType = null\n\t\t}\n\t}\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, pattern and image backgrounds (all FAITHFUL);\n * theme-indexed (`p:bgRef`) backgrounds are read-only for imported decks — surface\n * 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\tnumberValue,\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 { readColorRef, type ColorRef } from './theme-context.js'\nimport { readGradientFill, type GradientFill } from './gradient.js'\nimport { readPictureFill, type PictureFill } from './picture-fill.js'\nimport { readPatternFill, type PatternFill } 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 * `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'; colorRef: ColorRef }\n\t| { type: 'gradient'; gradient: GradientFill }\n\t| { type: 'image'; picture: PictureFill; relId: string | null; partName: string | null }\n\t| ({ type: 'pattern' } & PatternFill)\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`/`pattern`/`image`\n * are what the writer authors and round-trip faithfully; `themeRef` is read-only\n * (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; colorRef: ColorRef }\n\t| { type: 'gradient'; source: BackgroundSource; gradient: GradientFill }\n\t| { type: 'image'; source: BackgroundSource; picture: PictureFill; relId: string | null; partName: string | null }\n\t| ({ type: 'pattern'; source: BackgroundSource } & PatternFill)\n\t| {\n\t\t\ttype: 'themeRef'\n\t\t\tsource: BackgroundSource\n\t\t\tidx: number | null\n\t\t\tcolorRef: ColorRef\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', colorRef: readColorRef(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', ...patt }\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 * `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: numberValue(attr(bgRef, 'idx')),\n\t\t\tcolorRef: readColorRef(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 * 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, type Element } from '../../oxml/dom.js'\nimport type { DeckTarget } from './deck-target.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/**\n * Master partnames in `p:sldMasterIdLst` order -- the masters renderers treat as active.\n *\n * Takes the structural {@link DeckTarget} rather than a `Presentation`, because it reads only\n * `opc` and `presentationPart` and both callers exist: the import ops walk a source deck,\n * `part-reuse.ts` walks a destination that is not a `Presentation` at all and had its own copy\n * of this for that reason alone.\n */\nexport function slideMasterPartNames(deck: DeckTarget): string[] {\n\tconst root = deck.presentationPart.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldMasterIdLst')\n\tif (!lst) return []\n\tconst rels = deck.opc.relationshipsFor(deck.presentationPart.partName)\n\treturn idListTargets(lst, 'p:sldMasterId', (relId) => rels.resolveTarget(relId))\n}\n\n/**\n * A master's layout partnames in `p:sldLayoutIdLst` order -- its slice of the deck's gallery.\n *\n * Needs only the package, so a {@link SlideMaster} with no presentation part in reach walks its\n * layouts through here too.\n */\nexport function layoutPartNamesOf(deck: Pick<DeckTarget, 'opc'>, masterPartName: string): string[] {\n\tconst root = deck.opc.part(masterPartName)?.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:sldLayoutIdLst')\n\tif (!lst) return []\n\tconst rels = deck.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 * 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 * `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 { singleRelPart } from '../opc/partnames.js'\nimport type { Relationships } from '../opc/relationships.js'\nimport { attr, boolValue, firstChild, getElements, type Element } from '../oxml/dom.js'\nimport { parseClrMap, parseClrScheme, themeElementsOfRoot, type ThemeContext } from '../oxml/theme.js'\nimport { resolveLayoutColorContext, resolveMasterColorContext } from './theme-context.js'\nimport { placeholderOf } from '../oxml/placeholder-inherit.js'\nimport { backgroundElementOf, readSlideBackground, type SlideBackground } from './slide-background.js'\nimport { AutoShape, 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 { layoutPartNamesOf } from './ops/part-index.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 `pptx-ts/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/**\n\t * The 6-hex RGB of one colour-scheme slot, or `null` when the theme does not define it.\n\t *\n\t * Parsed once per proxy: the whole `a:clrScheme` is read to answer for one slot, and a\n\t * caller asking for several -- which is the normal way to ask -- re-read it each time.\n\t */\n\tcolor(slot: ThemeColorSlot): string | null {\n\t\tthis.#parsedClrScheme ??= parseClrScheme(this.#clrScheme())\n\t\treturn this.#parsedClrScheme.get(slot) ?? null\n\t}\n\n\t#parsedClrScheme?: Map<string, string>\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\treturn themeElementsOfRoot(this.part.dom.documentElement)\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\t/**\n\t * The same `p:sp` as an {@link AutoShape}. Identity, geometry and the text frame are\n\t * forwarded to it rather than re-derived here.\n\t *\n\t * They used to be re-derived, and the two answers had drifted apart. `#cNvPr()` hard-coded\n\t * `p:nvSpPr` where `nonVisualCNvPr` finds any `p:nv*Pr`; the four geometry getters read the\n\t * `p:spPr/a:xfrm` chain through a helper no other caller used, against `Shape`'s own\n\t * `xfrm()` + `emuFrom`; and,\n\t * the one that showed, the text frame was built with **no** inheritance context, so\n\t * `Run.resolvedSizePt`, `resolvedFontFace`, `resolvedColor` and `resolvedBold` resolved\n\t * through `SlideMaster.shapes` and came back `null` through `SlideMaster.placeholders` —\n\t * two views of one element disagreeing about the same run.\n\t */\n\tprotected readonly shape: AutoShape\n\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 host: ShapeHost\n\t) {\n\t\tthis.shape = new AutoShape(sp, host)\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/**\n\t * Placeholder index (`p:ph/@idx`), or `null` when unset.\n\t *\n\t * Not forwarded to {@link AutoShape.placeholder}, whose `idx` defaults to `'0'` the way\n\t * PowerPoint resolves it. Here the absence is the contract: this view reports what the\n\t * part says.\n\t */\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\treturn this.shape.name\n\t}\n\n\t/** Drawing id (`p:cNvPr/@id`), or `null` when absent. */\n\tget id(): number | null {\n\t\treturn this.shape.id\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 this.shape.left\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 this.shape.top\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 this.shape.width\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 this.shape.height\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 tier's theme context and\n\t * placeholder identity, so a run's `resolved*` getters walk the same inheritance chain\n\t * they walk through {@link SlideMaster.shapes}.\n\t */\n\tget textFrame(): TextFrame | null {\n\t\treturn this.shape.textFrame\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.host.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\treturn placeholderShapes(this.spTree()).map((sp) => new Placeholder(sp, this))\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\treturn singleRelPart(this.opc, this.partName, type)\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\treturn layoutPartNamesOf(this, this.part.partName)\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 SlideLayout(this.opc, part))\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 part = this.relTarget(SLIDE_MASTER_REL)\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 type { Relationships } from '../opc/relationships.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'\nimport { buildShapes, findShapeByIdDeep, type AnyShape, type ShapeHost } from './shapes.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 an inheritance so\n\t\t// `Run.resolved*` walks that chain; the `sldNum` field frame needs none.\n\t\tconst ctx = this.host.themeContext()\n\t\tconst inherit = this.type === 'body' ? { ph: { type: this.type, idx: this.idx ?? '0' }, fontRef: null } : null\n\t\treturn new TextFrame(txBody, { part: this.host.part, ctx, rels: this.host.relationships, inherit })\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 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 implements ShapeHost {\n\t#themeContext?: ThemeContext\n\n\tconstructor(\n\t\t/** The package the notes slide belongs to, for reaching the notesMaster and its theme. */\n\t\treadonly 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/** The notes part's own relationships — a notes hyperlink resolves through these. */\n\tget relationships(): Relationships {\n\t\treturn this.opc.relationshipsFor(this.partName)\n\t}\n\n\t/**\n\t * The notes shape tree as full shapes, in document order.\n\t *\n\t * A notes slide holds nothing but its three placeholders, so {@link placeholders} is the\n\t * view to read. This one exists because a notes slide is a {@link ShapeHost} — which is\n\t * what lets a {@link NotesPlaceholder} be the same {@link AutoShape} view of its `p:sp`\n\t * that a master or layout placeholder is, rather than a second reading of one.\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 the notes 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/**\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\treturn getElements(spTree, 'p:sp').map((sp) => new NotesPlaceholder(sp, this))\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\tnumberValue,\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 { PRESENTATION_AFTER_SLD_MASTER_ID_LST, SLIDE_MASTER_AFTER_SLD_LAYOUT_ID_LST } from '../../../ooxml/sequence.js'\nimport { PackageReadError } from '../../../errors.js'\nimport { MIN_SLIDE_MASTER_ID } from '../../../ooxml/ids.js'\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', PRESENTATION_AFTER_SLD_MASTER_ID_LST)\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 *\n * Deliberately not routed through `part-index.ts`'s spine walkers: those resolve each entry's\n * `@r:id` to a partname, this reads each entry's `@id`, and this scans every master the\n * presentation *relates* to rather than only the ones its id list registers -- an id in an\n * unregistered master's layout list still occupies the shared space.\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 = numberValue(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 = numberValue(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', SLIDE_MASTER_AFTER_SLD_LAYOUT_ID_LST)\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 * ts-pptx: the one rule three copy traversals follow.\n *\n * Copying a page into another deck means walking its part graph, and two places walk it:\n * `rebuildRels`, the loop under every copy (and, run as a `CopyPlan`, under the dry run that has\n * to reach exactly the same parts before anything moves); and `identicalSubgraph`, which asks\n * whether the destination already holds what the copy would have produced. Each used to write\n * the rule out, and a separate dry run did too, with a comment asking the reader to keep the\n * copies in step by hand — it said the guarantee was \"only as good as the drift between them\".\n *\n * A leaf module rather than an export from `part-copy.ts`, because `part-copy.ts` already\n * imports from `part-reuse.ts` and the rule has to be reachable from both.\n */\n\nimport type { Part } from '../../opc/part.js'\nimport type { Relationship } from '../../opc/relationships.js'\nimport { NOTES_SLIDE_REL, SLIDE_LAYOUT_REL, SLIDE_MASTER_CONTENT_TYPE } from '../../../ooxml/rel-types.js'\n\n/**\n * What a copy traversal does with one relationship: skip it, carry it as an external link, or\n * follow it into the part it names.\n *\n * Notes pull in a notesMaster and its own theme, which an imported page does not need, so the\n * notes relationship is never followed — `carryNotes` picks it up afterwards for the pages\n * that asked. A master's relationships to its layouts are skipped so the copy stays lean:\n * copied layouts re-link themselves, and skipping the list is also what keeps one edited\n * layout from disqualifying every other layout that shares its master.\n *\n * Each caller still owns its own extra arms — a copy's overrides and its jump-link rule, the reuse\n * check's byte comparison — which is why this answers only the part they share.\n * @param part - the part the relationship belongs to\n * @param rel - the relationship being considered\n */\nexport function copyTraversalStep(part: Part, rel: Relationship): 'skip' | 'external' | 'recurse' {\n\tif (rel.type === NOTES_SLIDE_REL) return 'skip'\n\tif (part.contentType === SLIDE_MASTER_CONTENT_TYPE && rel.type === SLIDE_LAYOUT_REL) return 'skip'\n\treturn rel.targetMode === 'External' ? 'external' : 'recurse'\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 { SHARED_PARTS } from '../../../ooxml/rel-types.js'\n\n/**\n * Relationship types whose target two copies of one page may point at together: every kind in\n * {@link SHARED_PARTS}. That is deck furniture a page reaches and the deck owns, including the\n * author registry a comments part names; media blobs, which PowerPoint itself stores once and\n * points every shape at; and another page or an external link, where a jump points at whatever\n * copy of the target the import decided on.\n */\nconst SHARED_BY_PAGE_COPIES: ReadonlySet<string> = new Set(SHARED_PARTS.map((kind) => kind.relType))\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 * 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 type { OpcPackage } from '../../opc/package.js'\nimport type { DeckTarget } from './deck-target.js'\nimport { SLIDE_CONTENT_TYPE, SLIDE_LAYOUT_CONTENT_TYPE, SLIDE_MASTER_CONTENT_TYPE } from '../../../ooxml/rel-types.js'\nimport { copyTraversalStep } from './copy-traversal.js'\nimport { layoutPartNamesOf, slideMasterPartNames } from './part-index.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 * Both sides are compared as they would be **written** (`serialize()`), not as they were\n * read. The destination, so a part some earlier edit marked dirty is treated as different\n * even when the edit was a no-op; the source, because the copy that reuse stands in for\n * carries the source's edits too, and a source edited this session is not the part the\n * destination already holds. Under-reusing costs a duplicated part; over-reusing binds a\n * slide to something else's chrome.\n *\n * The traversal skips exactly what `copyPart` skips, because it asks `copyTraversalStep` --\n * so it is about the subgraph the copy would actually have made rather than about a rule\n * transcribed from it.\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.serialize(), 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 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 (copyTraversalStep(sourcePart, rel) !== 'recurse') 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 slideMasterPartNames(dest).includes(partName)\n\tif (contentType === SLIDE_LAYOUT_CONTENT_TYPE) {\n\t\treturn slideMasterPartNames(dest).some((master) => layoutPartNamesOf(dest, master).includes(partName))\n\t}\n\treturn true\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 * The same traversal is every import's dry run. With a {@link CopyPlan} in its\n * context it writes nothing and throws what the copy would throw, so an import\n * runs it that way before anything in the deck moves.\n */\n\nimport type { OpcPackage } from '../../opc/package.js'\nimport type { Part } from '../../opc/part.js'\nimport type { Relationship, Relationships } from '../../opc/relationships.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport type { DeckTarget } from './deck-target.js'\nimport { addLayoutToMaster, clearLayoutIdList, registerMaster } from './master-registry.js'\nimport {\n\tSLIDE_LAYOUT_CONTENT_TYPE,\n\tSLIDE_CONTENT_TYPE,\n\tSLIDE_MASTER_CONTENT_TYPE,\n\tSLIDE_MASTER_REL,\n\tSLIDE_REL,\n} from '../../../ooxml/rel-types.js'\nimport { copyTraversalStep } from './copy-traversal.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\t/**\n\t * Set when the traversal is planning rather than copying: every write goes to the\n\t * plan instead of `dest`, and `registry` is the plan's own copy of the real one.\n\t */\n\treadonly plan?: CopyPlan\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. */\ninterface SelectionPlan {\n\t/** Source slide partname → the destination partname reserved for it. */\n\treadonly destinations: ReadonlyMap<string, string>\n}\n\n/**\n * What a copy writes through: the destination package, or a {@link CopyPlan} standing in for it.\n * `OpcPackage` satisfies it.\n */\nexport interface CopyTarget {\n\treservePartNameLike(templatePartName: string): string\n\tpart(partName: string): unknown\n\taddPart(partName: string, contentType: string, bytes: Uint8Array): unknown\n\trelationshipsFor(partName: string): Pick<Relationships, 'add' | 'addWithId'>\n}\n\n/** Where a traversal writes: its plan when it is planning, its destination package otherwise. */\nexport function copyTarget(ctx: ImportContext): CopyTarget {\n\treturn ctx.plan ?? ctx.dest.opc\n}\n\n/** One part a {@link CopyPlan} would add. */\nexport interface PlannedPart {\n\treadonly partName: string\n\treadonly contentType: string\n}\n\n/** One relationship a {@link CopyPlan} would add; `id` is absent where the copy allocates one. */\nexport interface PlannedRel {\n\treadonly from: string\n\treadonly id?: string\n\treadonly type: string\n\treadonly target: string\n\treadonly targetMode?: 'Internal' | 'External'\n}\n\n/**\n * An import's copy, run without writing: the parts and relationships it would add, and every error\n * it would throw, found before anything in the destination moves.\n *\n * This is what lets a refused import leave the deck byte-identical. The copy changes the deck as it\n * goes — parts added, a master registered in `presentation.xml`, a layout linked into its master —\n * so a failure it met halfway would leave all of that behind. An import therefore runs the same\n * traversal twice: first with a plan in its context, which throws what the copy would and writes\n * nothing, then for real. The dry run used to be a separate walk of the source, transcribed from the\n * copy under a comment asking readers to keep the two in step, and it had drifted: it walked a\n * rebinding import's source layout chain, which the rebind never reads, and every source's notes\n * master in a batch, where the copy reads only the first one it installs.\n *\n * A plan stands in for the destination package as a {@link CopyTarget}. It hands out the partnames\n * the copy will be given, keeps its own copy of each source's registry so a part it planned is found\n * again as the copy would find it, and remembers the notes master it would install in a deck that has\n * none. Destination bookkeeping that adds no part — registering a master, linking a layout into it —\n * is not recorded.\n */\nexport class CopyPlan implements CopyTarget {\n\t/** The parts the copy would add, in the order it would add them. */\n\treadonly parts: PlannedPart[] = []\n\t/** The relationships the copy would add to the parts it copies. */\n\treadonly rels: PlannedRel[] = []\n\t/** The notes master the copy would install in a deck that has none; later notes bind to it. */\n\tnotesMaster: string | undefined\n\treadonly #dest: DeckTarget\n\t/** Every partname handed out, added or not yet added. */\n\treadonly #names = new Set<string>()\n\treadonly #added = new Set<string>()\n\treadonly #registries = new Map<OpcPackage, Map<string, string>>()\n\n\t/**\n\t * @param dest the deck the import copies into\n\t * @param api the public method planning, which opens every error the plan throws\n\t * @param linkable the pages a jump link may land on when the traversal has no selection of its\n\t * own: the page a rebinding import builds itself\n\t */\n\tconstructor(\n\t\tdest: DeckTarget,\n\t\treadonly api: string,\n\t\treadonly linkable?: ReadonlySet<string>\n\t) {\n\t\tthis.#dest = dest\n\t}\n\n\t/** This plan's context for an import out of `ctx.source`, over the plan's copy of its registry. */\n\tcontextFor(ctx: ImportContext): ImportContext {\n\t\tlet registry = this.#registries.get(ctx.source)\n\t\tif (!registry) {\n\t\t\tregistry = new Map(ctx.registry)\n\t\t\tthis.#registries.set(ctx.source, registry)\n\t\t}\n\t\treturn { dest: ctx.dest, source: ctx.source, registry, plan: this }\n\t}\n\n\treservePartNameLike(templatePartName: string): string {\n\t\tconst partName = this.#dest.opc.reservePartNameLike(templatePartName, this.#names)\n\t\tthis.#names.add(partName)\n\t\treturn partName\n\t}\n\n\tpart(partName: string): unknown {\n\t\treturn this.#added.has(partName) || this.#dest.opc.part(partName)\n\t}\n\n\taddPart(partName: string, contentType: string): void {\n\t\tthis.#names.add(partName)\n\t\tthis.#added.add(partName)\n\t\tthis.parts.push({ partName, contentType })\n\t}\n\n\trelationshipsFor(from: string): Pick<Relationships, 'add' | 'addWithId'> {\n\t\tconst record = (rel: PlannedRel): Relationship => {\n\t\t\tthis.rels.push(rel)\n\t\t\tconst { id = `planned${this.rels.length}`, type, target, targetMode } = rel\n\t\t\treturn { id, type, target, ...(targetMode ? { targetMode } : {}) }\n\t\t}\n\t\treturn {\n\t\t\tadd: (type, target, targetMode) => record({ from, type, target, ...(targetMode ? { targetMode } : {}) }),\n\t\t\taddWithId: (id, type, target, targetMode) =>\n\t\t\t\trecord({ from, id, type, target, ...(targetMode ? { targetMode } : {}) }),\n\t\t}\n\t}\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, copyTarget(ctx).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 as each link is\n * followed (see {@link rebuildRels}). Imports run this traversal as a\n * {@link CopyPlan} first, which throws that and every other failure the copy\n * could meet — so once copying starts there is nothing left to throw, and a\n * 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 = registeredCopy(ctx, 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(\n\t\t\t'package/part-missing',\n\t\t\t`${ctx.plan?.api ?? 'importSlide'}: source package has no part ${sourcePartName}`\n\t\t)\n\n\tconst target = copyTarget(ctx)\n\tconst newPartName = owned\n\t\t? target.reservePartNameLike(sourcePartName)\n\t\t: (ctx.selection?.destinations.get(sourcePartName) ?? target.reservePartNameLike(sourcePartName))\n\t// A selected page's part was already materialized by the batch allocator.\n\tif (!target.part(newPartName)) target.addPart(newPartName, sourcePart.contentType, sourcePart.serialize())\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\trebuildRels(ctx, {\n\t\tsource: sourcePart,\n\t\tnewPartName,\n\t\towned: scope,\n\t\t// Reuse decides at the page boundary and never below it. A part reached from\n\t\t// the page can be answered with the destination's own identical copy; a part\n\t\t// reached from something this import *copied* is copied too, so a copied\n\t\t// subgraph stays self-contained rather than half-linking into deck chrome\n\t\t// that merely happens to match.\n\t\tallowReuse: sourcePart.contentType === SLIDE_CONTENT_TYPE,\n\t})\n\n\tif (ctx.plan) {\n\t\t// A plan registers and links nothing. The dry run has always parsed a master or\n\t\t// layout it would copy, as the copy re-parses a master to empty its layout id\n\t\t// list, so XML that will not parse is refused before anything moves.\n\t\tif (sourcePart.contentType === SLIDE_MASTER_CONTENT_TYPE || sourcePart.contentType === SLIDE_LAYOUT_CONTENT_TYPE)\n\t\t\tvoid sourcePart.dom\n\t\treturn newPartName\n\t}\n\n\tif (sourcePart.contentType === SLIDE_MASTER_CONTENT_TYPE) {\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, ctx.source.relationshipsFor(sourcePartName), newPartName)\n\t}\n\n\treturn newPartName\n}\n\n/**\n * The copy `ctx.registry` names for `sourcePartName`, while that part is still in the destination.\n *\n * An entry whose part has gone is not a copy to reuse: returning it would wire the import to a\n * name that no longer holds anything, or to whatever part was added under it since. Removing a\n * slide forgets the names it frees, so this is the backstop for bookkeeping that ever misses one.\n */\nfunction registeredCopy(ctx: ImportContext, sourcePartName: string): string | undefined {\n\tconst existing = ctx.registry.get(sourcePartName)\n\treturn existing !== undefined && copyTarget(ctx).part(existing) ? existing : undefined\n}\n\n/**\n * What a caller decides about one relationship before the shared rule is asked: leave it out\n * (`skip`), carry it exactly as the source wrote it (`keep`), or point it at a destination part of\n * the caller's choosing. `undefined` hands it to the rule.\n */\nexport type RelOverride = 'skip' | 'keep' | { target: string } | undefined\n\n/** What {@link rebuildRels} rebuilds, and the caller's special cases. */\nexport interface RebuildRelsOptions {\n\t/** The source part whose relationships are copied. */\n\tsource: Part\n\t/** The destination part they are rebuilt on. */\n\tnewPartName: string\n\t/** The ownership scope of the page copy this part belongs to, if it belongs to one. */\n\towned?: OwnedScope | undefined\n\t/** Whether a followed target the destination already holds may be bound to rather than copied. */\n\tallowReuse: boolean\n\t/** Sees every relationship first; see {@link RelOverride}. */\n\toverride?: (rel: Relationship) => RelOverride\n}\n\n/**\n * Rebuild a copied part's relationships from its source's: the one loop every import that copies a\n * part runs.\n *\n * Each relationship keeps its source id, so the copied body's `r:id` and `r:embed` references stay\n * valid without the body being rewritten; only targets change. A caller's `override` sees each\n * relationship first and may skip it or name its target: the rebinding import points the layout at\n * this deck's, and a notes copy points its slide and its notes master at theirs. Everything else\n * follows {@link copyTraversalStep}: skipped, carried as an external link, or followed into the\n * part {@link copyPart} makes for it, inside `owned` unless {@link isSharedByPageCopies} says the\n * page may share it.\n *\n * It is also where a jump link is held to the pages the import brings. A `slide` relationship the\n * rule would follow must land on a page of `ctx.selection` (or, for a traversal with no selection of\n * its own, a page its plan names), or on one an earlier import from this source already brought\n * across. Anything else would drag a page nobody asked for into the deck, or strand the link, so it\n * is refused; imports plan first, so the refusal comes before anything moves.\n */\nexport function rebuildRels(ctx: ImportContext, options: RebuildRelsOptions): void {\n\tconst { source, newPartName, owned, allowReuse, override } = options\n\tconst sourceRels = ctx.source.relationshipsFor(source.partName)\n\tconst targetRels = copyTarget(ctx).relationshipsFor(newPartName)\n\tconst linkable = ctx.selection?.destinations ?? ctx.plan?.linkable\n\tfor (const rel of sourceRels) {\n\t\tconst decided = override?.(rel)\n\t\tif (decided === 'skip') continue\n\t\tif (decided === 'keep') {\n\t\t\ttargetRels.addWithId(rel.id, rel.type, rel.target, rel.targetMode)\n\t\t\tcontinue\n\t\t}\n\t\tif (decided) {\n\t\t\ttargetRels.addWithId(rel.id, rel.type, relativePartName(newPartName, decided.target))\n\t\t\tcontinue\n\t\t}\n\t\tconst step = copyTraversalStep(source, rel)\n\t\tif (step === 'skip') continue\n\t\tif (step === 'external') {\n\t\t\ttargetRels.addWithId(rel.id, rel.type, rel.target, 'External')\n\t\t\tcontinue\n\t\t}\n\t\tconst targetPartName = sourceRels.resolveTarget(rel.id)\n\t\tif (\n\t\t\trel.type === SLIDE_REL &&\n\t\t\tlinkable &&\n\t\t\t!linkable.has(targetPartName) &&\n\t\t\tregisteredCopy(ctx, targetPartName) === undefined\n\t\t) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/unresolved-slide-link',\n\t\t\t\t`${ctx.plan?.api ?? 'importSlides'}: source slide ${source.partName} links to ${targetPartName}, which is not among the imported pages`\n\t\t\t)\n\t\t}\n\t\tconst target = copyPart(ctx, targetPartName, isSharedByPageCopies(rel.type) ? undefined : owned, allowReuse)\n\t\ttargetRels.addWithId(rel.id, rel.type, relativePartName(newPartName, target))\n\t}\n}\n\n/**\n * Give a page cloned within its own package the source page's relationships, with its own copy of\n * every part the source page owned.\n *\n * The page's shared targets are carried as the source wrote them. Each owned one is repointed at a\n * fresh copy, and the subtree under it is copied the same way, so a chart's workbook and\n * user-shapes drawing come along while the image inside that drawing stays shared. A relationship\n * *back* to the source page — a notes slide names the slide it annotates — is repointed at the\n * clone, which is what makes the copied notes belong to it.\n *\n * Unlike an import, a clone keeps its page's notes, and nothing here consults the copy registry or\n * the reuse check: every relationship is decided by an override, so {@link copyTraversalStep} is\n * never asked. 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 dest the deck both pages live in\n * @param sourcePart the page that was cloned\n * @param clonePartName partname of the clone, which has no relationships yet\n */\nexport function rebuildClonedPageRels(dest: DeckTarget, sourcePart: Part, clonePartName: string): void {\n\t// Within one package the source is the destination.\n\tconst ctx: ImportContext = { dest, source: dest.opc, registry: new Map() }\n\t// Seeded with the page itself, so a back-reference to it lands on the clone.\n\tconst copies = new Map<string, string>([[sourcePart.partName, clonePartName]])\n\tconst sourceRels = dest.opc.relationshipsFor(sourcePart.partName)\n\trebuildRels(ctx, {\n\t\tsource: sourcePart,\n\t\tnewPartName: clonePartName,\n\t\tallowReuse: false,\n\t\toverride: (rel) => {\n\t\t\tif (rel.targetMode === 'External' || isSharedByPageCopies(rel.type)) return 'keep'\n\t\t\tconst target = sourceRels.resolveTarget(rel.id)\n\t\t\tconst fresh = copyOwnedSubtree(ctx, target, copies)\n\t\t\treturn fresh === target ? 'keep' : { target: fresh }\n\t\t},\n\t})\n}\n\n/**\n * Copy `partName` and, recursively, every part it owns, into fresh partnames in the same package.\n * `copies` dedupes within the one page copy, so a part two of the page's relationships reach is\n * copied once here even though the next page copy gets its own. Returns the copy's partname, or\n * `partName` unchanged when there is no such part to copy.\n */\nfunction copyOwnedSubtree(ctx: ImportContext, partName: string, copies: Map<string, string>): string {\n\tconst already = copies.get(partName)\n\tif (already !== undefined) return already\n\tconst opc = ctx.dest.opc\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.serialize())\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\trebuildRels(ctx, {\n\t\tsource: part,\n\t\tnewPartName: fresh,\n\t\tallowReuse: false,\n\t\toverride: (rel) => {\n\t\t\tif (rel.targetMode === 'External') return 'keep'\n\t\t\tconst target = sourceRels.resolveTarget(rel.id)\n\t\t\t// A shared target is still routed through `copies`: that is how the notes\n\t\t\t// slide's `slide` relationship finds the clone instead of the original.\n\t\t\tif (isSharedByPageCopies(rel.type)) return { target: copies.get(target) ?? target }\n\t\t\treturn { target: copyOwnedSubtree(ctx, target, copies) }\n\t\t},\n\t})\n\treturn fresh\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, type Element } from '../../oxml/dom.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport { copyPart, copyTarget, newOwnedScope, rebuildRels, type ImportContext } from './part-copy.js'\nimport type { Presentation } from '../presentation.js'\nimport {\n\tNOTES_MASTER_CONTENT_TYPE,\n\tNOTES_MASTER_REL,\n\tNOTES_SLIDE_CONTENT_TYPE,\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 { PRESENTATION_AFTER_NOTES_MASTER_ID_LST } from '../../../ooxml/sequence.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's current body into a fresh partname, then wire slide → notesSlide.\n\tconst target = copyTarget(ctx)\n\tconst newNotesPartName = target.reservePartNameLike(sourceNotesPartName)\n\ttarget.addPart(newNotesPartName, sourceNotesPart.contentType, sourceNotesPart.serialize())\n\ttarget.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. Each keeps its source id so the\n\t// notesSlide body's r:id references stay valid; only the targets are rewritten.\n\tconst notesSourceRels = source.opc.relationshipsFor(sourceNotesPartName)\n\trebuildRels(ctx, {\n\t\tsource: sourceNotesPart,\n\t\tnewPartName: newNotesPartName,\n\t\towned,\n\t\tallowReuse: false,\n\t\toverride: (rel) => {\n\t\t\t// Back-reference to the annotated slide → the new slide, never a copy of the source one.\n\t\t\tif (rel.type === SLIDE_REL) return { target: newSlidePartName }\n\t\t\tif (rel.type === NOTES_MASTER_REL)\n\t\t\t\treturn { target: ensureNotesMaster(dest, ctx, notesSourceRels.resolveTarget(rel.id)) }\n\t\t\treturn undefined\n\t\t},\n\t})\n}\n\n/**\n * Add a notes slide part holding `xml`, with the relationships every notes slide carries:\n * `notesMaster` as rId1 and the slide it annotates as rId2, the ids and order the write path\n * serializes a notes body against. The slide's own relationship *to* the notes part is left to\n * the caller, because the append path has to add it after every id the slide body names.\n * @param dest - the deck the part is added to\n * @param xml - the notes slide body\n * @param slidePartName - the slide it annotates\n * @param notesMasterPartName - the deck's notes master, or `null` to leave rId1 unallocated\n * @returns the notes slide's partname\n */\nexport function addNotesSlidePart(\n\tdest: Presentation,\n\txml: string,\n\tslidePartName: string,\n\tnotesMasterPartName: string | null\n): string {\n\tconst notesPartName = dest.opc.reservePartNameLike('/ppt/notesSlides/notesSlide1.xml')\n\tdest.opc.addPart(notesPartName, NOTES_SLIDE_CONTENT_TYPE, textEncoder.encode(xml))\n\tconst notesRels = dest.opc.relationshipsFor(notesPartName)\n\tif (notesMasterPartName)\n\t\tnotesRels.addWithId('rId1', NOTES_MASTER_REL, relativePartName(notesPartName, notesMasterPartName))\n\tnotesRels.addWithId('rId2', SLIDE_REL, relativePartName(notesPartName, slidePartName))\n\treturn notesPartName\n}\n\n/** The partname of this deck's notes master, or `null` when it has none. */\nfunction existingNotesMaster(dest: Presentation): string | null {\n\tconst presRels = presentationRels(dest)\n\tconst existing = presRels.byType(NOTES_MASTER_REL)[0]\n\treturn existing ? presRels.resolveTarget(existing.id) : null\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 existing = existingNotesMaster(dest)\n\tif (existing) return existing\n\n\t// No notesMaster yet: copy the source's (pulls its theme) and register it. A plan\n\t// registers nothing, so it remembers the master it would install instead, and the\n\t// later notes it plans bind to that one as they would to the registered master.\n\tif (ctx.plan) return (ctx.plan.notesMaster ??= copyPart(ctx, sourceNotesMasterPartName))\n\treturn registerNotesMaster(dest, copyPart(ctx, sourceNotesMasterPartName))\n}\n\n/** `presentation.xml`'s root, where a notes master is registered. */\nfunction presentationRoot(dest: Presentation): Element {\n\tconst root = dest.presentationPart.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\treturn root\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 root = presentationRoot(dest)\n\tconst relId = presentationRels(dest).add(\n\t\tNOTES_MASTER_REL,\n\t\trelativePartName(presPart.partName, notesMasterPartName)\n\t).id\n\t// `p:notesMasterIdLst` follows `p:sldMasterIdLst` in CT_Presentation order.\n\tconst lst = getOrAddChild(root, 'p:notesMasterIdLst', PRESENTATION_AFTER_NOTES_MASTER_ID_LST)\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 * Add a notes master and a theme part of its own, and register the master.\n *\n * The two paths that build a notes master rather than copy one differ only in where the bytes come\n * from. The presentation root is checked first, so a deck that cannot register a master is refused\n * before either part is added.\n * @param dest - the deck to install into\n * @param masterBytes - the notes master body\n * @param themeBytes - the theme body the master binds to\n * @param themeContentType - the theme part's content type\n * @returns the notes master's partname\n */\nfunction installNotesMaster(\n\tdest: Presentation,\n\tmasterBytes: Uint8Array,\n\tthemeBytes: Uint8Array,\n\tthemeContentType: string = THEME_CONTENT_TYPE\n): string {\n\tpresentationRoot(dest)\n\tconst masterPartName = dest.opc.reservePartNameLike('/ppt/notesMasters/notesMaster1.xml')\n\tdest.opc.addPart(masterPartName, NOTES_MASTER_CONTENT_TYPE, masterBytes)\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, themeContentType, themeBytes)\n\tdest.opc.relationshipsFor(masterPartName).add(THEME_REL, relativePartName(masterPartName, themePartName))\n\n\treturn registerNotesMaster(dest, masterPartName)\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\treturn (\n\t\texistingNotesMaster(dest) ??\n\t\tinstallNotesMaster(dest, textEncoder.encode(master.xml), textEncoder.encode(master.themeXml))\n\t)\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 existing = existingNotesMaster(dest)\n\tif (existing) return existing\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\t// Clone the deck's theme rather than share the slide master's part.\n\treturn installNotesMaster(\n\t\tdest,\n\t\ttextEncoder.encode(makeXmlNotesMaster()),\n\t\tthemePart.serialize(),\n\t\tthemePart.contentType\n\t)\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_SLIDE_REL } from '../../../ooxml/rel-types.js'\nimport { InternalError, PackageReadError } from '../../../errors.js'\nimport { addNotesSlidePart, 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\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 notes master comes first, because resolving it is the step\n\t// that can refuse, and it adds nothing until it can succeed: a refusal then leaves no notes part\n\t// behind with the slide pointing at it. The slide-number field caches this slide's 1-based\n\t// position, the value the write path stamps; PowerPoint recomputes it.\n\tconst masterPartName = ensureNotesMasterForAuthoring(slide.presentation, slide.partName)\n\tconst slideNum = slide.index + 1\n\tconst partName = addNotesSlidePart(\n\t\tslide.presentation,\n\t\tmakeXmlNotesSlideSkeleton(notesParagraphsXml(text), slideNum),\n\t\tslide.partName,\n\t\tmasterPartName\n\t)\n\tslide.relationships.add(NOTES_SLIDE_REL, relativePartName(slide.partName, partName))\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 { singleRelPart } from '../opc/partnames.js'\nimport { attr, firstChild, getElements, numberValue, type Element } from '../oxml/dom.js'\nimport {\n\tCOMMENT_AUTHORS_REL,\n\tCOMMENTS_CONTENT_TYPE,\n\tCOMMENTS_REL,\n\tMODERN_COMMENT_AUTHORS_REL,\n\tMS_POWERPOINT_CONTENT,\n\tMS_REL,\n} from '../../ooxml/rel-types.js'\n\n/** The slide → modern-comments-part relationship type (2018 schema). Only this module reads one. */\nconst MODERN_COMMENTS_REL_TYPE = MS_REL + '2018/10/relationships/comments'\n/** Content type of the modern per-slide comments part (`ppt/comments/modernComment_*.xml`). */\nconst MODERN_COMMENTS_CONTENT_TYPE = MS_POWERPOINT_CONTENT + '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: numberValue(attr(el, 'id')),\n\t\tname: attr(el, 'name') ?? '',\n\t\tinitials: attr(el, 'initials') ?? '',\n\t\tlastIdx: numberValue(attr(el, 'lastIdx')),\n\t\tclrIdx: numberValue(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 part = singleRelPart(opc, presentationPartName, COMMENT_AUTHORS_REL)\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 root = singleRelPart(opc, slidePart.partName, COMMENTS_REL)?.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 = numberValue(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: numberValue(attr(cm, 'idx')),\n\t\t\ttext: textEl?.textContent ?? '',\n\t\t\tx: pos ? numberValue(attr(pos, 'x')) : null,\n\t\t\ty: pos ? numberValue(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 ? numberValue(attr(pos, 'x')) : null,\n\t\ty: pos ? numberValue(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 root = singleRelPart(opc, presentationPartName, MODERN_COMMENT_AUTHORS_REL)?.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 root = singleRelPart(opc, slidePart.partName, MODERN_COMMENTS_REL_TYPE)?.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(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'\nimport { OFFICE_REL } from '../../ooxml/rel-types.js'\n\n/** The owner → tags-part relationship type. Only this module follows one. */\nconst TAGS_REL_TYPE = OFFICE_REL + '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/contributing/design/animations.md`.\n */\nimport { InvalidOptionError } from '../../errors.js'\nimport { transitionSpeedForDuration } from '../../ooxml/transition-speed.js'\nimport {\n\tOOXML_NS,\n\tattr,\n\tboolValue,\n\tchildElements,\n\tcreateElement,\n\tfirstChild,\n\tnumberValue,\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/**\n * Transition fields accepted by the {@link Slide.transition} setter. A {@link TransitionInfo} read\n * from the same slide is a valid input, so `slide.transition = { ...slide.transition, speed: 'slow' }`\n * changes the speed and keeps everything else, the sound included.\n */\nexport interface TransitionInput {\n\ttype: string\n\t/** Namespace prefix for the type element; defaults to `p` (base ECMA-376). */\n\tnamespace?: string\n\t/**\n\t * Coarse speed bucket (`spd`). When omitted it is derived from `durationMs` if one is given, and\n\t * otherwise not written. A stated `fast`, the schema default, is not written when the slide's\n\t * transition had no `spd` either, so a transition read back and assigned again keeps its markup.\n\t */\n\tspeed?: TransitionSpeed\n\t/** Exact duration in milliseconds (`p14:dur`), a finite number from 0; `null` or omitted writes none. */\n\tdurationMs?: number | null\n\tadvanceOnClick?: boolean\n\t/** Auto-advance delay in milliseconds (`advTm`), a finite number from 0; `null` or omitted writes none. */\n\tadvanceAfterMs?: number | null\n\tvariant?: Record<string, string>\n\t/**\n\t * The transition sound (`p:sndAc`), in three states.\n\t *\n\t * - **omitted** keeps the sound the slide's transition already has;\n\t * - **`null`** removes it;\n\t * - **a value** is accepted only when it is that same sound, as a spread of the getter passes it.\n\t *\n\t * A different sound throws `transition/sound-unsupported`: a start sound names an embedded audio\n\t * part, which this setter does not add, so writing one would point the slide at a relationship it\n\t * may not have. Add a sound when authoring the deck (`slide.transition = { sound }` on the write\n\t * side) instead.\n\t */\n\tsound?: TransitionSoundInfo | null\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\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 = numberValue(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: numberValue(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/**\n * A transition time the caller stated, as whole milliseconds, or `null` when not stated. `NaN`,\n * `Infinity` and a negative number throw: each was written straight into `p14:dur` or `advTm`.\n */\nfunction transitionTime(value: number | null | undefined, name: 'durationMs' | 'advanceAfterMs'): number | null {\n\tif (value === undefined || value === null) return null\n\tif (typeof value !== 'number' || !Number.isFinite(value) || value < 0)\n\t\tthrow new InvalidOptionError(\n\t\t\t'transition/invalid-time',\n\t\t\t`slide.transition: \\`${name}\\` is a number of milliseconds from 0; got ${String(value)}.`\n\t\t)\n\treturn Math.round(value)\n}\n\n/**\n * The `p:sndAc` the new transition carries: the current one when the caller left `sound` out or\n * passed that same sound back, none for `null`, and a refusal for any other sound. See\n * {@link TransitionInput.sound}.\n */\nfunction soundFor(input: TransitionSoundInfo | null | undefined, current: Element | null): Element | null {\n\tconst existing = current ? firstChild(current, 'p:sndAc') : null\n\tif (input === undefined) return existing\n\tif (input === null) return null\n\tconst now = current ? parseSound(current) : null\n\tconst same =\n\t\t!!existing &&\n\t\t!!now &&\n\t\tnow.form === input.form &&\n\t\tnow.loop === !!input.loop &&\n\t\tnow.embedRid === (input.embedRid ?? null) &&\n\t\tnow.name === (input.name ?? null)\n\tif (same) return existing\n\tthrow new InvalidOptionError(\n\t\t'transition/sound-unsupported',\n\t\t\"slide.transition: `sound` can keep the slide's own transition sound (leave it out, or pass the one `slide.transition` reads) or remove it (`null`); adding a different sound is not supported here.\"\n\t)\n}\n\n/** What {@link buildTransitionElement} writes, resolved and checked once for both forms. */\ninterface ResolvedTransition {\n\tspeed: TransitionSpeed | null\n\tdurationMs: number | null\n\tadvanceAfterMs: number | null\n\tsound: Element | null\n}\n\n/** Build a `p:transition` element (without the `p14:dur` attribute unless `withDur`) from an input. */\nfunction buildTransitionElement(\n\tdoc: Document,\n\tinput: TransitionInput,\n\tresolved: ResolvedTransition,\n\twithDur: boolean\n): Element {\n\tconst transition = createElement(doc, 'p:transition')\n\tif (resolved.speed) setAttr(transition, 'spd', resolved.speed)\n\tif (withDur && resolved.durationMs !== null) setAttr(transition, 'p14:dur', String(resolved.durationMs))\n\tif (input.advanceOnClick === false) setAttr(transition, 'advClick', '0')\n\tif (resolved.advanceAfterMs !== null) setAttr(transition, 'advTm', String(resolved.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\t// `CT_SlideTransition` orders the sound after the type choice.\n\tif (resolved.sound) transition.appendChild(resolved.sound.cloneNode(true))\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 *\n * Every value is checked before anything is built, so a refused input changes nothing.\n * @param doc - the slide part's document\n * @param input - the caller's transition\n * @param root - the slide's root `p:sld`, whose current transition supplies the sound and the\n * `spd` a round trip keeps; omit it for a slide with no transition to carry over\n */\nexport function buildTransition(doc: Document, input: TransitionInput, root?: Element | null): Element {\n\tconst current = root ? (findTransition(root)?.transition ?? null) : null\n\tconst durationMs = transitionTime(input.durationMs, 'durationMs')\n\tconst advanceAfterMs = transitionTime(input.advanceAfterMs, 'advanceAfterMs')\n\tconst sound = soundFor(input.sound, current)\n\tconst stated = input.speed ?? (durationMs !== null ? transitionSpeedForDuration(durationMs) : null)\n\t// `fast` is the schema default. Keeping it absent where it was absent is what lets a transition\n\t// read back (whose `speed` reports `fast` for a missing `spd`) be assigned again unchanged.\n\tconst keepsDefaultAbsent = stated === 'fast' && !!current && attr(current, 'spd') === null\n\tconst resolved: ResolvedTransition = { speed: keepsDefaultAbsent ? null : stated, durationMs, advanceAfterMs, sound }\n\n\tif (durationMs === null) return buildTransitionElement(doc, input, resolved, false)\n\n\tconst alt = createElement(doc, 'mc:AlternateContent')\n\tconst choice = createElement(doc, 'mc:Choice')\n\t// `Requires` names a prefix, so the prefix is declared where `Requires` is read, as PowerPoint\n\t// writes it. Declared only on the inner `p:transition` (which `p14:dur` does), it was out of\n\t// scope on a slide whose root does not declare it, and the schema refused the choice.\n\tchoice.setAttributeNS('http://www.w3.org/2000/xmlns/', 'xmlns:p14', OOXML_NS.p14)\n\tsetAttr(choice, 'Requires', 'p14')\n\tchoice.appendChild(buildTransitionElement(doc, input, resolved, true))\n\talt.appendChild(choice)\n\tconst fallback = createElement(doc, 'mc:Fallback')\n\tfallback.appendChild(buildTransitionElement(doc, input, resolved, 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 * ts-pptx: building the DOM for a shape added through the read model.\n *\n * Write-side element construction, living in `read/` because that is where the caller is:\n * `Slide.addTextBox` and `Slide.addPicture` mint a `p:sp`/`p:pic` and splice it into a loaded\n * deck's `p:spTree`. It is not the write path's emitter -- that builds strings for a package\n * assembled from nothing, while these build nodes for a package that already exists -- and it\n * shares no state with `Slide`, which is why it sat as a hundred lines of free functions at the\n * bottom of that module with no reference to the class above them.\n */\n\nimport type { Document, Element } from '@xmldom/xmldom'\nimport { createElement, ownerDocumentOf, setAttr } from '../oxml/dom.js'\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). */\nexport function 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). */\nexport function 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-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, singleRelPart } from '../opc/partnames.js'\nimport type { Relationships } from '../opc/relationships.js'\nimport { attr, boolValue, firstChild, insertInOrder, removeAttr, setAttr, type Element } from '../oxml/dom.js'\nimport type { ThemeContext } from '../oxml/theme.js'\nimport { resolveSlideColorContext, resolveSlideThemeParts, type SlideThemeParts } 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 { SLIDE_AFTER_TRANSITION } from '../../ooxml/sequence.js'\nimport { imageFormatForBytes } from '../../media/image-formats.js'\nimport { checkFiniteEmu, checkPositiveEmu } from './coords.js'\nimport { InternalError, InvalidOptionError, PackageReadError } from '../../errors.js'\nimport { cSldOf, nextDrawingId, spTreeOf } from '../oxml/slide-dom.js'\nimport { buildPicture, buildTextBox } from './slide-build.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 common raster format from its leading bytes, through the shared registry. */\nfunction sniffImageType(bytes: Uint8Array): ImageType | null {\n\tconst format = imageFormatForBytes(bytes)\n\treturn format ? { extension: format.ext, contentType: format.contentType } : 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.#slideThemeParts()))\n\t}\n\n\t#themeParts?: SlideThemeParts\n\n\t/**\n\t * The slide's layout, master and theme parts, walked once and cached on this proxy.\n\t *\n\t * The colour context is built from them, and {@link background} also needs the part *names*,\n\t * which the context does not carry. Each resolved the chain itself, so reading a background\n\t * walked it twice.\n\t */\n\t#slideThemeParts(): SlideThemeParts {\n\t\treturn (this.#themeParts ??= resolveSlideThemeParts(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\treturn boolValue(root && attr(root, '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\t * The new transition is built from the current one before that is removed: it keeps the sound\n\t * unless `sound` says otherwise (see {@link TransitionInput.sound}), and a value that is refused\n\t * (a `durationMs` or `advanceAfterMs` that is not a number of milliseconds from 0, or a sound\n\t * that is not the slide's own) leaves the slide as it was.\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\tconst built = value ? buildTransition(this.part.dom, value, root) : null\n\t\tremoveTransition(root)\n\t\tif (built) insertInOrder(root, built, SLIDE_AFTER_TRANSITION)\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 `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 notesPart = singleRelPart(this.presentation.opc, this.partName, NOTES_SLIDE_REL)\n\t\treturn notesPart ? new NotesSlide(this.presentation.opc, notesPart) : null\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 part = singleRelPart(this.presentation.opc, this.partName, SLIDE_LAYOUT_REL)\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, read by {@link modernComments}.\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, pattern and image backgrounds are the ones the writer authors and so\n\t * round-trip faithfully; `themeRef` is read-only for imported decks.\n\t */\n\tget background(): SlideBackground | null {\n\t\tconst opc = this.presentation.opc\n\t\t// The colour context and the part names both come from the one parts walk this proxy caches.\n\t\tconst ctx = this.themeContext()\n\t\tconst parts = this.#slideThemeParts()\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 a slide given\n\t * `slide.slideNumber`, or added to a master defined with `slideNumber`; 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 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\t// Checked and rounded up front, so the builder below is handed whole EMU.\n\t\tconst left = checkFiniteEmu(options.left, 'left')\n\t\tconst top = checkFiniteEmu(options.top, 'top')\n\t\tconst width = checkPositiveEmu(options.width, 'width')\n\t\tconst height = checkPositiveEmu(options.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,\n\t\t\ttop,\n\t\t\twidth,\n\t\t\theight,\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\t// Checked and rounded up front, so the builder below is handed whole EMU.\n\t\tconst left = checkFiniteEmu(options.left, 'left')\n\t\tconst top = checkFiniteEmu(options.top, 'top')\n\t\tconst width = checkPositiveEmu(options.width, 'width')\n\t\tconst height = checkPositiveEmu(options.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,\n\t\t\ttop,\n\t\t\twidth,\n\t\t\theight,\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 One past the highest drawing id (`p:cNvPr/@id`) in use on this slide. Exposed so\n\t * `Presentation.importShape` can give a lifted shape (and its group children) collision-free\n\t * ids on the host.\n\t *\n\t * It does NOT fill gaps, and it does not reserve what it hands out: calling it twice without\n\t * appending in between returns the same id both times. A caller allocating several ids at\n\t * once counts up from one call rather than calling repeatedly.\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/** One past the highest drawing id (`p:cNvPr/@id`) in use on the slide. */\n\t#nextShapeId(): number {\n\t\treturn nextDrawingId(this.part.dom.documentElement)\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","/**\n * Read a deck's document properties — the `docProps/core.xml` core properties\n * (Dublin Core title/subject/creator + OPC keywords/revision/timestamps), the\n * `docProps/app.xml` extended properties, and the `docProps/custom.xml`\n * user-defined name/value pairs. These are the read counterparts of the write-side\n * `pptx.title`/`subject`/`author`/`revision` setters (`makeXmlCore`), `pptx.company`\n * (`makeXmlApp`) and `pptx.setCustomProperty(...)` (`makeXmlCustomProperties`),\n * so a reader is verified by a genuine write→read round-trip.\n *\n * All three parts are declared at the package root (`/_rels/.rels`): core-properties\n * via the OPC `metadata/core-properties` rel, extended-properties and\n * custom-properties via the officeDocument `extended-properties` /\n * `custom-properties` rels.\n */\nimport type { CustomPropertyValue } from '../../types/index.js'\nimport { OpcPackage } from '../opc/package.js'\nimport { singleRelPart } from '../opc/partnames.js'\nimport { attr, childElements, firstChild, firstChildElement, numberValue, type Element } from '../oxml/dom.js'\n// The content types are the fallback lookup for when a part's rel is absent.\nimport {\n\tCORE_PROPS_CONTENT_TYPE,\n\tCORE_PROPS_REL,\n\tCUSTOM_PROPS_CONTENT_TYPE,\n\tCUSTOM_PROPS_REL,\n\tEXTENDED_PROPS_CONTENT_TYPE,\n\tEXTENDED_PROPS_REL,\n} from '../../ooxml/rel-types.js'\nimport { boolValue } from '../../ooxml/xsd-boolean.js'\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/**\n * Decoded `docProps/app.xml` — the *extended* properties, which are the producer's own\n * account of the deck rather than the author's metadata. Every field is optional (present\n * only when the element is).\n *\n * Deliberately a subset. `<Slides>`, `<Words>`, `<Paragraphs>` and the rest are statistics\n * the producing application computed for the file it wrote; reporting them from a read model\n * that can hand back an edited deck would be reporting a number about a document that no\n * longer exists. The four here identify the producer and name the deck's parts, which stay\n * true, and `company` is the one this library's write API can set.\n */\nexport interface ExtendedProperties {\n\t/** `<Application>` — the producing application, e.g. `Microsoft Office PowerPoint`. */\n\tapplication?: string\n\t/** `<AppVersion>` — that application's version, in its own `major.minor` spelling (`16.0000`). */\n\tappVersion?: string\n\t/** `<Company>` (the write-side `pptx.company`). */\n\tcompany?: string\n\t/**\n\t * `<TitlesOfParts>` — the flat `vt:lpstr` vector naming the deck's fonts, themes and slide\n\t * titles in one list. It is the vector as written, NOT split by section: `<HeadingPairs>`\n\t * holds the counts that partition it, and this library does not read them, so the caller\n\t * that wants the slide titles alone has to pair the two itself.\n\t */\n\ttitlesOfParts?: 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 part = singleRelPart(opc, '/', CORE_PROPS_REL) ?? 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 * Read the deck's extended document properties from `/docProps/app.xml`, resolved\n * via the package-root `extended-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 *\n * Children are matched by **local name**: the extended-properties namespace is not in the\n * read model's qname registry, and its elements are unprefixed there, so this reads them the\n * way {@link readCustomProperties} reads a `<property>`'s `vt:` child.\n */\nexport function readExtendedProperties(opc: OpcPackage): ExtendedProperties {\n\tconst part = singleRelPart(opc, '/', EXTENDED_PROPS_REL) ?? opc.partsByContentType(EXTENDED_PROPS_CONTENT_TYPE)[0]\n\tconst root = part?.dom.documentElement\n\tif (!root) return {}\n\tconst out: ExtendedProperties = {}\n\tfor (const child of childElements(root)) {\n\t\tswitch (child.localName) {\n\t\t\tcase 'Application':\n\t\t\t\tout.application = child.textContent ?? ''\n\t\t\t\tbreak\n\t\t\tcase 'AppVersion':\n\t\t\t\tout.appVersion = child.textContent ?? ''\n\t\t\t\tbreak\n\t\t\tcase 'Company':\n\t\t\t\tout.company = child.textContent ?? ''\n\t\t\t\tbreak\n\t\t\tcase 'TitlesOfParts': {\n\t\t\t\t// `<TitlesOfParts>` wraps exactly one `<vt:vector>`; the entries are its `vt:lpstr`\n\t\t\t\t// children. An empty vector is still a stated one, so `[]` is reported rather than\n\t\t\t\t// the key being left off.\n\t\t\t\tconst vector = firstChildElement(child)\n\t\t\t\tif (vector) out.titlesOfParts = childElements(vector).map((item) => item.textContent ?? '')\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tdefault:\n\t\t\t\tbreak\n\t\t}\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 numberValue(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\t// `vt:bool` is `xsd:boolean`, so `boolValue` is the one reading of its four lexical\n\t\t\t// forms. The hand-rolled test accepted `'TRUE'`, which `xsd:boolean` does not.\n\t\t\treturn boolValue(text.trim()) ?? false\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 part = singleRelPart(opc, '/', CUSTOM_PROPS_REL) ?? 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 * 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 { EMBEDDED_FONT_ENTRY_AFTER, PRESENTATION_AFTER_EMBEDDED_FONT_LST } from '../../../ooxml/sequence.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, type DeckTarget } from './deck-target.js'\n\n/** One `p:embeddedFont` entry as {@link readEmbeddedFontEntries} reads it. */\nexport interface EmbeddedFontEntry {\n\ttypeface: string\n\t/** `p:font/@panose`, or `null` when the entry declares none. */\n\tpanose: string | null\n\t/** `p:font` identity attrs other than `typeface` (panose/pitchFamily/charset), in document order. */\n\tidentity: Array<{ name: string; value: string }>\n\t/**\n\t * Every face slot that carries an `r:id`, in schema order. `partName` is the part that id\n\t * resolves to, or `null` when it names no internal relationship of the presentation part.\n\t */\n\tfaces: Array<{ slot: EmbeddedFontSlot; relId: string; partName: string | null }>\n}\n\n/**\n * A deck's `p:embeddedFontLst`, read once.\n *\n * The getter, the import check and the carry each walked the list themselves and disagreed on a\n * face whose `r:id` names no relationship: the getter skipped it, the other two called\n * `resolveTarget` and threw an option error. Reading it here, with the dangling face reported as\n * `partName: null` rather than thrown, lets each consumer decide what that face means for it. An\n * entry with no `@typeface` and a face slot with no `r:id` are left out, as all three always did.\n */\nexport function readEmbeddedFontEntries(deck: DeckTarget): EmbeddedFontEntry[] {\n\tconst root = deck.presentationPart.dom.documentElement\n\tconst lst = root && firstChild(root, 'p:embeddedFontLst')\n\tif (!lst) return []\n\tconst rels = presentationRels(deck)\n\tconst entries: EmbeddedFontEntry[] = []\n\tfor (const entry of getElements(lst, 'p:embeddedFont')) {\n\t\tconst font = firstChild(entry, 'p:font')\n\t\tconst typeface = font && attr(font, 'typeface')\n\t\tif (!font || !typeface) continue\n\t\tconst identity: EmbeddedFontEntry['identity'] = []\n\t\tfor (const name of ['panose', 'pitchFamily', 'charset']) {\n\t\t\tconst value = attr(font, name)\n\t\t\tif (value !== null) identity.push({ name, value })\n\t\t}\n\t\tconst faces: EmbeddedFontEntry['faces'] = []\n\t\tfor (const slot of EMBEDDED_FONT_SLOTS) {\n\t\t\tconst face = firstChild(entry, `p:${slot}`)\n\t\t\tconst relId = face && attr(face, 'r:id')\n\t\t\tif (!relId) continue\n\t\t\tconst rel = rels.get(relId)\n\t\t\tfaces.push({ slot, relId, partName: rel && rel.targetMode !== 'External' ? rels.resolveTarget(relId) : null })\n\t\t}\n\t\tentries.push({ typeface, panose: attr(font, 'panose'), identity, faces })\n\t}\n\treturn entries\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 * Dry-run {@link carryEmbeddedFonts} against one source, reading only the *source* package:\n * every face this deck would copy names a part that is actually there.\n *\n * Every import that carries fonts calls it before it changes anything, because the carry runs\n * last — after the page or the masters are already in the deck — and a face it cannot copy would\n * throw with parts added and no way back. A face whose `r:id` names no relationship and a face\n * whose relationship names no part are the same failure to a caller, the face's binary is not in\n * the package, so both are `package/part-missing`.\n *\n * It reads the list through {@link readEmbeddedFontEntries}, as the carry does, so the two cannot\n * skip different entries. The one throw the carry has past this point is\n * `package/part-has-no-root` on the *destination*.\n * @param source - the deck whose fonts would be carried\n * @param api - the public method asking, which opens the error message\n */\nexport function checkEmbeddedFontsCopyable(source: Presentation, api = 'importSlides'): void {\n\tfor (const { typeface, faces } of readEmbeddedFontEntries(source)) {\n\t\tfor (const { slot, relId, partName } of faces) {\n\t\t\tif (partName === null)\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/part-missing',\n\t\t\t\t\t`${api}: embedded font ${typeface} (${slot}) names relationship ${relId}, which ${source.presentationPart.partName} does not have`\n\t\t\t\t)\n\t\t\tif (!source.opc.part(partName))\n\t\t\t\tthrow new PackageReadError(\n\t\t\t\t\t'package/part-missing',\n\t\t\t\t\t`${api}: source package has no part ${partName} (embedded font ${typeface}, ${slot})`\n\t\t\t\t)\n\t\t}\n\t}\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 incoming: IncomingEmbeddedFont[] = readEmbeddedFontEntries(source).map(({ typeface, identity, faces }) => ({\n\t\ttypeface,\n\t\tidentity,\n\t\t// Every caller runs `checkEmbeddedFontsCopyable` first, so a face with no part cannot reach\n\t\t// here. Binary comes across via copyPart, so the per-source registry dedupes faces shared\n\t\t// across repeated imports; the thunk runs only when the face is added.\n\t\tfaces: faces.flatMap(({ slot, partName }) =>\n\t\t\tpartName === null ? [] : [{ slot, createPart: () => copyPart(ctx, partName) }]\n\t\t),\n\t}))\n\t// An entry with no faces carries nothing, and copied it would be an empty `p:embeddedFont`.\n\tmergeEmbeddedFontEntries(\n\t\tdest,\n\t\tincoming.filter((font) => font.faces.length > 0)\n\t)\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, and a merge that adds a face sets `embedTrueTypeFonts`, without which\n * PowerPoint drops every embedded font on its next save. 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_AFTER_EMBEDDED_FONT_LST)\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_ENTRY_AFTER[`p:${face.slot}`] ?? [])\n\t\t\tcopiedAny = true\n\t\t}\n\t}\n\n\tif (copiedAny) {\n\t\t// PowerPoint drops every embedded font from a deck without this flag when it saves.\n\t\tsetAttr(presRoot, 'embedTrueTypeFonts', '1')\n\t\tpresPart.markDirty()\n\t}\n}\n","/**\n * ts-pptx: slide-size preconditions for the import surface\n *\n * Every import entry point starts by asking whether the two decks agree on canvas size, and\n * the five that asked wrote out the same comparison, the same `unknown`-printing formatter\n * and the same `InvalidOptionError` each time. That cost more than the duplication: the\n * copies disagreed on what an *unknown* size means, so a consumer branching on `err.code`\n * could not tell \"these decks are different sizes\" from \"I could not read a size\" anywhere\n * except `importSlide`, and only when a rescale had been asked for.\n *\n * The two conditions are separated here, and the codes now mean what their names say:\n * - `import/slide-size-unknown` — a deck does not declare `p:sldSz`, so there is no size to\n * compare and no rescale to compute. Nothing the caller passes can make it comparable.\n * - `import/slide-size-mismatch` — both sizes are known and they differ. This one *is*\n * answerable, which is why each caller supplies the escape hatch it offers.\n */\n\nimport { InvalidOptionError } from '../../../errors.js'\nimport type { SlideSize } from '../presentation-types.js'\n\n/** A size as the error messages print it. */\nfunction fmt(size: SlideSize | null): string {\n\treturn size ? `${size.widthEmu}×${size.heightEmu} EMU` : 'unknown'\n}\n\n/**\n * Both decks' sizes, or a throw when either deck does not declare one.\n *\n * Returned rather than asserted because every caller that needs both sizes known needs the\n * values too — to compute a rescale — and TypeScript cannot narrow two parameters from one\n * assertion signature.\n *\n * @param target - this deck's slide size\n * @param incoming - the source deck's slide size\n * @param api - the method name, opening the message\n */\nexport function requireKnownSlideSizes(\n\ttarget: SlideSize | null,\n\tincoming: SlideSize | null,\n\tapi: string\n): [SlideSize, SlideSize] {\n\tif (!target || !incoming)\n\t\tthrow new InvalidOptionError(\n\t\t\t'import/slide-size-unknown',\n\t\t\t`${api} requires both decks to declare a slide size (p:sldSz); target is ${fmt(target)}, source is ${fmt(incoming)}`\n\t\t)\n\treturn [target, incoming]\n}\n\n/**\n * Assert the two decks share a canvas, throwing whichever condition actually applies.\n *\n * @param target - this deck's slide size\n * @param incoming - the source deck's slide size\n * @param api - the method name, opening the message\n * @param hint - the escape hatch this caller offers, parenthesised into the message; omit\n * where there is none (`importSlides` and `appendSlides` have no rescale spelling)\n */\nexport function requireEqualSlideSize(\n\ttarget: SlideSize | null,\n\tincoming: SlideSize | null,\n\tapi: string,\n\thint = ''\n): void {\n\tconst [known, source] = requireKnownSlideSizes(target, incoming, api)\n\tif (known.widthEmu === source.widthEmu && known.heightEmu === source.heightEmu) return\n\tthrow new InvalidOptionError(\n\t\t'import/slide-size-mismatch',\n\t\t`${api} requires equal slide sizes${hint ? ` (${hint})` : ''}; target is ${fmt(target)}, source is ${fmt(incoming)}`\n\t)\n}\n\n/** Whether both sizes are known and equal — the question a caller with a rescale asks first. */\nexport function slideSizesMatch(target: SlideSize | null, incoming: SlideSize | null): boolean {\n\treturn !!target && !!incoming && target.widthEmu === incoming.widthEmu && target.heightEmu === incoming.heightEmu\n}\n","/**\n * ts-pptx: the body of {@link Presentation.appendSlides}\n *\n * The hybrid \"generate onto an existing deck\" path: a slide producer authors slides, they are\n * spliced into this package under fresh partnames, and every dependency each one carries —\n * images, embedded and online media, hyperlinks, speaker notes, charts, intra-batch slide links\n * — is wired into its `.rels`.\n *\n * Here rather than on the class for the reason `presentation.ts` states about the four import\n * bodies: the *contract* is the doc comment a caller reads and stays on the public method, while\n * the wiring is one job with a lot of parts. It was the largest thing left in that file. Each\n * loop that used to be an anonymous `for` inside one closure is now a named function carrying the\n * paragraph that explains the relationship layout it produces.\n *\n * The rel ids these functions allocate depend on the order they run in, so the two passes below\n * and the sequence inside pass 2 are both load-bearing.\n */\n\nimport { emuToInches } from '../../../units.js'\nimport { relativePartName } from '../../opc/partnames.js'\nimport type { Part } from '../../opc/part.js'\nimport type { Relationships } from '../../opc/relationships.js'\nimport { InternalError, InvalidOptionError, PackageReadError } from '../../../errors.js'\nimport {\n\tAUDIO_REL,\n\tCHART_COLOR_STYLE_CONTENT_TYPE,\n\tCHART_COLOR_STYLE_REL,\n\tCHART_CONTENT_TYPE,\n\tCHART_REL,\n\tCHART_STYLE_CONTENT_TYPE,\n\tCHART_STYLE_REL,\n\tCHARTEX_CONTENT_TYPE,\n\tCHARTEX_REL,\n\tHYPERLINK_REL,\n\tIMAGE_REL,\n\tMS_MEDIA_REL,\n\tNOTES_SLIDE_REL,\n\tPACKAGE_REL,\n\tSLIDE_CONTENT_TYPE,\n\tSLIDE_LAYOUT_REL,\n\tSLIDE_REL,\n\tVIDEO_REL,\n\tXLSX_CONTENT_TYPE,\n} from '../../../ooxml/rel-types.js'\nimport type { Presentation } from '../presentation.js'\nimport type { Slide } from '../slide.js'\nimport type { AppendSlidesOptions, LayoutHandle, SlideSource } from '../presentation-types.js'\nimport { carryGeneratedEmbeddedFonts } from './embedded-fonts.js'\nimport { addNotesSlidePart, ensureNotesMasterFromXml } from './notes-master.js'\nimport { requireEqualSlideSize } from './slide-size.js'\nimport { pickDefined } from '../../../options-internal.js'\n\nconst textEncoder = new TextEncoder()\n\n/** One extracted slide as pass 1 left it: the source body, the part it landed in, and its name. */\ntype PlacedSlide = {\n\tslide: Awaited<ReturnType<SlideSource['extractSlides']>>['slides'][number]\n\tpart: Part\n\tpartName: string\n}\n\n/**\n * Resolve `options.layout` — a layout *name* or a {@link LayoutHandle} — against this deck's\n * gallery, with no silent fallback: an unusable value is one of three named errors rather than a\n * default layout, because a slide bound to the wrong layout is a deck that looks authored.\n *\n * Split out because it is the part of the append most likely to be wanted by a second caller, and\n * because it is the only place `layout/ambiguous-name`, `layout/not-found` and\n * `layout/foreign-handle` are raised.\n *\n * @param deck - the destination deck, whose `layouts()` gallery is searched\n * @param layout - the caller's layout name or handle\n * @param api - the method name, opening each error message\n */\nfunction resolveLayoutTarget(\n\tdeck: Presentation,\n\tlayout: AppendSlidesOptions['layout'],\n\tapi = 'appendSlides'\n): LayoutHandle {\n\tconst gallery = deck.layouts()\n\tif (typeof layout !== 'string') {\n\t\tif (!gallery.some((l) => l.partName === layout.partName)) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'layout/foreign-handle',\n\t\t\t\t`${api}: layout ${layout.partName} does not belong to this presentation`\n\t\t\t)\n\t\t}\n\t\treturn layout\n\t}\n\tconst matches = gallery.filter((l) => l.name === layout)\n\tif (matches.length > 1) {\n\t\tthrow new InvalidOptionError(\n\t\t\t'layout/ambiguous-name',\n\t\t\t`${api}: layout name ${JSON.stringify(layout)} is ambiguous (${matches.length} layouts share it); pass a LayoutHandle from layouts() instead`\n\t\t)\n\t}\n\tconst [only] = matches\n\tif (!only) {\n\t\tconst names = gallery.map((l) => JSON.stringify(l.name)).join(', ')\n\t\tthrow new InvalidOptionError(\n\t\t\t'layout/not-found',\n\t\t\t`${api}: no layout named ${JSON.stringify(layout)}; available: ${names || '(none)'}`\n\t\t)\n\t}\n\treturn only\n}\n\n/** Image parts behind the slide body's `image` rels, each keeping the id the body was built with. */\nfunction wireMedia(deck: Presentation, rels: Relationships, partName: string, slide: PlacedSlide['slide']): void {\n\tfor (const m of slide.media) {\n\t\tconst mediaPartName = deck.opc.reserveMediaPartName(m.extn)\n\t\tdeck.opc.addPart(mediaPartName, m.contentType, m.bytes)\n\t\trels.addWithId(`rId${m.rId}`, IMAGE_REL, relativePartName(partName, mediaPartName))\n\t}\n}\n\n/**\n * Embedded audio and video. One media part backs two rels (ECMA audio/video + MS-2007 media)\n * sharing its Target; the preview poster is a separate image part. `ensureDefault` runs before\n * `addPart` so the content type resolves via a Default extension entry (what PowerPoint authors)\n * rather than a per-part Override.\n */\nfunction wireAvMedia(deck: Presentation, rels: Relationships, partName: string, slide: PlacedSlide['slide']): void {\n\tfor (const av of slide.avMedia) {\n\t\tconst mediaPartName = deck.opc.reserveMediaPartName(av.mediaExtn, 'media')\n\t\tdeck.opc.contentTypes.ensureDefault(av.mediaExtn, av.mediaContentType)\n\t\tdeck.opc.addPart(mediaPartName, av.mediaContentType, av.mediaBytes)\n\t\tconst mediaTarget = relativePartName(partName, mediaPartName)\n\t\trels.addWithId(`rId${av.mediaRid}`, av.mtype === 'audio' ? AUDIO_REL : VIDEO_REL, mediaTarget)\n\t\trels.addWithId(`rId${av.msMediaRid}`, MS_MEDIA_REL, mediaTarget)\n\n\t\tconst previewPartName = deck.opc.reserveMediaPartName(av.previewExtn)\n\t\tdeck.opc.contentTypes.ensureDefault(av.previewExtn, av.previewContentType)\n\t\tdeck.opc.addPart(previewPartName, av.previewContentType, av.previewBytes)\n\t\trels.addWithId(`rId${av.previewRid}`, IMAGE_REL, relativePartName(partName, previewPartName))\n\t}\n}\n\n/**\n * Online (external-link) video: two External rels share the link Target — the ECMA video rel and\n * the MS-2007 media rel — with no media binary part and no content-type entry. The poster image is\n * wired by {@link wireMedia}, which runs first.\n */\nfunction wireOnlineMedia(rels: Relationships, slide: PlacedSlide['slide']): void {\n\tfor (const ov of slide.onlineMedia) {\n\t\trels.addWithId(`rId${ov.mediaRid}`, VIDEO_REL, ov.link, 'External')\n\t\trels.addWithId(`rId${ov.msMediaRid}`, MS_MEDIA_REL, ov.link, 'External')\n\t}\n}\n\n/** External hyperlink rels, each keeping the id the slide body references it by. */\nfunction wireHyperlinks(rels: Relationships, slide: PlacedSlide['slide']): void {\n\tfor (const h of slide.hyperlinks) {\n\t\trels.addWithId(`rId${h.rId}`, HYPERLINK_REL, h.target, 'External')\n\t}\n}\n\n/**\n * Speaker notes. The notes part carries its own rel namespace, independent of the slide's:\n * rId1 = notesMaster, rId2 = the slide it annotates, hyperlinks from rId3 — the order the\n * generator's body was serialized against, so these are added by explicit id rather than left to\n * auto-numbering.\n *\n * Creates the notes part only. The slide's own rel *to* it is named by no id in the slide body,\n * so {@link wireAutoIdRels} adds it once every id the body does name is claimed.\n * @returns the notes part's name, or `null` when the slide has no notes\n */\nfunction wireNotes(\n\tdeck: Presentation,\n\tpartName: string,\n\tslide: PlacedSlide['slide'],\n\tsourceNotesMaster: { xml: string; themeXml: string } | undefined | null\n): string | null {\n\tif (!slide.notes) return null\n\tconst notesMasterPartName = sourceNotesMaster ? ensureNotesMasterFromXml(deck, sourceNotesMaster) : null\n\tconst notesPartName = addNotesSlidePart(deck, slide.notes.xml, partName, notesMasterPartName)\n\tconst notesRels = deck.opc.relationshipsFor(notesPartName)\n\tfor (const h of slide.notes.hyperlinks) {\n\t\tnotesRels.addWithId(`rId${h.rId}`, HYPERLINK_REL, h.target, 'External')\n\t}\n\treturn notesPartName\n}\n\n/**\n * Chart part + its embedded workbook, each under a fresh name. Both chart flavours reference the\n * workbook through the chart part's own rId1, so the chart `.rels` is rebuilt here against the\n * reserved workbook partname.\n *\n * A chartEx chart differs in every other coordinate: the `chartEx{N}.xml` name family, the MS\n * chartex content type, the MS `chartEx` rel off the slide, and two mandatory sidecars at\n * rId2/rId3 — without which PowerPoint reports the deck as corrupt (schema-valid but unopenable).\n * `c.chartEx` carries both sidecar bodies; the generator built them, so nothing here reaches into\n * the emitters.\n */\nfunction wireCharts(deck: Presentation, rels: Relationships, partName: string, slide: PlacedSlide['slide']): void {\n\tfor (const c of slide.charts) {\n\t\tconst isChartEx = c.chartEx !== undefined\n\t\tconst chartPartName = deck.opc.reservePartNameLike(\n\t\t\tisChartEx ? '/ppt/charts/chartEx1.xml' : '/ppt/charts/chart1.xml'\n\t\t)\n\t\tdeck.opc.addPart(\n\t\t\tchartPartName,\n\t\t\tisChartEx ? CHARTEX_CONTENT_TYPE : CHART_CONTENT_TYPE,\n\t\t\ttextEncoder.encode(c.chartXml)\n\t\t)\n\t\tconst embeddingPartName = deck.opc.reservePartNameLike('/ppt/embeddings/Microsoft_Excel_Worksheet1.xlsx')\n\t\tdeck.opc.contentTypes.ensureDefault('xlsx', XLSX_CONTENT_TYPE)\n\t\tdeck.opc.addPart(embeddingPartName, XLSX_CONTENT_TYPE, c.embeddingBytes)\n\t\tconst chartRels = deck.opc.relationshipsFor(chartPartName)\n\t\tchartRels.addWithId('rId1', PACKAGE_REL, relativePartName(chartPartName, embeddingPartName))\n\t\tif (c.chartEx) {\n\t\t\t// rId2 = colors, rId3 = style: the order the write path authors\n\t\t\t// (`buildChartExRelsXml` in gen/chart/embed-xlsx.ts).\n\t\t\tconst colorsPartName = deck.opc.reservePartNameLike('/ppt/charts/colors1.xml')\n\t\t\tdeck.opc.addPart(colorsPartName, CHART_COLOR_STYLE_CONTENT_TYPE, textEncoder.encode(c.chartEx.colorsXml))\n\t\t\tchartRels.addWithId('rId2', CHART_COLOR_STYLE_REL, relativePartName(chartPartName, colorsPartName))\n\n\t\t\tconst stylePartName = deck.opc.reservePartNameLike('/ppt/charts/style1.xml')\n\t\t\tdeck.opc.addPart(stylePartName, CHART_STYLE_CONTENT_TYPE, textEncoder.encode(c.chartEx.styleXml))\n\t\t\tchartRels.addWithId('rId3', CHART_STYLE_REL, relativePartName(chartPartName, stylePartName))\n\t\t}\n\t\trels.addWithId(`rId${c.rId}`, isChartEx ? CHARTEX_REL : CHART_REL, relativePartName(partName, chartPartName))\n\t}\n}\n\n/**\n * Intra-batch slide-to-slide links: a `slide:N` in the source is repointed at the Nth appended\n * slide's new partname, which is why pass 1 places every slide before any of this runs. A link out\n * of the batch was refused before pass 1 by {@link requireLinksInBatch}.\n */\nfunction wireSlideLinks(\n\trels: Relationships,\n\tpartName: string,\n\tslide: PlacedSlide['slide'],\n\tpartBySourceNumber: Map<number, string>,\n\tindex: number\n): void {\n\tfor (const link of slide.slideLinks) {\n\t\tconst targetPartName = partBySourceNumber.get(link.sourceSlideNumber)\n\t\tif (!targetPartName) {\n\t\t\tthrow new InternalError(\n\t\t\t\t'import/slide-link-not-placed',\n\t\t\t\t`appendSlides: slide ${index} links to source slide ${link.sourceSlideNumber}, which was checked against the batch but has no appended slide`\n\t\t\t)\n\t\t}\n\t\trels.addWithId(`rId${link.rId}`, SLIDE_REL, relativePartName(partName, targetPartName))\n\t}\n}\n\n/**\n * Refuse a batch holding a slide link to a source slide the batch does not append. It has no\n * counterpart to point at, and finding that while wiring meant the slides ahead of it were already\n * in the deck.\n */\nfunction requireLinksInBatch(slides: readonly PlacedSlide['slide'][]): void {\n\tslides.forEach((slide, index) => {\n\t\tfor (const link of slide.slideLinks) {\n\t\t\tif (link.sourceSlideNumber > slides.length) {\n\t\t\t\tthrow new InvalidOptionError(\n\t\t\t\t\t'import/unresolved-slide-link',\n\t\t\t\t\t`appendSlides: slide ${index} links to source slide ${link.sourceSlideNumber}, which is not among the appended slides`\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t})\n}\n\n/**\n * The first of pass 2's two phases: every rel the slide body names by id — media, embedded and\n * online media, hyperlinks, charts, slide links — each added with the rId the generator wrote.\n * Also creates the notes part, whose own rels are fixed ids too.\n *\n * A new rel the body references by id belongs here, and nowhere after {@link wireAutoIdRels}.\n * @returns the notes part's name, or `null` when the slide has no notes\n */\nfunction wireFixedIdRels(\n\tdeck: Presentation,\n\trels: Relationships,\n\tplaced: PlacedSlide,\n\tsourceNotesMaster: { xml: string; themeXml: string } | undefined | null,\n\tpartBySourceNumber: Map<number, string>,\n\tindex: number\n): string | null {\n\tconst { slide, partName } = placed\n\twireMedia(deck, rels, partName, slide)\n\twireAvMedia(deck, rels, partName, slide)\n\twireOnlineMedia(rels, slide)\n\twireHyperlinks(rels, slide)\n\tconst notesPartName = wireNotes(deck, partName, slide, sourceNotesMaster)\n\twireCharts(deck, rels, partName, slide)\n\twireSlideLinks(rels, partName, slide, partBySourceNumber, index)\n\treturn notesPartName\n}\n\n/**\n * The second phase: the rels the slide body names by no id — its notes and its layout — numbered\n * by `add()`, which takes one past the highest id present.\n *\n * Strictly after {@link wireFixedIdRels}. The generator numbers a slide's rels from rId1, so an\n * auto id taken before a fixed one is claimed is routinely that fixed one: the notes rel used to\n * be added in the middle of the first phase, and a slide carrying notes and a chart or a slide\n * link threw `relationship/duplicate-id`.\n */\nfunction wireAutoIdRels(\n\trels: Relationships,\n\tpartName: string,\n\tnotesPartName: string | null,\n\tlayoutPartName: string\n): void {\n\tif (notesPartName) rels.add(NOTES_SLIDE_REL, relativePartName(partName, notesPartName))\n\trels.add(SLIDE_LAYOUT_REL, relativePartName(partName, layoutPartName))\n}\n\n/**\n * Append a slide producer's slides onto `deck`. The caller-facing contract is the doc comment on\n * {@link Presentation.appendSlides}.\n */\nexport async function appendSlides(\n\tdeck: Presentation,\n\tsource: SlideSource,\n\toptions: AppendSlidesOptions\n): Promise<Slide[]> {\n\t// 1. Resolve the target layout partname (explicit; no silent fallback).\n\tconst target = resolveLayoutTarget(deck, options.layout)\n\n\t// 2. Author + extract; enforce equal slide size (no geometry rescale in v1).\n\tconst extracted = await source.extractSlides(pickDefined(options, ['onMediaError']))\n\t// The extracted size is always known, so it is lifted into a `SlideSize` rather than kept\n\t// as a loose pair — that is what let this call site keep a second formatter alive.\n\trequireEqualSlideSize(\n\t\tdeck.slideSize,\n\t\t{\n\t\t\twidthEmu: extracted.widthEmu,\n\t\t\theightEmu: extracted.heightEmu,\n\t\t\twidthIn: emuToInches(extracted.widthEmu),\n\t\t\theightIn: emuToInches(extracted.heightEmu),\n\t\t},\n\t\t'appendSlides'\n\t)\n\t// Everything below adds to the deck as it goes, so whatever can refuse the batch is asked first.\n\trequireLinksInBatch(extracted.slides)\n\tif (!deck.presentationPart.dom.documentElement) {\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 insert slides into'\n\t\t)\n\t}\n\n\t// Any existing slide partname seeds the fresh-partname family; fall back to a\n\t// literal seed for a slide-less template shell (reservePartNameLike parses the\n\t// string, it does not require the part to exist).\n\tconst slideTemplate = deck.slides[0]?.partName ?? '/ppt/slides/slide1.xml'\n\n\t// Pass 1: reserve + add every slide body first, so internal slide-to-slide\n\t// links (which may point forward) can resolve to any appended slide. Adding\n\t// each part immediately claims its name — reservePartNameLike returns max+1\n\t// from the existing parts, so the next reservation sees it. (addPart registers\n\t// the slide's Override content type.)\n\tconst placed: PlacedSlide[] = extracted.slides.map((slide) => {\n\t\tconst partName = deck.opc.reservePartNameLike(slideTemplate)\n\t\tconst part = deck.opc.addPart(partName, SLIDE_CONTENT_TYPE, textEncoder.encode(slide.xml))\n\t\treturn { slide, part, partName }\n\t})\n\n\t// 1-based source slide number -> the appended slide's new partname.\n\tconst partBySourceNumber = new Map<number, string>(placed.map((p, i) => [i + 1, p.partName]))\n\n\t// Pass 2: build each slide's .rels and wire it into presentation.xml. Every rel the body\n\t// names by id first, then the ones it does not, so an auto id cannot land on a fixed one.\n\tconst added: Slide[] = []\n\tplaced.forEach((placedSlide, i) => {\n\t\tconst rels = deck.opc.relationshipsFor(placedSlide.partName)\n\t\tconst notesPartName = wireFixedIdRels(deck, rels, placedSlide, extracted.notesMaster, partBySourceNumber, i)\n\t\twireAutoIdRels(rels, placedSlide.partName, notesPartName, target.partName)\n\n\t\t// Wire into presentation.xml (rel + p:sldId) at the requested position.\n\t\tconst at = options.at === undefined ? undefined : options.at + i\n\t\tadded.push(deck.insertSlidePart(placedSlide.part, at))\n\t})\n\n\t// Carry the generator's presentation-level embedded fonts (pptx.embedFont) into\n\t// this deck, so author-side embedded fonts survive the append onto a template.\n\tcarryGeneratedEmbeddedFonts(deck, extracted.embeddedFonts || [])\n\n\treturn added\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 type { Element } from '@xmldom/xmldom'\nimport type { Relationships } from '../../opc/relationships.js'\nimport type { Presentation } from '../presentation.js'\nimport { OOXML_NS } from '../../../ooxml/namespaces.js'\nimport { descendantsByTag } from '../../oxml/dom.js'\nimport { SHARED_PARTS } from '../../../ooxml/rel-types.js'\n\n/**\n * Content types that are shared deck chrome, not owned by any one slide: the `deck` rows of\n * {@link SHARED_PARTS}, reached through the presentation → master → layout → theme graph or named\n * by every comment part. {@link Presentation.removeSlide} never prunes these as a removed slide's\n * orphan, even while momentarily unreferenced.\n */\nconst SHARED_CHROME_CONTENT_TYPES: ReadonlySet<string> = new Set(\n\tSHARED_PARTS.flatMap((kind) => (kind.scope === 'deck' && kind.contentType !== null ? [kind.contentType] : []))\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 * @returns every partname removed, `partName` first when it was\n */\nexport function pruneIfOrphan(pres: Presentation, partName: string): string[] {\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(partName)\n\tconst removed = [partName]\n\tfor (const child of childTargets) removed.push(...pruneIfOrphan(pres, child))\n\treturn removed\n}\n\n/** A part that still held a relationship to a removed part, and whether it was unlinked. */\nexport interface InboundLink {\n\t/** The part holding the relationship, or `/` for the package root. */\n\treadonly referrer: string\n\t/** `true` when the relationship and the link elements naming it were removed; `false` when it was kept. */\n\treadonly unlinked: boolean\n}\n\n/**\n * Unlink what still points at `partName`, a part that has left the package, where that can be done\n * without leaving markup behind that names a relationship which is gone.\n *\n * A relationship left pointing at the removed name dangles, and the next part given that name\n * silently becomes its target. Removing only the relationship is worse: PowerPoint refuses a\n * package whose `a:hlinkClick` names an `r:id` the part does not hold. So a relationship is\n * removed when nothing but click and hover links name it, and those links go with it; the run or\n * shape carrying them stays. A relationship any other element names is kept, because that element\n * cannot be dropped the same way. A custom show's `p:sld` is not one of them: removing a slide\n * drops it first ({@link dropFromShowsAndSections}).\n *\n * Dropping the links is a deliberate departure from PowerPoint, which keeps a jump link to a\n * deleted slide and, once it renumbers the slides, lets it jump to whichever slide takes the\n * deleted one's part name (`test/read/fixtures/slide-jump-link-target-deleted.pptx`).\n * @returns each part that held such a relationship, in package order\n */\nexport function unlinkInbound(pres: Presentation, partName: string): InboundLink[] {\n\tconst found: InboundLink[] = []\n\tfor (const owner of relationshipOwners(pres)) {\n\t\tconst rels = pres.opc.relationshipsFor(owner)\n\t\tconst inbound = [...rels].filter((rel) => rel.targetMode !== 'External' && rels.resolveTarget(rel.id) === partName)\n\t\tif (inbound.length === 0) continue\n\t\tconst part = owner === '/' ? undefined : pres.opc.part(owner)\n\t\tconst root = part?.isXmlPart ? part.dom.documentElement : null\n\t\tlet unlinked = root !== null\n\t\tfor (const rel of inbound) {\n\t\t\tconst references = root ? elementsNamingRel(root, rel.id) : []\n\t\t\tif (!root || !references.every(isLinkElement)) {\n\t\t\t\tunlinked = false\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfor (const element of references) element.parentNode?.removeChild(element)\n\t\t\tif (references.length > 0) part?.markDirty()\n\t\t\trels.remove(rel.id)\n\t\t}\n\t\tfound.push({ referrer: owner, unlinked })\n\t}\n\treturn found\n}\n\n/**\n * Take a slide that is leaving the package out of the presentation's custom shows and sections.\n *\n * PowerPoint does this when a slide is deleted: the slide's `p:sld` leaves every custom show and\n * its `p14:sldId` leaves every section, and a show or section left empty stays\n * (`test/read/fixtures/slide-jump-link-target-deleted.pptx`). Call it while the presentation's\n * relationships still resolve to the slide. A relationship nothing names once the entries are gone\n * is removed here, so {@link unlinkInbound} does not report it as a reference it had to keep.\n * @param root - the presentation part's root element\n * @param rels - the presentation part's relationships\n * @param partName - the slide leaving the package\n * @param slideId - its `p:sldId/@id`\n * @returns whether anything was removed\n */\nexport function dropFromShowsAndSections(\n\troot: Element,\n\trels: Relationships,\n\tpartName: string,\n\tslideId: number | null\n): boolean {\n\tconst toSlide = new Set(\n\t\t[...rels]\n\t\t\t.filter((rel) => rel.targetMode !== 'External' && rels.resolveTarget(rel.id) === partName)\n\t\t\t.map((rel) => rel.id)\n\t)\n\tlet changed = false\n\tfor (const sld of descendantsByTag(root, OOXML_NS.p, 'sld')) {\n\t\tif (!toSlide.has(sld.getAttributeNS(OOXML_NS.r, 'id') ?? '')) continue\n\t\tsld.parentNode?.removeChild(sld)\n\t\tchanged = true\n\t}\n\tif (slideId !== null) {\n\t\tfor (const sldId of descendantsByTag(root, OOXML_NS.p14, 'sldId')) {\n\t\t\tif (sldId.getAttribute('id') !== String(slideId)) continue\n\t\t\tsldId.parentNode?.removeChild(sldId)\n\t\t\tchanged = true\n\t\t}\n\t}\n\tif (changed) {\n\t\tfor (const relId of toSlide) if (elementsNamingRel(root, relId).length === 0) rels.remove(relId)\n\t}\n\treturn changed\n}\n\n/** Link elements that can be dropped with the relationship they name, leaving their run or shape intact. */\nconst LINK_ELEMENTS: ReadonlySet<string> = new Set(['hlinkClick', 'hlinkMouseOver'])\n\nfunction isLinkElement(element: Element): boolean {\n\treturn element.namespaceURI === OOXML_NS.a && LINK_ELEMENTS.has(element.localName ?? '')\n}\n\n/** Every element under `root`, `root` included, with an attribute in the relationships namespace naming `relId`. */\nfunction elementsNamingRel(root: Element, relId: string): Element[] {\n\tconst out: Element[] = []\n\tfor (const element of [root, ...descendantsByTag(root, '*', '*')]) {\n\t\tfor (let i = 0; i < element.attributes.length; i++) {\n\t\t\tconst attribute = element.attributes[i]\n\t\t\tif (attribute?.namespaceURI === OOXML_NS.r && attribute.value === relId) {\n\t\t\t\tout.push(element)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn out\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 relationshipOwners(pres)) {\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/** Every partname that can own relationships: each part that is not itself a `.rels` part, and the package root. */\nfunction relationshipOwners(pres: Presentation): string[] {\n\treturn [...[...pres.opc.parts.keys()].filter((partName) => !partName.endsWith('.rels')), '/']\n}\n","/**\n * What a deck remembers between imports, and the one place that forgets it.\n *\n * Two memos outlive any one import call. The copy registry maps each source package's partnames to\n * the partnames their copies were given here, so a second import from the same source reuses the\n * layout, master, theme and media it already brought across. The rescale memo holds the parts whose\n * geometry a rescale has already rewritten, and in which mode, so a layout or master shared by\n * several imports is scaled once and never asked to take a second, different scaling.\n *\n * Both hold destination partnames, and removing a slide frees names that `reservePartNameLike`\n * hands out again. An entry left behind then answers for a part that is no longer there: the\n * registry calls a deleted slide or image already copied, and the rescale memo calls a new slide\n * already scaled. So both live behind one object whose {@link ImportMemo.forget} is how a part\n * leaves the deck's import state, and a memo added here has to answer to it.\n */\n\nimport type { OpcPackage } from '../../opc/package.js'\nimport type { RescaleMode } from './rescale.js'\n\nexport class ImportMemo {\n\treadonly #registries = new Map<OpcPackage, Map<string, string>>()\n\treadonly #rescaled = new Map<string, RescaleMode>()\n\n\t/** The copy registry for imports out of `source`: source partname → destination partname. */\n\tregistryFor(source: OpcPackage): Map<string, string> {\n\t\tlet registry = this.#registries.get(source)\n\t\tif (!registry) {\n\t\t\tregistry = new Map()\n\t\t\tthis.#registries.set(source, registry)\n\t\t}\n\t\treturn registry\n\t}\n\n\t/** Destination partname → the mode a rescale rewrote its geometry in, as a live map the rescale adds to. */\n\tget rescaledParts(): Map<string, RescaleMode> {\n\t\treturn this.#rescaled\n\t}\n\n\t/** Drop every entry naming one of `partNames`, which have left the deck. */\n\tforget(partNames: Iterable<string>): void {\n\t\tconst gone = new Set(partNames)\n\t\tfor (const registry of this.#registries.values()) {\n\t\t\tfor (const [sourcePartName, destPartName] of registry) {\n\t\t\t\tif (gone.has(destPartName)) registry.delete(sourcePartName)\n\t\t\t}\n\t\t}\n\t\tfor (const partName of gone) this.#rescaled.delete(partName)\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 * A shape that is not a placeholder takes the same properties from the presentation's\n * `p:defaultTextStyle` instead, which the rebind swaps for the destination's, so those\n * are baked from the source one. A table cell's text takes its size from the master's\n * `p:otherStyle`, and its weight too where the table style states none, so those are\n * baked from the source master.\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\tboolAttr,\n\tchildElements,\n\tcreateElement,\n\tdescendantsByTag,\n\tfirstChild,\n\tfirstChildElement,\n\tgetElements,\n\tgetOrAddChild,\n\tinsertInOrder,\n\tnumberAttr,\n\tnumberValue,\n\townerDocumentOf,\n\tremoveChildrenByQName,\n\tsetAttr,\n\ttype Element,\n} from '../../oxml/dom.js'\nimport { hasFillChoice } from '../../oxml/fill.js'\nimport {\n\tLST_STYLE_LEVELS,\n\tRUN_PROP_NAMES,\n\tlstStyleLevelDefRPr,\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\ttype ColorContext,\n\tfmtEntry,\n\tisA,\n\treplaceColorElement,\n\tresolveColor,\n\ttype ResolvedColorRef,\n\tresolveSchemeToken,\n\tstyleRefFill,\n\tstyleRefLine,\n\tsubstitutePhClr,\n\ttype ThemeContext,\n} from '../../oxml/theme.js'\nimport {\n\tCSLD_AFTER_BG,\n\tLN_SLOTS,\n\tRPR_FILL_AFTER,\n\tRUN_AFTER_RPR,\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\tTXBODY_AFTER_BODYPR,\n\tTXBODY_AFTER_LSTSTYLE,\n} from '../../../ooxml/sequence.js'\nimport { THEME_COLOR_SLOTS } from '../../../ooxml/st-enums.js'\nimport { cSldOf, nvPrOf } from '../../oxml/slide-dom.js'\nimport { resolveTableCellTextStyle, type TableConditionFlags } from '../table-style-resolve.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\t/**\n\t * The *source* deck's `a:tblStyleLst` (`tableStyles.xml`), or `null` when it has none. A table\n\t * cell's bold and italic come from its table style before `p:otherStyle`, so the cell-text bake\n\t * has to know what the style states to leave it the last word.\n\t */\n\ttableStyles?: 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, each other\n * shape's run the ones it takes from the source `p:defaultTextStyle`, and each\n * table cell's run the ones it takes from the source `p:otherStyle`;\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\tresolveDefaultTextStyleRuns(slideRoot, ctx)\n\tresolveTableCellRuns(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\tresolveDefaultTextStyleRuns(shapeRoot, ctx)\n\tresolveTableCellRuns(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\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\t// Routed through the source clrMap; dk1/lt1/… are themselves valid tokens.\n\t\treplaceColorElement(srgb, 'a:schemeClr', tokenBySlot.get(slot) ?? slot)\n\t}\n}\n\n/** Reverse a slot → RGB `clrScheme` into RGB → slot, in `THEME_COLOR_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 THEME_COLOR_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, CSLD_AFTER_BG)\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\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\treplaceColorElement(schemeClr, 'a:srgbClr', hex)\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 */\n/**\n * Visit every placeholder shape in a lifted subtree that has a text body, with the two\n * identifiers each pass resolves inheritance against.\n *\n * The preamble is the same for all three of them: nothing to inherit *from* when neither a\n * layout nor a master came across, a `p:sp` without a `p:ph` is not a placeholder, and one\n * without a `p:txBody` has no text to inherit anything for. It was written out three times,\n * which is one more than the file's own {@link bakePlaceholderRunProperty} was already\n * generalising over.\n *\n * @param shapeRoot - the root of the lifted subtree\n * @param ctx - the flatten context, carrying the source layout/master roots\n * @param visit - called per placeholder with its text body, `p:ph/@type` and `@idx`\n */\nfunction forEachPlaceholderTextBody(\n\tshapeRoot: Element,\n\tctx: FlattenContext,\n\tvisit: (txBody: Element, type: string | null, idx: string) => void\n): 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\tvisit(txBody, attr(ph, 'type'), attr(ph, 'idx') ?? '0')\n\t}\n}\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\tforEachPlaceholderTextBody(slideRoot, ctx, (txBody, type, idx) => {\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 && numberValue(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: ResolvedColorRef): void {\n\tconst doc = ownerDocumentOf(run)\n\tconst rPr = getOrAddChild(run, 'a:rPr', RUN_AFTER_RPR)\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\tforEachPlaceholderTextBody(shapeRoot, ctx, (txBody, type, idx) => {\n\t\tconst bodyPr = firstChild(txBody, 'a:bodyPr')\n\t\tif (bodyPr && attr(bodyPr, 'anchor') != null) return // slide fixes it — not inherited\n\t\tconst anchor = placeholderInheritedAnchor(type, idx, ctx)\n\t\tif (!anchor) return\n\t\tsetAttr(bodyPr ?? getOrAddChild(txBody, 'a:bodyPr', TXBODY_AFTER_BODYPR), '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\tforEachPlaceholderTextBody(shapeRoot, ctx, (txBody, type, idx) => {\n\t\tconst tiers = placeholderInheritedListStyles(type, idx, ctx)\n\t\tif (tiers.length === 0) return\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) return\n\t\tif (slideLst) txBody.replaceChild(merged, slideLst)\n\t\telse insertInOrder(txBody, merged, TXBODY_AFTER_LSTSTYLE)\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/**\n * Bake what the runs of a shape that is not a placeholder take from the source `p:defaultTextStyle`:\n * size, bold, italic and colour, per paragraph level, wherever the run, its paragraph and its text\n * body state none of them.\n *\n * Rebinding swaps the presentation's default text style for the destination's along with everything\n * else, so without this a plain text box from a deck with an 18pt default turns 28pt in a deck with\n * a 28pt one. PowerPoint's Keep Source Formatting paste writes the same values onto the runs\n * (`test/read/fixtures/authoring/probe-default-text-style-paste.ps1`).\n *\n * A colour is left alone where the shape's `p:style/a:fontRef` names one, since that tier sits above\n * this one and travels with the shape. Placeholders are left to the placeholder passes: they resolve\n * through their layout and master, and the measurement covered plain shapes only. Typeface\n * re-binds here as it does for every other tier. A table cell's text is not a `p:sp` run and\n * resolves through the master's `p:otherStyle` instead, which {@link resolveTableCellRuns} bakes.\n */\nfunction resolveDefaultTextStyleRuns(root: Element, ctx: FlattenContext): void {\n\tconst defaults = ctx.defaultTextStyle\n\tif (!defaults) return\n\tfor (const sp of descendantsByTag(root, OOXML_NS.p, 'sp')) {\n\t\tif (placeholderOf(sp)) continue\n\t\tconst txBody = firstChild(sp, 'p:txBody')\n\t\tif (!txBody) continue\n\t\tconst style = firstChild(sp, 'p:style')\n\t\tconst fontRef = style && firstChild(style, 'a:fontRef')\n\t\tconst colorFromFontRef = !!(fontRef && firstChildElement(fontRef))\n\t\tconst slideLst = firstChild(txBody, 'a:lstStyle')\n\t\tfor (const p of getElements(txBody, 'a:p')) {\n\t\t\tconst runs = [...getElements(p, 'a:r'), ...getElements(p, 'a:fld')]\n\t\t\tif (runs.length === 0) continue\n\t\t\tconst pPr = firstChild(p, 'a:pPr')\n\t\t\tconst level = (pPr && numberValue(attr(pPr, 'lvl'))) ?? 0\n\t\t\tconst defRPr = lstStyleLevelDefRPr(defaults, level)\n\t\t\tif (!defRPr) continue\n\t\t\tconst props = {} as RunProps\n\t\t\tfor (const name of RUN_PROP_NAMES) props[name] = attr(defRPr, name)\n\t\t\tconst fill = colorFromFontRef ? null : firstChild(defRPr, 'a:solidFill')\n\t\t\tconst color = fill ? resolveColor(firstChildElement(fill), ctx) : null\n\t\t\tfor (const run of runs) {\n\t\t\t\twriteRunProps(run, props, pPr, slideLst, level)\n\t\t\t\tif (color && !slideDefinesColor(run, pPr, slideLst, level)) writeRunColor(run, color)\n\t\t\t}\n\t\t}\n\t}\n}\n\n/**\n * Bake what a table cell's runs take from the source master's `p:otherStyle`: size, and bold and\n * italic where the cell's table style states neither, per paragraph level, wherever the run, its\n * paragraph and the cell's own list style state none of them.\n *\n * Cell text resolves through `p:otherStyle`, not `p:defaultTextStyle` (`TableCell.textFrame`), and\n * the rebind swaps the source master for the destination's, so without this a cell's text changes\n * size between two decks whose masters differ there. PowerPoint's Keep Source Formatting paste\n * writes nothing onto the cells; it keeps them on a copy of the source master instead\n * (`test/read/fixtures/authoring/probe-table-text-paste.ps1`), which is the look this pins.\n *\n * The table style travels with the slide, so what it states is left to it. Where the table names a\n * style the source does not define, a built-in PowerPoint draws from its own definition, and bold\n * and italic are left alone because what that style states is unknown. A cell's colour and face do\n * not come from `p:otherStyle` at all, so they are not visited.\n */\nfunction resolveTableCellRuns(root: Element, ctx: FlattenContext): void {\n\tconst txStyles = ctx.masterRoot ? firstChild(ctx.masterRoot, 'p:txStyles') : null\n\tconst otherStyle = txStyles && firstChild(txStyles, 'p:otherStyle')\n\tif (!otherStyle) return\n\tfor (const tbl of descendantsByTag(root, OOXML_NS.a, 'tbl')) {\n\t\tconst tblPr = firstChild(tbl, 'a:tblPr')\n\t\tconst idEl = tblPr && firstChild(tblPr, 'a:tableStyleId')\n\t\tconst styleId = idEl?.textContent?.trim() || null\n\t\tconst style = styleId ? sourceTableStyle(ctx, styleId) : null\n\t\tconst styleUnknown = styleId !== null && style === null\n\t\tconst flag = (name: keyof TableConditionFlags) => (tblPr ? boolAttr(tblPr, name) === true : false)\n\t\tconst flags: TableConditionFlags = {\n\t\t\tfirstRow: flag('firstRow'),\n\t\t\tlastRow: flag('lastRow'),\n\t\t\tfirstCol: flag('firstCol'),\n\t\t\tlastCol: flag('lastCol'),\n\t\t\tbandRow: flag('bandRow'),\n\t\t\tbandCol: flag('bandCol'),\n\t\t}\n\t\tconst rows = getElements(tbl, 'a:tr')\n\t\tconst grid = firstChild(tbl, 'a:tblGrid')\n\t\tconst colCount = grid ? getElements(grid, 'a:gridCol').length : 0\n\t\trows.forEach((tr, rowIndex) => {\n\t\t\tgetElements(tr, 'a:tc').forEach((tc, colIndex) => {\n\t\t\t\tconst txBody = firstChild(tc, 'a:txBody')\n\t\t\t\tif (!txBody) return\n\t\t\t\tconst styled = style\n\t\t\t\t\t? resolveTableCellTextStyle(style, flags, rowIndex, colIndex, rows.length, colCount, ctx)\n\t\t\t\t\t: null\n\t\t\t\tconst cellLst = firstChild(txBody, 'a:lstStyle')\n\t\t\t\tfor (const p of getElements(txBody, 'a:p')) {\n\t\t\t\t\tconst runs = [...getElements(p, 'a:r'), ...getElements(p, 'a:fld')]\n\t\t\t\t\tif (runs.length === 0) continue\n\t\t\t\t\tconst pPr = firstChild(p, 'a:pPr')\n\t\t\t\t\tconst level = (pPr && numberValue(attr(pPr, 'lvl'))) ?? 0\n\t\t\t\t\tconst defRPr = lstStyleLevelDefRPr(otherStyle, level)\n\t\t\t\t\tif (!defRPr) continue\n\t\t\t\t\tconst props: RunProps = {\n\t\t\t\t\t\tsz: attr(defRPr, 'sz'),\n\t\t\t\t\t\tb: styleUnknown || styled?.bold != null ? null : attr(defRPr, 'b'),\n\t\t\t\t\t\ti: styleUnknown || styled?.italic != null ? null : attr(defRPr, 'i'),\n\t\t\t\t\t}\n\t\t\t\t\tfor (const run of runs) writeRunProps(run, props, pPr, cellLst, level)\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\n/** The source deck's `a:tblStyle` with this id, or `null` when the source defines none. */\nfunction sourceTableStyle(ctx: FlattenContext, styleId: string): Element | null {\n\tif (!ctx.tableStyles) return null\n\treturn getElements(ctx.tableStyles, 'a:tblStyle').find((st) => attr(st, 'styleId') === styleId) ?? null\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', RUN_AFTER_RPR)\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 (!hasFillChoice(spPr)) {\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\tconst styleLn = styleRefLine(lnRef, ctx)\n\tif (styleLn) {\n\t\tconst own = firstChild(spPr, 'a:ln')\n\t\tif (own) mergeStyleLine(own, styleLn)\n\t\telse insertInOrder(spPr, styleLn, SPPR_LN_AFTER)\n\t}\n\tneutralizeRef(lnRef)\n}\n\n/**\n * Fill in what a shape's own `a:ln` leaves unstated from the style line its `lnRef` names.\n *\n * PowerPoint layers the two one property at a time: changing only an outline's weight writes\n * `<a:ln w=\"76200\"/>` and still paints the style's colour, dash and join\n * (`test/read/fixtures/shape-line-style-override.pptx`). So the own line is not a replacement,\n * and neutralizing the ref without this merge would drop everything the shape never stated.\n */\nfunction mergeStyleLine(own: Element, style: Element): void {\n\tfor (const name of ['w', 'cap', 'cmpd', 'algn']) {\n\t\tconst value = attr(style, name)\n\t\tif (value !== null && attr(own, name) === null) setAttr(own, name, value)\n\t}\n\tLN_SLOTS.forEach((slot, index) => {\n\t\tif (slot.some((qname) => firstChild(own, qname))) return\n\t\tconst inherited = slot.map((qname) => firstChild(style, qname)).find((child) => child !== null)\n\t\tif (inherited) insertInOrder(own, inherited, LN_SLOTS.slice(index + 1).flat())\n\t})\n}\n\nfunction materializeEffect(spPr: Element, effectRef: Element | null, ctx: FlattenContext): void {\n\tif (!effectRef) return\n\tconst idx = numberAttr(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 * 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: Pick<Relationships, 'add'>,\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: Pick<Relationships, 'add'>,\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 * 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 type { Element } from '../../oxml/dom.js'\nimport type { OpcPackage } from '../../opc/package.js'\nimport type { FlattenContext } from './flatten.js'\nimport { resolveSlideColorContext, resolveSlideThemeParts } from '../theme-context.js'\nimport { backgroundElementOf } from '../slide-background.js'\nimport { TABLE_STYLES_CONTENT_TYPE } from '../../../ooxml/rel-types.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: the colour context the slide's read-model\n * getters resolve against, built from one slide → layout → master → theme walk, plus the\n * background the slide inherits.\n *\n * The presentation's default text style rides along, because a run in a shape that is not a\n * placeholder inherits its size, weight and colour from it, and the rebind would hand that run the\n * destination's instead. The flatten pass bakes those values onto the run. The source table styles\n * ride along for the same bake in table cells, which must leave what a table style states to it.\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\tconst parts = resolveSlideThemeParts(sourceOpc, slidePartName)\n\tconst ctx = resolveSlideColorContext(sourceOpc, parts)\n\treturn {\n\t\t...ctx,\n\t\tinheritedBackground: effectiveBackground(sourceOpc, parts.slideRoot, parts.layoutPartName, parts.masterPartName),\n\t\ttableStyles: sourceOpc.partsByContentType(TABLE_STYLES_CONTENT_TYPE)[0]?.dom.documentElement ?? null,\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'\nimport { TABLE_STYLES_CONTENT_TYPE, TABLE_STYLES_REL } from '../../../ooxml/rel-types.js'\nimport { XML_DECL } from '../../../ooxml/xml-decl.js'\n\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_DECL}\\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 * 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 { InternalError, PackageReadError, InvalidOptionError } from '../../../errors.js'\nimport { flattenSlide, remapLiteralColors, restyleSlide } from './flatten.js'\nimport { resolveSlideThemeParts } from '../theme-context.js'\nimport {\n\tcarriedDecorations,\n\tfirstShapeChild,\n\tnextDrawingId,\n\treassignDrawingIds,\n\tspTreeOf,\n} from '../../oxml/slide-dom.js'\nimport { copySourceTableStyles } from './table-styles.js'\nimport { copyTarget, newOwnedScope, rebuildRels, type ImportContext, type OwnedScope } from './part-copy.js'\nimport type { Presentation } from '../presentation.js'\nimport type { Slide } from '../slide.js'\nimport { SLIDE_LAYOUT_REL, SLIDE_MASTER_REL } from '../../../ooxml/rel-types.js'\nimport { layoutPartNamesOf, resolveSingleRel, slideMasterPartNames } 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 { newPartName, slideRoot } = rebind(dest, ctx, source, sourceSlide, carryGraphics)\n\tconst newPart = dest.opc.part(newPartName)\n\tif (!newPart) throw new InternalError('import/part-went-missing', `Imported slide part went missing: ${newPartName}`)\n\treturn { newPartName, slideRoot, newPart }\n}\n\n/**\n * The rebind run as a plan (`ctx.plan` set): what {@link importSlideRebind} would copy and what it\n * would throw, with nothing written. Returns the partname the page would be given.\n * @param {Presentation} dest - the destination deck\n * @param {ImportContext} ctx - the plan's context for the 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} the partname the new slide part would be given\n */\nexport function planSlideRebind(\n\tdest: Presentation,\n\tctx: ImportContext,\n\tsource: Presentation,\n\tsourceSlide: Slide,\n\tcarryGraphics: boolean\n): string {\n\treturn rebind(dest, ctx, source, sourceSlide, carryGraphics).newPartName\n}\n\n/** {@link importSlideRebind}'s body, which a plan runs too. */\nfunction rebind(\n\tdest: Presentation,\n\tctx: ImportContext,\n\tsource: Presentation,\n\tsourceSlide: Slide,\n\tcarryGraphics: boolean\n): { newPartName: string; slideRoot: Element } {\n\tconst destLayout = destinationLayoutPartName(dest)\n\n\t// Copy the slide's current body into a fresh partname; we then mutate that copy's DOM\n\t// (a distinct document, so the source package is never touched). A plan adds no part, so\n\t// it reads the source's root instead: the same bytes, and nothing is written to them.\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 target = copyTarget(ctx)\n\tconst newPartName = target.reservePartNameLike(sourceSlide.partName)\n\ttarget.addPart(newPartName, sourcePart.contentType, sourcePart.serialize())\n\tconst slideRoot = (ctx.plan ? sourcePart : dest.opc.part(newPartName))?.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// This page is built here rather than by `copyPart`, so it is entered in the copy registry\n\t// here too, before its relationships are followed, as `copyPart` records a page before\n\t// recursing. Otherwise a jump link from the page to itself is a registry miss, and `copyPart`\n\t// materializes the source page a second time, as a slide part no `p:sldIdLst` lists.\n\tctx.registry.set(sourceSlide.partName, newPartName)\n\n\t// Rebuild the slide's relationships: notes are dropped and every other internal target\n\t// (media, charts) is copied as for any page, but the layout is this deck's own.\n\t// Its ownership scope is opened here for the same reason: the chart or diagram under a\n\t// page rebound twice must not be the same part twice (see `page-owned.ts`).\n\tconst owned = newOwnedScope()\n\trebuildRels(ctx, {\n\t\tsource: sourcePart,\n\t\tnewPartName,\n\t\towned,\n\t\t// These are the page's own relationships, so a target the destination already\n\t\t// holds byte-for-byte is bound to rather than copied (see `part-reuse.ts`).\n\t\tallowReuse: true,\n\t\toverride: (rel) => (rel.type === SLIDE_LAYOUT_REL ? { target: destLayout } : undefined),\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(ctx, slideRoot, newPartName, sourceSlide.partName, owned)\n\n\treturn { newPartName, slideRoot }\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 *\n * A plan carries a throwaway copy of each decoration, so rewriting its references writes to\n * neither package, and inserts nothing: `slideRoot` is then the source slide's own.\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\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 = copyTarget(ctx).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// A decoration's source id means nothing on this slide and routinely equals one of the slide's\n\t// own, which leaves an animation `spid` or a connector binding naming two shapes. Each part's\n\t// set is renumbered past everything already on the slide.\n\tlet nextId = nextDrawingId(slideRoot)\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\tconst carried = decorations.map((deco) => {\n\t\t\tconst imported = ctx.plan ? (deco.cloneNode(true) as Element) : doc.importNode(deco, true)\n\t\t\trewriteCarriedRels(imported, ctx, sourceRels, newPartName, slideRels, relIdMap, owned)\n\t\t\tif (!ctx.plan) spTree.insertBefore(imported, anchor)\n\t\t\treturn imported\n\t\t})\n\t\tif (!ctx.plan) nextId = reassignDrawingIds(carried, nextId).next\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\t// \"First\" in id-list order, which is the deck's gallery order. The order a `.rels` file lists\n\t// its relationships in carries no meaning, and took `slideLayout8` over `slideLayout1` on\n\t// PowerPoint-authored decks, and an appended master over one a primary graft had put first.\n\tconst [masterPartName] = slideMasterPartNames(dest)\n\tif (!masterPartName)\n\t\tthrow new InvalidOptionError(\n\t\t\t'import/destination-missing-master',\n\t\t\t\"importSlide with theme 'preserve' or 'restyle' requires a slide master in the destination deck\"\n\t\t)\n\tconst [layoutPartName] = layoutPartNamesOf(dest, masterPartName)\n\tif (!layoutPartName)\n\t\tthrow new InvalidOptionError(\n\t\t\t'import/destination-missing-layout',\n\t\t\t\"importSlide with theme 'preserve' or 'restyle' requires a slide layout in the destination deck\"\n\t\t)\n\treturn layoutPartName\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\tnumberValue,\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/** How an import's rescale maps the source canvas onto the destination's. */\nexport type RescaleMode = 'fit' | 'stretch'\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: RescaleMode): 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 = numberValue(attr(off, 'x'))\n\t\tconst y = numberValue(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 = numberValue(attr(ext, 'cx'))\n\t\tconst cy = numberValue(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 = numberValue(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 = numberValue(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 * 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 records the mode each part was rescaled in, because a\n * shared part can hold only one scaling: a later import asking for the other mode is refused\n * before it copies anything. The memo is owned by the calling `Presentation` and threaded through\n * here, so it lives as long as the deck does rather than as long as one call.\n */\n\nimport { computeRescale, rescaleSpTree, type RescaleMode, type RescaleTransform } from './rescale.js'\nimport { resolveSingleRel } from './part-index.js'\nimport type { ImportContext } from './part-copy.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'\nimport { InternalError, InvalidOptionError } from '../../../errors.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: Map<string, RescaleMode>,\n\tslidePartName: string,\n\ttheme: ImportSlideOptions['theme'],\n\tsource: SlideSize,\n\ttarget: SlideSize,\n\tmode: RescaleMode\n): void {\n\tconst transform = computeRescale(source, target, mode)\n\trescalePartGeometry(dest, rescaledParts, slidePartName, transform, mode)\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, mode)\n\t\tif (master) rescalePartGeometry(dest, rescaledParts, master, transform, mode)\n\t}\n}\n\n/**\n * Refuse a `copy`-themed import whose rescale disagrees with the one an earlier import from the\n * same source already applied to the layout or master this import would share.\n *\n * A second import from a source reuses the layout and master the first one copied, and those were\n * rewritten in the first import's mode. Scaling them again in the other mode would move them under\n * the first import's page. Checked before anything is copied, through the copy registry that\n * decides the reuse, so a refusal leaves the deck as it was.\n * @param rescaledParts - the deck's rescale memo\n * @param ctx - the import's context, whose registry names what an earlier import copied\n * @param sourceSlidePartName - the source page being imported\n * @param mode - the mode this import rescales in\n * @param api - the public method, opening the error message\n */\nexport function requireRescaleAgrees(\n\trescaledParts: ReadonlyMap<string, RescaleMode>,\n\tctx: ImportContext,\n\tsourceSlidePartName: string,\n\tmode: RescaleMode,\n\tapi: string\n): void {\n\tconst layout = resolveSingleRel(ctx.source, sourceSlidePartName, SLIDE_LAYOUT_REL)\n\tconst master = layout ? resolveSingleRel(ctx.source, layout, SLIDE_MASTER_REL) : null\n\tfor (const sourcePartName of [layout, master]) {\n\t\tconst destPartName = sourcePartName ? ctx.registry.get(sourcePartName) : undefined\n\t\tconst applied = destPartName === undefined ? undefined : rescaledParts.get(destPartName)\n\t\tif (applied !== undefined && applied !== mode) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/rescale-conflict',\n\t\t\t\t`${api}: ${destPartName} was rescaled with ${JSON.stringify(applied)} by an earlier import from this source, and this import asks for ${JSON.stringify(mode)}`\n\t\t\t)\n\t\t}\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: Map<string, RescaleMode>,\n\tpartName: string,\n\ttransform: RescaleTransform,\n\tmode: RescaleMode\n): void {\n\tconst applied = rescaledParts.get(partName)\n\tif (applied === mode) return\n\tif (applied !== undefined) {\n\t\tthrow new InternalError(\n\t\t\t'import/rescale-mode-changed',\n\t\t\t`${partName} was rescaled with ${JSON.stringify(applied)} and is now asked for ${JSON.stringify(mode)}; the import should have been refused before it copied anything`\n\t\t)\n\t}\n\trescaledParts.set(partName, mode)\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 * ts-pptx: Presentation import entry points\n *\n * The four ways a `Presentation` takes content out of another open package: one page\n * ({@link importSlide}), a batch of pages ({@link importSlides}), a master with its layout\n * family ({@link importSlideMasters}), and shapes ({@link importShape} / {@link importShapes}).\n * Each is the body of the same-named `Presentation` method, which keeps the public contract in\n * its doc comment and delegates here -- so the class reads as its own table of contents and one\n * feature's internals stop outnumbering the read model's surface.\n *\n * These are free functions taking the destination deck, the shape every module in `ops/`\n * already has. The difference, and the cost of this split, is that they are not independent of\n * `Presentation` the way an `ops/` module is: three things they need stay on the class and are\n * reached back through its `@internal` accessors. `insertSlidePart` stays because\n * `cloneSlide` and `appendSlides` wire slides in through it too. `importContext` and\n * `rescaledParts` stay for a different reason -- both are memos that must outlive any one\n * call, which is what makes a second import from the same source reuse what it already copied\n * and stops a shared layout being scaled twice. Neither reason is removable by moving more\n * code, so three `#private` members were widened into an internal API. Paid deliberately: the\n * coupling was already there, and naming it here is what keeps it visible.\n */\n\nimport type { OpcPackage } from '../opc/package.js'\nimport { createElement, firstChild, type Element } from '../oxml/dom.js'\nimport { cSldName, nthShapeChild, reassignDrawingIds } from '../oxml/slide-dom.js'\nimport { InternalError, InvalidOptionError, PackageReadError, UnsupportedFeatureError } from '../../errors.js'\nimport { carryShapeAnimations } from './animation.js'\nimport { checkFiniteEmu, checkPositiveEmu } from './coords.js'\nimport { flattenShape } from './ops/flatten.js'\nimport { wrapShapeElement, type AnyShape } from './shapes.js'\nimport type { Presentation } from './presentation.js'\nimport type { Slide } from './slide.js'\nimport type {\n\tImportShapeOptions,\n\tImportSlideMastersOptions,\n\tImportSlideOptions,\n\tImportSlidesRequest,\n\tImportedSlideMaster,\n} from './presentation-types.js'\nimport { rewriteCarriedRels } from './ops/carried-rels.js'\nimport { carryEmbeddedFonts, checkEmbeddedFontsCopyable } from './ops/embedded-fonts.js'\nimport { sourceFlattenContext } from './ops/flatten-context.js'\nimport { importSlidePreserve, importSlideRestyle, planSlideRebind } from './ops/import-slide.js'\nimport { promoteMasters } from './ops/master-registry.js'\nimport { carryNotes } from './ops/notes-master.js'\nimport { layoutPartNamesOf, slideMasterPartNames } from './ops/part-index.js'\nimport {\n\tcopyPart,\n\tCopyPlan,\n\tcopySlidePart,\n\tnewOwnedScope,\n\ttype CopyTarget,\n\ttype ImportContext,\n} from './ops/part-copy.js'\nimport { resolveSlideThemeParts } from './theme-context.js'\nimport { computeRescale, rescaleSpTree, type RescaleTransform } from './ops/rescale.js'\nimport { requireRescaleAgrees, rescaleImportedGeometry } from './ops/rescale-import.js'\nimport { requireEqualSlideSize, requireKnownSlideSizes, slideSizesMatch } from './ops/slide-size.js'\nimport { carryTableStyles } from './ops/table-styles.js'\n\n/** Body of {@link Presentation.importSlide}, whose doc comment carries the contract. */\nexport function importSlide(\n\tdeck: Presentation,\n\tsource: Presentation,\n\tindex: number,\n\toptions: ImportSlideOptions = {}\n): Slide {\n\tconst sourceSlide = source.slides[index]\n\tif (!sourceSlide) throw new InvalidOptionError('slide/index-out-of-range', `No slide at index ${index} to import`)\n\n\t// 1. Pre-flight: slide sizes must match unless the caller opts into a rescale. Either way\n\t// both decks have to declare one — a rescale cannot be computed from a size that is\n\t// not there, and neither can a comparison.\n\tconst target = deck.slideSize\n\tconst incoming = source.slideSize\n\tif (options.rescale) requireKnownSlideSizes(target, incoming, 'importSlide rescale')\n\telse requireEqualSlideSize(target, incoming, 'importSlide', \"pass { rescale: 'fit' | 'stretch' } to rescale\")\n\tconst sizesDiffer = !slideSizesMatch(target, incoming)\n\t// A copy reuses the layout and master an earlier import from this source brought, so it may not\n\t// rescale them in the other mode.\n\tif (sizesDiffer && options.rescale && (options.theme === undefined || options.theme === 'copy')) {\n\t\trequireRescaleAgrees(\n\t\t\tdeck.rescaledParts,\n\t\t\tdeck.importContext(source.opc),\n\t\t\tsourceSlide.partName,\n\t\t\toptions.rescale === true ? 'fit' : options.rescale,\n\t\t\t'importSlide'\n\t\t)\n\t}\n\n\t// 1b. Dry-run the copy of this one page, reading only the source, before anything here moves:\n\t// steps 2 and 4 run as a plan. A jump link to a page this import does not bring is refused\n\t// with the code `importSlides` uses, where the copy used to follow the link and leave the\n\t// target page in the package listed nowhere. A source part that is missing or will not\n\t// parse throws here too, rather than after the deck is half changed.\n\tplanSlideImport(deck, source, sourceSlide, options)\n\tconst importCtx = deck.importContext(source.opc)\n\t// The font carry runs last, after the slide is already in the deck, so its dry run belongs\n\t// here too.\n\tif (options.embedFonts) checkEmbeddedFontsCopyable(source, 'importSlide')\n\n\t// 2. Copy the slide and its dependencies. 'preserve' flattens the theme into\n\t// the slide and attaches it to this deck's master; 'restyle' attaches it\n\t// to this deck's master with theme refs left symbolic (re-brand); 'copy'\n\t// brings the source theme subgraph across wholesale.\n\tconst newPartName =\n\t\toptions.theme === 'preserve'\n\t\t\t? importSlidePreserve(deck, importCtx, source, sourceSlide, options.carryMasterGraphics === true)\n\t\t\t: options.theme === 'restyle'\n\t\t\t\t? importSlideRestyle(\n\t\t\t\t\t\tdeck,\n\t\t\t\t\t\timportCtx,\n\t\t\t\t\t\tsource,\n\t\t\t\t\t\tsourceSlide,\n\t\t\t\t\t\toptions.carryMasterGraphics === true,\n\t\t\t\t\t\toptions.remapLiterals === true\n\t\t\t\t\t)\n\t\t\t\t: copySlidePart(importCtx, sourceSlide.partName)\n\tconst newPart = deck.opc.part(newPartName)\n\tif (!newPart) throw new InternalError('import/part-went-missing', `Imported slide part went missing: ${newPartName}`)\n\n\t// 2b. Rescale the imported geometry to this deck's canvas when sizes differ.\n\tif (sizesDiffer && options.rescale && target && incoming) {\n\t\trescaleImportedGeometry(\n\t\t\tdeck,\n\t\t\tdeck.rescaledParts,\n\t\t\tnewPartName,\n\t\t\toptions.theme,\n\t\t\tincoming,\n\t\t\ttarget,\n\t\t\toptions.rescale === true ? 'fit' : options.rescale\n\t\t)\n\t}\n\n\t// 3. Wire the new slide into the presentation (rel + p:sldId entry) at `at`.\n\tconst slide = deck.insertSlidePart(newPart, options.at)\n\n\t// 4. Optionally carry the source slide's speaker notes. The slide copy above\n\t// drops the notesSlide rel (both copyPart and importSlideRebind do); this\n\t// re-adds it wired to the new slide and merged onto a single notesMaster.\n\tif (options.importNotes) carryNotes(deck, source, importCtx, sourceSlide.partName, newPartName)\n\n\t// 5. Optionally carry the source deck's embedded fonts (presentation-level, so\n\t// a separate traversal from the slide-part copy chain above).\n\tif (options.embedFonts) carryEmbeddedFonts(deck, source, importCtx)\n\n\treturn slide\n}\n\n/** Body of {@link Presentation.importSlides}, whose doc comment carries the contract. */\nexport function importSlides(deck: Presentation, requests: readonly ImportSlidesRequest[]): Slide[] {\n\t// 1. Validate everything up front: indexes exist, selections and output\n\t// positions are unique, sizes match. No part is touched until all pass.\n\tconst resolved = requests.map((request, requestIndex) => {\n\t\tif (!Number.isInteger(request.sourceIndex) || request.sourceIndex < 0) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'slide/index-out-of-range',\n\t\t\t\t`importSlides: sourceIndex must be a non-negative integer; received ${request.sourceIndex}`\n\t\t\t)\n\t\t}\n\t\tif (!Number.isInteger(request.outputIndex) || request.outputIndex < 0) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/output-index-out-of-range',\n\t\t\t\t`importSlides: outputIndex must be a non-negative integer; received ${request.outputIndex}`\n\t\t\t)\n\t\t}\n\t\tconst sourceSlide = request.source.slides[request.sourceIndex]\n\t\tif (!sourceSlide) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'slide/index-out-of-range',\n\t\t\t\t`importSlides: no slide at index ${request.sourceIndex} to import`\n\t\t\t)\n\t\t}\n\t\treturn { ...request, requestIndex, sourceSlide }\n\t})\n\tif (resolved.length === 0) return []\n\n\t// Step 4 inserts into this element; failing on it here rather than there\n\t// keeps the wiring loop, like the copy, unable to stop half-way.\n\tif (!deck.presentationPart.dom.documentElement) {\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 insert slides into'\n\t\t)\n\t}\n\n\tconst finalSlideCount = deck.slides.length + resolved.length\n\t// `fontSources` and `rescaleBySource` are the two deck-level options wearing a\n\t// per-request spelling, reconciled here so the copy below reads one answer per\n\t// source rather than re-deciding per page.\n\tconst fontSources = new Map<OpcPackage, Presentation>()\n\tconst rescaleBySource = new Map<OpcPackage, 'fit' | 'stretch' | false>()\n\tfor (const request of resolved) {\n\t\tif (request.embedFonts) fontSources.set(request.source.opc, request.source)\n\t\t// A rescale rewrites the shared imported layout and master as well as the\n\t\t// page, so the requests naming one source have to agree on it: rescaling one\n\t\t// of a source's pages and not another would leave the second aligned against\n\t\t// a master that moved under it. Normalized first, so `true` and `'fit'` are\n\t\t// the same answer rather than a conflict.\n\t\tconst rescale = request.rescale === true ? 'fit' : (request.rescale ?? false)\n\t\tconst agreed = rescaleBySource.get(request.source.opc)\n\t\tif (agreed !== undefined && agreed !== rescale) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/rescale-conflict',\n\t\t\t\t`importSlides: requests from one source must agree on \\`rescale\\`; got ${JSON.stringify(agreed)} and ${JSON.stringify(rescale)}`\n\t\t\t)\n\t\t}\n\t\trescaleBySource.set(request.source.opc, rescale)\n\t}\n\n\tconst target = deck.slideSize\n\tconst outputIndexes = new Set<number>()\n\tfor (const request of resolved) {\n\t\tif (request.outputIndex >= finalSlideCount) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/output-index-out-of-range',\n\t\t\t\t`importSlides: outputIndex ${request.outputIndex} is outside the final slide list of ${finalSlideCount} slides`\n\t\t\t)\n\t\t}\n\t\tif (outputIndexes.has(request.outputIndex)) {\n\t\t\tthrow new InvalidOptionError(\n\t\t\t\t'import/output-index-conflict',\n\t\t\t\t`importSlides: outputIndex ${request.outputIndex} is requested more than once`\n\t\t\t)\n\t\t}\n\t\toutputIndexes.add(request.outputIndex)\n\t\t// A rescale needs both sizes known but not equal; without one they must match,\n\t\t// and the hint names the spelling that answers the mismatch.\n\t\tif (rescaleBySource.get(request.source.opc))\n\t\t\trequireKnownSlideSizes(target, request.source.slideSize, 'importSlides rescale')\n\t\telse\n\t\t\trequireEqualSlideSize(\n\t\t\t\ttarget,\n\t\t\t\trequest.source.slideSize,\n\t\t\t\t'importSlides',\n\t\t\t\t\"pass { rescale: 'fit' | 'stretch' } on the request to rescale\"\n\t\t\t)\n\t}\n\n\t// Requests that agree with each other may still disagree with an earlier call from the same\n\t// source, whose rescale already moved the layout and master this batch would reuse.\n\tfor (const request of resolved) {\n\t\tconst mode = rescaleBySource.get(request.source.opc)\n\t\tif (!mode || slideSizesMatch(target, request.source.slideSize)) continue\n\t\trequireRescaleAgrees(\n\t\t\tdeck.rescaledParts,\n\t\t\tdeck.importContext(request.source.opc),\n\t\t\trequest.sourceSlide.partName,\n\t\t\tmode,\n\t\t\t'importSlides'\n\t\t)\n\t}\n\n\t// 1b. Dry-run the copy against every source, still reading only source\n\t// packages: steps 2 to 3b, run as a plan (see `copyBatch`). Every part the\n\t// traversal will reach exists and parses, no selected page links outside\n\t// the selection, and the notes asked for can be carried. Once this passes\n\t// the copy below has no reachable throw, which is what lets a rejected\n\t// batch leave this deck byte-identical instead of half-stitched.\n\tcopyBatch(deck, resolved, new CopyPlan(deck, 'importSlides'))\n\t// The font carry runs after the copy and reaches parts the page graph never\n\t// touches, so it gets its own dry run for the same reason the notes do.\n\tfor (const source of fontSources.values()) checkEmbeddedFontsCopyable(source)\n\n\t// 2–3b. Materialize each request's output page, copy the pages with their\n\t// dependencies, and carry the notes that were asked for.\n\tconst planned = copyBatch(deck, resolved).map((request) => {\n\t\tconst destPart = deck.opc.part(request.destPartName)\n\t\tif (!destPart)\n\t\t\tthrow new InternalError('import/part-went-missing', `Imported slide part went missing: ${request.destPartName}`)\n\t\treturn { ...request, destPart }\n\t})\n\n\t// 3c. Rescale each rescaling source's pages onto this deck's canvas. Nothing\n\t// to do where the sizes already match, and the memo makes the shared layout\n\t// and master — which `'copy'` semantics rescale alongside the page — move\n\t// exactly once however many of that source's pages the batch brought over.\n\tfor (const request of planned) {\n\t\tconst mode = rescaleBySource.get(request.source.opc)\n\t\tif (!mode) continue\n\t\tconst incoming = request.source.slideSize\n\t\tif (!target || !incoming || slideSizesMatch(target, incoming)) continue\n\t\trescaleImportedGeometry(deck, deck.rescaledParts, request.destPart.partName, 'copy', incoming, target, mode)\n\t}\n\n\t// 3d. Carry the embedded fonts of every source that asked, once per source. A\n\t// face this deck already embeds is reused rather than duplicated, and the\n\t// binaries come across through the same per-source registry the pages used,\n\t// so a repeated import copies each face once.\n\tfor (const [sourceOpc, source] of fontSources) {\n\t\tcarryEmbeddedFonts(deck, source, deck.importContext(sourceOpc))\n\t}\n\n\t// 4. Wire into p:sldIdLst at each requested final position. Ascending order\n\t// makes the raw final index the correct insertion point at every step:\n\t// earlier inserts all sit before it, so they shift it by exactly the\n\t// number of entries the final position already counts. The result is\n\t// written back by request index, so `result[i]` is `requests[i]`'s page\n\t// whatever order the positions were given in.\n\tconst added: Slide[] = []\n\tfor (const request of [...planned].sort((left, right) => left.outputIndex - right.outputIndex)) {\n\t\tadded[request.requestIndex] = deck.insertSlidePart(request.destPart, request.outputIndex)\n\t}\n\treturn added\n}\n\n/**\n * The copy {@link importSlide} makes, run as a {@link CopyPlan}: its steps 2 and 4 with nothing\n * written. Throws what the copy would throw, which is why `importSlide` calls it before anything\n * moves.\n * @param deck - the deck the page would land in\n * @param source - the deck the page comes from\n * @param sourceSlide - the page\n * @param options - the import's options\n * @returns the plan, listing the parts the import would add\n */\nexport function planSlideImport(\n\tdeck: Presentation,\n\tsource: Presentation,\n\tsourceSlide: Slide,\n\toptions: ImportSlideOptions = {}\n): CopyPlan {\n\t// The page the import builds is the whole selection a jump link may land on.\n\tconst plan = new CopyPlan(deck, 'importSlide', new Set([sourceSlide.partName]))\n\tconst ctx = plan.contextFor(deck.importContext(source.opc))\n\tlet newPartName: string\n\tif (options.theme === 'preserve' || options.theme === 'restyle') {\n\t\t// A restyle that remaps literals reads the source theme chain after the rebind has written,\n\t\t// so read it now: a part there that will not parse is refused first. `preserve` reads the\n\t\t// same chain before it writes anything.\n\t\tif (options.theme === 'restyle' && options.remapLiterals) resolveSlideThemeParts(source.opc, sourceSlide.partName)\n\t\tnewPartName = planSlideRebind(deck, ctx, source, sourceSlide, options.carryMasterGraphics === true)\n\t} else {\n\t\tnewPartName = copySlidePart(ctx, sourceSlide.partName)\n\t}\n\tif (options.importNotes) carryNotes(deck, source, ctx, sourceSlide.partName, newPartName)\n\treturn plan\n}\n\n/**\n * Steps 2 to 3b of {@link importSlides}: materialize each request's output page, copy each source's\n * selected pages with their dependency subgraphs, and carry the notes of the pages that asked.\n * Returns each request with the partname of its output page.\n *\n * `importSlides` runs it twice, first as a {@link CopyPlan}, which is the batch's dry run, and then\n * for real, so the dry run is this code rather than a transcription of it.\n * @param deck - the deck the batch lands in\n * @param requests - the batch, each request resolved to its source page\n * @param plan - plan instead of copying: nothing in `deck` is written\n * @returns each request with its output page's partname\n */\nexport function copyBatch<R extends ImportSlidesRequest & { readonly sourceSlide: Slide }>(\n\tdeck: Presentation,\n\trequests: readonly R[],\n\tplan?: CopyPlan\n): Array<R & { destPartName: string }> {\n\tconst target: CopyTarget = plan ?? deck.opc\n\tconst contextFor = (opc: OpcPackage): ImportContext =>\n\t\tplan ? plan.contextFor(deck.importContext(opc)) : deck.importContext(opc)\n\n\t// 2. Materialize each request's output page now, so the copy traversals can\n\t// wire slide→slide relationships to their pre-allocated destinations.\n\t// One request is one output page, so a source page asked for twice gets\n\t// two reservations, in request order.\n\t// The reservation list is typed non-empty, so round 0 needs no fallback.\n\tconst destinationsBySource = new Map<OpcPackage, Map<string, [string, ...string[]]>>()\n\tconst placed = requests.map((request) => {\n\t\tlet destinations = destinationsBySource.get(request.source.opc)\n\t\tif (!destinations) {\n\t\t\tdestinations = new Map()\n\t\t\tdestinationsBySource.set(request.source.opc, destinations)\n\t\t}\n\t\tconst sourcePart = request.sourceSlide.part\n\t\tconst destPartName = target.reservePartNameLike(request.sourceSlide.partName)\n\t\ttarget.addPart(destPartName, sourcePart.contentType, sourcePart.serialize())\n\t\tconst reserved = destinations.get(request.sourceSlide.partName)\n\t\tif (reserved) reserved.push(destPartName)\n\t\telse destinations.set(request.sourceSlide.partName, [destPartName])\n\t\treturn { ...request, destPartName }\n\t})\n\n\t// 3. Copy each selected page and its dependency subgraph (theme/master/\n\t// layout/media/…), with links constrained to the selection.\n\t//\n\t// `copyPart`'s selection holds one destination per source page, so a page\n\t// requested N times is copied in N rounds: round K materializes every\n\t// page that has a Kth reservation, and names each other page's *first*\n\t// copy so a jump link out of the round still lands on a page of this\n\t// batch. A page duplicated alongside another therefore links to its\n\t// round-mate, and a link into a single-copy page resolves to that one\n\t// copy from every round. Rounds after the first re-materialize only the\n\t// pages they name: everything else is a registry hit `copyPart` returns\n\t// unchanged.\n\tfor (const [sourceOpc, destinations] of destinationsBySource) {\n\t\tconst base = contextFor(sourceOpc)\n\t\tconst rounds = Math.max(...[...destinations.values()].map((reserved) => reserved.length))\n\t\tfor (let round = 0; round < rounds; round++) {\n\t\t\tconst roundDestinations = new Map<string, string>()\n\t\t\tfor (const [sourcePartName, reserved] of destinations)\n\t\t\t\troundDestinations.set(sourcePartName, reserved[round] ?? reserved[0])\n\t\t\tconst ctx: ImportContext = { ...base, selection: { destinations: roundDestinations } }\n\t\t\tfor (const [sourcePartName, reserved] of destinations) {\n\t\t\t\tif (round < reserved.length) void copyPart(ctx, sourcePartName)\n\t\t\t}\n\t\t}\n\t}\n\n\t// 3b. Carry the notes of the pages that asked for them, in request order, so\n\t// the deck's single notesMaster comes from the first such page. The copy\n\t// above dropped every notesSlide rel, so this is the only thing that\n\t// re-adds one, and a page named twice gets a notes part per copy.\n\tfor (const request of placed) {\n\t\tif (!request.importNotes) continue\n\t\tcarryNotes(deck, request.source, contextFor(request.source.opc), request.sourceSlide.partName, request.destPartName)\n\t}\n\treturn placed\n}\n\n/** Body of {@link Presentation.importSlideMasters}, whose doc comment carries the contract. */\nexport function importSlideMasters(\n\tdeck: Presentation,\n\tsource: Presentation,\n\toptions: ImportSlideMastersOptions = {}\n): ImportedSlideMaster[] {\n\tif (options.requireEqualSize !== false) {\n\t\trequireEqualSlideSize(\n\t\t\tdeck.slideSize,\n\t\t\tsource.slideSize,\n\t\t\t'importSlideMasters',\n\t\t\t'pass { requireEqualSize: false } to override'\n\t\t)\n\t}\n\n\t// The font carry runs after the masters and layouts are copied, so a face it cannot copy is\n\t// found now, before anything is.\n\tif (options.embedFonts) checkEmbeddedFontsCopyable(source, 'importSlideMasters')\n\n\tconst pickMaster = options.masters ?? (() => true)\n\tconst pickLayout = options.layouts ?? (() => true)\n\n\t// What to import is decided once, so the caller's filters run once per master and layout and the\n\t// dry run below walks exactly what the copy does.\n\tconst selected = slideMasterPartNames(source).flatMap((masterPartName, masterIndex) => {\n\t\tif (!pickMaster(cSldName(source.opc.part(masterPartName)), masterIndex)) return []\n\t\tconst layouts = layoutPartNamesOf(source, masterPartName).filter((layoutPartName, layoutIndex) =>\n\t\t\tpickLayout(cSldName(source.opc.part(layoutPartName)), layoutIndex)\n\t\t)\n\t\treturn [{ masterPartName, layouts }]\n\t})\n\n\t// The copy registers each master in presentation.xml before its layouts come across, so a layout\n\t// or theme part missing from the source would leave a registered master holding part of its\n\t// family. Run it as a plan first, which throws what the copy would and writes nothing.\n\tconst ctx = deck.importContext(source.opc)\n\tconst planned = new CopyPlan(deck, 'importSlideMasters').contextFor(ctx)\n\tfor (const { masterPartName, layouts } of selected) {\n\t\tcopyPart(planned, masterPartName)\n\t\tfor (const layoutPartName of layouts) copyPart(planned, layoutPartName)\n\t}\n\n\t// Copy the (lean) master first: copyPart registers it in p:sldMasterIdLst\n\t// and clears its layout list, then each copied layout re-links itself in.\n\tconst imported: ImportedSlideMaster[] = selected.map(({ masterPartName, layouts }) => ({\n\t\tpartName: copyPart(ctx, masterPartName),\n\t\tlayoutPartNames: layouts.map((layoutPartName) => copyPart(ctx, layoutPartName)),\n\t}))\n\n\t// Optionally carry the source deck's presentation-level styling parts. Both are\n\t// separate traversals from the master/layout copy chain above, and both are\n\t// whole-deck: neither part records which font/style belongs to which master.\n\tif (options.embedFonts) carryEmbeddedFonts(deck, source, deck.importContext(source.opc))\n\tif (options.tableStyles) carryTableStyles(deck, source.opc)\n\tif (options.primary)\n\t\tpromoteMasters(\n\t\t\tdeck,\n\t\t\timported.map((m) => m.partName)\n\t\t)\n\n\treturn imported\n}\n\n/** Body of {@link Presentation.importShape}, whose doc comment carries the contract. */\nexport function importShape(\n\tdeck: Presentation,\n\ttarget: Slide,\n\tsource: Slide,\n\tshapeIndex: number,\n\toptions: ImportShapeOptions = {}\n): AnyShape {\n\tconst [shape] = importShapes(deck, target, source, [shapeIndex], options)\n\tif (!shape)\n\t\tthrow new InvalidOptionError(\n\t\t\t'shape/index-out-of-range',\n\t\t\t`importShape: source slide has no shape at index ${shapeIndex}`\n\t\t)\n\treturn shape\n}\n\n/** Body of {@link Presentation.importShapes}, whose doc comment carries the contract. */\nexport function importShapes(\n\tdeck: Presentation,\n\ttarget: Slide,\n\tsource: Slide,\n\tshapeIndices: number[],\n\toptions: ImportShapeOptions = {}\n): AnyShape[] {\n\tif (target.presentation !== deck)\n\t\tthrow new InvalidOptionError('slide/foreign-target', 'importShape: target slide must belong to deck presentation')\n\n\t// Pre-flight: slide sizes must match unless { rescale } opts into scaling the\n\t// lifted geometry onto this canvas (computed once, applied per shape below).\n\tconst targetSize = deck.slideSize\n\tconst sourceSize = source.presentation.slideSize\n\tlet transform: RescaleTransform | null = null\n\tif (!slideSizesMatch(targetSize, sourceSize)) {\n\t\tif (!options.rescale) requireEqualSlideSize(targetSize, sourceSize, 'importShape', 'or { rescale }')\n\t\tconst [known, incoming] = requireKnownSlideSizes(targetSize, sourceSize, 'importShape rescale')\n\t\ttransform = computeRescale(incoming, known, options.rescale === 'stretch' ? 'stretch' : 'fit')\n\t}\n\n\t// Resolve + validate every index up front so a bad batch throws before mutating.\n\tconst sourceShapes = source.shapes\n\tconst sourceElements = shapeIndices.map((i) => {\n\t\tconst shape = sourceShapes[i]\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`No shape at index ${i} on the source slide (it has ${sourceShapes.length})`\n\t\t\t)\n\t\treturn shape.element_\n\t})\n\t// The position options are applied once a shape is already in the tree, so a value their\n\t// setters refuse is refused here instead, before anything moves.\n\tif (options.left != null) checkFiniteEmu(options.left, 'x')\n\tif (options.top != null) checkFiniteEmu(options.top, 'y')\n\tif (options.width != null) checkPositiveEmu(options.width, 'cx')\n\tif (options.height != null) checkPositiveEmu(options.height, 'cy')\n\n\tconst spTree = target.shapeTree()\n\tif (!spTree)\n\t\tthrow new PackageReadError('slide/no-shape-tree', `importShape: target slide ${target.partName} has no shape tree`)\n\tconst targetDoc = spTree.ownerDocument\n\tif (!targetDoc)\n\t\tthrow new InternalError('oxml/node-has-no-document', 'importShape: target slide DOM has no owner document')\n\n\tconst theme = options.theme ?? 'preserve'\n\tconst sourceOpc = source.presentation.opc\n\tconst sourceRels = sourceOpc.relationshipsFor(source.partName)\n\tconst targetRels = deck.opc.relationshipsFor(target.partName)\n\t// One rel-id map across the batch so shapes sharing a source image share a rel.\n\tconst relIdMap = new Map<string, string>()\n\t// preserve: build the source theme context once; copy/restyle need none.\n\tconst ctx = theme === 'preserve' ? sourceFlattenContext(sourceOpc, source.partName) : null\n\tconst importCtx = deck.importContext(sourceOpc)\n\n\t// Carry every shape's relationships once as a plan, on a copy of the shape, before the first one\n\t// goes in: a source part that is missing or will not parse then refuses the whole call with the\n\t// host slide as it was, rather than after the shapes ahead of it were inserted.\n\tconst plan = new CopyPlan(deck, 'importShapes')\n\tconst planCtx = plan.contextFor(importCtx)\n\tconst plannedRels = plan.relationshipsFor(target.partName)\n\tconst plannedRelIds = new Map<string, string>()\n\tfor (const shapeEl of sourceElements) {\n\t\tconst copy = shapeEl.cloneNode(true) as Element\n\t\trewriteCarriedRels(copy, planCtx, sourceRels, target.partName, plannedRels, plannedRelIds, newOwnedScope())\n\t}\n\n\t// Anchor for z-order: the existing shape currently at `at` (insert before it,\n\t// preserving batch order), else append before any trailing p:extLst.\n\tconst extLst = firstChild(spTree, 'p:extLst')\n\tconst anchor = options.at == null ? extLst : (nthShapeChild(spTree, options.at) ?? extLst)\n\n\tconst result: AnyShape[] = []\n\t/** Source shape id → host id, across every shape this call carries. */\n\tconst carriedSpids = new Map<number, number>()\n\tfor (const shapeEl of sourceElements) {\n\t\tconst imported = targetDoc.importNode(shapeEl, true)\n\n\t\t// Drag media/charts/embeddings across and rewrite refs to fresh host rels.\n\t\t// A scope per shape: media are shared through `relIdMap`, but the chart or\n\t\t// diagram under this frame is its own — importing one chart shape twice must\n\t\t// not point both frames at one chart part (see `page-owned.ts`).\n\t\trewriteCarriedRels(imported, importCtx, sourceRels, target.partName, targetRels, relIdMap, newOwnedScope())\n\n\t\t// preserve: bake the source theme onto the subtree. The flatten passes match\n\t\t// descendants (not the root), so wrap the shape in a throwaway container.\n\t\tif (ctx) {\n\t\t\tconst holder = createElement(targetDoc, 'p:spTree')\n\t\t\tholder.appendChild(imported)\n\t\t\tflattenShape(holder, ctx)\n\t\t}\n\n\t\t// Rescale geometry onto this canvas (after flatten, so a placeholder's just-baked\n\t\t// inherited a:xfrm is scaled too). rescaleSpTree wants a p:spTree, so wrap the shape.\n\t\tif (transform) {\n\t\t\tconst holder = createElement(targetDoc, 'p:spTree')\n\t\t\tholder.appendChild(imported)\n\t\t\trescaleSpTree(holder, transform)\n\t\t}\n\n\t\t// Give the shape and any group children collision-free host ids and repoint the connector\n\t\t// bindings inside it, keeping the source id → new id map so a carried build animation can be\n\t\t// remapped onto it.\n\t\tconst { map: spidMap } = reassignDrawingIds([imported], target.nextShapeId())\n\t\tfor (const [sourceId, hostId] of spidMap) carriedSpids.set(sourceId, hostId)\n\n\t\t// Insert into the host tree (this reparents it out of any holder). The part is dirty from here,\n\t\t// so the saved bytes never disagree with a model that already shows the shape.\n\t\tspTree.insertBefore(imported, anchor)\n\t\ttarget.part.markDirty()\n\n\t\tconst shape = wrapShapeElement(imported, target)\n\t\tif (!shape)\n\t\t\tthrow new UnsupportedFeatureError(\n\t\t\t\t'shape/element-unsupported',\n\t\t\t\t`importShape: unsupported shape element <${imported.localName}>`\n\t\t\t)\n\t\tif (options.left != null) shape.left = options.left\n\t\tif (options.top != null) shape.top = options.top\n\t\tif (options.width != null) shape.width = options.width\n\t\tif (options.height != null) shape.height = options.height\n\t\tresult.push(shape)\n\t}\n\n\t// Carry the shapes' slide-scoped build animation (opt-in): append their effect click groups and\n\t// `p:bldP` entries into the destination timing, remapped to the new ids. Once for the whole call,\n\t// so a click group animating two of the carried shapes comes across once with both remapped,\n\t// rather than once per shape with the other's source id left in it.\n\tif (options.carryAnimation) {\n\t\tconst sourceRoot = source.part.dom.documentElement\n\t\tconst targetRoot = target.part.dom.documentElement\n\t\tif (sourceRoot && targetRoot) carryShapeAnimations(sourceRoot, targetRoot, carriedSpids)\n\t}\n\n\treturn result\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 *\n * The four import entry points went the same way, and {@link appendSlides} after them: their\n * contracts stay here as the doc comments a caller reads, and their bodies live in\n * `presentation-imports.ts` and `ops/append-slides.ts`. Those bodies are the one thing in this\n * directory that is not independent of this class — they reach back for {@link importContext},\n * {@link insertSlidePart} and {@link rescaledParts}, which {@link cloneSlide} reads too and so\n * could not travel with them. Those three are `@internal` for that and nothing else.\n */\nimport { emuToInches } from '../../units.js'\nimport { OpcPackage, type OpcInput } from '../opc/package.js'\nimport type { Part } from '../opc/part.js'\nimport { relativePartName } from '../opc/partnames.js'\nimport { attr, createElement, firstChild, getElements, getOrAddChild, numberValue, setAttr } from '../oxml/dom.js'\nimport { PRESENTATION_AFTER_SLD_ID_LST } from '../../ooxml/sequence.js'\nimport { MAX_SLIDE_ID, MIN_SLIDE_ID } from '../../ooxml/ids.js'\nimport { Slide } from './slide.js'\nimport { SlideMaster } from './chrome.js'\nimport type { AnyShape } from './shapes.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\treadExtendedProperties,\n\ttype CoreProperties,\n\ttype CustomProperty,\n\ttype ExtendedProperties,\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 } from '../oxml/slide-dom.js'\nimport { rebuildClonedPageRels, 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 { appendSlides as appendSlidesInto } from './ops/append-slides.js'\nimport { layoutPartNamesOf, slideMasterPartNames } from './ops/part-index.js'\nimport { readEmbeddedFontEntries } from './ops/embedded-fonts.js'\nimport { dropFromShowsAndSections, pruneIfOrphan, unlinkInbound } from './ops/prune.js'\nimport { ImportMemo } from './ops/import-memo.js'\nimport type { RescaleMode } from './ops/rescale.js'\nimport { OFFICE_DOCUMENT_REL, PRESENTATION_MAIN_CONTENT_TYPE, SLIDE_REL } from '../../ooxml/rel-types.js'\nimport { InternalError, InvalidOptionError, PackageReadError } from '../../errors.js'\nimport { warn } from '../../diagnostics.js'\nimport { presentationRels } from './ops/deck-target.js'\nimport {\n\timportShape as importShapeInto,\n\timportShapes as importShapesInto,\n\timportSlide as importSlideInto,\n\timportSlideMasters as importSlideMastersInto,\n\timportSlides as importSlidesInto,\n} from './presentation-imports.js'\n\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\nexport class Presentation {\n\t#presentationPart: Part | undefined\n\t/**\n\t * The import memos: the per-source copy registry that lets parts shared across imports from\n\t * one source deck (layout, master, theme, media) be copied once, and the parts a rescale has\n\t * already rewritten. {@link removeSlide} makes them forget the names it frees.\n\t */\n\treadonly #imports = new ImportMemo()\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, numberValue(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 = numberValue(attr(sldSz, 'cx'))\n\t\tconst heightEmu = numberValue(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\treturn readEmbeddedFontEntries(this).map(({ typeface, panose, faces }) => ({\n\t\t\ttypeface,\n\t\t\tpanose,\n\t\t\tfaces: faces.flatMap(({ slot, partName }) => (partName === null ? [] : [{ slot, partName }])),\n\t\t}))\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, read by\n\t * {@link modernCommentAuthors}.\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 extended document properties (`docProps/app.xml`): the producing\n\t * application and its version, the company, and the flat `TitlesOfParts` vector.\n\t * `{}` when the deck carries no extended-properties part. The read counterpart of\n\t * the write-side `pptx.company` setter — the only one of the four this library\n\t * writes from a caller's value; the other three it states about itself.\n\t *\n\t * A deliberate subset of the part: see {@link ExtendedProperties} for why the\n\t * statistics (`Slides`, `Words`, `Paragraphs`, …) are not reported.\n\t */\n\tget appProperties(): ExtendedProperties {\n\t\treturn readExtendedProperties(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's current body into a fresh slide partname, so an edit made\n\t\t// earlier in the session comes along.\n\t\tconst newPartName = opc.reservePartNameLike(sourcePart.partName)\n\t\tconst newPart = opc.addPart(newPartName, sourcePart.contentType, sourcePart.serialize())\n\n\t\t// 2. Give the clone the slide's relationships (targets resolve identically — same dir),\n\t\t// with copies of the parts the page owned and the shared ones left shared. Through\n\t\t// the live relationship set, not the `.rels` part bytes: a page this session\n\t\t// imported or edited holds its rels in memory until the deck is saved, and copying\n\t\t// the bytes gave such a clone no relationships at all — a slide whose `r:id`s\n\t\t// resolved to nothing.\n\t\trebuildClonedPageRels(this, sourcePart, newPartName)\n\n\t\t// 3. 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). The slide also\n\t * leaves every custom show and section it was in, which stay even when that\n\t * empties them, as PowerPoint leaves them.\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\t// Before the slide's relationship goes, while a custom show's entry still resolves to it.\n\t\tif (root) dropFromShowsAndSections(root, presRels, partName, slide.slideId)\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(partName)\n\t\tconst removed = [partName]\n\t\tfor (const target of formerTargets) removed.push(...pruneIfOrphan(this, target))\n\n\t\t// A jump link from another slide still names the removed part, whose name is free for the next\n\t\t// slide added. See `unlinkInbound` for which of those references can be removed.\n\t\tfor (const { referrer, unlinked } of unlinkInbound(this, partName)) {\n\t\t\twarn(\n\t\t\t\t'slide/removed-link-target',\n\t\t\t\tunlinked\n\t\t\t\t\t? `removeSlide: ${referrer} linked to ${partName}; the link was removed with the slide, and the text or shape that carried it stays`\n\t\t\t\t\t: `removeSlide: ${referrer} references ${partName} from markup that cannot drop the reference, so its relationship still names the removed slide and will resolve to the next part given that name`\n\t\t\t)\n\t\t}\n\n\t\t// The freed names are handed out again, so no import memo may keep answering for them.\n\t\tthis.#imports.forget(removed)\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 * By default the source slide size must equal this presentation's. Pass\n\t * `{ rescale: 'fit' | 'stretch' }` to rescale the imported geometry onto this\n\t * deck's canvas instead (geometry only, not fonts or line widths). Source notes\n\t * are dropped unless you pass `{ importNotes: true }`.\n\t *\n\t * A jump link on the page must land on a page an earlier import from the same source already\n\t * brought across, the rule {@link importSlides} applies to a batch: a link to any other page\n\t * throws `import/unresolved-slide-link`. Like that check, a missing or unparseable source part\n\t * is found before anything is copied, so a refused import leaves this deck unchanged.\n\t */\n\timportSlide(source: Presentation, index: number, options: ImportSlideOptions = {}): Slide {\n\t\treturn importSlideInto(this, source, index, options)\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 * `embedFonts` and `rescale` travel per request as well, and both are whole-deck\n\t * decisions wearing a per-page spelling, so the batch reconciles them before it\n\t * moves anything. A source deck's embedded fonts are carried once when *any* of\n\t * its requests asks for them (the list does not record which page uses which\n\t * face, so there is nothing finer to carry), and the font parts are part of the\n\t * up-front dry run like everything else. `rescale` must **agree** across every\n\t * request naming one source: a `'copy'` import rescales the imported layout and\n\t * master alongside the page, and those are shared, so a batch that rescaled one\n\t * page of a source and not another would leave the second bound to a rescaled\n\t * master. Disagreement is `import/rescale-conflict` rather than a silent pick.\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). There is\n\t * still no batch spelling for `theme`, `carryMasterGraphics` or `remapLiterals`;\n\t * use {@link importSlide} when you need one of those.\n\t */\n\timportSlides(requests: readonly ImportSlidesRequest[]): Slide[] {\n\t\treturn importSlidesInto(this, requests)\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}). Geometry is never rescaled: unlike\n\t * {@link importSlide}, {@link importSlides} and {@link importShape}, this method\n\t * takes no `rescale` option.\n\t */\n\timportSlideMasters(source: Presentation, options: ImportSlideMastersOptions = {}): ImportedSlideMaster[] {\n\t\treturn importSlideMastersInto(this, source, options)\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\treturn appendSlidesInto(this, source, options)\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\treturn importShapeInto(this, target, source, shapeIndex, options)\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\treturn importShapesInto(this, target, source, shapeIndices, options)\n\t}\n\n\t/**\n\t * @internal Wire a new slide part into `p:sldIdLst` at position `at`, as the private\n\t * method below does. Exposed for `presentation-imports.ts`; this one stays because\n\t * {@link cloneSlide} and {@link appendSlides} wire their slides in through it too.\n\t */\n\tinsertSlidePart(newPart: Part, at?: number): Slide {\n\t\treturn this.#insertSlidePart(newPart, at)\n\t}\n\n\t/**\n\t * @internal The parts whose geometry a rescale has already rewritten, and in which mode.\n\t * Exposed for `presentation-imports.ts` as a live map the callee adds to — the memo is what\n\t * makes a layout or master shared across repeated imports from one source scale exactly\n\t * once, so like the copy registry it has to outlive the call that fills it.\n\t */\n\tget rescaledParts(): Map<string, RescaleMode> {\n\t\treturn this.#imports.rescaledParts\n\t}\n\n\t/**\n\t * @internal Open an import out of `source`: this deck as the destination, paired with\n\t * the 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 — that is\n\t * what makes a second import from the same source reuse the layout, master, theme, and\n\t * media it already copied instead of duplicating them, and it is why the import bodies\n\t * in `presentation-imports.ts` call back here rather than carrying it with them.\n\t */\n\timportContext(source: OpcPackage): ImportContext {\n\t\treturn { dest: this, source, registry: this.#imports.registryFor(source) }\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_AFTER_SLD_ID_LST)\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/**\n\t * A slide id one past the highest existing, but at least ST_SlideId's minimum.\n\t *\n\t * The module named and enforced that minimum and not the maximum, so a deck near the ceiling\n\t * got an out-of-range `p:sldId/@id` written with no diagnostic — the package then needs\n\t * repair, for a reason nothing reported. Past the ceiling there is no \"next\" id to hand out,\n\t * so the allocation falls back to the lowest id in range that the deck is not already using;\n\t * a deck holding every one of the two billion has no legal answer and says so.\n\t */\n\t#nextSlideId(sldIds: ReturnType<typeof getElements>): number {\n\t\tconst used = new Set<number>()\n\t\tlet max = MIN_SLIDE_ID - 1\n\t\tfor (const sldId of sldIds) {\n\t\t\tconst id = numberValue(attr(sldId, 'id'))\n\t\t\tif (id === null) continue\n\t\t\tused.add(id)\n\t\t\tif (id > max) max = id\n\t\t}\n\t\tif (max < MAX_SLIDE_ID) return max + 1\n\t\tfor (let id = MIN_SLIDE_ID; id <= MAX_SLIDE_ID; id++) {\n\t\t\tif (!used.has(id)) return id\n\t\t}\n\t\tthrow new InvalidOptionError(\n\t\t\t'slide/id-space-exhausted',\n\t\t\t`this deck already uses every slide id ST_SlideId allows (${MIN_SLIDE_ID}-${MAX_SLIDE_ID}); no slide can be added.`\n\t\t)\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"],"mappings":";;;;;;;;;;;;;;;;AAaA,IAAa,eAAb,MAAa,aAAa;CACzB,4BAAY,IAAI,IAAoB;CACpC,6BAAa,IAAI,IAAoB;CACrC,SAAS;CAET,OAAO,MAAM,KAA2B;EACvC,MAAM,eAAe,IAAI,aAAa;EACtC,MAAM,QAAQ,SAAS,GAAG,CAAC,CAAC;EAC5B,IAAI,CAAC,SAAS,MAAM,cAAc,SACjC,MAAM,IAAI,iBACT,sCACA,oDACD;EACD,KAAK,MAAM,WAAW,YAAY,OAAO,YA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