@office-open/docx 0.10.11 → 0.10.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{context-nyQP2Fkk.mjs → context-CiyAhqTX.mjs} +2 -2
- package/dist/{context-nyQP2Fkk.mjs.map → context-CiyAhqTX.mjs.map} +1 -1
- package/dist/core-properties-CIG9ZnsW.d.mts.map +1 -1
- package/dist/{generate-CG1wp4pb.mjs → generate-DjODfjQ1.mjs} +3 -3
- package/dist/{generate-CG1wp4pb.mjs.map → generate-DjODfjQ1.mjs.map} +1 -1
- package/dist/generate.mjs +1 -1
- package/dist/index.mjs +4 -4
- package/dist/{parse-IeJ0NXYz.mjs → parse-DDWWDGbX.mjs} +4 -4
- package/dist/parse-DDWWDGbX.mjs.map +1 -0
- package/dist/parse.mjs +1 -1
- package/dist/{parts-D0KoDfg7.mjs → parts-B7Sfx_F0.mjs} +40 -23
- package/dist/parts-B7Sfx_F0.mjs.map +1 -0
- package/dist/patch/index.mjs +1 -1
- package/package.json +3 -3
- package/dist/parse-IeJ0NXYz.mjs.map +0 -1
- package/dist/parts-D0KoDfg7.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generate-CG1wp4pb.mjs","names":[],"sources":["../src/parts/fonts/obfuscate-ttf-to-odttf.ts","../src/parts/header-footer.ts","../src/compiler.ts","../src/generate.ts"],"sourcesContent":["/**\n * Font obfuscation module for embedding fonts in WordprocessingML documents.\n *\n * This module implements the OOXML font obfuscation algorithm used to embed\n * fonts in DOCX documents. Obfuscation is required by the OOXML specification\n * to prevent simple extraction of embedded font files.\n *\n * Reference: ECMA-376 Part 2, Section 11.1 (Font Embedding)\n *\n * @module\n */\n\n/** Start offset for obfuscation in the font file */\nconst obfuscatedStartOffset = 0;\n/** End offset for obfuscation (first 32 bytes are obfuscated) */\nconst obfuscatedEndOffset = 32;\n/** Expected GUID size (32 hex characters without dashes) */\nconst guidSize = 32;\n\n/**\n * Obfuscates a TrueType font file for embedding in OOXML documents.\n *\n * The obfuscation algorithm XORs the first 32 bytes of the font file\n * with a reversed byte sequence derived from the font's GUID key.\n * This prevents simple extraction while maintaining font functionality.\n *\n * @param buf - The original font file as a byte array\n * @param fontKey - The GUID key for the font (with or without dashes)\n * @returns The obfuscated font data\n * @throws Error if the fontKey is not a valid 32-character GUID\n *\n * @example\n * ```typescript\n * const fontData = readFileSync(\"font.ttf\");\n * const fontKey = \"00000000-0000-0000-0000-000000000000\";\n * const obfuscatedData = obfuscate(fontData, fontKey);\n * ```\n *\n * @internal\n */\nexport const obfuscate = (buf: Uint8Array, fontKey: string): Uint8Array => {\n const guid = fontKey.replace(/-/g, \"\");\n if (guid.length !== guidSize) {\n throw new Error(`Error: Cannot extract GUID from font filename: ${fontKey}`);\n }\n\n const hexStrings = guid.replace(/(..)/g, \"$1 \").trim().split(\" \");\n const hexNumbers = hexStrings.map((hexString) => parseInt(hexString, 16));\n hexNumbers.reverse();\n\n const bytesToObfuscate = buf.slice(obfuscatedStartOffset, obfuscatedEndOffset);\n const obfuscatedBytes = bytesToObfuscate.map(\n (byte, i) => byte ^ hexNumbers[i % hexNumbers.length],\n );\n\n const out = new Uint8Array(\n obfuscatedStartOffset + obfuscatedBytes.length + Math.max(0, buf.length - obfuscatedEndOffset),\n );\n out.set(buf.slice(0, obfuscatedStartOffset));\n out.set(obfuscatedBytes, obfuscatedStartOffset);\n out.set(buf.slice(obfuscatedEndOffset), obfuscatedStartOffset + obfuscatedBytes.length);\n return out;\n};\n","/**\n * Header/Footer entry module for WordprocessingML documents.\n *\n * Replaces the former HeaderWrapper/FooterWrapper/Header/Footer/HeaderFooterBase\n * class hierarchy with a simple data structure + pure serialization function.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_HdrFtr\n *\n * @module\n */\n\nimport type { Relationships } from \"@office-open/core\";\nimport { escapeXml } from \"@office-open/xml\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport { stringifyBodyChild } from \"../body\";\nimport type { BodyContext } from \"../context\";\nimport { DocumentAttributeNamespaces } from \"./document/document-attributes\";\nimport type { DocumentAttributeNamespace } from \"./document/document-attributes\";\n\n/**\n * Simple data structure for a header or footer entry.\n *\n * Replaces HeaderWrapper/FooterWrapper — holds children, relationships,\n * and the reference ID needed for section property references.\n *\n * Children are raw SectionChild objects (plain JSON or class instances).\n */\nexport interface HeaderFooterEntry {\n children: SectionChild[];\n relationships: Relationships;\n referenceId: number;\n}\n\n/**\n * Namespace keys used by header elements.\n * @internal\n */\nexport const HEADER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"cx\",\n \"cx1\",\n \"cx2\",\n \"cx3\",\n \"cx4\",\n \"cx5\",\n \"cx6\",\n \"cx7\",\n \"cx8\",\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"w16cid\",\n \"w16se\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Namespace keys used by footer elements.\n * @internal\n */\nexport const FOOTER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Serialize a header or footer to XML.\n *\n * Builds the `<w:hdr>` or `<w:ftr>` element with namespace declarations,\n * then serializes each child element via `stringifyBodyChild()`.\n *\n * @param tag - Element tag name (\"w:hdr\" or \"w:ftr\")\n * @param namespaces - Namespace keys to declare on the root element\n * @param children - Block-level child elements (raw SectionChild objects)\n * @param ctx - Body context for stringification\n */\nexport function stringifyHeaderFooter(\n tag: string,\n namespaces: DocumentAttributeNamespace[],\n children: SectionChild[],\n ctx: BodyContext,\n): string {\n const attrParts: string[] = [];\n for (const ns of namespaces) {\n attrParts.push(`xmlns:${ns}=\"${escapeXml(DocumentAttributeNamespaces[ns])}\"`);\n }\n // mc:Ignorable must declare the ignorable namespaces (w14/w15/wp14) that\n // header/footer content uses (e.g. w14:paraId). Without it, Word in\n // compatibility mode 14 rejects the part as unreadable content.\n attrParts.push('mc:Ignorable=\"w14 w15 wp14\"');\n const attrStr = attrParts.join(\" \");\n\n const childParts: string[] = [];\n for (const child of children) {\n childParts.push(stringifyBodyChild(child, ctx));\n }\n\n const body = childParts.join(\"\");\n return body.length === 0 ? `<${tag} ${attrStr}/>` : `<${tag} ${attrStr}>${body}</${tag}>`;\n}\n","/**\n * DOCX document compiler — pure function entry point.\n *\n * compileDocument() accepts DocumentOptions directly,\n * creates a DocxWriteContext internally, and produces a Zippable result.\n * All XML parts are produced via descriptors or serialize() —\n * no Formatter dependency.\n *\n * @module\n */\n\nimport {\n addSmartArtRelationships,\n createThemeXml,\n findAndReplaceImagePlaceholders,\n formatId,\n hasPlaceholders,\n levelForMediaName,\n optionalRelsPart,\n replaceAllPlaceholders,\n replaceNumberingPlaceholders,\n} from \"@office-open/core\";\nimport type { XmlifyedFile, ZipOptions, Zippable } from \"@office-open/core\";\nimport {\n DEFAULT_DRAWING_XML,\n getColorXml,\n getLayoutXml,\n getStyleXml,\n} from \"@office-open/core/smartart\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport { obfuscate } from \"@parts/fonts/obfuscate-ttf-to-odttf\";\nimport { HEADER_NAMESPACES, FOOTER_NAMESPACES, stringifyHeaderFooter } from \"@parts/header-footer\";\nimport type { CommentOptions } from \"@parts/paragraph/run/comment-run\";\n\nimport { stringifyDocumentXml, stringifyBodyChild, type BodyContext } from \"./body\";\nimport { DocxWriteContext } from \"./context\";\nimport {\n corePropertiesDesc,\n customPropertiesDesc,\n appPropertiesDesc,\n contentTypesDesc,\n buildContentTypesFromRegistry,\n withAltChunkOverrides,\n withMediaDefaults,\n fontTableDesc,\n webSettingsDesc,\n commentsDesc,\n bibliographyDesc,\n settingsDesc,\n footnotesDesc,\n endnotesDesc,\n glossaryDesc,\n} from \"./parts\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\n/** XML declaration prepended to every OOXML part. */\nconst XML_DECL = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>';\n\n/** Extended context for header/footer formatted view caching. */\ntype DocxContext = BodyContext & {\n headerFormattedViews?: Map<number, string>;\n footerFormattedViews?: Map<number, string>;\n};\n\n// ── Public API ──\n\n/**\n * Compile document options into a flat file map suitable for fflate zipSync.\n *\n * This is the primary entry point for DOCX generation — accepts DocumentOptions\n * directly.\n */\nexport function compileDocument(\n options: DocumentOptions,\n overrides: XmlifyedFile[] = [],\n mediaLevel: number = 0,\n): Zippable {\n const ctx = new DocxWriteContext(options);\n const files: Zippable = {};\n\n const headerFormattedViews = new Map<number, string>();\n const footerFormattedViews = new Map<number, string>();\n\n const xmlifiedFileMapping = xmlifyContext(ctx, headerFormattedViews, footerFormattedViews);\n const map = new Map<string, XmlifyedFile | XmlifyedFile[]>(Object.entries(xmlifiedFileMapping));\n\n for (const [, obj] of map) {\n if (obj === undefined) continue;\n if (Array.isArray(obj)) {\n for (const subFile of obj) {\n files[subFile.path] =\n typeof subFile.data === \"string\" ? encoder.encode(subFile.data) : subFile.data;\n }\n } else {\n files[obj.path] = typeof obj.data === \"string\" ? encoder.encode(obj.data) : obj.data;\n }\n }\n\n for (const subFile of overrides) {\n files[subFile.path] =\n typeof subFile.data === \"string\" ? encoder.encode(subFile.data) : subFile.data;\n }\n\n // Media files\n const mediaArray = ctx.media.array;\n for (const mediaData of mediaArray) {\n files[`word/media/${mediaData.fileName}`] = [\n mediaData.data as Uint8Array,\n { level: levelForMediaName(mediaData.fileName, mediaLevel) as ZipOptions[\"level\"] },\n ];\n if (mediaData.type === \"svg\") {\n files[`word/media/${mediaData.fallback.fileName}`] = [\n mediaData.fallback.data as Uint8Array,\n {\n level: levelForMediaName(mediaData.fallback.fileName, mediaLevel) as ZipOptions[\"level\"],\n },\n ];\n }\n }\n\n // OLE embedding binaries (word/embeddings/oleObjectN.bin)\n for (const embedding of ctx.embeddings.array) {\n files[`word/embeddings/${embedding.fileName}`] = [\n embedding.data as Uint8Array,\n { level: levelForMediaName(embedding.fileName, mediaLevel) as ZipOptions[\"level\"] },\n ];\n }\n\n // Font files — only fonts carrying binary data produce a .odttf part.\n // Round-tripped fonts (rawOdttf) keep their original obfuscated bytes.\n for (const font of ctx.fontTable.fontOptionsWithKey) {\n if (font.data === undefined) continue;\n const [nameWithoutExtension] = font.name.split(\".\");\n const filePath = font.odttfPath ?? `word/fonts/${nameWithoutExtension}.odttf`;\n files[filePath] = font.rawOdttf ? font.data : obfuscate(font.data, font.fontKey);\n }\n\n // Raw passthrough parts (word/theme/*, customXml/*, …) — generate doesn't\n // rebuild these, so copy their original bytes verbatim to keep [Content_Types]\n // declarations valid and the package openable in Word.\n for (const part of ctx._options.rawParts ?? []) {\n files[part.path] = part.data;\n }\n\n // [Content_Types].xml is serialized last: parts register their media/fonts\n // during stringify (run by xmlifyContext above), so backfilling <Default>\n // extensions from `ctx` now sees the complete set. Building it inside\n // xmlifyContext's object literal evaluated it before header/footer/font media\n // was registered, leaving jpg/gif/odttf without a covering Default.\n files[\"[Content_Types].xml\"] = encoder.encode(buildContentTypesData(ctx, files));\n\n return files;\n}\n\n// ── Internal ──\n\n/**\n * Complete mapping of all XML files in an OOXML document package.\n */\ninterface XmlifyedFileMapping {\n Document: XmlifyedFile;\n Styles: XmlifyedFile;\n Properties: XmlifyedFile;\n Numbering?: XmlifyedFile;\n Relationships: XmlifyedFile;\n FileRelationships: XmlifyedFile;\n Headers: XmlifyedFile[];\n Footers: XmlifyedFile[];\n HeaderRelationships: XmlifyedFile[];\n FooterRelationships: XmlifyedFile[];\n CustomProperties: XmlifyedFile;\n AppProperties: XmlifyedFile;\n FootNotes?: XmlifyedFile;\n FootNotesRelationships?: XmlifyedFile;\n Endnotes?: XmlifyedFile;\n EndnotesRelationships?: XmlifyedFile;\n Settings: XmlifyedFile;\n Comments?: XmlifyedFile;\n CommentsRelationships?: XmlifyedFile;\n FontTable?: XmlifyedFile;\n FontTableRelationships?: XmlifyedFile;\n Bibliography?: XmlifyedFile;\n Charts?: XmlifyedFile[];\n DiagramData?: XmlifyedFile[];\n DiagramLayout?: XmlifyedFile[];\n DiagramStyle?: XmlifyedFile[];\n DiagramColors?: XmlifyedFile[];\n DiagramDrawing?: XmlifyedFile[];\n AltChunks?: XmlifyedFile[];\n SubDocs?: XmlifyedFile[];\n Glossary?: XmlifyedFile;\n WebSettings?: XmlifyedFile;\n}\n\n/**\n * Comments carried by the document: those the caller listed explicitly\n * (`options.comments`) plus entries registered by `{ comment }` sugar children\n * during body stringification. Drives both word/comments.xml generation and the\n * [Content_Types] comments Override, which must stay in sync (OPC consistency).\n */\nfunction mergedCommentChildren(ctx: DocxWriteContext): CommentOptions[] {\n return [...(ctx._options.comments?.children ?? []), ...ctx.comments.entries];\n}\n\n/**\n * Serialize [Content_Types].xml from the part registry, then backfill media/\n * font/embedding `<Default>` entries from the parts actually written.\n *\n * Must run after every part has been stringified (parts call `ctx.addMedia`\n * during stringify), so call this once `xmlifyContext` has finished — not from\n * inside its object literal, where ContentTypes would evaluate before the\n * later-defined header/footer/font parts have registered their media.\n */\nfunction buildContentTypesData(ctx: DocxWriteContext, files: Zippable): string {\n const altChunks = ctx.altChunks.array.map((ac) => ({\n path: `/word/${ac.path}`,\n contentType: ac.contentType ?? \"application/xhtml+xml\",\n }));\n // Round-trip passes the source [Content_Types] through, but the compiler\n // regenerates altChunk part paths — realign the afchunk Overrides to the\n // freshly written parts (else O5/O6).\n const base = ctx._options.contentTypes\n ? withAltChunkOverrides(ctx._options.contentTypes, altChunks)\n : buildContentTypesFromRegistry(\n new Map<string, boolean | number>([\n [\"freshCompile\", true],\n [\"hasComments\", mergedCommentChildren(ctx).length > 0],\n [\"hasBibliography\", !!ctx._options.bibliography],\n [\"hasGlossary\", !!ctx.glossaryOptions],\n [\"hasWebSettings\", !!ctx.webSettings],\n [\"headerCount\", ctx.headers.length],\n [\"footerCount\", ctx.footers.length],\n [\"chartCount\", ctx.charts.array.length],\n [\"smartArtCount\", ctx.smartArts.array.length],\n ]),\n {\n altChunks,\n subDocs: ctx.subDocs.array.map((sd) => ({ path: `/word/${sd.path}` })),\n },\n );\n // Backfill <Default> extensions from every part actually written to the\n // package — the parts on disk are the single source of truth, so media/font/\n // embedding defaults can never drift from what the package contains (e.g. a\n // font written via the fallback path when `odttfPath` is unset).\n const withMedia = withMediaDefaults(base, Object.keys(files));\n return XML_DECL + (contentTypesDesc.stringify(withMedia, ctx) ?? \"\");\n}\n\nfunction xmlifyContext(\n ctx: DocxWriteContext,\n headerFormattedViews: Map<number, string>,\n footerFormattedViews: Map<number, string>,\n): XmlifyedFileMapping {\n const mkCtx = (viewWrapper: DocxContext[\"viewWrapper\"] = ctx.document): DocxContext => ({\n fileData: ctx,\n file: ctx,\n viewWrapper,\n stringifyChild: stringifyBodyChild,\n addRelationship: (type: string, target: string, mode?: string) =>\n ctx.addRelationship(type, target, mode),\n addMedia: (data: Uint8Array, type: string) => ctx.addMedia(data, type),\n });\n\n const documentRelationshipCount = ctx.document.relationships.relationshipCount + 1;\n // Per-part media-replacement results shared between the .rels pass and the\n // body-XML pass so both use identical rId offsets. Each header/footer part\n // has its own relationship numbering (independent of the document part).\n const footerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const headerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const docCtx = mkCtx(ctx.document);\n const documentXmlData = XML_DECL + stringifyDocumentXml(ctx, docCtx);\n\n // Comments is an optional part — skip it entirely (no comments.xml, no\n // comments rels, no [Content_Types] Override) when the document carries none.\n // Emitting an empty comments.xml with a dangling relationship is the OPC\n // violation that makes Word reject the package on open.\n const mergedCommentChildrenList = mergedCommentChildren(ctx);\n const hasComments = mergedCommentChildrenList.length > 0;\n const commentRelationshipCount = hasComments\n ? ctx.comments.relationships.relationshipCount + 1\n : 0;\n const commentCtx = hasComments ? mkCtx({ relationships: ctx.comments.relationships }) : null;\n const commentXmlData = commentCtx\n ? XML_DECL + commentsDesc.stringify({ children: mergedCommentChildrenList }, commentCtx)\n : \"\";\n\n const footnoteRelationshipCount = ctx.footNotes.relationships.relationshipCount + 1;\n const footnoteCtx = mkCtx({\n relationships: ctx.footNotes.relationships,\n });\n const footnoteXmlData =\n XML_DECL +\n (footnotesDesc.stringify(\n {\n notes: ctx.footNotes.notes,\n separator: ctx.footNotes.separator,\n continuationSeparator: ctx.footNotes.continuationSeparator,\n },\n footnoteCtx,\n ) ?? \"\");\n\n const documentMedia = findAndReplaceImagePlaceholders(\n documentXmlData,\n ctx.media.array,\n documentRelationshipCount,\n );\n // OLE embeddings reuse the same {fileName} placeholder bridge as images; run\n // after media so {oleObjectN.bin} placeholders resolve against the embedding array.\n const documentEmbeddingOffset = documentRelationshipCount + documentMedia.referenced.length;\n const documentEmbeddings = findAndReplaceImagePlaceholders(\n documentMedia.xml,\n ctx.embeddings.array,\n documentEmbeddingOffset,\n );\n const commentMedia = hasComments\n ? findAndReplaceImagePlaceholders(commentXmlData, ctx.media.array, commentRelationshipCount)\n : { xml: \"\", referenced: [] as { fileName: string }[] };\n const footnoteMedia = findAndReplaceImagePlaceholders(\n footnoteXmlData,\n ctx.media.array,\n footnoteRelationshipCount,\n );\n // Register footnote media relationships eagerly so the relationshipCount used\n // to gate footnotes.xml.rels reflects the final state (see FootNotesRelationships).\n for (let i = 0; i < footnoteMedia.referenced.length; i++) {\n ctx.footNotes.relationships.addRelationship(\n footnoteRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${footnoteMedia.referenced[i].fileName}`,\n );\n }\n\n return {\n AppProperties: {\n data: XML_DECL + (appPropertiesDesc.stringify(ctx._options.appProperties ?? {}, ctx) ?? \"\"),\n path: \"docProps/app.xml\",\n },\n ...(hasComments\n ? {\n Comments: {\n data: (() => {\n const xmlData =\n commentMedia.referenced.length > 0 ? commentMedia.xml : commentXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/comments.xml\",\n },\n CommentsRelationships: (() => {\n for (let i = 0; i < commentMedia.referenced.length; i++) {\n ctx.comments.relationships.addRelationship(\n commentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${commentMedia.referenced[i].fileName}`,\n );\n }\n return optionalRelsPart(\n ctx.comments.relationships,\n XML_DECL,\n \"word/_rels/comments.xml.rels\",\n );\n })(),\n }\n : {}),\n CustomProperties: {\n data:\n XML_DECL +\n (customPropertiesDesc.stringify({ properties: ctx._options.customProperties ?? [] }, ctx) ??\n \"\"),\n path: \"docProps/custom.xml\",\n },\n Document: {\n data: (() => {\n let xmlData = documentEmbeddings.xml;\n if (hasPlaceholders(xmlData)) {\n const mediaCount = documentMedia.referenced.length;\n const embeddingCount = documentEmbeddings.referenced.length;\n const chartKeys = ctx.charts.array.map((c) => c.key);\n const smartArtKeys = ctx.smartArts.array.map((s) => s.key);\n const chartOffset = documentRelationshipCount + mediaCount + embeddingCount;\n const smartArtOffset = chartOffset + chartKeys.length;\n\n // Build combined replacement entries for charts, smartart, and numbering\n const entries: Array<{ prefix?: string; key: string; value: string }> = [];\n for (let i = 0; i < chartKeys.length; i++) {\n entries.push({\n prefix: \"chart:\",\n key: chartKeys[i],\n value: formatId(chartOffset, i, \"rId\"),\n });\n }\n const saPrefixes = [\"smartart:\", \"smartart-lo:\", \"smartart-qs:\", \"smartart-cs:\"];\n for (let i = 0; i < smartArtKeys.length; i++) {\n for (let p = 0; p < saPrefixes.length; p++) {\n entries.push({\n prefix: saPrefixes[p],\n key: smartArtKeys[i],\n value: formatId(smartArtOffset + p * smartArtKeys.length, i, \"rId\"),\n });\n }\n }\n for (const { reference, instance, numId } of ctx.numbering.concreteNumbering) {\n entries.push({ key: `${reference}-${instance}`, value: numId.toString() });\n }\n xmlData = replaceAllPlaceholders(xmlData, entries);\n } else {\n xmlData = replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n }\n return xmlData;\n })(),\n path: \"word/document.xml\",\n },\n // Theme — fresh-compile emits a language-neutral default theme\n // (createThemeXml). Round-trip carries the source theme in rawParts,\n // already copied verbatim above, so skip emitting here to avoid a duplicate.\n ...(ctx._options.rawParts?.some((part) => part.path.startsWith(\"word/theme/\"))\n ? {}\n : {\n Theme: {\n data: XML_DECL + createThemeXml(),\n path: \"word/theme/theme1.xml\",\n },\n }),\n ...(ctx.hasEndnotes\n ? {\n Endnotes: {\n data: (() => {\n const endnoteCtx = mkCtx({\n relationships: ctx.endnotes.relationships,\n });\n const xmlData =\n XML_DECL +\n (endnotesDesc.stringify(\n {\n notes: ctx.endnotes.notes,\n separator: ctx.endnotes.separator,\n continuationSeparator: ctx.endnotes.continuationSeparator,\n },\n endnoteCtx,\n ) ?? \"\");\n const endnoteRelCount = ctx.endnotes.relationships.relationshipCount + 1;\n const endnoteMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n endnoteRelCount,\n );\n if (endnoteMedia.referenced.length > 0) {\n for (let i = 0; i < endnoteMedia.referenced.length; i++) {\n ctx.endnotes.relationships.addRelationship(\n endnoteRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${endnoteMedia.referenced[i].fileName}`,\n );\n }\n return replaceNumberingPlaceholders(\n endnoteMedia.xml,\n ctx.numbering.concreteNumbering,\n );\n }\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/endnotes.xml\",\n },\n EndnotesRelationships:\n ctx.endnotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.endnotes.relationships.serialize(),\n path: \"word/_rels/endnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FileRelationships: {\n data: XML_DECL + ctx.fileRelationships.serialize(),\n path: \"_rels/.rels\",\n },\n FontTable: {\n data:\n XML_DECL +\n (fontTableDesc.stringify({ fonts: ctx.fontTable.fontOptionsWithKey }, ctx) ?? \"\"),\n path: \"word/fontTable.xml\",\n },\n FontTableRelationships: optionalRelsPart(\n ctx.fontTable.relationships,\n XML_DECL,\n \"word/_rels/fontTable.xml.rels\",\n ),\n ...(ctx.hasFootnotes\n ? {\n FootNotes: {\n data: (() => {\n const xmlData =\n footnoteMedia.referenced.length > 0 ? footnoteMedia.xml : footnoteXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/footnotes.xml\",\n },\n FootNotesRelationships:\n ctx.footNotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.footNotes.relationships.serialize(),\n path: \"word/_rels/footnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FooterRelationships: ctx.footers\n .map((entry, index) => {\n const footerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:ftr\", FOOTER_NAMESPACES, entry.children, footerCtx);\n footerFormattedViews.set(index, xmlData);\n // Footer images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const footerRelCount = entry.relationships.relationshipCount + 1;\n const footerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n footerRelCount,\n );\n footerMediaResults.set(index, footerMedia);\n\n for (let i = 0; i < footerMedia.referenced.length; i++) {\n entry.relationships.addRelationship(\n footerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${footerMedia.referenced[i].fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/footer${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Footers: ctx.footers.map((_entry, index) => {\n const footerMedia = footerMediaResults.get(index)!;\n const tempXmlData = footerFormattedViews.get(index)!;\n const xmlData = footerMedia.referenced.length > 0 ? footerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/footer${index + 1}.xml`,\n };\n }),\n HeaderRelationships: ctx.headers\n .map((entry, index) => {\n const headerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:hdr\", HEADER_NAMESPACES, entry.children, headerCtx);\n headerFormattedViews.set(index, xmlData);\n // Header images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const headerRelCount = entry.relationships.relationshipCount + 1;\n const headerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n headerRelCount,\n );\n headerMediaResults.set(index, headerMedia);\n\n for (let i = 0; i < headerMedia.referenced.length; i++) {\n entry.relationships.addRelationship(\n headerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${headerMedia.referenced[i].fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/header${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Headers: ctx.headers.map((_entry, index) => {\n const headerMedia = headerMediaResults.get(index)!;\n const tempXmlData = headerFormattedViews.get(index)!;\n const xmlData = headerMedia.referenced.length > 0 ? headerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/header${index + 1}.xml`,\n };\n }),\n ...(ctx.hasNumbering\n ? {\n Numbering: {\n data: ctx.numbering.serialize(),\n path: \"word/numbering.xml\",\n },\n }\n : {}),\n Properties: {\n data: XML_DECL + (corePropertiesDesc.stringify(ctx._options, ctx) ?? \"\"),\n path: \"docProps/core.xml\",\n },\n Relationships: {\n data: (() => {\n for (let i = 0; i < documentMedia.referenced.length; i++) {\n ctx.document.relationships.addRelationship(\n documentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${documentMedia.referenced[i].fileName}`,\n );\n }\n for (let i = 0; i < documentEmbeddings.referenced.length; i++) {\n ctx.document.relationships.addRelationship(\n documentEmbeddingOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject\",\n `embeddings/${documentEmbeddings.referenced[i].fileName}`,\n );\n }\n\n const chartOffset =\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length;\n for (let i = 0; i < ctx.charts.array.length; i++) {\n ctx.document.relationships.addRelationship(\n chartOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `charts/chart${i + 1}.xml`,\n );\n }\n\n addSmartArtRelationships(\n ctx.smartArts.array.map((s) => s.key),\n (id, type, target) => {\n ctx.document.relationships.addRelationship(id, type, target);\n },\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length +\n ctx.charts.array.length,\n 0,\n {\n pathPrefix: \"\",\n styleRelType: \"http://schemas.microsoft.com/office/2007/relationships/diagramStyle\",\n },\n );\n\n ctx.document.relationships.addRelationship(\n ctx.document.relationships.relationshipCount + 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable\",\n \"fontTable.xml\",\n );\n\n return XML_DECL + ctx.document.relationships.serialize();\n })(),\n path: \"word/_rels/document.xml.rels\",\n },\n Settings: {\n data: XML_DECL + (settingsDesc.stringify(ctx._settingsOptions, ctx) ?? \"\"),\n path: \"word/settings.xml\",\n },\n Styles: {\n data: (() => {\n const xmlStyles = ctx.styles.serialize();\n return replaceNumberingPlaceholders(xmlStyles, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/styles.xml\",\n },\n ...(ctx._options.bibliography\n ? {\n Bibliography: {\n data: XML_DECL + (bibliographyDesc.stringify(ctx._options.bibliography, ctx) ?? \"\"),\n path: \"word/bibliography.xml\",\n },\n }\n : {}),\n ...(ctx.charts.array.length > 0\n ? {\n Charts: ctx.charts.array.map((chartData, i) => ({\n data: XML_DECL + chartData.chartSpaceXml,\n path: `word/charts/chart${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.smartArts.array.length > 0\n ? {\n DiagramData: ctx.smartArts.array.map((smartArtData, i) => ({\n data: XML_DECL + smartArtData.dataModelXml,\n path: `word/diagrams/data${i + 1}.xml`,\n })),\n DiagramLayout: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getLayoutXml(smartArtData.layout),\n path: `word/diagrams/layout${i + 1}.xml`,\n })),\n DiagramStyle: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getStyleXml(smartArtData.style),\n path: `word/diagrams/quickStyle${i + 1}.xml`,\n })),\n DiagramColors: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getColorXml(smartArtData.color),\n path: `word/diagrams/colors${i + 1}.xml`,\n })),\n DiagramDrawing: ctx.smartArts.array.map((_, i) => ({\n data: DEFAULT_DRAWING_XML,\n path: `word/diagrams/drawing${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.altChunks.array.length > 0\n ? {\n AltChunks: ctx.altChunks.array.map((altChunkData) => ({\n data: altChunkData.data,\n path: `word/${altChunkData.path}`,\n })),\n }\n : {}),\n ...(ctx.subDocs.array.length > 0\n ? {\n SubDocs: ctx.subDocs.array.map((subDocData) => ({\n data: subDocData.data,\n path: `word/${subDocData.path}`,\n })),\n }\n : {}),\n ...(ctx.glossaryOptions\n ? {\n Glossary: {\n data: (() => {\n const glossaryCtx = mkCtx(undefined);\n return XML_DECL + (glossaryDesc.stringify(ctx.glossaryOptions!, glossaryCtx) ?? \"\");\n })(),\n path: \"word/glossary/document.xml\",\n },\n }\n : {}),\n ...(ctx.webSettings\n ? {\n WebSettings: {\n data: XML_DECL + (webSettingsDesc.stringify(ctx._options.webSettings ?? {}, ctx) ?? \"\"),\n path: \"word/webSettings.xml\",\n },\n }\n : {}),\n };\n}\n","/**\n * Pure function API for generating DOCX files.\n *\n * @module\n */\n\nimport { createPacker, OoxmlMimeType } from \"@office-open/core\";\nimport type { OutputByType, OutputType, PackerOptions } from \"@office-open/core\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\n\nimport { compileDocument } from \"./compiler\";\n\n/** @internal Packer instance for DOCX generation. */\nconst Packer = createPacker<DocumentOptions>({\n compile: (options, overrides, mediaLevel) => compileDocument(options, overrides, mediaLevel),\n mimeType: OoxmlMimeType.DOCX,\n});\n\n/**\n * Generate a DOCX file from pure JSON options.\n *\n * The output format is controlled by `packerOptions.type` (default: `\"nodebuffer\"` → Buffer).\n * For synchronous generation, use {@link generateDocumentSync}. For streaming, use {@link generateDocumentStream}.\n *\n * @param options - Document options (sections, styles, numbering, etc.)\n * @param packerOptions - Optional packer configuration (type, compression, overrides, etc.)\n *\n * @example\n * ```typescript\n * import { generateDocument } from \"@office-open/docx\";\n *\n * const buffer = await generateDocument({ sections: [...] });\n * const bytes = await generateDocument({ sections: [...] }, { type: \"uint8array\" });\n * const blob = await generateDocument({ sections: [...] }, { type: \"blob\" });\n * ```\n */\nexport function generateDocument<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): Promise<OutputByType[T]> {\n return Packer.pack(options, packerOptions) as Promise<OutputByType[T]>;\n}\n\n/**\n * Synchronously generate a DOCX file from pure JSON options.\n */\nexport function generateDocumentSync<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): OutputByType[T] {\n return Packer.packSync(options, packerOptions) as OutputByType[T];\n}\n\n/**\n * Generate a DOCX file as a `ReadableStream<Uint8Array>`.\n */\nexport function generateDocumentStream(\n options: DocumentOptions,\n packerOptions?: PackerOptions,\n): ReadableStream<Uint8Array> {\n return Packer.toStream(options, packerOptions);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAaA,MAAM,wBAAwB;;AAE9B,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;;;;;;;;;;;;;;;;;;;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generate-DjODfjQ1.mjs","names":[],"sources":["../src/parts/fonts/obfuscate-ttf-to-odttf.ts","../src/parts/header-footer.ts","../src/compiler.ts","../src/generate.ts"],"sourcesContent":["/**\n * Font obfuscation module for embedding fonts in WordprocessingML documents.\n *\n * This module implements the OOXML font obfuscation algorithm used to embed\n * fonts in DOCX documents. Obfuscation is required by the OOXML specification\n * to prevent simple extraction of embedded font files.\n *\n * Reference: ECMA-376 Part 2, Section 11.1 (Font Embedding)\n *\n * @module\n */\n\n/** Start offset for obfuscation in the font file */\nconst obfuscatedStartOffset = 0;\n/** End offset for obfuscation (first 32 bytes are obfuscated) */\nconst obfuscatedEndOffset = 32;\n/** Expected GUID size (32 hex characters without dashes) */\nconst guidSize = 32;\n\n/**\n * Obfuscates a TrueType font file for embedding in OOXML documents.\n *\n * The obfuscation algorithm XORs the first 32 bytes of the font file\n * with a reversed byte sequence derived from the font's GUID key.\n * This prevents simple extraction while maintaining font functionality.\n *\n * @param buf - The original font file as a byte array\n * @param fontKey - The GUID key for the font (with or without dashes)\n * @returns The obfuscated font data\n * @throws Error if the fontKey is not a valid 32-character GUID\n *\n * @example\n * ```typescript\n * const fontData = readFileSync(\"font.ttf\");\n * const fontKey = \"00000000-0000-0000-0000-000000000000\";\n * const obfuscatedData = obfuscate(fontData, fontKey);\n * ```\n *\n * @internal\n */\nexport const obfuscate = (buf: Uint8Array, fontKey: string): Uint8Array => {\n const guid = fontKey.replace(/-/g, \"\");\n if (guid.length !== guidSize) {\n throw new Error(`Error: Cannot extract GUID from font filename: ${fontKey}`);\n }\n\n const hexStrings = guid.replace(/(..)/g, \"$1 \").trim().split(\" \");\n const hexNumbers = hexStrings.map((hexString) => parseInt(hexString, 16));\n hexNumbers.reverse();\n\n const bytesToObfuscate = buf.slice(obfuscatedStartOffset, obfuscatedEndOffset);\n const obfuscatedBytes = bytesToObfuscate.map(\n (byte, i) => byte ^ hexNumbers[i % hexNumbers.length],\n );\n\n const out = new Uint8Array(\n obfuscatedStartOffset + obfuscatedBytes.length + Math.max(0, buf.length - obfuscatedEndOffset),\n );\n out.set(buf.slice(0, obfuscatedStartOffset));\n out.set(obfuscatedBytes, obfuscatedStartOffset);\n out.set(buf.slice(obfuscatedEndOffset), obfuscatedStartOffset + obfuscatedBytes.length);\n return out;\n};\n","/**\n * Header/Footer entry module for WordprocessingML documents.\n *\n * Replaces the former HeaderWrapper/FooterWrapper/Header/Footer/HeaderFooterBase\n * class hierarchy with a simple data structure + pure serialization function.\n *\n * Reference: ISO/IEC 29500-4, wml.xsd, CT_HdrFtr\n *\n * @module\n */\n\nimport type { Relationships } from \"@office-open/core\";\nimport { escapeXml } from \"@office-open/xml\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport { stringifyBodyChild } from \"../body\";\nimport type { BodyContext } from \"../context\";\nimport { DocumentAttributeNamespaces } from \"./document/document-attributes\";\nimport type { DocumentAttributeNamespace } from \"./document/document-attributes\";\n\n/**\n * Simple data structure for a header or footer entry.\n *\n * Replaces HeaderWrapper/FooterWrapper — holds children, relationships,\n * and the reference ID needed for section property references.\n *\n * Children are raw SectionChild objects (plain JSON or class instances).\n */\nexport interface HeaderFooterEntry {\n children: SectionChild[];\n relationships: Relationships;\n referenceId: number;\n}\n\n/**\n * Namespace keys used by header elements.\n * @internal\n */\nexport const HEADER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"cx\",\n \"cx1\",\n \"cx2\",\n \"cx3\",\n \"cx4\",\n \"cx5\",\n \"cx6\",\n \"cx7\",\n \"cx8\",\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"w16cid\",\n \"w16se\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Namespace keys used by footer elements.\n * @internal\n */\nexport const FOOTER_NAMESPACES: DocumentAttributeNamespace[] = [\n \"m\",\n \"mc\",\n \"o\",\n \"r\",\n \"v\",\n \"w\",\n \"w10\",\n \"w14\",\n \"w15\",\n \"wne\",\n \"wp\",\n \"wp14\",\n \"wpc\",\n \"wpg\",\n \"wpi\",\n \"wps\",\n];\n\n/**\n * Serialize a header or footer to XML.\n *\n * Builds the `<w:hdr>` or `<w:ftr>` element with namespace declarations,\n * then serializes each child element via `stringifyBodyChild()`.\n *\n * @param tag - Element tag name (\"w:hdr\" or \"w:ftr\")\n * @param namespaces - Namespace keys to declare on the root element\n * @param children - Block-level child elements (raw SectionChild objects)\n * @param ctx - Body context for stringification\n */\nexport function stringifyHeaderFooter(\n tag: string,\n namespaces: DocumentAttributeNamespace[],\n children: SectionChild[],\n ctx: BodyContext,\n): string {\n const attrParts: string[] = [];\n for (const ns of namespaces) {\n attrParts.push(`xmlns:${ns}=\"${escapeXml(DocumentAttributeNamespaces[ns])}\"`);\n }\n // mc:Ignorable must declare the ignorable namespaces (w14/w15/wp14) that\n // header/footer content uses (e.g. w14:paraId). Without it, Word in\n // compatibility mode 14 rejects the part as unreadable content.\n attrParts.push('mc:Ignorable=\"w14 w15 wp14\"');\n const attrStr = attrParts.join(\" \");\n\n const childParts: string[] = [];\n for (const child of children) {\n childParts.push(stringifyBodyChild(child, ctx));\n }\n\n const body = childParts.join(\"\");\n return body.length === 0 ? `<${tag} ${attrStr}/>` : `<${tag} ${attrStr}>${body}</${tag}>`;\n}\n","/**\n * DOCX document compiler — pure function entry point.\n *\n * compileDocument() accepts DocumentOptions directly,\n * creates a DocxWriteContext internally, and produces a Zippable result.\n * All XML parts are produced via descriptors or serialize() —\n * no Formatter dependency.\n *\n * @module\n */\n\nimport {\n addSmartArtRelationships,\n createThemeXml,\n findAndReplaceImagePlaceholders,\n formatId,\n hasPlaceholders,\n levelForMediaName,\n optionalRelsPart,\n replaceAllPlaceholders,\n replaceNumberingPlaceholders,\n} from \"@office-open/core\";\nimport type { XmlifyedFile, ZipOptions, Zippable } from \"@office-open/core\";\nimport {\n DEFAULT_DRAWING_XML,\n getColorXml,\n getLayoutXml,\n getStyleXml,\n} from \"@office-open/core/smartart\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport { obfuscate } from \"@parts/fonts/obfuscate-ttf-to-odttf\";\nimport { HEADER_NAMESPACES, FOOTER_NAMESPACES, stringifyHeaderFooter } from \"@parts/header-footer\";\nimport type { CommentOptions } from \"@parts/paragraph/run/comment-run\";\n\nimport { stringifyDocumentXml, stringifyBodyChild, type BodyContext } from \"./body\";\nimport { DocxWriteContext } from \"./context\";\nimport {\n corePropertiesDesc,\n customPropertiesDesc,\n appPropertiesDesc,\n contentTypesDesc,\n buildContentTypesFromRegistry,\n withAltChunkOverrides,\n withMediaDefaults,\n fontTableDesc,\n webSettingsDesc,\n commentsDesc,\n bibliographyDesc,\n settingsDesc,\n footnotesDesc,\n endnotesDesc,\n glossaryDesc,\n} from \"./parts\";\n\n/** Reusable TextEncoder (stateless, safe to share). */\nconst encoder = new TextEncoder();\n\n/** XML declaration prepended to every OOXML part. */\nconst XML_DECL = '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>';\n\n/** Extended context for header/footer formatted view caching. */\ntype DocxContext = BodyContext & {\n headerFormattedViews?: Map<number, string>;\n footerFormattedViews?: Map<number, string>;\n};\n\n// ── Public API ──\n\n/**\n * Compile document options into a flat file map suitable for fflate zipSync.\n *\n * This is the primary entry point for DOCX generation — accepts DocumentOptions\n * directly.\n */\nexport function compileDocument(\n options: DocumentOptions,\n overrides: XmlifyedFile[] = [],\n mediaLevel: number = 0,\n): Zippable {\n const ctx = new DocxWriteContext(options);\n const files: Zippable = {};\n\n const headerFormattedViews = new Map<number, string>();\n const footerFormattedViews = new Map<number, string>();\n\n const xmlifiedFileMapping = xmlifyContext(ctx, headerFormattedViews, footerFormattedViews);\n const map = new Map<string, XmlifyedFile | XmlifyedFile[]>(Object.entries(xmlifiedFileMapping));\n\n for (const [, obj] of map) {\n if (obj === undefined) continue;\n if (Array.isArray(obj)) {\n for (const subFile of obj) {\n files[subFile.path] =\n typeof subFile.data === \"string\" ? encoder.encode(subFile.data) : subFile.data;\n }\n } else {\n files[obj.path] = typeof obj.data === \"string\" ? encoder.encode(obj.data) : obj.data;\n }\n }\n\n for (const subFile of overrides) {\n files[subFile.path] =\n typeof subFile.data === \"string\" ? encoder.encode(subFile.data) : subFile.data;\n }\n\n // Media files\n const mediaArray = ctx.media.array;\n for (const mediaData of mediaArray) {\n files[`word/media/${mediaData.fileName}`] = [\n mediaData.data as Uint8Array,\n { level: levelForMediaName(mediaData.fileName, mediaLevel) as ZipOptions[\"level\"] },\n ];\n if (mediaData.type === \"svg\") {\n files[`word/media/${mediaData.fallback.fileName}`] = [\n mediaData.fallback.data as Uint8Array,\n {\n level: levelForMediaName(mediaData.fallback.fileName, mediaLevel) as ZipOptions[\"level\"],\n },\n ];\n }\n }\n\n // OLE embedding binaries (word/embeddings/oleObjectN.bin)\n for (const embedding of ctx.embeddings.array) {\n files[`word/embeddings/${embedding.fileName}`] = [\n embedding.data as Uint8Array,\n { level: levelForMediaName(embedding.fileName, mediaLevel) as ZipOptions[\"level\"] },\n ];\n }\n\n // Font files — only fonts carrying binary data produce a .odttf part.\n // Round-tripped fonts (rawOdttf) keep their original obfuscated bytes.\n for (const font of ctx.fontTable.fontOptionsWithKey) {\n if (font.data === undefined) continue;\n const [nameWithoutExtension] = font.name.split(\".\");\n const filePath = font.odttfPath ?? `word/fonts/${nameWithoutExtension}.odttf`;\n files[filePath] = font.rawOdttf ? font.data : obfuscate(font.data, font.fontKey);\n }\n\n // Raw passthrough parts (word/theme/*, customXml/*, …) — generate doesn't\n // rebuild these, so copy their original bytes verbatim to keep [Content_Types]\n // declarations valid and the package openable in Word.\n for (const part of ctx._options.rawParts ?? []) {\n files[part.path] = part.data;\n }\n\n // [Content_Types].xml is serialized last: parts register their media/fonts\n // during stringify (run by xmlifyContext above), so backfilling <Default>\n // extensions from `ctx` now sees the complete set. Building it inside\n // xmlifyContext's object literal evaluated it before header/footer/font media\n // was registered, leaving jpg/gif/odttf without a covering Default.\n files[\"[Content_Types].xml\"] = encoder.encode(buildContentTypesData(ctx, files));\n\n return files;\n}\n\n// ── Internal ──\n\n/**\n * Complete mapping of all XML files in an OOXML document package.\n */\ninterface XmlifyedFileMapping {\n Document: XmlifyedFile;\n Styles: XmlifyedFile;\n Properties: XmlifyedFile;\n Numbering?: XmlifyedFile;\n Relationships: XmlifyedFile;\n FileRelationships: XmlifyedFile;\n Headers: XmlifyedFile[];\n Footers: XmlifyedFile[];\n HeaderRelationships: XmlifyedFile[];\n FooterRelationships: XmlifyedFile[];\n CustomProperties: XmlifyedFile;\n AppProperties: XmlifyedFile;\n FootNotes?: XmlifyedFile;\n FootNotesRelationships?: XmlifyedFile;\n Endnotes?: XmlifyedFile;\n EndnotesRelationships?: XmlifyedFile;\n Settings: XmlifyedFile;\n Comments?: XmlifyedFile;\n CommentsRelationships?: XmlifyedFile;\n FontTable?: XmlifyedFile;\n FontTableRelationships?: XmlifyedFile;\n Bibliography?: XmlifyedFile;\n Charts?: XmlifyedFile[];\n DiagramData?: XmlifyedFile[];\n DiagramLayout?: XmlifyedFile[];\n DiagramStyle?: XmlifyedFile[];\n DiagramColors?: XmlifyedFile[];\n DiagramDrawing?: XmlifyedFile[];\n AltChunks?: XmlifyedFile[];\n SubDocs?: XmlifyedFile[];\n Glossary?: XmlifyedFile;\n WebSettings?: XmlifyedFile;\n}\n\n/**\n * Comments carried by the document: those the caller listed explicitly\n * (`options.comments`) plus entries registered by `{ comment }` sugar children\n * during body stringification. Drives both word/comments.xml generation and the\n * [Content_Types] comments Override, which must stay in sync (OPC consistency).\n */\nfunction mergedCommentChildren(ctx: DocxWriteContext): CommentOptions[] {\n return [...(ctx._options.comments?.children ?? []), ...ctx.comments.entries];\n}\n\n/**\n * Serialize [Content_Types].xml from the part registry, then backfill media/\n * font/embedding `<Default>` entries from the parts actually written.\n *\n * Must run after every part has been stringified (parts call `ctx.addMedia`\n * during stringify), so call this once `xmlifyContext` has finished — not from\n * inside its object literal, where ContentTypes would evaluate before the\n * later-defined header/footer/font parts have registered their media.\n */\nfunction buildContentTypesData(ctx: DocxWriteContext, files: Zippable): string {\n const altChunks = ctx.altChunks.array.map((ac) => ({\n path: `/word/${ac.path}`,\n contentType: ac.contentType ?? \"application/xhtml+xml\",\n }));\n // Round-trip passes the source [Content_Types] through, but the compiler\n // regenerates altChunk part paths — realign the afchunk Overrides to the\n // freshly written parts (else O5/O6).\n const base = ctx._options.contentTypes\n ? withAltChunkOverrides(ctx._options.contentTypes, altChunks)\n : buildContentTypesFromRegistry(\n new Map<string, boolean | number>([\n [\"freshCompile\", true],\n [\"hasComments\", mergedCommentChildren(ctx).length > 0],\n [\"hasBibliography\", !!ctx._options.bibliography],\n [\"hasGlossary\", !!ctx.glossaryOptions],\n [\"hasWebSettings\", !!ctx.webSettings],\n [\"headerCount\", ctx.headers.length],\n [\"footerCount\", ctx.footers.length],\n [\"chartCount\", ctx.charts.array.length],\n [\"smartArtCount\", ctx.smartArts.array.length],\n ]),\n {\n altChunks,\n subDocs: ctx.subDocs.array.map((sd) => ({ path: `/word/${sd.path}` })),\n },\n );\n // Backfill <Default> extensions from every part actually written to the\n // package — the parts on disk are the single source of truth, so media/font/\n // embedding defaults can never drift from what the package contains (e.g. a\n // font written via the fallback path when `odttfPath` is unset).\n const withMedia = withMediaDefaults(base, Object.keys(files));\n return XML_DECL + (contentTypesDesc.stringify(withMedia, ctx) ?? \"\");\n}\n\nfunction xmlifyContext(\n ctx: DocxWriteContext,\n headerFormattedViews: Map<number, string>,\n footerFormattedViews: Map<number, string>,\n): XmlifyedFileMapping {\n const mkCtx = (viewWrapper: DocxContext[\"viewWrapper\"] = ctx.document): DocxContext => ({\n fileData: ctx,\n file: ctx,\n viewWrapper,\n stringifyChild: stringifyBodyChild,\n addRelationship: (type: string, target: string, mode?: string) =>\n ctx.addRelationship(type, target, mode),\n addMedia: (data: Uint8Array, type: string) => ctx.addMedia(data, type),\n });\n\n const documentRelationshipCount = ctx.document.relationships.relationshipCount + 1;\n // Per-part media-replacement results shared between the .rels pass and the\n // body-XML pass so both use identical rId offsets. Each header/footer part\n // has its own relationship numbering (independent of the document part).\n const footerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const headerMediaResults = new Map<number, { xml: string; referenced: { fileName: string }[] }>();\n const docCtx = mkCtx(ctx.document);\n const documentXmlData = XML_DECL + stringifyDocumentXml(ctx, docCtx);\n\n // Comments is an optional part — skip it entirely (no comments.xml, no\n // comments rels, no [Content_Types] Override) when the document carries none.\n // Emitting an empty comments.xml with a dangling relationship is the OPC\n // violation that makes Word reject the package on open.\n const mergedCommentChildrenList = mergedCommentChildren(ctx);\n const hasComments = mergedCommentChildrenList.length > 0;\n const commentRelationshipCount = hasComments\n ? ctx.comments.relationships.relationshipCount + 1\n : 0;\n const commentCtx = hasComments ? mkCtx({ relationships: ctx.comments.relationships }) : null;\n const commentXmlData = commentCtx\n ? XML_DECL + commentsDesc.stringify({ children: mergedCommentChildrenList }, commentCtx)\n : \"\";\n\n const footnoteRelationshipCount = ctx.footNotes.relationships.relationshipCount + 1;\n const footnoteCtx = mkCtx({\n relationships: ctx.footNotes.relationships,\n });\n const footnoteXmlData =\n XML_DECL +\n (footnotesDesc.stringify(\n {\n notes: ctx.footNotes.notes,\n separator: ctx.footNotes.separator,\n continuationSeparator: ctx.footNotes.continuationSeparator,\n },\n footnoteCtx,\n ) ?? \"\");\n\n const documentMedia = findAndReplaceImagePlaceholders(\n documentXmlData,\n ctx.media.array,\n documentRelationshipCount,\n );\n // OLE embeddings reuse the same {fileName} placeholder bridge as images; run\n // after media so {oleObjectN.bin} placeholders resolve against the embedding array.\n const documentEmbeddingOffset = documentRelationshipCount + documentMedia.referenced.length;\n const documentEmbeddings = findAndReplaceImagePlaceholders(\n documentMedia.xml,\n ctx.embeddings.array,\n documentEmbeddingOffset,\n );\n const commentMedia = hasComments\n ? findAndReplaceImagePlaceholders(commentXmlData, ctx.media.array, commentRelationshipCount)\n : { xml: \"\", referenced: [] as { fileName: string }[] };\n const footnoteMedia = findAndReplaceImagePlaceholders(\n footnoteXmlData,\n ctx.media.array,\n footnoteRelationshipCount,\n );\n // Register footnote media relationships eagerly so the relationshipCount used\n // to gate footnotes.xml.rels reflects the final state (see FootNotesRelationships).\n for (let i = 0; i < footnoteMedia.referenced.length; i++) {\n ctx.footNotes.relationships.addRelationship(\n footnoteRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${footnoteMedia.referenced[i].fileName}`,\n );\n }\n\n return {\n AppProperties: {\n data: XML_DECL + (appPropertiesDesc.stringify(ctx._options.appProperties ?? {}, ctx) ?? \"\"),\n path: \"docProps/app.xml\",\n },\n ...(hasComments\n ? {\n Comments: {\n data: (() => {\n const xmlData =\n commentMedia.referenced.length > 0 ? commentMedia.xml : commentXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/comments.xml\",\n },\n CommentsRelationships: (() => {\n for (let i = 0; i < commentMedia.referenced.length; i++) {\n ctx.comments.relationships.addRelationship(\n commentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${commentMedia.referenced[i].fileName}`,\n );\n }\n return optionalRelsPart(\n ctx.comments.relationships,\n XML_DECL,\n \"word/_rels/comments.xml.rels\",\n );\n })(),\n }\n : {}),\n CustomProperties: {\n data:\n XML_DECL +\n (customPropertiesDesc.stringify({ properties: ctx._options.customProperties ?? [] }, ctx) ??\n \"\"),\n path: \"docProps/custom.xml\",\n },\n Document: {\n data: (() => {\n let xmlData = documentEmbeddings.xml;\n if (hasPlaceholders(xmlData)) {\n const mediaCount = documentMedia.referenced.length;\n const embeddingCount = documentEmbeddings.referenced.length;\n const chartKeys = ctx.charts.array.map((c) => c.key);\n const smartArtKeys = ctx.smartArts.array.map((s) => s.key);\n const chartOffset = documentRelationshipCount + mediaCount + embeddingCount;\n const smartArtOffset = chartOffset + chartKeys.length;\n\n // Build combined replacement entries for charts, smartart, and numbering\n const entries: Array<{ prefix?: string; key: string; value: string }> = [];\n for (let i = 0; i < chartKeys.length; i++) {\n entries.push({\n prefix: \"chart:\",\n key: chartKeys[i],\n value: formatId(chartOffset, i, \"rId\"),\n });\n }\n const saPrefixes = [\"smartart:\", \"smartart-lo:\", \"smartart-qs:\", \"smartart-cs:\"];\n for (let i = 0; i < smartArtKeys.length; i++) {\n for (let p = 0; p < saPrefixes.length; p++) {\n entries.push({\n prefix: saPrefixes[p],\n key: smartArtKeys[i],\n value: formatId(smartArtOffset + p * smartArtKeys.length, i, \"rId\"),\n });\n }\n }\n for (const { reference, instance, numId } of ctx.numbering.concreteNumbering) {\n entries.push({ key: `${reference}-${instance}`, value: numId.toString() });\n }\n xmlData = replaceAllPlaceholders(xmlData, entries);\n } else {\n xmlData = replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n }\n return xmlData;\n })(),\n path: \"word/document.xml\",\n },\n // Theme — fresh-compile emits a language-neutral default theme\n // (createThemeXml). Round-trip carries the source theme in rawParts,\n // already copied verbatim above, so skip emitting here to avoid a duplicate.\n ...(ctx._options.rawParts?.some((part) => part.path.startsWith(\"word/theme/\"))\n ? {}\n : {\n Theme: {\n data: XML_DECL + createThemeXml(),\n path: \"word/theme/theme1.xml\",\n },\n }),\n ...(ctx.hasEndnotes\n ? {\n Endnotes: {\n data: (() => {\n const endnoteCtx = mkCtx({\n relationships: ctx.endnotes.relationships,\n });\n const xmlData =\n XML_DECL +\n (endnotesDesc.stringify(\n {\n notes: ctx.endnotes.notes,\n separator: ctx.endnotes.separator,\n continuationSeparator: ctx.endnotes.continuationSeparator,\n },\n endnoteCtx,\n ) ?? \"\");\n const endnoteRelCount = ctx.endnotes.relationships.relationshipCount + 1;\n const endnoteMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n endnoteRelCount,\n );\n if (endnoteMedia.referenced.length > 0) {\n for (let i = 0; i < endnoteMedia.referenced.length; i++) {\n ctx.endnotes.relationships.addRelationship(\n endnoteRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${endnoteMedia.referenced[i].fileName}`,\n );\n }\n return replaceNumberingPlaceholders(\n endnoteMedia.xml,\n ctx.numbering.concreteNumbering,\n );\n }\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/endnotes.xml\",\n },\n EndnotesRelationships:\n ctx.endnotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.endnotes.relationships.serialize(),\n path: \"word/_rels/endnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FileRelationships: {\n data: XML_DECL + ctx.fileRelationships.serialize(),\n path: \"_rels/.rels\",\n },\n FontTable: {\n data:\n XML_DECL +\n (fontTableDesc.stringify({ fonts: ctx.fontTable.fontOptionsWithKey }, ctx) ?? \"\"),\n path: \"word/fontTable.xml\",\n },\n FontTableRelationships: optionalRelsPart(\n ctx.fontTable.relationships,\n XML_DECL,\n \"word/_rels/fontTable.xml.rels\",\n ),\n ...(ctx.hasFootnotes\n ? {\n FootNotes: {\n data: (() => {\n const xmlData =\n footnoteMedia.referenced.length > 0 ? footnoteMedia.xml : footnoteXmlData;\n return replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/footnotes.xml\",\n },\n FootNotesRelationships:\n ctx.footNotes.relationships.relationshipCount > 0\n ? {\n data: XML_DECL + ctx.footNotes.relationships.serialize(),\n path: \"word/_rels/footnotes.xml.rels\",\n }\n : undefined,\n }\n : {}),\n FooterRelationships: ctx.footers\n .map((entry, index) => {\n const footerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:ftr\", FOOTER_NAMESPACES, entry.children, footerCtx);\n footerFormattedViews.set(index, xmlData);\n // Footer images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const footerRelCount = entry.relationships.relationshipCount + 1;\n const footerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n footerRelCount,\n );\n footerMediaResults.set(index, footerMedia);\n\n for (let i = 0; i < footerMedia.referenced.length; i++) {\n entry.relationships.addRelationship(\n footerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${footerMedia.referenced[i].fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/footer${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Footers: ctx.footers.map((_entry, index) => {\n const footerMedia = footerMediaResults.get(index)!;\n const tempXmlData = footerFormattedViews.get(index)!;\n const xmlData = footerMedia.referenced.length > 0 ? footerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/footer${index + 1}.xml`,\n };\n }),\n HeaderRelationships: ctx.headers\n .map((entry, index) => {\n const headerCtx = mkCtx({ relationships: entry.relationships });\n const xmlData =\n XML_DECL + stringifyHeaderFooter(\"w:hdr\", HEADER_NAMESPACES, entry.children, headerCtx);\n headerFormattedViews.set(index, xmlData);\n // Header images get per-part relationship IDs starting at\n // relationshipCount+1, mirroring the document part. The placeholder pass\n // uses referenced-local positions, so body r:embed and .rels stay aligned.\n const headerRelCount = entry.relationships.relationshipCount + 1;\n const headerMedia = findAndReplaceImagePlaceholders(\n xmlData,\n ctx.media.array,\n headerRelCount,\n );\n headerMediaResults.set(index, headerMedia);\n\n for (let i = 0; i < headerMedia.referenced.length; i++) {\n entry.relationships.addRelationship(\n headerRelCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${headerMedia.referenced[i].fileName}`,\n );\n }\n\n return optionalRelsPart(\n entry.relationships,\n XML_DECL,\n `word/_rels/header${index + 1}.xml.rels`,\n );\n })\n .filter((r): r is XmlifyedFile => r !== undefined),\n Headers: ctx.headers.map((_entry, index) => {\n const headerMedia = headerMediaResults.get(index)!;\n const tempXmlData = headerFormattedViews.get(index)!;\n const xmlData = headerMedia.referenced.length > 0 ? headerMedia.xml : tempXmlData;\n\n return {\n data: replaceNumberingPlaceholders(xmlData, ctx.numbering.concreteNumbering),\n path: `word/header${index + 1}.xml`,\n };\n }),\n ...(ctx.hasNumbering\n ? {\n Numbering: {\n data: ctx.numbering.serialize(),\n path: \"word/numbering.xml\",\n },\n }\n : {}),\n Properties: {\n data: XML_DECL + (corePropertiesDesc.stringify(ctx._options, ctx) ?? \"\"),\n path: \"docProps/core.xml\",\n },\n Relationships: {\n data: (() => {\n for (let i = 0; i < documentMedia.referenced.length; i++) {\n ctx.document.relationships.addRelationship(\n documentRelationshipCount + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/image\",\n `media/${documentMedia.referenced[i].fileName}`,\n );\n }\n for (let i = 0; i < documentEmbeddings.referenced.length; i++) {\n ctx.document.relationships.addRelationship(\n documentEmbeddingOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject\",\n `embeddings/${documentEmbeddings.referenced[i].fileName}`,\n );\n }\n\n const chartOffset =\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length;\n for (let i = 0; i < ctx.charts.array.length; i++) {\n ctx.document.relationships.addRelationship(\n chartOffset + i,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart\",\n `charts/chart${i + 1}.xml`,\n );\n }\n\n addSmartArtRelationships(\n ctx.smartArts.array.map((s) => s.key),\n (id, type, target) => {\n ctx.document.relationships.addRelationship(id, type, target);\n },\n documentRelationshipCount +\n documentMedia.referenced.length +\n documentEmbeddings.referenced.length +\n ctx.charts.array.length,\n 0,\n {\n pathPrefix: \"\",\n styleRelType: \"http://schemas.microsoft.com/office/2007/relationships/diagramStyle\",\n },\n );\n\n ctx.document.relationships.addRelationship(\n ctx.document.relationships.relationshipCount + 1,\n \"http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable\",\n \"fontTable.xml\",\n );\n\n return XML_DECL + ctx.document.relationships.serialize();\n })(),\n path: \"word/_rels/document.xml.rels\",\n },\n Settings: {\n data: XML_DECL + (settingsDesc.stringify(ctx._settingsOptions, ctx) ?? \"\"),\n path: \"word/settings.xml\",\n },\n Styles: {\n data: (() => {\n const xmlStyles = ctx.styles.serialize();\n return replaceNumberingPlaceholders(xmlStyles, ctx.numbering.concreteNumbering);\n })(),\n path: \"word/styles.xml\",\n },\n ...(ctx._options.bibliography\n ? {\n Bibliography: {\n data: XML_DECL + (bibliographyDesc.stringify(ctx._options.bibliography, ctx) ?? \"\"),\n path: \"word/bibliography.xml\",\n },\n }\n : {}),\n ...(ctx.charts.array.length > 0\n ? {\n Charts: ctx.charts.array.map((chartData, i) => ({\n data: XML_DECL + chartData.chartSpaceXml,\n path: `word/charts/chart${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.smartArts.array.length > 0\n ? {\n DiagramData: ctx.smartArts.array.map((smartArtData, i) => ({\n data: XML_DECL + smartArtData.dataModelXml,\n path: `word/diagrams/data${i + 1}.xml`,\n })),\n DiagramLayout: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getLayoutXml(smartArtData.layout),\n path: `word/diagrams/layout${i + 1}.xml`,\n })),\n DiagramStyle: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getStyleXml(smartArtData.style),\n path: `word/diagrams/quickStyle${i + 1}.xml`,\n })),\n DiagramColors: ctx.smartArts.array.map((smartArtData, i) => ({\n data: getColorXml(smartArtData.color),\n path: `word/diagrams/colors${i + 1}.xml`,\n })),\n DiagramDrawing: ctx.smartArts.array.map((_, i) => ({\n data: DEFAULT_DRAWING_XML,\n path: `word/diagrams/drawing${i + 1}.xml`,\n })),\n }\n : {}),\n ...(ctx.altChunks.array.length > 0\n ? {\n AltChunks: ctx.altChunks.array.map((altChunkData) => ({\n data: altChunkData.data,\n path: `word/${altChunkData.path}`,\n })),\n }\n : {}),\n ...(ctx.subDocs.array.length > 0\n ? {\n SubDocs: ctx.subDocs.array.map((subDocData) => ({\n data: subDocData.data,\n path: `word/${subDocData.path}`,\n })),\n }\n : {}),\n ...(ctx.glossaryOptions\n ? {\n Glossary: {\n data: (() => {\n const glossaryCtx = mkCtx(undefined);\n return XML_DECL + (glossaryDesc.stringify(ctx.glossaryOptions!, glossaryCtx) ?? \"\");\n })(),\n path: \"word/glossary/document.xml\",\n },\n }\n : {}),\n ...(ctx.webSettings\n ? {\n WebSettings: {\n data: XML_DECL + (webSettingsDesc.stringify(ctx._options.webSettings ?? {}, ctx) ?? \"\"),\n path: \"word/webSettings.xml\",\n },\n }\n : {}),\n };\n}\n","/**\n * Pure function API for generating DOCX files.\n *\n * @module\n */\n\nimport { createPacker, OoxmlMimeType } from \"@office-open/core\";\nimport type { OutputByType, OutputType, PackerOptions } from \"@office-open/core\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\n\nimport { compileDocument } from \"./compiler\";\n\n/** @internal Packer instance for DOCX generation. */\nconst Packer = createPacker<DocumentOptions>({\n compile: (options, overrides, mediaLevel) => compileDocument(options, overrides, mediaLevel),\n mimeType: OoxmlMimeType.DOCX,\n});\n\n/**\n * Generate a DOCX file from pure JSON options.\n *\n * The output format is controlled by `packerOptions.type` (default: `\"nodebuffer\"` → Buffer).\n * For synchronous generation, use {@link generateDocumentSync}. For streaming, use {@link generateDocumentStream}.\n *\n * @param options - Document options (sections, styles, numbering, etc.)\n * @param packerOptions - Optional packer configuration (type, compression, overrides, etc.)\n *\n * @example\n * ```typescript\n * import { generateDocument } from \"@office-open/docx\";\n *\n * const buffer = await generateDocument({ sections: [...] });\n * const bytes = await generateDocument({ sections: [...] }, { type: \"uint8array\" });\n * const blob = await generateDocument({ sections: [...] }, { type: \"blob\" });\n * ```\n */\nexport function generateDocument<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): Promise<OutputByType[T]> {\n return Packer.pack(options, packerOptions) as Promise<OutputByType[T]>;\n}\n\n/**\n * Synchronously generate a DOCX file from pure JSON options.\n */\nexport function generateDocumentSync<T extends OutputType = \"nodebuffer\">(\n options: DocumentOptions,\n packerOptions?: PackerOptions<T>,\n): OutputByType[T] {\n return Packer.packSync(options, packerOptions) as OutputByType[T];\n}\n\n/**\n * Generate a DOCX file as a `ReadableStream<Uint8Array>`.\n */\nexport function generateDocumentStream(\n options: DocumentOptions,\n packerOptions?: PackerOptions,\n): ReadableStream<Uint8Array> {\n return Packer.toStream(options, packerOptions);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAaA,MAAM,wBAAwB;;AAE9B,MAAM,sBAAsB;;AAE5B,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;AAuBjB,MAAa,aAAa,KAAiB,YAAgC;CACzE,MAAM,OAAO,QAAQ,QAAQ,MAAM,EAAE;CACrC,IAAI,KAAK,WAAW,UAClB,MAAM,IAAI,MAAM,kDAAkD,SAAS;CAI7E,MAAM,aADa,KAAK,QAAQ,SAAS,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAAM,GACjC,CAAC,CAAC,KAAK,cAAc,SAAS,WAAW,EAAE,CAAC;CACxE,WAAW,QAAQ;CAGnB,MAAM,kBADmB,IAAI,MAAM,uBAAuB,mBACnB,CAAC,CAAC,KACtC,MAAM,MAAM,OAAO,WAAW,IAAI,WAAW,OAChD;CAEA,MAAM,MAAM,IAAI,WACd,wBAAwB,gBAAgB,SAAS,KAAK,IAAI,GAAG,IAAI,SAAS,mBAAmB,CAC/F;CACA,IAAI,IAAI,IAAI,MAAM,GAAG,qBAAqB,CAAC;CAC3C,IAAI,IAAI,iBAAiB,qBAAqB;CAC9C,IAAI,IAAI,IAAI,MAAM,mBAAmB,GAAG,wBAAwB,gBAAgB,MAAM;CACtF,OAAO;AACT;;;;;;;ACxBA,MAAa,oBAAkD;CAC7D;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAC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AG,KAAK;GACpF,MAAM;EACR,EACF,IACA,CAAC;CACP;AACF;;;;;;;;;AC5tBA,MAAM,SAAS,aAA8B;CAC3C,UAAU,SAAS,WAAW,eAAe,gBAAgB,SAAS,WAAW,UAAU;CAC3F,UAAU,cAAc;AAC1B,CAAC;;;;;;;;;;;;;;;;;;;AAoBD,SAAgB,iBACd,SACA,eAC0B;CAC1B,OAAO,OAAO,KAAK,SAAS,aAAa;AAC3C;;;;AAKA,SAAgB,qBACd,SACA,eACiB;CACjB,OAAO,OAAO,SAAS,SAAS,aAAa;AAC/C;;;;AAKA,SAAgB,uBACd,SACA,eAC4B;CAC5B,OAAO,OAAO,SAAS,SAAS,aAAa;AAC/C"}
|
package/dist/generate.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as generateDocumentStream, r as generateDocumentSync, t as generateDocument } from "./generate-
|
|
1
|
+
import { n as generateDocumentStream, r as generateDocumentSync, t as generateDocument } from "./generate-DjODfjQ1.mjs";
|
|
2
2
|
export { generateDocument, generateDocumentStream, generateDocumentSync };
|
package/dist/index.mjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { $ as PageBorderZOrder, $t as stringifyCustomXmlShell, A as StyleLevel, An as TextHorzOverflowType, At as sectionPageSizeDefaults, B as stringifyNumberingStyle, Bn as TextEffect, Bt as NumberFormat, C as footnotesDesc, Cn as RubyAlign, Ct as parseSdtBlock, D as selectTocEntryElements, Dn as EmphasisMarkType, Dt as sectionPropertiesDesc, E as parseTocFieldInstruction, En as PositionalTabRelativeTo, Et as parseSectionPropertiesEl, F as extractStyleId, Fn as parseBodyProperties, Ft as createVerticalPosition, G as createHeaderFooterReference, Gn as TextboxTightWrapType, Gt as TextWrappingSide, H as stringifyTableStyle, Hn as PageNumber, Ht as VerticalPositionAlign, I as parseStyleDefinitions, In as createImageData, It as createHorizontalPosition, J as LineNumberRestartFormat, Jn as AlignmentType, Jt as checkboxSymbolRunInner, K as SectionType, Kn as HeadingLevel, Kt as TextWrappingType, L as DefaultStylesFactory, Ln as Media, Lt as HorizontalPositionRelativeFrom, M as Styles, Mn as TextVerticalType, Mt as PageOrientation, N as buildNumberingCache, Nn as VerticalAnchor, Nt as PageNumberSeparator, O as SdtDateMappingType, On as UnderlineType, Ot as stringifySectionPropertiesXml, P as buildStyleCache, Pn as createBodyProperties, Pt as createPageNumberType, Q as PageBorderOffsetFrom, Qt as setBodyParseChild, R as stringifyCharacterStyle, Rn as createTransformation, Rt as VerticalPositionRelativeFrom, S as endnotesDesc, Sn as parseFormFieldData, St as stringifyTableOfContents, T as parseTocFieldFromElements, Tn as PositionalTabLeader, U as HeaderFooterReferenceType, Un as breakXml, Ut as createWrapThrough, V as stringifyParagraphStyle, Vn as EMPTY_RUN_ELEMENTS, Vt as SpaceType, W as HeaderFooterType, Wn as TextAlignmentType, Wt as createWrapTight, X as createPageMargin, Xt as parseCustomXmlProperties, Y as createLineNumberType, Yt as customXmlBlockDesc, Z as PageBorderDisplay, Zt as sdtBlockDesc, _ as glossaryDesc, _n as TextDirection, a as appPropertiesDesc, an as parseShading, at as LevelFormat, b as CharacterSet, bn as FormFieldTextType, c as relationshipsDesc, cn as widthFiftiethsToPct, ct as parseTablePropertiesEl, d as withAltChunkOverrides, dn as BorderStyle, dt as tableDesc, en as stringifySdtPr, et as DocumentGridType, f as withMediaDefaults, fn as TableLayoutType, ft as stringifyChildDispatch, g as DocPartType, gn as TableAnchorType, gt as resetDrawingIdGen, h as DocPartGallery, hn as RelativeVerticalPosition, ht as drawingDesc, i as webSettingsDesc, in as ShadingType, it as parseNumberingDefinitions, j as settingsDesc, jn as TextVertOverflowType, jt as PageTextDirectionType, k as SdtLock, kn as TextBodyWrappingType, kt as sectionMarginDefaults, l as buildContentTypesFromRegistry, ln as widthPctToFiftieths, lt as parseTableRowPropertiesEl, m as DocPartBehavior, mn as RelativeHorizontalPosition, mt as stringifyRunInline, n as frameXml, nn as subDocDesc, nt as DocumentAttributeNamespaces, o as customPropertiesDesc, on as objectDesc, ot as LevelSuffix, p as commentsDesc, pn as OverlapType, pt as stringifyParagraphInline, q as createSectionType, qn as LineRuleType, qt as altChunkDesc, r as framesetXml, rt as Numbering, s as corePropertiesDesc, sn as WidthType, st as parseTableCellPropertiesEl, t as TargetScreenSize, tn as stringifySdtShell, tt as createDocumentGrid, u as contentTypesDesc, un as TABLE_BORDERS_NONE, ut as setTableParseChild, v as bibliographyDesc, vn as VerticalMergeType, w as parseToc, wn as PositionalTabAlignment, wt as parseSdtProperties, x as EditGroupType, xn as createFormFieldData, y as fontTableDesc, yn as ProofErrorType, z as stringifyConditionalTableStyle, zn as HighlightColor, zt as HorizontalPositionAlign } from "./parts-
|
|
2
|
-
import { i as AltChunkCollection, n as DocxWriteContext, r as SubDocCollection, t as DocxReadContext } from "./context-
|
|
1
|
+
import { $ as PageBorderZOrder, $t as stringifyCustomXmlShell, A as StyleLevel, An as TextHorzOverflowType, At as sectionPageSizeDefaults, B as stringifyNumberingStyle, Bn as TextEffect, Bt as NumberFormat, C as footnotesDesc, Cn as RubyAlign, Ct as parseSdtBlock, D as selectTocEntryElements, Dn as EmphasisMarkType, Dt as sectionPropertiesDesc, E as parseTocFieldInstruction, En as PositionalTabRelativeTo, Et as parseSectionPropertiesEl, F as extractStyleId, Fn as parseBodyProperties, Ft as createVerticalPosition, G as createHeaderFooterReference, Gn as TextboxTightWrapType, Gt as TextWrappingSide, H as stringifyTableStyle, Hn as PageNumber, Ht as VerticalPositionAlign, I as parseStyleDefinitions, In as createImageData, It as createHorizontalPosition, J as LineNumberRestartFormat, Jn as AlignmentType, Jt as checkboxSymbolRunInner, K as SectionType, Kn as HeadingLevel, Kt as TextWrappingType, L as DefaultStylesFactory, Ln as Media, Lt as HorizontalPositionRelativeFrom, M as Styles, Mn as TextVerticalType, Mt as PageOrientation, N as buildNumberingCache, Nn as VerticalAnchor, Nt as PageNumberSeparator, O as SdtDateMappingType, On as UnderlineType, Ot as stringifySectionPropertiesXml, P as buildStyleCache, Pn as createBodyProperties, Pt as createPageNumberType, Q as PageBorderOffsetFrom, Qt as setBodyParseChild, R as stringifyCharacterStyle, Rn as createTransformation, Rt as VerticalPositionRelativeFrom, S as endnotesDesc, Sn as parseFormFieldData, St as stringifyTableOfContents, T as parseTocFieldFromElements, Tn as PositionalTabLeader, U as HeaderFooterReferenceType, Un as breakXml, Ut as createWrapThrough, V as stringifyParagraphStyle, Vn as EMPTY_RUN_ELEMENTS, Vt as SpaceType, W as HeaderFooterType, Wn as TextAlignmentType, Wt as createWrapTight, X as createPageMargin, Xt as parseCustomXmlProperties, Y as createLineNumberType, Yt as customXmlBlockDesc, Z as PageBorderDisplay, Zt as sdtBlockDesc, _ as glossaryDesc, _n as TextDirection, a as appPropertiesDesc, an as parseShading, at as LevelFormat, b as CharacterSet, bn as FormFieldTextType, c as relationshipsDesc, cn as widthFiftiethsToPct, ct as parseTablePropertiesEl, d as withAltChunkOverrides, dn as BorderStyle, dt as tableDesc, en as stringifySdtPr, et as DocumentGridType, f as withMediaDefaults, fn as TableLayoutType, ft as stringifyChildDispatch, g as DocPartType, gn as TableAnchorType, gt as resetDrawingIdGen, h as DocPartGallery, hn as RelativeVerticalPosition, ht as drawingDesc, i as webSettingsDesc, in as ShadingType, it as parseNumberingDefinitions, j as settingsDesc, jn as TextVertOverflowType, jt as PageTextDirectionType, k as SdtLock, kn as TextBodyWrappingType, kt as sectionMarginDefaults, l as buildContentTypesFromRegistry, ln as widthPctToFiftieths, lt as parseTableRowPropertiesEl, m as DocPartBehavior, mn as RelativeHorizontalPosition, mt as stringifyRunInline, n as frameXml, nn as subDocDesc, nt as DocumentAttributeNamespaces, o as customPropertiesDesc, on as objectDesc, ot as LevelSuffix, p as commentsDesc, pn as OverlapType, pt as stringifyParagraphInline, q as createSectionType, qn as LineRuleType, qt as altChunkDesc, r as framesetXml, rt as Numbering, s as corePropertiesDesc, sn as WidthType, st as parseTableCellPropertiesEl, t as TargetScreenSize, tn as stringifySdtShell, tt as createDocumentGrid, u as contentTypesDesc, un as TABLE_BORDERS_NONE, ut as setTableParseChild, v as bibliographyDesc, vn as VerticalMergeType, w as parseToc, wn as PositionalTabAlignment, wt as parseSdtProperties, x as EditGroupType, xn as createFormFieldData, y as fontTableDesc, yn as ProofErrorType, z as stringifyConditionalTableStyle, zn as HighlightColor, zt as HorizontalPositionAlign } from "./parts-B7Sfx_F0.mjs";
|
|
2
|
+
import { i as AltChunkCollection, n as DocxWriteContext, r as SubDocCollection, t as DocxReadContext } from "./context-CiyAhqTX.mjs";
|
|
3
3
|
import { patchDetector, patchDocument } from "./patch/index.mjs";
|
|
4
|
-
import { n as parseDocument, r as parseDocx, t as parseArchive } from "./parse-
|
|
5
|
-
import { i as compileDocument, n as generateDocumentStream, r as generateDocumentSync, t as generateDocument } from "./generate-
|
|
4
|
+
import { n as parseDocument, r as parseDocx, t as parseArchive } from "./parse-DDWWDGbX.mjs";
|
|
5
|
+
import { i as compileDocument, n as generateDocumentStream, r as generateDocumentSync, t as generateDocument } from "./generate-DjODfjQ1.mjs";
|
|
6
6
|
//#region src/parts/paragraph/formatting/break.ts
|
|
7
7
|
/**
|
|
8
8
|
* Break type values for WordprocessingML documents.
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { C as footnotesDesc, Ct as parseSdtBlock, D as selectTocEntryElements, Et as parseSectionPropertiesEl, I as parseStyleDefinitions, N as buildNumberingCache, P as buildStyleCache, Qt as setBodyParseChild, S as endnotesDesc, T as parseTocFieldFromElements, Xt as parseCustomXmlProperties, _ as glossaryDesc, _t as parseParagraph, a as appPropertiesDesc, dt as tableDesc, i as webSettingsDesc, it as parseNumberingDefinitions, j as settingsDesc, o as customPropertiesDesc, p as commentsDesc, rn as stringifyElement, s as corePropertiesDesc, u as contentTypesDesc, ut as setTableParseChild, v as bibliographyDesc, vt as parseParagraphProperties, w as parseToc, xt as replaceRelsWithPlaceholders, y as fontTableDesc } from "./parts-
|
|
2
|
-
import { t as DocxReadContext } from "./context-
|
|
1
|
+
import { C as footnotesDesc, Ct as parseSdtBlock, D as selectTocEntryElements, Et as parseSectionPropertiesEl, I as parseStyleDefinitions, N as buildNumberingCache, P as buildStyleCache, Qt as setBodyParseChild, S as endnotesDesc, T as parseTocFieldFromElements, Xt as parseCustomXmlProperties, _ as glossaryDesc, _t as parseParagraph, a as appPropertiesDesc, dt as tableDesc, i as webSettingsDesc, it as parseNumberingDefinitions, j as settingsDesc, o as customPropertiesDesc, p as commentsDesc, rn as stringifyElement, s as corePropertiesDesc, u as contentTypesDesc, ut as setTableParseChild, v as bibliographyDesc, vt as parseParagraphProperties, w as parseToc, xt as replaceRelsWithPlaceholders, y as fontTableDesc } from "./parts-B7Sfx_F0.mjs";
|
|
2
|
+
import { t as DocxReadContext } from "./context-CiyAhqTX.mjs";
|
|
3
3
|
import { parseArchive, toUint8Array } from "@office-open/core";
|
|
4
4
|
import { attr, findChild, findDeep, findFirst, textOf } from "@office-open/xml";
|
|
5
5
|
//#region \0polyfill-node.global.js
|
|
@@ -1532,7 +1532,7 @@ function parseBody(body, ctx) {
|
|
|
1532
1532
|
let start = 0;
|
|
1533
1533
|
for (let i = 0; i < boundaries.length; i++) {
|
|
1534
1534
|
const boundary = boundaries[i];
|
|
1535
|
-
const endIdx =
|
|
1535
|
+
const endIdx = boundary.index;
|
|
1536
1536
|
const sectionElements = bodyChildren.slice(start, endIdx);
|
|
1537
1537
|
const parsedProps = parseSectionProperties(boundary.sectPr, ctx);
|
|
1538
1538
|
const { parsedHeaders, parsedFooters } = parsedProps;
|
|
@@ -1934,4 +1934,4 @@ function parseDocx(data) {
|
|
|
1934
1934
|
//#endregion
|
|
1935
1935
|
export { parseDocument as n, parseDocx as r, parseArchive as t };
|
|
1936
1936
|
|
|
1937
|
-
//# sourceMappingURL=parse-
|
|
1937
|
+
//# sourceMappingURL=parse-DDWWDGbX.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse-DDWWDGbX.mjs","names":[],"sources":["../src/parts/alt-chunk/alt-chunk-parse.ts","../src/parts/custom-xml/custom-xml-parse.ts","../src/parts/sub-doc/sub-doc-parse.ts","../src/parts/textbox/textbox-parse.ts","../src/parse/body.ts","../src/parse.ts"],"sourcesContent":["/**\n * AltChunk parser for DOCX documents.\n *\n * Parses w:altChunk elements and extracts embedded content from the ZIP.\n *\n * @module\n */\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { AltChunkOptions } from \"@parts/alt-chunk/alt-chunk\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse a w:altChunk element into AltChunkOptions.\n * Reads the referenced data from the ZIP package.\n */\nexport function parseAltChunk(el: Element, ctx: DocxReadContext): AltChunkOptions {\n const rId = attr(el, \"r:id\");\n if (!rId) {\n throw new Error(\"w:altChunk missing r:id attribute\");\n }\n\n // Look up the path from relationships\n const path = ctx.docx.partRefs.afChunks.get(rId);\n if (!path) {\n throw new Error(`AltChunk relationship ${rId} not found`);\n }\n\n // Read raw data from ZIP\n const data = ctx.docx.doc.getRaw(path);\n if (!data) {\n throw new Error(`AltChunk data not found at ${path}`);\n }\n\n // Determine content type from extension\n const ext = path.split(\".\").pop() ?? \"txt\";\n let contentType: \"text/html\" | \"application/rtf\" | \"text/plain\";\n let extension: \"html\" | \"rtf\" | \"txt\";\n\n switch (ext) {\n case \"html\":\n contentType = \"text/html\";\n extension = \"html\";\n break;\n case \"rtf\":\n contentType = \"application/rtf\";\n extension = \"rtf\";\n break;\n default:\n contentType = \"text/plain\";\n extension = \"txt\";\n break;\n }\n\n return {\n data,\n contentType,\n extension,\n };\n}\n","/**\n * Parser for custom XML block elements (w:customXml).\n *\n * @module\n */\nimport { attr, findChild } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport type { DocxReadContext } from \"../../context\";\nimport { parseCustomXmlProperties } from \"../bodychildren\";\nimport type { CustomXmlBlockOptions } from \"./custom-xml\";\n\n/**\n * Parse w:customXml element into CustomXmlBlockOptions.\n *\n * Uses a callback for child parsing to avoid circular dependencies\n * (same pattern as parseTable).\n */\nexport function parseCustomXmlBlock(\n el: Element,\n ctx: DocxReadContext,\n parseChild: (el: Element, ctx: DocxReadContext) => SectionChild,\n): CustomXmlBlockOptions {\n const opts: Partial<CustomXmlBlockOptions> = {};\n\n // Required attribute\n const element = attr(el, \"w:element\");\n if (element) opts.element = element;\n\n // Optional URI\n const uri = attr(el, \"w:uri\");\n if (uri) opts.uri = uri;\n\n // Parse w:customXmlPr\n const xmlPr = findChild(el, \"w:customXmlPr\");\n if (xmlPr) {\n opts.customXmlPr = parseCustomXmlProperties(xmlPr);\n }\n\n // Parse block-level children\n const children: SectionChild[] = [];\n for (const child of el.elements ?? []) {\n if (child.name === \"w:customXmlPr\") continue;\n const parsed = parseChild(child, ctx);\n children.push(parsed);\n }\n if (children.length > 0) opts.children = children;\n\n return opts as CustomXmlBlockOptions;\n}\n","/**\n * SubDoc parser for DOCX documents.\n *\n * Parses w:subDoc elements and extracts embedded document data.\n *\n * @module\n */\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport type { SubDocOptions } from \"@parts/sub-doc/sub-doc\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse a w:subDoc element into SubDocOptions.\n * Reads the referenced document data from the ZIP package.\n */\nexport function parseSubDoc(el: Element, ctx: DocxReadContext): SubDocOptions {\n const rId = attr(el, \"r:id\");\n if (!rId) {\n throw new Error(\"w:subDoc missing r:id attribute\");\n }\n\n const path = ctx.docx.partRefs.subDocs.get(rId);\n if (!path) {\n throw new Error(`SubDoc relationship ${rId} not found`);\n }\n\n const data = ctx.docx.doc.getRaw(path);\n if (!data) {\n throw new Error(`SubDoc data not found at ${path}`);\n }\n\n return { data };\n}\n","/**\n * Textbox parser for DOCX documents.\n *\n * Parses w:pict → v:shape → v:textbox → w:txbxContent elements.\n *\n * @module\n */\nimport { attr, findChild, findFirst } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\n\nimport type { DocxReadContext } from \"../../context\";\n\n/**\n * Parse VML shape style string into VmlShapeStyle-like object.\n */\nfunction parseVmlStyle(styleStr: string): Record<string, string> {\n const style: Record<string, string> = {};\n for (const part of styleStr.split(\";\")) {\n const [key, val] = part.split(\":\").map((s) => s.trim());\n if (key && val) style[key] = val;\n }\n return style;\n}\n\n/**\n * Parse a w:pict element that contains a textbox.\n * Returns an object suitable for the { textbox: ... } SectionChild variant.\n */\nexport function parseTextbox(\n el: Element,\n ctx: DocxReadContext,\n parseChildren: (elements: Element[], ctx: DocxReadContext) => unknown[],\n): {\n style?: Record<string, string>;\n children?: unknown[];\n} {\n const shape = findFirst(el, \"v:shape\");\n if (!shape) return {};\n\n const opts: Record<string, unknown> = {};\n\n // Parse VML style\n const styleAttr = attr(shape, \"style\");\n if (styleAttr) {\n opts.style = parseVmlStyle(styleAttr);\n }\n\n // Parse textbox content\n const textbox = findFirst(shape, \"v:textbox\");\n if (textbox) {\n const txbxContent = findChild(textbox, \"w:txbxContent\");\n if (txbxContent) {\n const childList = parseChildren(txbxContent.elements ?? [], ctx);\n if (childList.length > 0) opts.children = childList;\n }\n }\n\n return opts as { style?: Record<string, string>; children?: unknown[] };\n}\n","/**\n * Body parser for DOCX documents.\n *\n * Parses w:body → SectionOptions[] by splitting at w:sectPr boundaries.\n *\n * @module\n */\nimport { attr, findChild, findDeep, findFirst, textOf } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { parseAltChunk } from \"@parts/alt-chunk/alt-chunk-parse\";\nimport { parseCustomXmlBlock } from \"@parts/custom-xml/custom-xml-parse\";\nimport { parseSectionPropertiesEl } from \"@parts/document/body/section-properties/descriptor\";\nimport type { SectionPropertiesOptions } from \"@parts/document/body/section-properties/section-properties\";\nimport type { MarkupRangeOptions, BookmarkStartOptions } from \"@parts/paragraph/links/bookmark\";\nimport { parseSdtBlock } from \"@parts/sdt/sdt-parse\";\nimport { parseSubDoc } from \"@parts/sub-doc/sub-doc-parse\";\nimport {\n parseToc,\n parseTocFieldFromElements,\n selectTocEntryElements,\n} from \"@parts/table-of-contents/toc-parse\";\nimport { tableDesc } from \"@parts/table/descriptor\";\nimport type { TableOptions } from \"@parts/table/table\";\nimport { parseTextbox } from \"@parts/textbox/textbox-parse\";\nimport type { SectionOptions } from \"@shared/section\";\nimport type { SectionChild } from \"@shared/section\";\n\nimport { parseParagraph } from \"../body\";\nimport { DocxReadContext } from \"../context\";\nimport { setBodyParseChild } from \"../parts\";\nimport { stringifyElement } from \"../util/stringify-element\";\n\n// ── Section properties parser ────────────────────────────────────────────────\n\n/** Internal parse result: section properties with extracted header/footer refs. */\ntype ParsedSectionProperties = SectionPropertiesOptions & {\n parsedHeaders?: Record<string, SectionChild[]>;\n parsedFooters?: Record<string, SectionChild[]>;\n};\n\n/**\n * Parse w:sectPr element into SectionPropertiesOptions.\n * Delegates to the section properties descriptor's parse method.\n */\nfunction parseSectionProperties(el: Element, ctx: DocxReadContext): ParsedSectionProperties {\n const opts: ParsedSectionProperties = parseSectionPropertiesEl(el);\n\n // Headers/footers - parse from references and store in a separate field\n const headerRefs: Record<string, SectionChild[]> = {};\n const footerRefs: Record<string, SectionChild[]> = {};\n\n for (const child of el.elements ?? []) {\n if (child.name === \"w:headerReference\") {\n const rId = attr(child, \"r:id\");\n const type = attr(child, \"w:type\");\n if (rId && type) {\n const headerChildren = parseHeaderFooterRef(rId, ctx);\n if (headerChildren) headerRefs[type] = headerChildren;\n }\n }\n if (child.name === \"w:footerReference\") {\n const rId = attr(child, \"r:id\");\n const type = attr(child, \"w:type\");\n if (rId && type) {\n const footerChildren = parseHeaderFooterRef(rId, ctx);\n if (footerChildren) footerRefs[type] = footerChildren;\n }\n }\n }\n\n if (Object.keys(headerRefs).length > 0) {\n opts.parsedHeaders = headerRefs;\n }\n if (Object.keys(footerRefs).length > 0) {\n opts.parsedFooters = footerRefs;\n }\n\n return opts;\n}\n\n/**\n * Parse a header/footer reference by following the relationship to its XML part.\n */\nfunction parseHeaderFooterRef(rId: string, ctx: DocxReadContext): SectionChild[] | undefined {\n const path = ctx.docx.partRefs.headers.get(rId) ?? ctx.docx.partRefs.footers.get(rId);\n if (!path) return undefined;\n\n const partEl = ctx.docx.doc.get(path);\n if (!partEl) return undefined;\n\n // The header/footer XML root element contains w:p, w:tbl, etc. Parse under\n // the part's own relationship scope so its drawings resolve images correctly.\n const children: SectionChild[] = [];\n ctx.withPart(path, () => {\n for (const child of partEl.elements ?? []) {\n const sectionChild = parseSectionChild(child, ctx);\n if (sectionChild !== undefined) {\n children.push(sectionChild);\n }\n }\n });\n\n return children.length > 0 ? children : undefined;\n}\n\n// ── Section child dispatch ───────────────────────────────────────────────────\n\n/**\n * Parse a single body child element into a SectionChild.\n */\nexport function parseSectionChild(el: Element, ctx: DocxReadContext): SectionChild {\n switch (el.name) {\n case \"w:p\": {\n // Check for textbox (w:pict containing v:textbox)\n const pict = findChild(el, \"w:pict\");\n if (pict) {\n const textbox = findFirst(pict, \"v:textbox\");\n if (textbox) {\n const textboxOpts = parseTextbox(pict, ctx, parseSectionChildrenElements);\n return { textbox: textboxOpts as SectionChild extends { textbox: infer T } ? T : never };\n }\n }\n\n return { paragraph: parseParagraph(el, ctx) };\n }\n case \"w:tbl\":\n return { table: tableDesc.parse(el, ctx) as TableOptions };\n case \"w:sdt\": {\n // Try TOC first\n const tocResult = parseToc(el, ctx, parseSectionChildrenElements);\n if (tocResult) {\n return { toc: tocResult };\n }\n // Otherwise parse as generic SDT block\n const sdtResult = parseSdtBlock(el, ctx, parseSectionChildrenElements);\n return {\n sdt: {\n properties: sdtResult.properties,\n children: sdtResult.children as SectionChild[] | undefined,\n },\n };\n }\n case \"w:altChunk\":\n return { altChunk: parseAltChunk(el, ctx) };\n case \"w:subDoc\":\n return { subDoc: parseSubDoc(el, ctx) };\n case \"w:customXml\":\n return { customXml: parseCustomXmlBlock(el, ctx, parseSectionChild) };\n case \"w:bookmarkStart\": {\n // Body-level range markers sitting between paragraphs (e.g. _Toc bookmark\n // ends grouped after a heading). Carry them as first-class children so\n // they round-trip even though they are not wrapped in a paragraph.\n const idRaw = attr(el, \"w:id\");\n const name = attr(el, \"w:name\");\n if (idRaw !== undefined && name) {\n const bookmarkStart: Partial<BookmarkStartOptions> = { id: Number(idRaw), name };\n const disp = attr(el, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") bookmarkStart.displacedByCustomXml = disp;\n const colFirstRaw = attr(el, \"w:colFirst\");\n if (colFirstRaw !== undefined) bookmarkStart.colFirst = Number(colFirstRaw);\n const colLastRaw = attr(el, \"w:colLast\");\n if (colLastRaw !== undefined) bookmarkStart.colLast = Number(colLastRaw);\n return { bookmarkStart: bookmarkStart as BookmarkStartOptions };\n }\n return { rawXml: stringifyElement(el) };\n }\n case \"w:bookmarkEnd\": {\n const idRaw = attr(el, \"w:id\");\n if (idRaw !== undefined) {\n const bookmarkEnd: Partial<MarkupRangeOptions> = { id: Number(idRaw) };\n const disp = attr(el, \"w:displacedByCustomXml\");\n if (disp === \"before\" || disp === \"after\") bookmarkEnd.displacedByCustomXml = disp;\n return { bookmarkEnd: bookmarkEnd as MarkupRangeOptions };\n }\n return { rawXml: stringifyElement(el) };\n }\n default:\n return { rawXml: stringifyElement(el) };\n }\n}\n\n// ── Body parsing with section splitting ───────────────────────────────────────\n\n/**\n * Parse w:body element into SectionOptions[].\n *\n * Splits body content at w:sectPr boundaries to create sections.\n * The last w:sectPr (child of w:body directly) defines the last section.\n * Previous w:sectPr elements appear inside w:pPr elements.\n */\nexport function parseBody(body: Element, ctx: DocxReadContext): SectionOptions[] {\n // Register the body child parser for descriptor parse callbacks\n setBodyParseChild(parseSectionChild);\n\n // Collect body children and detect section breaks\n interface SectionBoundary {\n index: number;\n sectPr: Element;\n }\n\n const bodyChildren: Element[] = [];\n const boundaries: SectionBoundary[] = [];\n\n for (const child of body.elements ?? []) {\n if (child.name === \"w:sectPr\") {\n // Final section properties (last section)\n boundaries.push({ index: bodyChildren.length, sectPr: child });\n } else {\n bodyChildren.push(child);\n\n // Check for inline sectPr in paragraph properties\n if (child.name === \"w:p\") {\n const pPr = findChild(child, \"w:pPr\");\n if (pPr) {\n const sectPr = findChild(pPr, \"w:sectPr\");\n if (sectPr) {\n boundaries.push({ index: bodyChildren.length, sectPr });\n }\n }\n }\n }\n }\n\n // If no boundaries, the whole body is one section\n if (boundaries.length === 0) {\n return [\n {\n children: parseBodyChildren(bodyChildren, ctx),\n },\n ];\n }\n\n // Split into sections\n const sections: SectionOptions[] = [];\n let start = 0;\n\n for (let i = 0; i < boundaries.length; i++) {\n const boundary = boundaries[i];\n // A sectPr inside a paragraph's pPr marks that paragraph as the final\n // content paragraph of its section. Its runs/drawings ARE section content\n // (e.g. an inline image), so include it in the slice — the paragraph parser\n // ignores pPr/w:sectPr, and stringify re-injects the sectPr into this same\n // paragraph's pPr. The last boundary is a body-level sectPr (never in a\n // paragraph), so boundary.index already points past every real child.\n const endIdx = boundary.index;\n const sectionElements = bodyChildren.slice(start, endIdx);\n const parsedProps = parseSectionProperties(boundary.sectPr, ctx);\n\n // Extract headers/footers that were stored as parsedHeaders/parsedFooters\n const { parsedHeaders, parsedFooters } = parsedProps;\n\n // Build clean properties without internal fields\n const cleanProps = { ...parsedProps };\n delete cleanProps.parsedHeaders;\n delete cleanProps.parsedFooters;\n\n const section = {\n children: parseBodyChildren(sectionElements, ctx),\n properties: cleanProps,\n ...(parsedHeaders ? { headers: parsedHeaders } : {}),\n ...(parsedFooters ? { footers: parsedFooters } : {}),\n } as SectionOptions;\n\n sections.push(section);\n start = boundary.index;\n }\n\n // If there are elements after the last boundary, they form the last section\n // with the body-level w:sectPr (already captured)\n // Actually the body-level sectPr IS the last boundary\n\n return sections;\n}\n\n// ── Cross-paragraph TOC field aggregation ───────────────────────────────────\n\n/**\n * Net field-nesting change across all descendant fldChar markers\n * (begin: +1, end: -1). Balances cross-paragraph field boundaries without a\n * stack — the running depth hits 0 exactly when the outermost field closes.\n */\nfunction countFieldDelta(el: Element): number {\n let delta = 0;\n const walk = (node: Element): void => {\n if (node.name === \"w:fldChar\") {\n const type = attr(node, \"w:fldCharType\");\n if (type === \"begin\") delta += 1;\n else if (type === \"end\") delta -= 1;\n }\n for (const c of node.elements ?? []) {\n if (c.type === \"element\") walk(c);\n }\n };\n walk(el);\n return delta;\n}\n\n/**\n * True when a w:p opens a bare TOC complex field: it carries a fldChar begin\n * whose instrText starts with \"TOC\". Such fields span multiple paragraphs and\n * defeat the per-paragraph field accumulator, so they are aggregated as rawXml.\n */\nfunction isTocFieldBegin(el: Element): boolean {\n if (el.name !== \"w:p\") return false;\n let hasBegin = false;\n let instr = \"\";\n const walk = (node: Element): void => {\n if (node.name === \"w:fldChar\" && attr(node, \"w:fldCharType\") === \"begin\") hasBegin = true;\n if (node.name === \"w:instrText\") instr += textOf(node);\n for (const c of node.elements ?? []) {\n if (c.type === \"element\") walk(c);\n }\n };\n walk(el);\n return hasBegin && instr.trim().toUpperCase().startsWith(\"TOC\");\n}\n\n/**\n * Parse a run of body-level elements into SectionChild[], aggregating any\n * cross-paragraph TOC complex field into a single rawXml child so its nested\n * HYPERLINK/PAGEREF fields and bookmark markers round-trip intact.\n */\nfunction parseBodyChildren(elements: Element[], ctx: DocxReadContext): SectionChild[] {\n const children: SectionChild[] = [];\n let tocBuffer: Element[] | null = null;\n let tocDepth = 0;\n\n const flushToc = (): void => {\n if (!tocBuffer) return;\n children.push(buildTocChild(tocBuffer, ctx));\n // buildTocChild preserves the rendered entries (paragraphs between the\n // separate and end markers) but not the end-closing paragraph, which often\n // carries a trailing page break (the section break before the first\n // heading). Rescue that page break as a standalone child to avoid silently\n // dropping it on round-trip.\n const lastEl = tocBuffer[tocBuffer.length - 1];\n const pageBreakCount = findDeep(lastEl, \"w:br\").filter(\n (b) => attr(b, \"w:type\") === \"page\",\n ).length;\n for (let i = 0; i < pageBreakCount; i++) {\n children.push({ paragraph: { children: [{ pageBreak: true }] } });\n }\n tocBuffer = null;\n tocDepth = 0;\n };\n\n for (const el of elements) {\n if (tocBuffer !== null) {\n tocBuffer.push(el);\n tocDepth += countFieldDelta(el);\n if (tocDepth <= 0) flushToc();\n continue;\n }\n if (isTocFieldBegin(el)) {\n tocBuffer = [el];\n tocDepth = countFieldDelta(el);\n if (tocDepth <= 0) flushToc();\n continue;\n }\n children.push(parseSectionChild(el, ctx));\n }\n\n // Unclosed TOC field at end of content — flush what we have (best effort).\n flushToc();\n\n return children;\n}\n\n/**\n * Build a structured TOC SectionChild from a captured bare TOC field. Extracts\n * the field instruction (switches → TableOfContentsOptions) and preserves the\n * rendered entries (separate→end paragraphs) structurally so MS Office and WPS\n * both display the existing TOC. The field is emitted clean (no dirty flag).\n */\nfunction buildTocChild(els: Element[], ctx: DocxReadContext): SectionChild {\n const tocOpts = parseTocFieldFromElements(els);\n const entryEls = selectTocEntryElements(els);\n if (entryEls.length > 0) {\n tocOpts.entries = entryEls.map((el) => parseSectionChild(el, ctx));\n }\n return { toc: tocOpts };\n}\n\n/**\n * Parse a list of elements into SectionChild[].\n * Used by SDT and textbox parsers for their content.\n */\nfunction parseSectionChildrenElements(elements: Element[], ctx: DocxReadContext): SectionChild[] {\n return parseBodyChildren(elements, ctx);\n}\n","import type { ParsedArchive } from \"@office-open/core\";\nimport { parseArchive } from \"@office-open/core\";\nimport type { DataType } from \"@office-open/core\";\nimport { toUint8Array } from \"@office-open/core\";\nimport { attr } from \"@office-open/xml\";\nimport type { Element } from \"@office-open/xml\";\nimport { appPropertiesDesc } from \"@parts/app-properties\";\nimport { bibliographyDesc } from \"@parts/bibliography\";\nimport { setBodyParseChild } from \"@parts/bodychildren\";\nimport { commentsDesc } from \"@parts/comments\";\nimport { contentTypesDesc } from \"@parts/contenttypes\";\nimport { corePropertiesDesc } from \"@parts/core-properties\";\nimport type { DocumentOptions } from \"@parts/core-properties\";\nimport { customPropertiesDesc } from \"@parts/custom-properties\";\nimport { endnotesDesc } from \"@parts/endnotes/descriptor\";\nimport { fontTableDesc } from \"@parts/fonts/descriptor\";\nimport type { EmbeddedFontOptionsWithKey } from \"@parts/fonts/font-wrapper\";\nimport { footnotesDesc } from \"@parts/footnotes/descriptor\";\nimport { glossaryDesc } from \"@parts/glossary-document\";\nimport { parseNumberingDefinitions } from \"@parts/numbering/numbering\";\nimport { settingsDesc } from \"@parts/settings/descriptor\";\nimport { buildStyleCache, buildNumberingCache, parseStyleDefinitions } from \"@parts/styles/styles\";\nimport { setTableParseChild } from \"@parts/table/descriptor\";\nimport { webSettingsDesc } from \"@parts/web-settings\";\n\nimport { parseParagraphProperties } from \"./body\";\nimport { DocxReadContext } from \"./context\";\nimport { parseBody, parseSectionChild } from \"./parse/body\";\nimport { replaceRelsWithPlaceholders } from \"./util/replace-media-placeholders\";\nimport { stringifyElement } from \"./util/stringify-element\";\n\nexport { parseArchive };\n\n/**\n * All part paths extracted from the DOCX package.\n * Field names correspond directly to the OOXML directory structure.\n */\nexport interface DocxPartRefs {\n /** word/headerN.xml keyed by rId */\n headers: Map<string, string>;\n /** word/footerN.xml keyed by rId */\n footers: Map<string, string>;\n /** word/footnotes.xml */\n footnotes?: string;\n /** word/endnotes.xml */\n endnotes?: string;\n /** word/comments.xml */\n comments?: string;\n /** Hyperlink targets keyed by rId (external URLs) */\n hyperlinks: Map<string, string>;\n /** word/charts/chartN.xml keyed by rId */\n charts: Map<string, string>;\n /** word/diagrams/dataN.xml keyed by rId */\n diagramData: Map<string, string>;\n /** word/media/* keyed by rId (from document.xml.rels) */\n media: Map<string, string>;\n /**\n * Per-part image/media relationships. Each part (document, headers, footers,\n * footnotes, …) has its own .rels with independent rId numbering, so drawings\n * inside a part must resolve images against that part's rels. Maps\n * partPath → (rId → mediaPath).\n */\n partMedia: Map<string, Map<string, string>>;\n /** Alternative format chunks (word/afchunkN.*) keyed by rId */\n afChunks: Map<string, string>;\n /** Sub-documents (word/subdocs/subdocN.docx) keyed by rId */\n subDocs: Map<string, string>;\n /** word/bibliography.xml */\n bibliography?: string;\n /** word/glossary/document.xml */\n glossary?: string;\n}\n\nexport interface DocxDocument {\n doc: ParsedArchive;\n /** word/document.xml → root w:document element */\n documentRoot: Element;\n /** word/document.xml → w:body element */\n body: Element;\n /** word/document.xml → w:background element */\n background?: Element;\n /** word/styles.xml */\n styles?: Element;\n /** word/numbering.xml */\n numbering?: Element;\n /** word/settings.xml */\n settings?: Element;\n /** word/fontTable.xml */\n fontTable?: Element;\n /** word/webSettings.xml */\n webSettings?: Element;\n partRefs: DocxPartRefs;\n /** docProps/core.xml */\n coreProps?: string;\n /** docProps/app.xml */\n appProps?: string;\n /** docProps/custom.xml */\n customProps?: string;\n /** [Content_Types].xml */\n contentTypes?: Element;\n}\n\nfunction resolveRelsPath(target: string): string {\n if (target.startsWith(\"/\")) return target.slice(1);\n if (target.startsWith(\"../\")) return target.replace(\"../\", \"\");\n return `word/${target}`;\n}\n\n/**\n * Resolve each embedded font's .odttf bytes through fontTable.xml.rels.\n * Reads the binary verbatim and flags it raw so the compiler copies it as-is\n * instead of re-obfuscating (the fontKey already matches the bytes).\n */\nfunction resolveEmbeddedFontData(fonts: EmbeddedFontOptionsWithKey[], doc: ParsedArchive): void {\n const relsEl = doc.get(\"word/_rels/fontTable.xml.rels\");\n if (!relsEl) return;\n const ridToPath = new Map<string, string>();\n for (const child of relsEl.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n if (!type.includes(\"/font\")) continue;\n const id = attr(child, \"Id\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (id && target) ridToPath.set(id, resolveRelsPath(target));\n }\n for (const font of fonts) {\n if (!font.embedRid) continue;\n const odttfPath = ridToPath.get(font.embedRid);\n if (!odttfPath) continue;\n const bytes = doc.getRaw(odttfPath);\n if (bytes) {\n font.data = Buffer.from(bytes);\n font.rawOdttf = true;\n font.odttfPath = odttfPath;\n }\n }\n}\n\nfunction parseDocPartRefs(doc: ParsedArchive): DocxPartRefs {\n const refs: DocxPartRefs = {\n headers: new Map(),\n footers: new Map(),\n hyperlinks: new Map(),\n charts: new Map(),\n diagramData: new Map(),\n media: new Map(),\n partMedia: new Map(),\n afChunks: new Map(),\n subDocs: new Map(),\n };\n\n const relsEl = doc.get(\"word/_rels/document.xml.rels\");\n if (!relsEl) return refs;\n\n for (const child of relsEl.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n const id = attr(child, \"Id\") ?? \"\";\n if (!target) continue;\n\n const path = resolveRelsPath(target);\n\n if (type.includes(\"/header\")) {\n refs.headers.set(id, path);\n } else if (type.includes(\"/footer\")) {\n refs.footers.set(id, path);\n } else if (type.includes(\"/footnotes\")) {\n refs.footnotes = path;\n } else if (type.includes(\"/endnotes\")) {\n refs.endnotes = path;\n } else if (type.includes(\"/comments\")) {\n refs.comments = path;\n } else if (type.includes(\"/chart\")) {\n refs.charts.set(id, path);\n } else if (type.includes(\"/diagramData\")) {\n refs.diagramData.set(id, path);\n } else if (type.includes(\"/image\") || type.includes(\"/media\")) {\n refs.media.set(id, path);\n } else if (type.includes(\"/aFChunk\")) {\n refs.afChunks.set(id, path);\n } else if (type.includes(\"/subDocument\")) {\n refs.subDocs.set(id, path);\n } else if (type.includes(\"/bibliography\")) {\n refs.bibliography = path;\n } else if (type.includes(\"/glossaryDocument\")) {\n refs.glossary = path;\n } else if (type.includes(\"/hyperlink\")) {\n refs.hyperlinks.set(id, target);\n }\n }\n\n // Per-part image relationships. Each part carries its own .rels with\n // independent rId numbering (document rId1 ≠ header rId1), so collect them\n // keyed by part path; drawings inside a part resolve images through its\n // own rels. Covers document, headers, footers, footnotes, endnotes, comments.\n for (const relsPath of doc.keys(\"word/_rels/\")) {\n if (!relsPath.endsWith(\".rels\")) continue;\n const relsEl = doc.get(relsPath);\n if (!relsEl) continue;\n const partPath = \"word/\" + relsPath.slice(\"word/_rels/\".length, -\".rels\".length);\n for (const rel of relsEl.elements ?? []) {\n if (rel.name !== \"Relationship\") continue;\n const type = attr(rel, \"Type\") ?? \"\";\n if (!type.includes(\"/image\") && !type.includes(\"/media\")) continue;\n const id = attr(rel, \"Id\") ?? \"\";\n const target = attr(rel, \"Target\") ?? \"\";\n if (!id || !target) continue;\n let partMap = refs.partMedia.get(partPath);\n if (!partMap) {\n partMap = new Map();\n refs.partMedia.set(partPath, partMap);\n }\n partMap.set(id, resolveRelsPath(target));\n }\n }\n\n return refs;\n}\n\nfunction parseRootRels(doc: ParsedArchive): {\n coreProps?: string;\n appProps?: string;\n customProps?: string;\n} {\n const relsEl = doc.get(\"_rels/.rels\");\n if (!relsEl) return {};\n\n let coreProps: string | undefined;\n let appProps: string | undefined;\n let customProps: string | undefined;\n\n for (const child of relsEl.elements ?? []) {\n if (child.name !== \"Relationship\") continue;\n const type = attr(child, \"Type\") ?? \"\";\n const target = attr(child, \"Target\") ?? \"\";\n if (!target) continue;\n\n const path = target.startsWith(\"/\") ? target.slice(1) : target;\n\n if (type.includes(\"/core-properties\")) {\n coreProps = path;\n } else if (type.includes(\"/extended-properties\")) {\n appProps = path;\n } else if (type.includes(\"/custom-properties\")) {\n customProps = path;\n }\n }\n\n return { coreProps, appProps, customProps };\n}\n\n/**\n * Parse a .docx file and convert it into DocumentOptions.\n *\n * This is the main public API for parsing DOCX files.\n * The returned options can be passed directly to `new Document(parsed)`\n * to recreate the document.\n *\n * @param data - Raw bytes of a .docx file\n * @returns Document options including sections and metadata\n */\nexport function parseDocument(data: DataType): DocumentOptions {\n const docx = parseDocx(data);\n const ctx = new DocxReadContext(\n docx,\n buildStyleCache(docx.styles),\n buildNumberingCache(docx.numbering),\n );\n\n // Register the child parser for table and body child descriptors\n setTableParseChild(parseSectionChild);\n setBodyParseChild(parseSectionChild);\n\n const sections = parseBody(docx.body, ctx);\n\n const opts: Partial<DocumentOptions> = { sections };\n\n // Document conformance class (w:document/@w:conformance)\n const conformance = attr(docx.documentRoot, \"w:conformance\");\n if (conformance === \"strict\" || conformance === \"transitional\") opts.conformance = conformance;\n\n // Background (w:background in document.xml)\n if (docx.background) {\n const hasChildren = (docx.background.elements ?? []).some((e) => e.type === \"element\");\n if (hasChildren) {\n // VML/structured background (e.g. v:background/v:fill pattern with a\n // texture image) that doesn't fit the color/theme model: carry the\n // element verbatim, rewriting relationship refs to {fileName} placeholders\n // so the media round-trips via the compiler's placeholder pass.\n const { rawXml, rawMedia } = replaceRelsWithPlaceholders(\n stringifyElement(docx.background),\n ctx,\n \"background\",\n );\n opts.background = rawMedia.length > 0 ? { rawXml, rawMedia } : { rawXml };\n } else {\n const bg: NonNullable<DocumentOptions[\"background\"]> = {};\n const color = attr(docx.background, \"w:color\");\n if (color) bg.color = color;\n const themeColor = attr(docx.background, \"w:themeColor\");\n if (themeColor) bg.themeColor = themeColor;\n const themeShade = attr(docx.background, \"w:themeShade\");\n if (themeShade) bg.themeShade = themeShade;\n const themeTint = attr(docx.background, \"w:themeTint\");\n if (themeTint) bg.themeTint = themeTint;\n if (Object.keys(bg).length > 0) opts.background = bg;\n }\n }\n\n // Core properties\n if (docx.coreProps) {\n const corePropsEl = docx.doc.get(docx.coreProps);\n if (corePropsEl) {\n const cp = corePropertiesDesc.parse(corePropsEl, ctx);\n if (cp.title) opts.title = cp.title;\n if (cp.subject) opts.subject = cp.subject;\n if (cp.creator) opts.creator = cp.creator;\n if (cp.keywords) opts.keywords = cp.keywords;\n if (cp.description) opts.description = cp.description;\n if (cp.lastModifiedBy) opts.lastModifiedBy = cp.lastModifiedBy;\n if (cp.revision) opts.revision = cp.revision;\n if (cp.lastPrinted) opts.lastPrinted = cp.lastPrinted;\n if (cp.created) opts.created = cp.created;\n if (cp.modified) opts.modified = cp.modified;\n }\n }\n\n // App (extended) properties\n if (docx.appProps) {\n const appPropsEl = docx.doc.get(docx.appProps);\n if (appPropsEl) {\n const ap = appPropertiesDesc.parse(appPropsEl, ctx);\n if (Object.keys(ap).length > 0) opts.appProperties = ap;\n }\n }\n\n // Settings — parse produces a structured SettingsOptions aligned with\n // generate (no verbatim rawXml fallback). Assign wholesale so context.ts\n // spreads it into _settingsOptions for the descriptor's stringify input.\n if (docx.settings) {\n opts.settings = settingsDesc.parse(docx.settings, ctx);\n }\n\n // Web settings — preserve the part on round-trip even when it has no\n // children. Dropping it leaves an orphaned Override in the passthrough\n // [Content_Types].xml (the part is gone but its Override remains), which is\n // an OPC violation; keeping presence keeps part + rel + Override in sync.\n if (docx.webSettings) {\n opts.webSettings = webSettingsDesc.parse(docx.webSettings, ctx);\n }\n\n // Custom properties\n if (docx.customProps) {\n const customPropsEl = docx.doc.get(docx.customProps);\n if (customPropsEl) {\n const cpResult = customPropertiesDesc.parse(customPropsEl, ctx);\n if (cpResult.properties && cpResult.properties.length > 0) {\n opts.customProperties = cpResult.properties;\n }\n }\n }\n\n // Comments content\n if (docx.partRefs.comments) {\n const commentsEl = docx.doc.get(docx.partRefs.comments);\n if (commentsEl) {\n const commentsResult = ctx.withPart(docx.partRefs.comments, () =>\n commentsDesc.parse(commentsEl, ctx),\n );\n const children = commentsResult.children;\n if (children && children.length > 0) {\n opts.comments = { children };\n }\n }\n }\n\n // Footnotes content\n if (docx.partRefs.footnotes) {\n const footnotesEl = docx.doc.get(docx.partRefs.footnotes);\n if (footnotesEl) {\n const fnResult = ctx.withPart(docx.partRefs.footnotes, () =>\n footnotesDesc.parse(footnotesEl, ctx),\n );\n const footnotesMap: NonNullable<DocumentOptions[\"footnotes\"]> = {};\n for (const [id, paragraphs] of fnResult.notes) {\n footnotesMap[String(id)] = { children: paragraphs };\n }\n // Preserve round-tripped separators so the generated ids stay consistent\n // with settings.footnotePr (which references them).\n if (\n Object.keys(footnotesMap).length > 0 ||\n fnResult.separator ||\n fnResult.continuationSeparator\n ) {\n if (fnResult.separator) footnotesMap.separator = fnResult.separator;\n if (fnResult.continuationSeparator)\n footnotesMap.continuationSeparator = fnResult.continuationSeparator;\n opts.footnotes = footnotesMap;\n }\n }\n }\n\n // Endnotes content\n if (docx.partRefs.endnotes) {\n const endnotesEl = docx.doc.get(docx.partRefs.endnotes);\n if (endnotesEl) {\n const enResult = ctx.withPart(docx.partRefs.endnotes, () =>\n endnotesDesc.parse(endnotesEl, ctx),\n );\n const endnotesMap: NonNullable<DocumentOptions[\"endnotes\"]> = {};\n for (const [id, paragraphs] of enResult.notes) {\n endnotesMap[String(id)] = { children: paragraphs };\n }\n if (\n Object.keys(endnotesMap).length > 0 ||\n enResult.separator ||\n enResult.continuationSeparator\n ) {\n if (enResult.separator) endnotesMap.separator = enResult.separator;\n if (enResult.continuationSeparator)\n endnotesMap.continuationSeparator = enResult.continuationSeparator;\n opts.endnotes = endnotesMap;\n }\n }\n }\n\n // Styles definitions\n if (docx.styles) {\n const styleOpts = parseStyleDefinitions(docx.styles, parseParagraphProperties, ctx);\n if (styleOpts) opts.styles = styleOpts;\n }\n\n // Numbering definitions\n if (docx.numbering) {\n const numOpts = parseNumberingDefinitions(docx.numbering, parseParagraphProperties, ctx);\n if (numOpts) opts.numbering = numOpts;\n }\n\n // Font table\n if (docx.fontTable) {\n const ftResult = fontTableDesc.parse(docx.fontTable, ctx);\n if (ftResult.fonts && ftResult.fonts.length > 0) {\n resolveEmbeddedFontData(ftResult.fonts, docx.doc);\n opts.fonts = ftResult.fonts;\n }\n }\n\n // Bibliography\n if (docx.partRefs.bibliography) {\n const bibEl = docx.doc.get(docx.partRefs.bibliography);\n if (bibEl) {\n const bibResult = bibliographyDesc.parse(bibEl, ctx);\n if (bibResult.sources && bibResult.sources.length > 0) opts.bibliography = bibResult;\n }\n }\n\n // Glossary document\n if (docx.partRefs.glossary) {\n const glossaryEl = docx.doc.get(docx.partRefs.glossary);\n if (glossaryEl) {\n const glossaryResult = ctx.withPart(docx.partRefs.glossary, () =>\n glossaryDesc.parse(glossaryEl, ctx),\n );\n if (glossaryResult.parts && glossaryResult.parts.length > 0) opts.glossary = glossaryResult;\n }\n }\n\n // Content types\n if (docx.contentTypes) {\n const ctResult = contentTypesDesc.parse(docx.contentTypes, ctx);\n if (ctResult) opts.contentTypes = ctResult;\n }\n\n // Raw passthrough: parts generate() doesn't rebuild (word/theme/*, customXml/*).\n // Carried verbatim so their [Content_Types] declarations stay valid and the\n // package opens in Word. (Media/fonts/headers/etc. are rebuilt by the compiler\n // and must NOT be passed through — they'd otherwise duplicate under renamed paths.)\n const rawParts: { path: string; data: Uint8Array }[] = [];\n for (const prefix of [\"word/theme/\", \"customXml/\"]) {\n for (const p of docx.doc.keys(prefix)) {\n if (p.endsWith(\"/\")) continue;\n const data = docx.doc.getRaw(p);\n if (data) rawParts.push({ path: p, data });\n }\n }\n if (rawParts.length > 0) opts.rawParts = rawParts;\n\n return opts as DocumentOptions;\n}\n\nexport function parseDocx(data: DataType): DocxDocument {\n const uint8 = toUint8Array(data);\n const doc = parseArchive(uint8);\n\n const documentEl = doc.get(\"word/document.xml\");\n if (!documentEl) throw new Error(\"word/document.xml not found\");\n const body = documentEl.elements?.find((e) => e.name === \"w:body\");\n if (!body) throw new Error(\"w:body not found in word/document.xml\");\n const background = documentEl.elements?.find((e) => e.name === \"w:background\");\n\n const styles = doc.get(\"word/styles.xml\");\n const numbering = doc.get(\"word/numbering.xml\");\n const settings = doc.get(\"word/settings.xml\");\n const fontTable = doc.get(\"word/fontTable.xml\");\n const webSettings = doc.get(\"word/webSettings.xml\");\n\n const partRefs = parseDocPartRefs(doc);\n const { coreProps, appProps, customProps } = parseRootRels(doc);\n\n const contentTypes = doc.get(\"[Content_Types].xml\");\n\n return {\n doc,\n documentRoot: documentEl,\n body,\n background,\n styles,\n numbering,\n settings,\n fontTable,\n webSettings,\n partRefs,\n coreProps,\n appProps,\n customProps,\n contentTypes,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;CAC5C,MAAM,YAAY,IAAI,IAAI,oBAAoB;CAC9C,MAAM,cAAc,IAAI,IAAI,sBAAsB;CAElD,MAAM,WAAW,iBAAiB,GAAG;CACrC,MAAM,EAAE,WAAW,UAAU,gBAAgB,cAAc,GAAG;CAI9D,OAAO;EACL;EACA,cAAc;EACd;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,cAhBmB,IAAI,IAAI,qBAgBhB;CACb;AACF"}
|
package/dist/parse.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as parseDocument, r as parseDocx, t as parseArchive } from "./parse-
|
|
1
|
+
import { n as parseDocument, r as parseDocx, t as parseArchive } from "./parse-DDWWDGbX.mjs";
|
|
2
2
|
export { parseArchive, parseDocument, parseDocx };
|
|
@@ -4925,8 +4925,8 @@ function stringifyParagraph(opts, ctx, sectionPropertiesXml) {
|
|
|
4925
4925
|
* Dispatches to the appropriate stringifier based on the child type.
|
|
4926
4926
|
* Pure JSON API — no class instance support.
|
|
4927
4927
|
*/
|
|
4928
|
-
function stringifyBodyChild(child, ctx) {
|
|
4929
|
-
if ("paragraph" in child) return stringifyParagraph(child.paragraph, ctx);
|
|
4928
|
+
function stringifyBodyChild(child, ctx, sectionPropertiesXml) {
|
|
4929
|
+
if ("paragraph" in child) return stringifyParagraph(child.paragraph, ctx, sectionPropertiesXml);
|
|
4930
4930
|
if ("table" in child) return tableDesc.stringify(child.table, ctx) ?? "";
|
|
4931
4931
|
if ("toc" in child) {
|
|
4932
4932
|
const { alias, ...options } = child.toc;
|
|
@@ -5040,14 +5040,18 @@ function stringifyDocumentXml(ctx, docCtx) {
|
|
|
5040
5040
|
if (ctx._options.background) parts.push(stringifyDocumentBackground(ctx._options.background, docCtx));
|
|
5041
5041
|
const bodyParts = [];
|
|
5042
5042
|
for (let si = 0; si < sections.length; si++) {
|
|
5043
|
-
const
|
|
5044
|
-
if (section.children) for (const child of section.children) bodyParts.push(stringifyBodyChild(child, docCtx));
|
|
5043
|
+
const children = sections[si].children ?? [];
|
|
5045
5044
|
const sectPrOpts = bodySections[si];
|
|
5046
|
-
|
|
5047
|
-
|
|
5048
|
-
|
|
5049
|
-
|
|
5045
|
+
const sectPrXml = sectPrOpts ? sectionPropertiesDesc.stringify(sectPrOpts, docCtx) ?? "" : "";
|
|
5046
|
+
const isLast = si === sections.length - 1;
|
|
5047
|
+
let sectPrHosted = isLast || !sectPrXml;
|
|
5048
|
+
for (let ci = 0; ci < children.length; ci++) {
|
|
5049
|
+
const inject = !isLast && sectPrXml && ci === children.length - 1 && "paragraph" in children[ci];
|
|
5050
|
+
if (inject) sectPrHosted = true;
|
|
5051
|
+
bodyParts.push(stringifyBodyChild(children[ci], docCtx, inject ? sectPrXml : void 0));
|
|
5050
5052
|
}
|
|
5053
|
+
if (!isLast && sectPrXml && !sectPrHosted) bodyParts.push(`<w:p><w:pPr>${sectPrXml}</w:pPr></w:p>`);
|
|
5054
|
+
if (isLast && sectPrXml) bodyParts.push(sectPrXml);
|
|
5051
5055
|
}
|
|
5052
5056
|
parts.push(`<w:body>${bodyParts.join("")}</w:body>`);
|
|
5053
5057
|
parts.push("</w:document>");
|
|
@@ -10238,7 +10242,7 @@ function stringifyDocDefaults(opts) {
|
|
|
10238
10242
|
else children.push("<w:rPrDefault><w:rPr><w:rFonts w:asciiTheme=\"minorHAnsi\" w:eastAsiaTheme=\"minorEastAsia\" w:hAnsiTheme=\"minorHAnsi\" w:cstheme=\"minorBidi\"/><w:kern w:val=\"2\"/><w:sz w:val=\"22\"/><w:szCs w:val=\"24\"/><w:lang w:val=\"en-US\" w:eastAsia=\"zh-CN\" w:bidi=\"ar-SA\"/><w14:ligatures w14:val=\"standardContextual\"/></w:rPr></w:rPrDefault>");
|
|
10239
10243
|
const pPr = stringifyParagraphProperties(opts.paragraph).xml;
|
|
10240
10244
|
if (pPr) children.push(`<w:pPrDefault>${pPr}</w:pPrDefault>`);
|
|
10241
|
-
else children.push("<w:pPrDefault><w:pPr><w:spacing w:after=\"160\" w:line=\"278\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault>");
|
|
10245
|
+
else children.push("<w:pPrDefault><w:pPr><w:widowControl/><w:spacing w:after=\"160\" w:line=\"278\" w:lineRule=\"auto\"/></w:pPr></w:pPrDefault>");
|
|
10242
10246
|
return `<w:docDefaults>${children.join("")}</w:docDefaults>`;
|
|
10243
10247
|
}
|
|
10244
10248
|
let cachedDefaultStyles = null;
|
|
@@ -10276,8 +10280,7 @@ var DefaultStylesFactory = class {
|
|
|
10276
10280
|
id: "Normal",
|
|
10277
10281
|
name: "Normal",
|
|
10278
10282
|
default: true,
|
|
10279
|
-
quickFormat: true
|
|
10280
|
-
paragraph: { widowControl: false }
|
|
10283
|
+
quickFormat: true
|
|
10281
10284
|
});
|
|
10282
10285
|
const headings = [
|
|
10283
10286
|
{
|
|
@@ -13219,8 +13222,20 @@ const contentTypesDesc = {
|
|
|
13219
13222
|
kind: "custom",
|
|
13220
13223
|
stringify(opts, _ctx) {
|
|
13221
13224
|
const p = ["<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\">"];
|
|
13222
|
-
|
|
13223
|
-
for (const
|
|
13225
|
+
const seenDefault = /* @__PURE__ */ new Set();
|
|
13226
|
+
for (const d of opts.defaults) {
|
|
13227
|
+
const key = d.extension.toLowerCase();
|
|
13228
|
+
if (seenDefault.has(key)) continue;
|
|
13229
|
+
seenDefault.add(key);
|
|
13230
|
+
p.push(defaultXml(d.extension, d.contentType));
|
|
13231
|
+
}
|
|
13232
|
+
const seenOverride = /* @__PURE__ */ new Set();
|
|
13233
|
+
for (const o of opts.overrides) {
|
|
13234
|
+
const key = o.partName.toLowerCase();
|
|
13235
|
+
if (seenOverride.has(key)) continue;
|
|
13236
|
+
seenOverride.add(key);
|
|
13237
|
+
p.push(overrideXml(o.partName, o.contentType));
|
|
13238
|
+
}
|
|
13224
13239
|
p.push("</Types>");
|
|
13225
13240
|
return p.join("");
|
|
13226
13241
|
},
|
|
@@ -13316,25 +13331,27 @@ const STANDARD_DEFAULTS = [
|
|
|
13316
13331
|
*
|
|
13317
13332
|
* Round-tripped packages pass through the source's [Content_Types], which may
|
|
13318
13333
|
* declare an uppercase extension (e.g. `JPG`) while the media is named `.jpg`.
|
|
13319
|
-
* OPC extension matching is case-
|
|
13320
|
-
*
|
|
13321
|
-
*
|
|
13322
|
-
* the media
|
|
13334
|
+
* OPC extension matching is **case-insensitive** (ECMA-376-2 §10.1.2), so `JPG`
|
|
13335
|
+
* and `jpg` are one key — emitting both yields a duplicate default that Word
|
|
13336
|
+
* rejects as unreadable content. Match existing defaults case-insensitively so
|
|
13337
|
+
* we never add a colliding extension; the media then resolves through the
|
|
13338
|
+
* source's already-declared default.
|
|
13323
13339
|
*/
|
|
13324
13340
|
function withMediaDefaults(input, mediaFileNames) {
|
|
13325
|
-
const have = new Set(input.defaults.map((d) => d.extension));
|
|
13341
|
+
const have = new Set(input.defaults.map((d) => d.extension.toLowerCase()));
|
|
13326
13342
|
const standard = new Map(STANDARD_DEFAULTS.map((d) => [d.extension, d.contentType]));
|
|
13327
13343
|
const defaults = [...input.defaults];
|
|
13328
13344
|
for (const fileName of mediaFileNames) {
|
|
13329
13345
|
const ext = fileName.slice(fileName.lastIndexOf(".") + 1);
|
|
13330
|
-
|
|
13331
|
-
|
|
13346
|
+
const key = ext.toLowerCase();
|
|
13347
|
+
if (!ext || have.has(key)) continue;
|
|
13348
|
+
const contentType = standard.get(key);
|
|
13332
13349
|
if (contentType) {
|
|
13333
13350
|
defaults.push({
|
|
13334
13351
|
extension: ext,
|
|
13335
13352
|
contentType
|
|
13336
13353
|
});
|
|
13337
|
-
have.add(
|
|
13354
|
+
have.add(key);
|
|
13338
13355
|
}
|
|
13339
13356
|
}
|
|
13340
13357
|
return {
|
|
@@ -13358,7 +13375,7 @@ const ALTCHUNK_DEFAULTS = {
|
|
|
13358
13375
|
*/
|
|
13359
13376
|
function withAltChunkOverrides(input, altChunks) {
|
|
13360
13377
|
const defaults = [...input.defaults];
|
|
13361
|
-
const haveExt = new Set(defaults.map((d) => d.extension));
|
|
13378
|
+
const haveExt = new Set(defaults.map((d) => d.extension.toLowerCase()));
|
|
13362
13379
|
for (const ac of altChunks) {
|
|
13363
13380
|
const ext = (ac.path.split(".").pop() ?? "").toLowerCase();
|
|
13364
13381
|
if (ext && !haveExt.has(ext) && ALTCHUNK_DEFAULTS[ext]) {
|
|
@@ -13850,4 +13867,4 @@ const webSettingsDesc = {
|
|
|
13850
13867
|
//#endregion
|
|
13851
13868
|
export { PageBorderZOrder as $, stringifyCustomXmlShell as $t, StyleLevel as A, TextHorzOverflowType as An, sectionPageSizeDefaults as At, stringifyNumberingStyle as B, TextEffect as Bn, NumberFormat as Bt, footnotesDesc as C, RubyAlign as Cn, parseSdtBlock as Ct, selectTocEntryElements as D, EmphasisMarkType as Dn, sectionPropertiesDesc as Dt, parseTocFieldInstruction as E, PositionalTabRelativeTo as En, parseSectionPropertiesEl as Et, extractStyleId as F, parseBodyProperties as Fn, createVerticalPosition as Ft, createHeaderFooterReference as G, TextboxTightWrapType as Gn, TextWrappingSide as Gt, stringifyTableStyle as H, PageNumber as Hn, VerticalPositionAlign as Ht, parseStyleDefinitions as I, createImageData$1 as In, createHorizontalPosition as It, LineNumberRestartFormat as J, AlignmentType as Jn, checkboxSymbolRunInner as Jt, SectionType as K, HeadingLevel as Kn, TextWrappingType as Kt, DefaultStylesFactory as L, Media as Ln, HorizontalPositionRelativeFrom as Lt, Styles as M, TextVerticalType as Mn, PageOrientation as Mt, buildNumberingCache as N, VerticalAnchor as Nn, PageNumberSeparator as Nt, SdtDateMappingType as O, UnderlineType as On, stringifySectionPropertiesXml as Ot, buildStyleCache as P, createBodyProperties as Pn, createPageNumberType as Pt, PageBorderOffsetFrom as Q, setBodyParseChild as Qt, stringifyCharacterStyle as R, createTransformation as Rn, VerticalPositionRelativeFrom as Rt, endnotesDesc as S, parseFormFieldData as Sn, stringifyTableOfContents as St, parseTocFieldFromElements as T, PositionalTabLeader as Tn, FontWrapper as Tt, HeaderFooterReferenceType as U, breakXml as Un, createWrapThrough as Ut, stringifyParagraphStyle as V, EMPTY_RUN_ELEMENTS as Vn, SpaceType as Vt, HeaderFooterType as W, TextAlignmentType as Wn, createWrapTight as Wt, createPageMargin as X, parseCustomXmlProperties as Xt, createLineNumberType as Y, customXmlBlockDesc as Yt, PageBorderDisplay as Z, sdtBlockDesc as Zt, glossaryDesc as _, TextDirection as _n, parseParagraph as _t, appPropertiesDesc as a, parseShading as an, LevelFormat as at, CharacterSet as b, FormFieldTextType as bn, stringifyDocumentXml as bt, relationshipsDesc as c, widthFiftiethsToPct as cn, parseTablePropertiesEl as ct, withAltChunkOverrides as d, BorderStyle as dn, tableDesc as dt, stringifySdtPr as en, DocumentGridType as et, withMediaDefaults as f, TableLayoutType as fn, stringifyChildDispatch as ft, DocPartType as g, TableAnchorType as gn, resetDrawingIdGen as gt, DocPartGallery as h, RelativeVerticalPosition as hn, drawingDesc as ht, webSettingsDesc as i, ShadingType as in, parseNumberingDefinitions as it, settingsDesc as j, TextVertOverflowType as jn, PageTextDirectionType as jt, SdtLock as k, TextBodyWrappingType as kn, sectionMarginDefaults as kt, buildContentTypesFromRegistry as l, widthPctToFiftieths as ln, parseTableRowPropertiesEl as lt, DocPartBehavior as m, RelativeHorizontalPosition as mn, stringifyRunInline as mt, frameXml as n, subDocDesc as nn, DocumentAttributeNamespaces as nt, customPropertiesDesc as o, objectDesc as on, LevelSuffix as ot, commentsDesc as p, OverlapType as pn, stringifyParagraphInline as pt, createSectionType as q, LineRuleType as qn, altChunkDesc as qt, framesetXml as r, stringifyElement as rn, Numbering as rt, corePropertiesDesc as s, WidthType as sn, parseTableCellPropertiesEl as st, TargetScreenSize as t, stringifySdtShell as tn, createDocumentGrid as tt, contentTypesDesc as u, TABLE_BORDERS_NONE as un, setTableParseChild as ut, bibliographyDesc as v, VerticalMergeType as vn, parseParagraphProperties as vt, parseToc as w, PositionalTabAlignment as wn, parseSdtProperties as wt, EditGroupType as x, createFormFieldData as xn, replaceRelsWithPlaceholders as xt, fontTableDesc as y, ProofErrorType as yn, stringifyBodyChild as yt, stringifyConditionalTableStyle as z, HighlightColor as zn, HorizontalPositionAlign as zt };
|
|
13852
13869
|
|
|
13853
|
-
//# sourceMappingURL=parts-
|
|
13870
|
+
//# sourceMappingURL=parts-B7Sfx_F0.mjs.map
|