@office-kit/xlsx 0.9.2 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/dist/{cell-style-CN9JXOwm.mjs → cell-style-DuvS_Lsg.mjs} +2 -2
  2. package/dist/cell-style-DuvS_Lsg.mjs.map +1 -0
  3. package/dist/{differential-YEjxNScf.mjs → differential-DvKU8fJt.mjs} +2 -2
  4. package/dist/{differential-YEjxNScf.mjs.map → differential-DvKU8fJt.mjs.map} +1 -1
  5. package/dist/drawing/drawing-xml.d.ts +7 -0
  6. package/dist/drawing/drawing.d.ts +25 -0
  7. package/dist/drawing-BxzLuryn.mjs.map +1 -1
  8. package/dist/io.mjs +2 -2
  9. package/dist/{load-BA30X4-M.mjs → load-CnPfhGo3.mjs} +54 -10
  10. package/dist/load-CnPfhGo3.mjs.map +1 -0
  11. package/dist/{manifest-CVL1_t0O.mjs → manifest-Cm9K7D62.mjs} +5 -5
  12. package/dist/{manifest-CVL1_t0O.mjs.map → manifest-Cm9K7D62.mjs.map} +1 -1
  13. package/dist/node.mjs +1 -1
  14. package/dist/packaging.mjs +1 -1
  15. package/dist/{parser-nk0Lqmcb.mjs → parser-D3SLaOFe.mjs} +27 -4
  16. package/dist/parser-D3SLaOFe.mjs.map +1 -0
  17. package/dist/{save-C9ChJfWM.mjs → save-2moCT3Af.mjs} +68 -34
  18. package/dist/save-2moCT3Af.mjs.map +1 -0
  19. package/dist/schema.mjs +1 -1
  20. package/dist/{serialize-55EnT30e.mjs → serialize-BC2Wu3bR.mjs} +2 -2
  21. package/dist/{serialize-55EnT30e.mjs.map → serialize-BC2Wu3bR.mjs.map} +1 -1
  22. package/dist/{serializer-DQzTTNOS.mjs → serializer-BtO2TrI7.mjs} +21 -9
  23. package/dist/serializer-BtO2TrI7.mjs.map +1 -0
  24. package/dist/streaming.mjs +9 -12
  25. package/dist/streaming.mjs.map +1 -1
  26. package/dist/styles/stylesheet.d.ts +8 -0
  27. package/dist/styles.mjs +3 -3
  28. package/dist/{stylesheet-writer-DOGKBGEk.mjs → stylesheet-writer-BrOw4jMY.mjs} +87 -41
  29. package/dist/stylesheet-writer-BrOw4jMY.mjs.map +1 -0
  30. package/dist/{table-BifavDVW.mjs → table-1P8we2gS.mjs} +2 -2
  31. package/dist/{table-BifavDVW.mjs.map → table-1P8we2gS.mjs.map} +1 -1
  32. package/dist/{tree-Bbs1C8Rc.mjs → tree-BX-sRRVp.mjs} +3 -1
  33. package/dist/tree-BX-sRRVp.mjs.map +1 -0
  34. package/dist/{utf8-D91g1XTG.mjs → utf8-Tn3nzyik.mjs} +2 -2
  35. package/dist/{utf8-D91g1XTG.mjs.map → utf8-Tn3nzyik.mjs.map} +1 -1
  36. package/dist/workbook/shared-strings.d.ts +15 -5
  37. package/dist/workbook/views.d.ts +7 -0
  38. package/dist/workbook/workbook.d.ts +15 -0
  39. package/dist/{workbook-T1Y3lstQ.mjs → workbook-CARZS94U.mjs} +39 -14
  40. package/dist/workbook-CARZS94U.mjs.map +1 -0
  41. package/dist/workbook.mjs +1 -1
  42. package/dist/workbook.mjs.map +1 -1
  43. package/dist/worksheet/hyperlinks.d.ts +5 -0
  44. package/dist/worksheet/reader.d.ts +7 -2
  45. package/dist/worksheet/worksheet.d.ts +4 -0
  46. package/dist/{worksheet-C6CWgvP5.mjs → worksheet-C5Ensf_j.mjs} +167 -135
  47. package/dist/worksheet-C5Ensf_j.mjs.map +1 -0
  48. package/dist/worksheet.mjs +2 -2
  49. package/dist/xml/parser.d.ts +20 -0
  50. package/dist/xml/serializer.d.ts +8 -0
  51. package/dist/xml.mjs +4 -4
  52. package/package.json +1 -1
  53. package/dist/cell-style-CN9JXOwm.mjs.map +0 -1
  54. package/dist/load-BA30X4-M.mjs.map +0 -1
  55. package/dist/parser-nk0Lqmcb.mjs.map +0 -1
  56. package/dist/save-C9ChJfWM.mjs.map +0 -1
  57. package/dist/serializer-DQzTTNOS.mjs.map +0 -1
  58. package/dist/stylesheet-writer-DOGKBGEk.mjs.map +0 -1
  59. package/dist/tree-Bbs1C8Rc.mjs.map +0 -1
  60. package/dist/workbook-T1Y3lstQ.mjs.map +0 -1
  61. package/dist/worksheet-C6CWgvP5.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"cell-style-CN9JXOwm.mjs","names":[],"sources":["../src/utils/stable-stringify.ts","../src/styles/alignment.ts","../src/styles/borders.ts","../src/styles/fills.ts","../src/styles/fonts.ts","../src/styles/numbers.ts","../src/styles/stylesheet.ts","../src/styles/named-styles.ts","../src/styles/protection.ts","../src/styles/cell-style.ts"],"sourcesContent":["// Deterministic JSON serialiser. Used by the Stylesheet pool to dedupe\n// value-object entries (Font / Fill / Border / CellXf …) by structural\n// equality regardless of property insertion order.\n//\n// Implemented as a JSON.stringify replacer that returns a key-sorted\n// shallow copy of every plain object it encounters; arrays keep their\n// element order. Circular references propagate as JSON.stringify's\n// native RangeError (\"Maximum call stack size exceeded\").\n\nconst sortKeysReplacer = (_key: string, value: unknown): unknown => {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) return value;\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const out: Record<string, unknown> = {};\n for (const k of keys) out[k] = obj[k];\n return out;\n};\n\n/**\n * Stringify `value` with object keys sorted recursively. Equal logical\n * values produce the same string regardless of insertion order; arrays\n * preserve their element order. Circular references throw (the error\n * comes straight from JSON.stringify's stack-overflow check).\n */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, sortKeysReplacer);\n}\n","// Cell alignment value object. Mirrors openpyxl/openpyxl/styles/alignment.py.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\n\nexport type HorizontalAlignment =\n | 'general'\n | 'left'\n | 'center'\n | 'right'\n | 'fill'\n | 'justify'\n | 'centerContinuous'\n | 'distributed';\n\nexport type VerticalAlignment = 'top' | 'center' | 'bottom' | 'justify' | 'distributed';\n\nexport const HORIZONTAL_ALIGNMENTS: ReadonlyArray<HorizontalAlignment> = Object.freeze([\n 'general',\n 'left',\n 'center',\n 'right',\n 'fill',\n 'justify',\n 'centerContinuous',\n 'distributed',\n]);\nexport const VERTICAL_ALIGNMENTS: ReadonlyArray<VerticalAlignment> = Object.freeze([\n 'top',\n 'center',\n 'bottom',\n 'justify',\n 'distributed',\n]);\n\nconst HORIZONTAL_SET: ReadonlySet<string> = new Set(HORIZONTAL_ALIGNMENTS);\nconst VERTICAL_SET: ReadonlySet<string> = new Set(VERTICAL_ALIGNMENTS);\n\nexport interface Alignment {\n readonly horizontal?: HorizontalAlignment;\n readonly vertical?: VerticalAlignment;\n /** 0..180 (degrees) OR 255 (vertical stacked text). */\n readonly textRotation?: number;\n readonly wrapText?: boolean;\n readonly shrinkToFit?: boolean;\n /** 0..255 indent levels. */\n readonly indent?: number;\n /** -255..255 relative indent. */\n readonly relativeIndent?: number;\n readonly justifyLastLine?: boolean;\n /** 0 = context-dependent, 1 = LTR, 2 = RTL. */\n readonly readingOrder?: number;\n}\n\nexport function makeAlignment(opts: Partial<Alignment> = {}): Alignment {\n const out: { -readonly [K in keyof Alignment]: Alignment[K] } = {};\n if (opts.horizontal !== undefined) {\n if (!HORIZONTAL_SET.has(opts.horizontal)) {\n throw new OpenXmlSchemaError(\n `Alignment horizontal must be one of [${HORIZONTAL_ALIGNMENTS.join(', ')}]; got \"${opts.horizontal}\"`,\n );\n }\n out.horizontal = opts.horizontal;\n }\n if (opts.vertical !== undefined) {\n if (!VERTICAL_SET.has(opts.vertical)) {\n throw new OpenXmlSchemaError(\n `Alignment vertical must be one of [${VERTICAL_ALIGNMENTS.join(', ')}]; got \"${opts.vertical}\"`,\n );\n }\n out.vertical = opts.vertical;\n }\n if (opts.textRotation !== undefined) {\n const r = opts.textRotation;\n if (!Number.isInteger(r) || r < 0 || (r > 180 && r !== 255)) {\n throw new OpenXmlSchemaError(`Alignment textRotation must be 0..180 or 255; got ${r}`);\n }\n out.textRotation = r;\n }\n if (opts.wrapText !== undefined) out.wrapText = opts.wrapText;\n if (opts.shrinkToFit !== undefined) out.shrinkToFit = opts.shrinkToFit;\n if (opts.indent !== undefined) {\n if (!Number.isFinite(opts.indent) || opts.indent < 0 || opts.indent > 255) {\n throw new OpenXmlSchemaError(`Alignment indent must be 0..255; got ${opts.indent}`);\n }\n out.indent = opts.indent;\n }\n if (opts.relativeIndent !== undefined) {\n const r = opts.relativeIndent;\n if (!Number.isFinite(r) || r < -255 || r > 255) {\n throw new OpenXmlSchemaError(`Alignment relativeIndent must be -255..255; got ${r}`);\n }\n out.relativeIndent = r;\n }\n if (opts.justifyLastLine !== undefined) out.justifyLastLine = opts.justifyLastLine;\n if (opts.readingOrder !== undefined) {\n if (!Number.isFinite(opts.readingOrder) || opts.readingOrder < 0) {\n throw new OpenXmlSchemaError(`Alignment readingOrder must be >= 0; got ${opts.readingOrder}`);\n }\n out.readingOrder = opts.readingOrder;\n }\n return Object.freeze(out);\n}\n\nexport const DEFAULT_ALIGNMENT: Alignment = makeAlignment();\n\nconst HORIZONTAL_TO_TEXT_ALIGN: Record<HorizontalAlignment, string | undefined> = {\n general: undefined, // Excel: numbers right, text left — caller decides per cell type.\n left: 'left',\n center: 'center',\n right: 'right',\n fill: 'left', // CSS has no fill; left is the closest non-stretched approximation.\n justify: 'justify',\n centerContinuous: 'center',\n distributed: 'justify',\n};\n\nconst VERTICAL_TO_VERTICAL_ALIGN: Record<VerticalAlignment, string | undefined> = {\n top: 'top',\n center: 'middle',\n bottom: 'bottom',\n justify: 'middle',\n distributed: 'middle',\n};\n\n/**\n * Translate an {@link Alignment} to a CSS-property record suitable for\n * HTML preview. `horizontal` → `text-align`, `vertical` →\n * `vertical-align` (table-cell semantics), `wrapText` → `white-space:\n * pre-wrap`, `textRotation` → `transform: rotate(<-deg>)` (Excel rotates\n * counter-clockwise relative to CSS) plus `transform-origin` to keep\n * the text anchored, and `indent` → `padding-left: <n>em`. `255`\n * stacked-text rotation maps to a 180° flip with `writing-mode`.\n *\n * Empty / undefined Alignment returns `{}`.\n */\nexport function alignmentToCss(alignment: Alignment | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!alignment) return css;\n if (alignment.horizontal !== undefined) {\n const ta = HORIZONTAL_TO_TEXT_ALIGN[alignment.horizontal];\n if (ta !== undefined) css['text-align'] = ta;\n }\n if (alignment.vertical !== undefined) {\n const va = VERTICAL_TO_VERTICAL_ALIGN[alignment.vertical];\n if (va !== undefined) css['vertical-align'] = va;\n }\n if (alignment.wrapText) css['white-space'] = 'pre-wrap';\n if (alignment.textRotation !== undefined) {\n if (alignment.textRotation === 255) {\n css['writing-mode'] = 'vertical-rl';\n } else if (alignment.textRotation !== 0) {\n // Excel: positive degrees rotate counter-clockwise; CSS rotate() is clockwise → negate.\n css['transform'] = `rotate(-${alignment.textRotation}deg)`;\n css['transform-origin'] = 'center center';\n }\n }\n if (alignment.indent !== undefined && alignment.indent > 0) {\n css['padding-left'] = `${alignment.indent}em`;\n }\n return css;\n}\n","// Border / Side value objects. Mirrors openpyxl/openpyxl/styles/borders.py.\n//\n// A `Border` describes the edges drawn around a cell. Each edge is a `Side`\n// carrying a stroke style and an optional `Color`. These are plain readonly\n// objects; the `make*` constructors freeze their results so the Stylesheet pool\n// can dedupe by reference identity once we wire it up.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport { type Color, colorToHex, makeColor } from './colors';\n\nexport type SideStyle =\n // ECMA-376 §18.18.3 ST_BorderStyle lists `none` (no stroke) as a first-class\n // value; Excel omits the side element for it, but OnlyOffice writes it out\n // explicitly, so we must accept and round-trip it (issue #99).\n | 'none'\n | 'thin'\n | 'medium'\n | 'thick'\n | 'double'\n | 'hair'\n | 'dotted'\n | 'dashed'\n | 'dashDot'\n | 'dashDotDot'\n | 'mediumDashed'\n | 'mediumDashDot'\n | 'mediumDashDotDot'\n | 'slantDashDot';\n\nexport const SIDE_STYLES: ReadonlyArray<SideStyle> = Object.freeze([\n 'none',\n 'thin',\n 'medium',\n 'thick',\n 'double',\n 'hair',\n 'dotted',\n 'dashed',\n 'dashDot',\n 'dashDotDot',\n 'mediumDashed',\n 'mediumDashDot',\n 'mediumDashDotDot',\n 'slantDashDot',\n]);\n\nconst SIDE_STYLE_SET: ReadonlySet<string> = new Set(SIDE_STYLES);\n\nexport interface Side {\n readonly style?: SideStyle;\n readonly color?: Color;\n}\n\n/** Build an immutable {@link Side}. */\nexport function makeSide(opts: Partial<Side> = {}): Side {\n const out: { -readonly [K in keyof Side]: Side[K] } = {};\n if (opts.style !== undefined) {\n if (!SIDE_STYLE_SET.has(opts.style)) {\n throw new OpenXmlSchemaError(`Side style must be one of [${SIDE_STYLES.join(', ')}]; got \"${opts.style}\"`);\n }\n out.style = opts.style;\n }\n if (opts.color !== undefined) {\n // Funnel through makeColor so we re-use its validation + freezing.\n out.color = Object.isFrozen(opts.color) ? opts.color : makeColor(opts.color);\n }\n return Object.freeze(out);\n}\n\nexport interface Border {\n /** Left edge. */\n readonly left?: Side;\n readonly right?: Side;\n readonly top?: Side;\n readonly bottom?: Side;\n /** Diagonal stroke (governed together with diagonalUp / diagonalDown). */\n readonly diagonal?: Side;\n /** Vertical stroke between cells of a merged range. */\n readonly vertical?: Side;\n /** Horizontal stroke between cells of a merged range. */\n readonly horizontal?: Side;\n readonly diagonalUp?: boolean;\n readonly diagonalDown?: boolean;\n /** Outline-only flag; defaults to true. */\n readonly outline?: boolean;\n}\n\n/** Build an immutable {@link Border}. */\nexport function makeBorder(opts: Partial<Border> = {}): Border {\n const out: { -readonly [K in keyof Border]: Border[K] } = {};\n if (opts.left !== undefined) out.left = freezeSide(opts.left);\n if (opts.right !== undefined) out.right = freezeSide(opts.right);\n if (opts.top !== undefined) out.top = freezeSide(opts.top);\n if (opts.bottom !== undefined) out.bottom = freezeSide(opts.bottom);\n if (opts.diagonal !== undefined) out.diagonal = freezeSide(opts.diagonal);\n if (opts.vertical !== undefined) out.vertical = freezeSide(opts.vertical);\n if (opts.horizontal !== undefined) out.horizontal = freezeSide(opts.horizontal);\n if (opts.diagonalUp !== undefined) out.diagonalUp = opts.diagonalUp;\n if (opts.diagonalDown !== undefined) out.diagonalDown = opts.diagonalDown;\n if (opts.outline !== undefined) out.outline = opts.outline;\n return Object.freeze(out);\n}\n\nconst freezeSide = (s: Side): Side => (Object.isFrozen(s) ? s : makeSide(s));\n\n/** Default empty side — convenient sentinel for `no edge stroke`. */\nexport const EMPTY_SIDE: Side = makeSide();\n/** Default empty border — every cell starts here until styled otherwise. */\nexport const DEFAULT_BORDER: Border = makeBorder();\n\n/**\n * Map an Excel {@link SideStyle} to a CSS `border` shorthand fragment (`<width>\n * <style>`). Returns `undefined` for unmappable styles or a missing/no-style\n * side. Colour is appended by the caller.\n */\nfunction sideStyleToCss(style: SideStyle | undefined): string | undefined {\n switch (style) {\n case 'thin':\n case 'hair':\n return '1px solid';\n case 'medium':\n return '2px solid';\n case 'thick':\n return '3px solid';\n case 'double':\n return '3px double';\n case 'dotted':\n return '1px dotted';\n case 'dashed':\n case 'dashDot':\n case 'dashDotDot':\n return '1px dashed';\n case 'mediumDashed':\n case 'mediumDashDot':\n case 'mediumDashDotDot':\n case 'slantDashDot':\n return '2px dashed';\n default:\n return undefined;\n }\n}\n\n/**\n * Translate a {@link Border} to a CSS-property record suitable for HTML\n * preview. Each present side becomes `border-<edge>: <width> <style> <#color>`.\n * Theme/auto/missing colours fall back to `currentColor`. Diagonal / vertical /\n * horizontal sides are skipped (CSS has no native equivalent for in-cell\n * strokes). Empty Border returns `{}`.\n */\nexport function borderToCss(border: Border | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!border) return css;\n const sides: Array<['top' | 'right' | 'bottom' | 'left', Side | undefined]> = [\n ['top', border.top],\n ['right', border.right],\n ['bottom', border.bottom],\n ['left', border.left],\n ];\n for (const [edge, side] of sides) {\n if (!side) continue;\n const stroke = sideStyleToCss(side.style);\n if (stroke === undefined) continue;\n const argb = colorToHex(side.color);\n const colour = argb !== undefined ? `#${argb.slice(2)}` : 'currentColor';\n css[`border-${edge}`] = `${stroke} ${colour}`;\n }\n return css;\n}\n","// Pattern + gradient fill value objects. Mirrors\n// openpyxl/openpyxl/styles/fills.py.\n//\n// In OOXML the cell `<fill>` element wraps exactly one of:\n// * <patternFill patternType=\"…\">[<fgColor>, <bgColor>]</patternFill>\n// * <gradientFill type=\"linear|path\" …>[<stop>, …]</gradientFill>\n//\n// The TS port models the inner variants as a discriminated union via a `kind`\n// tag; the wrapper is reconstructed during XML round-trip (see\n// fills.schema.ts). All values are plain readonly + frozen so the Stylesheet\n// pool can dedupe.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport { type Color, colorToHex, makeColor } from './colors';\n\n// ---- pattern fills ---------------------------------------------------------\n\n/** Predefined Excel pattern types. `'none'` lives here too as an explicit value. */\nexport type PatternType =\n | 'none'\n | 'solid'\n | 'darkDown'\n | 'darkGray'\n | 'darkGrid'\n | 'darkHorizontal'\n | 'darkTrellis'\n | 'darkUp'\n | 'darkVertical'\n | 'gray0625'\n | 'gray125'\n | 'lightDown'\n | 'lightGray'\n | 'lightGrid'\n | 'lightHorizontal'\n | 'lightTrellis'\n | 'lightUp'\n | 'lightVertical'\n | 'mediumGray';\n\nexport const PATTERN_TYPES: ReadonlyArray<PatternType> = Object.freeze([\n 'none',\n 'solid',\n 'darkDown',\n 'darkGray',\n 'darkGrid',\n 'darkHorizontal',\n 'darkTrellis',\n 'darkUp',\n 'darkVertical',\n 'gray0625',\n 'gray125',\n 'lightDown',\n 'lightGray',\n 'lightGrid',\n 'lightHorizontal',\n 'lightTrellis',\n 'lightUp',\n 'lightVertical',\n 'mediumGray',\n]);\n\nconst PATTERN_TYPE_SET: ReadonlySet<string> = new Set(PATTERN_TYPES);\n\nexport interface PatternFill {\n readonly kind: 'pattern';\n readonly patternType?: PatternType;\n readonly fgColor?: Color;\n readonly bgColor?: Color;\n}\n\nexport function makePatternFill(opts: Partial<Omit<PatternFill, 'kind'>> = {}): PatternFill {\n const out: { -readonly [K in keyof PatternFill]: PatternFill[K] } = { kind: 'pattern' };\n if (opts.patternType !== undefined) {\n if (!PATTERN_TYPE_SET.has(opts.patternType)) {\n throw new OpenXmlSchemaError(\n `PatternFill patternType must be one of [${PATTERN_TYPES.join(', ')}]; got \"${opts.patternType}\"`,\n );\n }\n out.patternType = opts.patternType;\n }\n if (opts.fgColor !== undefined) out.fgColor = freezeColor(opts.fgColor);\n if (opts.bgColor !== undefined) out.bgColor = freezeColor(opts.bgColor);\n return Object.freeze(out);\n}\n\n// ---- gradient fills --------------------------------------------------------\n\nexport interface GradientStop {\n /** 0..1 ratio along the gradient. */\n readonly position: number;\n readonly color: Color;\n}\n\nexport type GradientFillType = 'linear' | 'path';\n\nexport interface GradientFill {\n readonly kind: 'gradient';\n readonly type: GradientFillType;\n /** Rotation angle (degrees). Ignored when `type === 'path'`. */\n readonly degree?: number;\n /** path-mode insets (0..1 from each edge). */\n readonly left?: number;\n readonly right?: number;\n readonly top?: number;\n readonly bottom?: number;\n /** Colour stops along the gradient. */\n readonly stops: ReadonlyArray<GradientStop>;\n}\n\nexport function makeGradientStop(position: number, color: Color | Partial<Color>): GradientStop {\n if (!Number.isFinite(position) || position < 0 || position > 1) {\n throw new OpenXmlSchemaError(`GradientStop position must be in [0, 1]; got ${position}`);\n }\n return Object.freeze({ position, color: freezeColor(color) });\n}\n\nexport function makeGradientFill(opts: Partial<Omit<GradientFill, 'kind'>> = {}): GradientFill {\n const out: { -readonly [K in keyof GradientFill]: GradientFill[K] } = {\n kind: 'gradient',\n type: opts.type ?? 'linear',\n stops: opts.stops?.map((s) => freezeStop(s)) ?? [],\n };\n if (out.type !== 'linear' && out.type !== 'path') {\n throw new OpenXmlSchemaError(`GradientFill type must be \"linear\" or \"path\"; got \"${String(out.type)}\"`);\n }\n if (opts.degree !== undefined) out.degree = opts.degree;\n if (opts.left !== undefined) out.left = opts.left;\n if (opts.right !== undefined) out.right = opts.right;\n if (opts.top !== undefined) out.top = opts.top;\n if (opts.bottom !== undefined) out.bottom = opts.bottom;\n Object.freeze(out.stops);\n return Object.freeze(out);\n}\n\n// ---- Fill = PatternFill | GradientFill -------------------------------------\n\nexport type Fill = PatternFill | GradientFill;\n\n/**\n * Single-arg constructor that defers to the variant-specific maker based on\n * `kind`. Useful when the caller has a plain object in hand and wants the\n * freeze invariant applied uniformly.\n */\nexport function makeFill(opts: Partial<PatternFill> | Partial<GradientFill>): Fill {\n if (opts.kind === 'gradient') return makeGradientFill(opts as Partial<Omit<GradientFill, 'kind'>>);\n return makePatternFill(opts as Partial<Omit<PatternFill, 'kind'>>);\n}\n\n/** The empty PatternFill — Excel's default cellXf[0] points here. */\nexport const DEFAULT_EMPTY_FILL: Fill = makePatternFill();\n/** The 'gray125' PatternFill — Excel's default cellXf[1]. */\nexport const DEFAULT_GRAY_FILL: Fill = makePatternFill({ patternType: 'gray125' });\n\n// ---- internal helpers ------------------------------------------------------\n\nconst freezeColor = (c: Color | Partial<Color>): Color => (Object.isFrozen(c) ? (c as Color) : makeColor(c));\nconst freezeStop = (s: GradientStop): GradientStop => (Object.isFrozen(s) ? s : makeGradientStop(s.position, s.color));\n\nconst argbToCssHex = (color: Color | undefined): string | undefined => {\n const argb = colorToHex(color);\n return argb ? `#${argb.slice(2)}` : undefined;\n};\n\n/**\n * Translate a {@link Fill} to a CSS-property record suitable for HTML preview.\n * `'solid'` PatternFill renders as `background-color`, other pattern types\n * collapse to bgColor (CSS has no built-in equivalent of Excel hatch patterns).\n * GradientFill emits a CSS `background-image` with `linear-gradient(<angle>,\n * …)` for `type='linear'` or `radial-gradient(circle, …)` for `type='path'`.\n *\n * theme/auto colours and unresolvable inputs are skipped (returns `{}`) so\n * callers can spread without overwriting upstream defaults.\n */\nexport function fillToCss(fill: Fill | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!fill) return css;\n if (fill.kind === 'pattern') {\n if (fill.patternType === 'none' || fill.patternType === undefined) return css;\n if (fill.patternType === 'solid') {\n const fg = argbToCssHex(fill.fgColor);\n if (fg !== undefined) css['background-color'] = fg;\n return css;\n }\n // Non-solid patterns collapse to the bg colour as a coarse approximation;\n // CSS has no native Excel hatch equivalent.\n const bg = argbToCssHex(fill.bgColor) ?? argbToCssHex(fill.fgColor);\n if (bg !== undefined) css['background-color'] = bg;\n return css;\n }\n // Gradient fill — need at least one resolvable stop to emit anything.\n const stopParts: string[] = [];\n for (const s of fill.stops) {\n const hex = argbToCssHex(s.color);\n if (hex === undefined) continue;\n stopParts.push(`${hex} ${(s.position * 100).toFixed(2)}%`);\n }\n if (stopParts.length === 0) return css;\n if (fill.type === 'linear') {\n const angle = fill.degree ?? 0;\n css['background-image'] = `linear-gradient(${angle}deg, ${stopParts.join(', ')})`;\n } else {\n css['background-image'] = `radial-gradient(circle, ${stopParts.join(', ')})`;\n }\n return css;\n}\n","// Cell font value object. Mirrors openpyxl/openpyxl/styles/fonts.py.\n//\n// Font is the most varied of the styles slots — most fields are nested\n// elements with a single `val` attribute (`<sz val=\"11\"/>`), the boolean\n// toggles (`<b/>`, `<i/>`, ...) are presence-only marker tags, and\n// `<color>` is a fully nested object element. The schema layer carries\n// each pattern as its own ElementDef kind.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport { type Color, colorToHex, makeColor } from './colors';\n\n/** Underline styles per openpyxl's NestedNoneSet. */\nexport type UnderlineStyle = 'single' | 'double' | 'singleAccounting' | 'doubleAccounting';\nexport const UNDERLINE_STYLES: ReadonlyArray<UnderlineStyle> = Object.freeze([\n 'single',\n 'double',\n 'singleAccounting',\n 'doubleAccounting',\n]);\n\nexport type VertAlign = 'baseline' | 'superscript' | 'subscript';\nexport const VERT_ALIGNS: ReadonlyArray<VertAlign> = Object.freeze(['baseline', 'superscript', 'subscript']);\n\nexport type FontScheme = 'major' | 'minor';\nexport const FONT_SCHEMES: ReadonlyArray<FontScheme> = Object.freeze(['major', 'minor']);\n\nconst UNDERLINE_SET: ReadonlySet<string> = new Set(UNDERLINE_STYLES);\nconst VERT_SET: ReadonlySet<string> = new Set(VERT_ALIGNS);\nconst SCHEME_SET: ReadonlySet<string> = new Set(FONT_SCHEMES);\n\nexport interface Font {\n readonly name?: string;\n readonly charset?: number;\n /** Font family code (0..14). */\n readonly family?: number;\n /** Point size; openpyxl name = `sz`. */\n readonly size?: number;\n readonly color?: Color;\n readonly bold?: boolean;\n readonly italic?: boolean;\n readonly strike?: boolean;\n readonly outline?: boolean;\n readonly shadow?: boolean;\n readonly condense?: boolean;\n readonly extend?: boolean;\n readonly underline?: UnderlineStyle;\n readonly vertAlign?: VertAlign;\n readonly scheme?: FontScheme;\n}\n\nexport function makeFont(opts: Partial<Font> = {}): Font {\n const out: { -readonly [K in keyof Font]: Font[K] } = {};\n if (opts.name !== undefined) {\n if (typeof opts.name !== 'string') {\n throw new OpenXmlSchemaError(`Font name must be a string; got ${typeof opts.name}`);\n }\n out.name = opts.name;\n }\n if (opts.charset !== undefined) {\n if (!Number.isInteger(opts.charset)) {\n throw new OpenXmlSchemaError(`Font charset must be an integer; got ${opts.charset}`);\n }\n out.charset = opts.charset;\n }\n if (opts.family !== undefined) {\n if (!Number.isInteger(opts.family) || opts.family < 0 || opts.family > 14) {\n throw new OpenXmlSchemaError(`Font family must be 0..14; got ${opts.family}`);\n }\n out.family = opts.family;\n }\n if (opts.size !== undefined) {\n if (!Number.isFinite(opts.size) || opts.size <= 0) {\n throw new OpenXmlSchemaError(`Font size must be positive; got ${opts.size}`);\n }\n out.size = opts.size;\n }\n if (opts.color !== undefined) {\n out.color = Object.isFrozen(opts.color) ? opts.color : makeColor(opts.color);\n }\n if (opts.bold !== undefined) out.bold = opts.bold;\n if (opts.italic !== undefined) out.italic = opts.italic;\n if (opts.strike !== undefined) out.strike = opts.strike;\n if (opts.outline !== undefined) out.outline = opts.outline;\n if (opts.shadow !== undefined) out.shadow = opts.shadow;\n if (opts.condense !== undefined) out.condense = opts.condense;\n if (opts.extend !== undefined) out.extend = opts.extend;\n if (opts.underline !== undefined) {\n if (!UNDERLINE_SET.has(opts.underline)) {\n throw new OpenXmlSchemaError(\n `Font underline must be one of [${UNDERLINE_STYLES.join(', ')}]; got \"${opts.underline}\"`,\n );\n }\n out.underline = opts.underline;\n }\n if (opts.vertAlign !== undefined) {\n if (!VERT_SET.has(opts.vertAlign)) {\n throw new OpenXmlSchemaError(\n `Font vertAlign must be one of [${VERT_ALIGNS.join(', ')}]; got \"${opts.vertAlign}\"`,\n );\n }\n out.vertAlign = opts.vertAlign;\n }\n if (opts.scheme !== undefined) {\n if (!SCHEME_SET.has(opts.scheme)) {\n throw new OpenXmlSchemaError(`Font scheme must be one of [${FONT_SCHEMES.join(', ')}]; got \"${opts.scheme}\"`);\n }\n out.scheme = opts.scheme;\n }\n return Object.freeze(out);\n}\n\n/** Excel's default cell font: Calibri 11, minor scheme, theme=1 colour. */\nexport const DEFAULT_FONT: Font = makeFont({\n name: 'Calibri',\n size: 11,\n family: 2,\n scheme: 'minor',\n color: makeColor({ theme: 1 }),\n});\n\n/**\n * Translate a {@link Font} to a CSS-property record suitable for HTML\n * rendering / preview. Boolean toggles map to weight/style/decoration,\n * `size` becomes `font-size: <n>pt`, and an explicit rgb/indexed\n * `color` is rendered as `#RRGGBB` (alpha dropped). theme/auto colours\n * are skipped — callers without a theme can't resolve them.\n *\n * `vertAlign='superscript'|'subscript'` lowers `font-size` to 0.83em\n * (W3C convention) and sets `vertical-align`.\n *\n * Returns `{}` for an empty Font so callers can spread it without\n * overwriting upstream defaults.\n */\nexport function fontToCss(font: Font | undefined): Record<string, string> {\n const css: Record<string, string> = {};\n if (!font) return css;\n if (font.name !== undefined) {\n // CSS expects quoted family names that contain spaces; quote unconditionally\n // to keep the generator simple.\n css['font-family'] = `'${font.name.replace(/'/g, \"\\\\'\")}'`;\n }\n if (font.size !== undefined) css['font-size'] = `${font.size}pt`;\n if (font.bold) css['font-weight'] = 'bold';\n if (font.italic) css['font-style'] = 'italic';\n const decorations: string[] = [];\n if (font.underline !== undefined) decorations.push('underline');\n if (font.strike) decorations.push('line-through');\n if (decorations.length > 0) css['text-decoration'] = decorations.join(' ');\n if (font.color !== undefined) {\n const argb = colorToHex(font.color);\n if (argb !== undefined) {\n // Drop alpha (CSS hex with alpha is poorly-supported in Excel-style preview).\n css['color'] = `#${argb.slice(2)}`;\n }\n }\n if (font.vertAlign === 'superscript' || font.vertAlign === 'subscript') {\n css['vertical-align'] = font.vertAlign;\n // Match W3C-recommended scaling for sup/sub when font-size is not explicit.\n if (css['font-size'] === undefined) css['font-size'] = '0.83em';\n }\n return css;\n}\n","// Number-format value object + the OOXML built-in format catalogue.\n// Mirrors openpyxl/openpyxl/styles/numbers.py.\n//\n// Excel keeps two parallel namespaces for number formats:\n// * IDs 0–163 are reserved for the built-in catalogue (sparsely\n// populated; only 38 of them are actually defined).\n// * IDs ≥ 164 are user-defined / locale-specific. The Stylesheet\n// pool allocates these on demand (phase 2 §3.4).\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\n\n/** Canonical OOXML built-in number formats — verbatim from openpyxl. */\nexport const BUILTIN_FORMATS: Readonly<Record<number, string>> = Object.freeze({\n 0: 'General',\n 1: '0',\n 2: '0.00',\n 3: '#,##0',\n 4: '#,##0.00',\n 5: '\"$\"#,##0_);(\"$\"#,##0)',\n 6: '\"$\"#,##0_);[Red](\"$\"#,##0)',\n 7: '\"$\"#,##0.00_);(\"$\"#,##0.00)',\n 8: '\"$\"#,##0.00_);[Red](\"$\"#,##0.00)',\n 9: '0%',\n 10: '0.00%',\n 11: '0.00E+00',\n 12: '# ?/?',\n 13: '# ??/??',\n 14: 'mm-dd-yy',\n 15: 'd-mmm-yy',\n 16: 'd-mmm',\n 17: 'mmm-yy',\n 18: 'h:mm AM/PM',\n 19: 'h:mm:ss AM/PM',\n 20: 'h:mm',\n 21: 'h:mm:ss',\n 22: 'm/d/yy h:mm',\n 37: '#,##0_);(#,##0)',\n 38: '#,##0_);[Red](#,##0)',\n 39: '#,##0.00_);(#,##0.00)',\n 40: '#,##0.00_);[Red](#,##0.00)',\n 41: '_(* #,##0_);_(* \\\\(#,##0\\\\);_(* \"-\"_);_(@_)',\n 42: '_(\"$\"* #,##0_);_(\"$\"* \\\\(#,##0\\\\);_(\"$\"* \"-\"_);_(@_)',\n 43: '_(* #,##0.00_);_(* \\\\(#,##0.00\\\\);_(* \"-\"??_);_(@_)',\n 44: '_(\"$\"* #,##0.00_)_(\"$\"* \\\\(#,##0.00\\\\)_(\"$\"* \"-\"??_)_(@_)',\n 45: 'mm:ss',\n 46: '[h]:mm:ss',\n 47: 'mmss.0',\n 48: '##0.0E+0',\n 49: '@',\n});\n\n/** First numFmtId Excel reserves for user-defined formats. */\nexport const BUILTIN_FORMATS_MAX_SIZE = 164;\n\nconst REVERSE: ReadonlyMap<string, number> = new Map(Object.entries(BUILTIN_FORMATS).map(([k, v]) => [v, Number(k)]));\n\n// ---- well-known format codes (named exports for ergonomics) ---------------\n//\n// Inlined rather than indexed off BUILTIN_FORMATS to keep TS' tuple\n// lookup from widening to `string | undefined`.\n\nexport const FORMAT_GENERAL = 'General';\nexport const FORMAT_TEXT = '@';\nexport const FORMAT_NUMBER = '0';\nexport const FORMAT_NUMBER_00 = '0.00';\nexport const FORMAT_PERCENTAGE = '0%';\nexport const FORMAT_PERCENTAGE_00 = '0.00%';\nexport const FORMAT_DATE_DATETIME = 'yyyy-mm-dd h:mm:ss';\nexport const FORMAT_DATE_TIMEDELTA = '[hh]:mm:ss';\nexport const FORMAT_DATE_YYYYMMDD2 = 'yyyy-mm-dd';\n\n// ---- helpers ---------------------------------------------------------------\n\n/** Look up the format code for a given numFmtId, or `undefined` if unknown. */\nexport function builtinFormatCode(id: number): string | undefined {\n return Object.hasOwn(BUILTIN_FORMATS, id) ? BUILTIN_FORMATS[id] : undefined;\n}\n\n/** Look up the numFmtId for a given format code, or `undefined` if not built-in. */\nexport function builtinFormatId(code: string): number | undefined {\n return REVERSE.get(code);\n}\n\n/** True iff `code` is one of the OOXML built-in format strings. */\nexport function isBuiltinFormat(code: string): boolean {\n return REVERSE.has(code);\n}\n\n// ---- date / timedelta heuristics ------------------------------------------\n//\n// Mirror openpyxl's regex strategy verbatim. The two patterns work together\n// to decide whether a format implies a date / time / duration interpretation.\n\nconst COLORS_GROUP = '\\\\[(BLACK|BLUE|CYAN|GREEN|MAGENTA|RED|WHITE|YELLOW)\\\\]';\nconst LITERAL_GROUP = '\"[^\"]*\"';\nconst LOCALE_GROUP = '\\\\[(?!hh?\\\\]|mm?\\\\]|ss?\\\\])[^\\\\]]*\\\\]';\n\nconst STRIP_RE = new RegExp(`${COLORS_GROUP}|${LITERAL_GROUP}|${LOCALE_GROUP}`, 'g');\nconst DATE_TOKEN_RE = /(?<![_\\\\])[dmhysDMHYS]/;\nconst TIMEDELTA_RE = /\\[hh?\\](:mm(:ss(\\.0*)?)?)?|\\[mm?\\](:ss(\\.0*)?)?|\\[ss?\\](\\.0*)?/i;\n\n/**\n * Heuristic: does the format string imply a date / time interpretation?\n * Looks at only the first format section (positive-value branch); strips\n * literals, colour codes and locale modifiers before scanning for date\n * tokens (d/m/h/y/s, case-insensitive) that aren't escaped.\n */\nexport function isDateFormat(code: string | undefined | null): boolean {\n if (code == null) return false;\n const head = code.split(';')[0] ?? '';\n const stripped = head.replace(STRIP_RE, '');\n return DATE_TOKEN_RE.test(stripped);\n}\n\n/** Heuristic: does the format string indicate a duration ([h]:mm:ss etc.)? */\nexport function isTimedeltaFormat(code: string | undefined | null): boolean {\n if (code == null) return false;\n const head = code.split(';')[0] ?? '';\n return TIMEDELTA_RE.test(head);\n}\n\n/** Categorise a date format as 'date', 'time', 'datetime' or undefined. */\nexport function classifyDateFormat(code: string | undefined | null): 'date' | 'time' | 'datetime' | undefined {\n if (!isDateFormat(code)) return undefined;\n // Reach here only with a non-null code.\n const head = (code as string).split(';')[0] ?? '';\n // Same locale / literal stripping the date detector applies.\n const stripped = head.replace(STRIP_RE, '');\n let date = false;\n let time = false;\n for (const ch of stripped) {\n if (ch === 'd' || ch === 'D' || ch === 'y' || ch === 'Y') date = true;\n else if (ch === 'h' || ch === 'H' || ch === 's' || ch === 'S') time = true;\n if (date && time) break;\n }\n if (date && time) return 'datetime';\n if (date) return 'date';\n return 'time';\n}\n\n// ---- NumberFormat value -----------------------------------------------------\n\nexport interface NumberFormat {\n /** Stylesheet-relative numFmtId. */\n readonly numFmtId: number;\n readonly formatCode: string;\n}\n\nexport function makeNumberFormat(opts: { numFmtId: number; formatCode: string }): NumberFormat {\n if (!Number.isInteger(opts.numFmtId) || opts.numFmtId < 0) {\n throw new OpenXmlSchemaError(`NumberFormat numFmtId must be a non-negative integer; got ${opts.numFmtId}`);\n }\n if (typeof opts.formatCode !== 'string') {\n throw new OpenXmlSchemaError('NumberFormat formatCode must be a string');\n }\n return Object.freeze({ numFmtId: opts.numFmtId, formatCode: opts.formatCode });\n}\n","// Stylesheet pool. The workbook holds dedup pools per style component (fonts /\n// fills / borders / numFmts / cellXfs / cellStyleXfs); cells reference entries\n// by index via a `styleId` (an index into cellXfs).\n//\n// All adds run through `add*` free functions that look up the pool via\n// `stableStringify`-keyed maps so the same logical Font / Fill / etc. added\n// 1000× lands in a single pool slot.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport { stableStringify } from '../utils/stable-stringify';\nimport type { Alignment } from './alignment';\nimport type { Border } from './borders';\nimport { DEFAULT_BORDER } from './borders';\nimport type { Fill } from './fills';\nimport { DEFAULT_EMPTY_FILL, DEFAULT_GRAY_FILL } from './fills';\nimport type { Font } from './fonts';\nimport { DEFAULT_FONT } from './fonts';\nimport { BUILTIN_FORMATS_MAX_SIZE, builtinFormatId } from './numbers';\nimport type { Protection } from './protection';\n\n/**\n * One entry in the cellXfs / cellStyleXfs pool. Represents the union of\n * indexes-into-other-pools that a cell or named style points at.\n *\n * Mirrors openpyxl's CellStyle (styles/cell_style.py). The TS port keeps it as\n * a plain readonly object — no class, no methods. The Stylesheet `addCellXf`\n * allocates the index; cells store only that.\n */\nexport interface CellXf {\n readonly fontId: number;\n readonly fillId: number;\n readonly borderId: number;\n readonly numFmtId: number;\n /** Index into cellStyleXfs — only set for direct-cell xfs that point at a NamedStyle. */\n readonly xfId?: number;\n readonly alignment?: Alignment;\n readonly protection?: Protection;\n readonly applyFont?: boolean;\n readonly applyFill?: boolean;\n readonly applyBorder?: boolean;\n readonly applyNumberFormat?: boolean;\n readonly applyAlignment?: boolean;\n readonly applyProtection?: boolean;\n readonly pivotButton?: boolean;\n readonly quotePrefix?: boolean;\n}\n\nexport interface Stylesheet {\n fonts: Font[];\n fills: Fill[];\n borders: Border[];\n /** numFmtId → format code (custom IDs only; built-ins implicit). */\n numFmts: Map<number, string>;\n cellXfs: CellXf[];\n cellStyleXfs: CellXf[];\n /** Named styles (Excel's \"Cell Styles\" gallery; populated by addNamedStyle). */\n namedStyles?: Array<import('./named-styles').StylesheetNamedStyle>;\n\n // Internal dedup maps. Underscore-prefixed so JSON / structuredClone\n // serialisation can choose to skip them; never part of the public API.\n _fontIdByKey: Map<string, number>;\n _fillIdByKey: Map<string, number>;\n _borderIdByKey: Map<string, number>;\n _xfIdByKey: Map<string, number>;\n _styleXfIdByKey: Map<string, number>;\n _numFmtIdByCode: Map<string, number>;\n _namedStyleByName?: Map<string, import('./named-styles').StylesheetNamedStyle>;\n}\n\n/**\n * Build a fresh Stylesheet pre-populated with Excel's required default entries.\n * Mirrors openpyxl's empty Stylesheet: fonts: [DEFAULT_FONT] (index 0) fills:\n * [DEFAULT_EMPTY_FILL,\n * DEFAULT_GRAY_FILL] (indices 0, 1 — required)\n * borders: [DEFAULT_BORDER] (index 0) cellXfs: empty (indices allocated on\n * demand)\n */\nexport function makeStylesheet(): Stylesheet {\n const fontKey = stableStringify(DEFAULT_FONT);\n const fill0Key = stableStringify(DEFAULT_EMPTY_FILL);\n const fill1Key = stableStringify(DEFAULT_GRAY_FILL);\n const borderKey = stableStringify(DEFAULT_BORDER);\n\n return {\n fonts: [DEFAULT_FONT],\n fills: [DEFAULT_EMPTY_FILL, DEFAULT_GRAY_FILL],\n borders: [DEFAULT_BORDER],\n numFmts: new Map(),\n cellXfs: [],\n cellStyleXfs: [],\n _fontIdByKey: new Map([[fontKey, 0]]),\n _fillIdByKey: new Map([\n [fill0Key, 0],\n [fill1Key, 1],\n ]),\n _borderIdByKey: new Map([[borderKey, 0]]),\n _xfIdByKey: new Map(),\n _styleXfIdByKey: new Map(),\n _numFmtIdByCode: new Map(),\n };\n}\n\n// ---- pool add helpers ------------------------------------------------------\n\n/** Add a Font to the pool, returning its 0-based index. Idempotent. */\nexport function addFont(ss: Stylesheet, font: Font): number {\n return addToPool(font, ss.fonts, ss._fontIdByKey);\n}\n\n/** Add a Fill to the pool, returning its 0-based index. Idempotent. */\nexport function addFill(ss: Stylesheet, fill: Fill): number {\n return addToPool(fill, ss.fills, ss._fillIdByKey);\n}\n\n/** Add a Border to the pool, returning its 0-based index. Idempotent. */\nexport function addBorder(ss: Stylesheet, border: Border): number {\n return addToPool(border, ss.borders, ss._borderIdByKey);\n}\n\n/**\n * Resolve a number-format string to its numFmtId.\n * - Built-in codes return their canonical OOXML ID.\n * - Otherwise the custom code is registered (and allocated an ID\n * ≥ {@link BUILTIN_FORMATS_MAX_SIZE}). Idempotent.\n */\nexport function addNumFmt(ss: Stylesheet, formatCode: string): number {\n const builtin = builtinFormatId(formatCode);\n if (builtin !== undefined) return builtin;\n const cached = ss._numFmtIdByCode.get(formatCode);\n if (cached !== undefined) return cached;\n const id = BUILTIN_FORMATS_MAX_SIZE + ss.numFmts.size;\n ss.numFmts.set(id, formatCode);\n ss._numFmtIdByCode.set(formatCode, id);\n return id;\n}\n\n/** Add a CellXf to the cellXfs pool, returning its 0-based index. Idempotent. */\nexport function addCellXf(ss: Stylesheet, xf: CellXf): number {\n validateCellXfRefs(ss, xf, /* isStyle */ false);\n return addToPool(xf, ss.cellXfs, ss._xfIdByKey);\n}\n\n/** Add a CellXf to the cellStyleXfs pool. Idempotent. */\nexport function addCellStyleXf(ss: Stylesheet, xf: CellXf): number {\n validateCellXfRefs(ss, xf, /* isStyle */ true);\n return addToPool(xf, ss.cellStyleXfs, ss._styleXfIdByKey);\n}\n\n// ---- internals -------------------------------------------------------------\n\nconst addToPool = <T>(value: T, pool: T[], byKey: Map<string, number>): number => {\n const key = stableStringify(value);\n const cached = byKey.get(key);\n if (cached !== undefined) return cached;\n const id = pool.length;\n pool.push(value);\n byKey.set(key, id);\n return id;\n};\n\nconst validateCellXfRefs = (ss: Stylesheet, xf: CellXf, isStyle: boolean): void => {\n if (xf.fontId < 0 || xf.fontId >= ss.fonts.length) {\n throw new OpenXmlSchemaError(`CellXf.fontId ${xf.fontId} out of range [0, ${ss.fonts.length})`);\n }\n if (xf.fillId < 0 || xf.fillId >= ss.fills.length) {\n throw new OpenXmlSchemaError(`CellXf.fillId ${xf.fillId} out of range [0, ${ss.fills.length})`);\n }\n if (xf.borderId < 0 || xf.borderId >= ss.borders.length) {\n throw new OpenXmlSchemaError(`CellXf.borderId ${xf.borderId} out of range [0, ${ss.borders.length})`);\n }\n // numFmtId is permissive: built-ins or any registered custom ID.\n if (!Number.isInteger(xf.numFmtId) || xf.numFmtId < 0) {\n throw new OpenXmlSchemaError(`CellXf.numFmtId must be a non-negative integer; got ${xf.numFmtId}`);\n }\n if (!isStyle && xf.xfId !== undefined) {\n if (xf.xfId < 0 || xf.xfId >= ss.cellStyleXfs.length) {\n throw new OpenXmlSchemaError(`CellXf.xfId ${xf.xfId} out of range [0, ${ss.cellStyleXfs.length})`);\n }\n }\n};\n\n/** Returns the currently registered numFmt entries (built-ins are implicit and not included). */\nexport function getCustomNumFmts(ss: Stylesheet): ReadonlyArray<{ id: number; code: string }> {\n const out: Array<{ id: number; code: string }> = [];\n for (const [id, code] of ss.numFmts.entries()) out.push({ id, code });\n // numFmts is keyed by id; sort for deterministic output.\n out.sort((a, b) => a.id - b.id);\n return out;\n}\n\n/** Read-only snapshot of every Font entry in the pool, indexed by id. */\nexport function listFonts(ss: Stylesheet): ReadonlyArray<Font> {\n return ss.fonts;\n}\n\n/** Read-only snapshot of every Fill entry in the pool, indexed by id. */\nexport function listFills(ss: Stylesheet): ReadonlyArray<Fill> {\n return ss.fills;\n}\n\n/** Read-only snapshot of every Border entry in the pool, indexed by id. */\nexport function listBorders(ss: Stylesheet): ReadonlyArray<Border> {\n return ss.borders;\n}\n\n/** Read-only snapshot of every CellXf entry in the cellXfs pool. */\nexport function listCellXfs(ss: Stylesheet): ReadonlyArray<CellXf> {\n return ss.cellXfs;\n}\n\n/** Read-only snapshot of every CellStyleXf entry (named-style xfs). */\nexport function listCellStyleXfs(ss: Stylesheet): ReadonlyArray<CellXf> {\n return ss.cellStyleXfs;\n}\n\n/**\n * Convenience: build the default `cellXfs[0]` Excel emits — points at the\n * workbook's font 0 / fill 0 / border 0 / numFmtId 0 (General).\n */\nexport function defaultCellXf(): CellXf {\n return Object.freeze({ fontId: 0, fillId: 0, borderId: 0, numFmtId: 0 });\n}\n","// NamedStyle value object + curated built-in catalogue. Mirrors\n// openpyxl/openpyxl/styles/named_styles.py + styles/builtins.py.\n//\n// A `NamedStyle` is a label that bundles Font + Fill + Border +\n// Alignment + Protection + number-format string. Cells reference it\n// via the cellStyleXfs pool. This module:\n// 1. defines the value type;\n// 2. wires `addNamedStyle` (registers sub-objects in the Stylesheet,\n// allocates a cellStyleXf, then attaches the name);\n// 3. ships a curated subset of Excel's \"Cell Styles\" gallery as\n// plain-object specs and an `ensureBuiltinStyle` ergonomics\n// function that registers one on demand.\n//\n// The Accent1..6 with 20/40/60% variants and `pandas_highlight` are\n// deferred — they balloon the bundle without earning their keep on\n// the read/write hot path.\n\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport type { Alignment } from './alignment';\nimport type { Border } from './borders';\nimport { makeColor } from './colors';\nimport type { Fill } from './fills';\nimport { makePatternFill } from './fills';\nimport type { Font } from './fonts';\nimport { makeFont } from './fonts';\nimport { addBorder, addCellStyleXf, addFill, addFont, addNumFmt, type CellXf, type Stylesheet } from './stylesheet';\n\nexport interface NamedStyle {\n readonly name: string;\n /** OOXML built-in id (0..N); absent for user-defined styles. */\n readonly builtinId?: number;\n readonly customBuiltin?: boolean;\n readonly hidden?: boolean;\n readonly iLevel?: number;\n readonly font?: Font;\n readonly fill?: Fill;\n readonly border?: Border;\n readonly alignment?: Alignment;\n readonly protection?: Protection;\n readonly numberFormat?: string;\n}\n\nimport type { Protection } from './protection';\n\n/**\n * NamedStyle as it sits inside the Stylesheet (an `<cellStyles>` entry).\n * Captures the resolved cellStyleXfs index so the writer can emit the\n * `<cellStyle xfId=\"…\" name=\"…\" builtinId=\"…\"/>` element directly.\n */\nexport interface StylesheetNamedStyle {\n readonly name: string;\n readonly xfId: number;\n readonly builtinId?: number;\n readonly customBuiltin?: boolean;\n readonly hidden?: boolean;\n readonly iLevel?: number;\n}\n\n/**\n * Register a NamedStyle on the Stylesheet:\n * 1. add Font / Fill / Border / NumberFormat to their pools\n * 2. push a CellXf with apply* flags into cellStyleXfs\n * 3. append a {name, xfId, builtinId} entry into the workbook's\n * namedStyles list (caller-managed; this function returns the\n * xfId so callers can connect the dots)\n * Idempotent on (name): re-registering by the same name returns the\n * cached xfId.\n */\nexport function addNamedStyle(ss: Stylesheet, style: NamedStyle): number {\n const cached = ss._namedStyleByName?.get(style.name);\n if (cached !== undefined) return cached.xfId;\n\n const fontId = style.font !== undefined ? addFont(ss, style.font) : 0;\n const fillId = style.fill !== undefined ? addFill(ss, style.fill) : 0;\n const borderId = style.border !== undefined ? addBorder(ss, style.border) : 0;\n const numFmtId = style.numberFormat !== undefined ? addNumFmt(ss, style.numberFormat) : 0;\n\n // openpyxl convention: cellStyleXfs entries (the \"base\" XFs of named\n // styles) don't carry apply* flags. The cellXf that bridges a cell to\n // a named style is the one that sets apply* — that's what Excel reads\n // to decide whether to honour the inherited font / fill / border.\n const xf: CellXf = {\n fontId,\n fillId,\n borderId,\n numFmtId,\n ...(style.alignment !== undefined ? { alignment: style.alignment } : {}),\n ...(style.protection !== undefined ? { protection: style.protection } : {}),\n };\n const xfId = addCellStyleXf(ss, xf);\n\n if (ss._namedStyleByName === undefined) ss._namedStyleByName = new Map();\n if (ss.namedStyles === undefined) ss.namedStyles = [];\n const entry: StylesheetNamedStyle = {\n name: style.name,\n xfId,\n ...(style.builtinId !== undefined ? { builtinId: style.builtinId } : {}),\n ...(style.customBuiltin !== undefined ? { customBuiltin: style.customBuiltin } : {}),\n ...(style.hidden !== undefined ? { hidden: style.hidden } : {}),\n ...(style.iLevel !== undefined ? { iLevel: style.iLevel } : {}),\n };\n ss.namedStyles.push(entry);\n ss._namedStyleByName.set(style.name, entry);\n return xfId;\n}\n\n// ---- built-in catalogue ----------------------------------------------------\n//\n// Common ground: the gallery's body fonts are all Calibri 12, family 2,\n// minor scheme, theme-1 colour. Specific styles override font / fill /\n// border / numberFormat as needed.\n\nconst BODY_FONT: Font = makeFont({\n name: 'Calibri',\n family: 2,\n size: 12,\n color: makeColor({ theme: 1 }),\n scheme: 'minor',\n});\n\nconst fillRgb = (rgb: string, fg = true): Fill =>\n makePatternFill(\n fg ? { patternType: 'solid', bgColor: makeColor({ rgb }), fgColor: makeColor({ rgb }) } : { patternType: 'solid' },\n );\n\n/** Curated subset of openpyxl's `styles` dict. Keys match the user-visible names. */\nexport const BUILTIN_NAMED_STYLES: Readonly<Record<string, NamedStyle>> = Object.freeze({\n // -------- core ----------------------------------------------------------\n Normal: { name: 'Normal', builtinId: 0, font: BODY_FONT },\n\n // -------- semantic state ------------------------------------------------\n Good: {\n name: 'Good',\n builtinId: 26,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF006100' }) }),\n fill: fillRgb('FFC6EFCE'),\n },\n Bad: {\n name: 'Bad',\n builtinId: 27,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF9C0006' }) }),\n fill: fillRgb('FFFFC7CE'),\n },\n Neutral: {\n name: 'Neutral',\n builtinId: 28,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF9C5700' }) }),\n fill: fillRgb('FFFFEB9C'),\n },\n\n // -------- data ----------------------------------------------------------\n Calculation: {\n name: 'Calculation',\n builtinId: 22,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ rgb: 'FFFA7D00' }) }),\n fill: fillRgb('FFF2F2F2'),\n },\n 'Check Cell': {\n name: 'Check Cell',\n builtinId: 23,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ rgb: 'FFFFFFFF' }) }),\n fill: fillRgb('FFA5A5A5'),\n },\n 'Linked Cell': {\n name: 'Linked Cell',\n builtinId: 24,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FFFA7D00' }) }),\n },\n Note: {\n name: 'Note',\n builtinId: 10,\n font: BODY_FONT,\n fill: fillRgb('FFFFFFC0'),\n },\n 'Warning Text': {\n name: 'Warning Text',\n builtinId: 11,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FFFF0000' }) }),\n },\n Input: {\n name: 'Input',\n builtinId: 20,\n font: makeFont({ ...BODY_FONT, color: makeColor({ rgb: 'FF3F3F76' }) }),\n fill: fillRgb('FFFFCC99'),\n },\n Output: {\n name: 'Output',\n builtinId: 21,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ rgb: 'FF3F3F3F' }) }),\n fill: fillRgb('FFF2F2F2'),\n },\n 'Explanatory Text': {\n name: 'Explanatory Text',\n builtinId: 53,\n font: makeFont({ ...BODY_FONT, italic: true, color: makeColor({ rgb: 'FF7F7F7F' }) }),\n },\n\n // -------- titles & headings ---------------------------------------------\n Title: {\n name: 'Title',\n builtinId: 15,\n font: makeFont({ name: 'Cambria', family: 2, size: 18, scheme: 'major', color: makeColor({ theme: 3 }) }),\n },\n 'Headline 1': {\n name: 'Headline 1',\n builtinId: 16,\n font: makeFont({ ...BODY_FONT, bold: true, size: 15, color: makeColor({ theme: 3 }) }),\n },\n 'Headline 2': {\n name: 'Headline 2',\n builtinId: 17,\n font: makeFont({ ...BODY_FONT, bold: true, size: 13, color: makeColor({ theme: 3 }) }),\n },\n 'Headline 3': {\n name: 'Headline 3',\n builtinId: 18,\n font: makeFont({ ...BODY_FONT, bold: true, color: makeColor({ theme: 3 }) }),\n },\n 'Headline 4': {\n name: 'Headline 4',\n builtinId: 19,\n font: makeFont({ ...BODY_FONT, bold: true, italic: true, color: makeColor({ theme: 3 }) }),\n },\n Total: {\n name: 'Total',\n builtinId: 25,\n font: makeFont({ ...BODY_FONT, bold: true }),\n },\n\n // -------- numeric -------------------------------------------------------\n Comma: { name: 'Comma', builtinId: 3, font: BODY_FONT, numberFormat: '#,##0.00' },\n 'Comma [0]': { name: 'Comma [0]', builtinId: 6, font: BODY_FONT, numberFormat: '#,##0' },\n Currency: { name: 'Currency', builtinId: 4, font: BODY_FONT, numberFormat: '\"$\"#,##0.00' },\n 'Currency [0]': { name: 'Currency [0]', builtinId: 7, font: BODY_FONT, numberFormat: '\"$\"#,##0' },\n Percent: { name: 'Percent', builtinId: 5, font: BODY_FONT, numberFormat: '0%' },\n\n // -------- hyperlinks ----------------------------------------------------\n Hyperlink: {\n name: 'Hyperlink',\n builtinId: 8,\n font: makeFont({ ...BODY_FONT, underline: 'single', color: makeColor({ theme: 10 }) }),\n },\n 'Followed Hyperlink': {\n name: 'Followed Hyperlink',\n builtinId: 9,\n font: makeFont({ ...BODY_FONT, underline: 'single', color: makeColor({ theme: 11 }) }),\n },\n});\n\n/**\n * Register a built-in style with the supplied Stylesheet (idempotent).\n * Returns the cellStyleXfs index. Throws OpenXmlSchemaError when the\n * name is unknown.\n */\nexport function ensureBuiltinStyle(ss: Stylesheet, name: keyof typeof BUILTIN_NAMED_STYLES | string): number {\n const spec = BUILTIN_NAMED_STYLES[name as keyof typeof BUILTIN_NAMED_STYLES];\n if (spec === undefined) {\n throw new OpenXmlSchemaError(`ensureBuiltinStyle: unknown built-in style \"${String(name)}\"`);\n }\n return addNamedStyle(ss, spec);\n}\n","// Cell protection value object. Mirrors openpyxl/openpyxl/styles/protection.py.\n//\n// Protection only matters when the worksheet itself is protected; until\n// then it's metadata that round-trips with the cell's style.\n\nexport interface Protection {\n /** When true (the default), the cell can't be edited if the sheet is locked. */\n readonly locked?: boolean;\n /** When true, the formula bar hides this cell's contents on a protected sheet. */\n readonly hidden?: boolean;\n}\n\nexport function makeProtection(opts: Partial<Protection> = {}): Protection {\n const out: { -readonly [K in keyof Protection]: Protection[K] } = {};\n if (opts.locked !== undefined) out.locked = opts.locked;\n if (opts.hidden !== undefined) out.hidden = opts.hidden;\n return Object.freeze(out);\n}\n\n/** Excel's Stylesheet always contains an entry equal to {locked:true, hidden:false}. */\nexport const DEFAULT_PROTECTION: Protection = makeProtection({ locked: true, hidden: false });\n","// Cell ↔ Stylesheet bridge.\n//\n// A cell's `styleId` is an index into `Workbook.styles.cellXfs`. Each CellXf\n// points at slots in the font / fill / border / numFmt pools. To \"apply\" a Font\n// to a cell we therefore:\n// 1. read the cell's current CellXf (or `defaultCellXf` if it points\n// at a slot that hasn't been allocated yet — common right after\n// `makeCell` since `cellXfs` starts empty)\n// 2. resolve / register the new component in its pool\n// 3. build a new CellXf that carries the new id + the matching\n// `apply*` flag (Excel needs the flag to honour the override over\n// the underlying NamedStyle)\n// 4. dedup that CellXf via `addCellXf` and write the returned index\n// back to `c.styleId`\n//\n// Following the no-classes rule, this module is just a flat list of free\n// functions; the workbook is passed in so callers don't need to thread the\n// stylesheet manually.\n\nimport type { Cell } from '../cell/cell';\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport type { Workbook } from '../workbook/workbook';\nimport { parseRange } from '../worksheet/cell-range';\nimport { setCell, type Worksheet } from '../worksheet/worksheet';\nimport type { Alignment, HorizontalAlignment, VerticalAlignment } from './alignment';\nimport { alignmentToCss, makeAlignment } from './alignment';\nimport type { Border, SideStyle } from './borders';\nimport { borderToCss, DEFAULT_BORDER, makeBorder, makeSide } from './borders';\nimport type { Color } from './colors';\nimport { makeColor } from './colors';\nimport type { Fill } from './fills';\nimport { DEFAULT_EMPTY_FILL, fillToCss, makePatternFill } from './fills';\nimport type { Font, UnderlineStyle } from './fonts';\nimport { DEFAULT_FONT, fontToCss, makeFont } from './fonts';\nimport { ensureBuiltinStyle } from './named-styles';\nimport { builtinFormatCode } from './numbers';\nimport type { Protection } from './protection';\nimport { DEFAULT_PROTECTION } from './protection';\nimport {\n addBorder,\n addCellXf,\n addFill,\n addFont,\n addNumFmt,\n type CellXf,\n defaultCellXf,\n type Stylesheet,\n} from './stylesheet';\n\n/** Default General number format code (numFmtId 0). */\nconst GENERAL_FORMAT_CODE = 'General';\n\n/** Resolve a cell's current CellXf, falling back to defaults when unset. */\nfunction currentXf(ss: Stylesheet, c: Cell): CellXf {\n return ss.cellXfs[c.styleId] ?? defaultCellXf();\n}\n\n// ---- read accessors --------------------------------------------------------\n\nexport function getCellFont(wb: Workbook, c: Cell): Font {\n const xf = currentXf(wb.styles, c);\n return wb.styles.fonts[xf.fontId] ?? DEFAULT_FONT;\n}\n\nexport function getCellFill(wb: Workbook, c: Cell): Fill {\n const xf = currentXf(wb.styles, c);\n return wb.styles.fills[xf.fillId] ?? DEFAULT_EMPTY_FILL;\n}\n\nexport function getCellBorder(wb: Workbook, c: Cell): Border {\n const xf = currentXf(wb.styles, c);\n return wb.styles.borders[xf.borderId] ?? DEFAULT_BORDER;\n}\n\nexport function getCellAlignment(wb: Workbook, c: Cell): Alignment {\n return currentXf(wb.styles, c).alignment ?? {};\n}\n\nexport function getCellProtection(wb: Workbook, c: Cell): Protection {\n return currentXf(wb.styles, c).protection ?? DEFAULT_PROTECTION;\n}\n\n/**\n * Returns the cell's number-format **code** (e.g. `\"0.00\"`, `\"General\"`).\n * Built-in IDs resolve through `builtinFormatCode`; custom IDs come from the\n * workbook's numFmts map.\n */\nexport function getCellNumberFormat(wb: Workbook, c: Cell): string {\n const id = currentXf(wb.styles, c).numFmtId;\n const builtin = builtinFormatCode(id);\n if (builtin !== undefined) return builtin;\n return wb.styles.numFmts.get(id) ?? GENERAL_FORMAT_CODE;\n}\n\n/**\n * Aggregate `fontToCss` + `fillToCss` + `borderToCss` + `alignmentToCss` for a\n * cell into a single CSS-property record. Resolves the cell's `styleId` against\n * the workbook stylesheet, then merges the four partials. On key collision the\n * priority is alignment > border > fill > font (alignment is most specific,\n * font is the broad default). A fully-default cell (`styleId === 0` with empty\n * pools) returns `{}`.\n */\nexport function cellStyleToCss(wb: Workbook, c: Cell): Record<string, string> {\n // Don't pay the resolve cost when the cell points at the default xf and the\n // stylesheet is still in its initial state.\n if (c.styleId === 0) {\n const xf = wb.styles.cellXfs[0];\n if (!xf || (xf.fontId === 0 && xf.fillId === 0 && xf.borderId === 0 && xf.alignment === undefined)) {\n return {};\n }\n }\n const font = getCellFont(wb, c);\n const fill = getCellFill(wb, c);\n const border = getCellBorder(wb, c);\n const alignment = getCellAlignment(wb, c);\n return {\n ...fontToCss(font),\n ...fillToCss(fill),\n ...borderToCss(border),\n ...alignmentToCss(alignment),\n };\n}\n\n// ---- write accessors -------------------------------------------------------\n\n/**\n * Reserve cellXfs[0] for the implicit default xf when the pool is empty.\n * Excel's `<c>` elements without an `s=` attribute resolve to `cellXfs[0]`, so\n * the first time a caller styles any cell we need to make sure that slot stays\n * the default — otherwise unstyled cells in the same sheet would inherit the\n * freshly added styled xf.\n *\n * Idempotent: calling this on a non-empty pool is a no-op.\n */\nconst reserveDefaultXfSlot = (wb: Workbook): void => {\n if (wb.styles.cellXfs.length === 0) addCellXf(wb.styles, defaultCellXf());\n};\n\n/**\n * Replace one field on the cell's CellXf. Centralises the dedup + styleId\n * update so each `setCell*` is a single dispatch.\n */\nfunction applyXfPatch(wb: Workbook, c: Cell, patch: Partial<CellXf>): void {\n reserveDefaultXfSlot(wb);\n const next: CellXf = { ...currentXf(wb.styles, c), ...patch };\n c.styleId = addCellXf(wb.styles, next);\n}\n\nexport function setCellFont(wb: Workbook, c: Cell, font: Font): void {\n const fontId = addFont(wb.styles, font);\n applyXfPatch(wb, c, { fontId, applyFont: true });\n}\n\nexport function setCellFill(wb: Workbook, c: Cell, fill: Fill): void {\n const fillId = addFill(wb.styles, fill);\n applyXfPatch(wb, c, { fillId, applyFill: true });\n}\n\nexport function setCellBorder(wb: Workbook, c: Cell, border: Border): void {\n const borderId = addBorder(wb.styles, border);\n applyXfPatch(wb, c, { borderId, applyBorder: true });\n}\n\nexport function setCellAlignment(wb: Workbook, c: Cell, alignment: Alignment): void {\n applyXfPatch(wb, c, { alignment, applyAlignment: true });\n}\n\nexport function setCellProtection(wb: Workbook, c: Cell, protection: Protection): void {\n applyXfPatch(wb, c, { protection, applyProtection: true });\n}\n\n/**\n * Set the cell's number format by its **code** string. Built-in codes resolve\n * to their canonical id; custom codes are registered via `addNumFmt`.\n */\nexport function setCellNumberFormat(wb: Workbook, c: Cell, formatCode: string): void {\n const numFmtId = addNumFmt(wb.styles, formatCode);\n applyXfPatch(wb, c, { numFmtId, applyNumberFormat: true });\n}\n\n/**\n * Copy the source cell's `styleId` to the target cell. Both cells share the\n * same workbook stylesheet, so the styled appearance carries over without\n * allocating a new xf entry. Pass cells from different workbooks via {@link\n * cloneCellStyle} if you need a deep copy across workbooks.\n */\nexport function copyCellStyle(_wb: Workbook, source: Cell, target: Cell): void {\n target.styleId = source.styleId;\n}\n\n/**\n * Reset a cell back to the default (unstyled) appearance — equivalent to\n * Excel's \"Clear Formatting\" command. After the call, the cell inherits the\n * workbook's default font / fill / border / alignment / protection /\n * numberFormat. The underlying xf pool is **not** shrunk (Excel doesn't bother\n * either; the orphaned xf is harmless).\n */\nexport function clearCellStyle(_wb: Workbook, c: Cell): void {\n c.styleId = 0;\n}\n\n/**\n * Range-level shortcut for {@link clearCellStyle}. Walks every cell actually\n * present in the range and resets its `styleId` to 0; cells that don't exist\n * yet are **not** materialised (no-op for sparse regions, unlike the styled\n * `setRange*` family which has to create cells to make the patch observable).\n */\nexport function clearRangeStyle(wb: Workbook, ws: Worksheet, range: string): void {\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n for (let r = minRow; r <= maxRow; r++) {\n const row = ws.rows.get(r);\n if (!row) continue;\n for (let c = minCol; c <= maxCol; c++) {\n const cell = row.get(c);\n if (cell) clearCellStyle(wb, cell);\n }\n }\n}\n\n/**\n * Deep-copy the source cell's full xf (font / fill / border / alignment /\n * protection / numberFormat) into a possibly-different workbook. Returns the\n * new styleId in the target workbook.\n */\nexport function cloneCellStyle(\n sourceWb: Workbook,\n source: Cell,\n targetWb: Workbook,\n target: Cell,\n): number {\n reserveDefaultXfSlot(targetWb);\n const srcXf = currentXf(sourceWb.styles, source);\n const srcFont = sourceWb.styles.fonts[srcXf.fontId] ?? DEFAULT_FONT;\n const srcFill = sourceWb.styles.fills[srcXf.fillId] ?? DEFAULT_EMPTY_FILL;\n const srcBorder = sourceWb.styles.borders[srcXf.borderId] ?? DEFAULT_BORDER;\n const srcNumFmt = builtinFormatCode(srcXf.numFmtId)\n ?? sourceWb.styles.numFmts.get(srcXf.numFmtId)\n ?? GENERAL_FORMAT_CODE;\n const fontId = addFont(targetWb.styles, srcFont);\n const fillId = addFill(targetWb.styles, srcFill);\n const borderId = addBorder(targetWb.styles, srcBorder);\n const numFmtId = addNumFmt(targetWb.styles, srcNumFmt);\n const next: { -readonly [K in keyof CellXf]?: CellXf[K] } = {\n fontId,\n fillId,\n borderId,\n numFmtId,\n };\n if (srcXf.applyFont) next.applyFont = true;\n if (srcXf.applyFill) next.applyFill = true;\n if (srcXf.applyBorder) next.applyBorder = true;\n if (srcXf.applyNumberFormat) next.applyNumberFormat = true;\n if (srcXf.alignment !== undefined) {\n next.alignment = srcXf.alignment;\n next.applyAlignment = true;\n }\n if (srcXf.protection !== undefined) {\n next.protection = srcXf.protection;\n next.applyProtection = true;\n }\n target.styleId = addCellXf(targetWb.styles, next as CellXf);\n return target.styleId;\n}\n\n/**\n * Build a single CellXf id from a multi-axis style spec, then apply it to every\n * cell in `range`. The xf is registered once per style shape, so a 1000-cell\n * range allocates one xf — much faster than looping `setCellStyle` per cell.\n */\nexport function setRangeStyle(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n opts: {\n font?: Font;\n fill?: Fill;\n border?: Border;\n alignment?: Alignment;\n protection?: Protection;\n numberFormat?: string;\n },\n): void {\n const patch: { -readonly [K in keyof CellXf]?: CellXf[K] } = {};\n if (opts.font !== undefined) {\n patch.fontId = addFont(wb.styles, opts.font);\n patch.applyFont = true;\n }\n if (opts.fill !== undefined) {\n patch.fillId = addFill(wb.styles, opts.fill);\n patch.applyFill = true;\n }\n if (opts.border !== undefined) {\n patch.borderId = addBorder(wb.styles, opts.border);\n patch.applyBorder = true;\n }\n if (opts.alignment !== undefined) {\n patch.alignment = opts.alignment;\n patch.applyAlignment = true;\n }\n if (opts.protection !== undefined) {\n patch.protection = opts.protection;\n patch.applyProtection = true;\n }\n if (opts.numberFormat !== undefined) {\n patch.numFmtId = addNumFmt(wb.styles, opts.numberFormat);\n patch.applyNumberFormat = true;\n }\n if (Object.keys(patch).length === 0) return;\n reserveDefaultXfSlot(wb);\n\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n // Pre-register the xf for each existing cell — Excel dedupes by value, so the\n // inner xf-pool ends up the same shape for cells already carrying part of the\n // patch as for blanks.\n for (let r = minRow; r <= maxRow; r++) {\n for (let c = minCol; c <= maxCol; c++) {\n let cell = ws.rows.get(r)?.get(c);\n if (!cell) cell = setCell(ws, r, c);\n const next: CellXf = { ...currentXf(wb.styles, cell), ...patch };\n cell.styleId = addCellXf(wb.styles, next);\n }\n }\n}\n\n/**\n * Combined cell-style setter. Each axis is independent — pass any subset and\n * the corresponding `applyXxx` flags get set on the underlying CellXf. Avoids\n * 5+ separate stylesheet round-trips when a caller wants to style a single cell\n * across multiple axes (Excel dedupes the resulting xf record on every call).\n */\nexport function setCellStyle(\n wb: Workbook,\n c: Cell,\n opts: {\n font?: Font;\n fill?: Fill;\n border?: Border;\n alignment?: Alignment;\n protection?: Protection;\n numberFormat?: string;\n },\n): void {\n const patch: { -readonly [K in keyof CellXf]?: CellXf[K] } = {};\n if (opts.font !== undefined) {\n patch.fontId = addFont(wb.styles, opts.font);\n patch.applyFont = true;\n }\n if (opts.fill !== undefined) {\n patch.fillId = addFill(wb.styles, opts.fill);\n patch.applyFill = true;\n }\n if (opts.border !== undefined) {\n patch.borderId = addBorder(wb.styles, opts.border);\n patch.applyBorder = true;\n }\n if (opts.alignment !== undefined) {\n patch.alignment = opts.alignment;\n patch.applyAlignment = true;\n }\n if (opts.protection !== undefined) {\n patch.protection = opts.protection;\n patch.applyProtection = true;\n }\n if (opts.numberFormat !== undefined) {\n patch.numFmtId = addNumFmt(wb.styles, opts.numberFormat);\n patch.applyNumberFormat = true;\n }\n if (Object.keys(patch).length === 0) return;\n applyXfPatch(wb, c, patch as Partial<CellXf>);\n}\n\n// ---- fill presets -------------------------------------------------------\n\n/**\n * Set the cell's background to a solid color. Accepts a hex string\n * (`'FFAAFFAA'`) or a partial `Color` object (`{ theme: 4, tint: 0.4 }`).\n * Equivalent to `setCellFill(wb, c, makePatternFill({ patternType: 'solid',\n * fgColor: makeColor(...) }))`.\n */\nexport function setCellBackgroundColor(wb: Workbook, c: Cell, color: string | Partial<Color>): void {\n const colorObj = typeof color === 'string' ? makeColor({ rgb: color }) : makeColor(color);\n setCellFill(wb, c, makePatternFill({ patternType: 'solid', fgColor: colorObj }));\n}\n\n/** Strip the cell's background fill, returning it to the default. */\nexport function clearCellBackground(wb: Workbook, c: Cell): void {\n setCellFill(wb, c, DEFAULT_EMPTY_FILL);\n}\n\n/**\n * Range-level shortcut for `setCellBackgroundColor`. Each cell in the range\n * gets the same solid pattern fill via `setRangeStyle`, so the fill pool dedups\n * to a single entry across the whole range.\n */\nexport function setRangeBackgroundColor(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n color: string | Partial<Color>,\n): void {\n const colorObj = typeof color === 'string' ? makeColor({ rgb: color }) : makeColor(color);\n setRangeStyle(wb, ws, range, {\n fill: makePatternFill({ patternType: 'solid', fgColor: colorObj }),\n });\n}\n\n/** Range-level shortcut for `setCellFont` (full Font replacement). */\nexport function setRangeFont(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n font: Font,\n): void {\n setRangeStyle(wb, ws, range, { font });\n}\n\n/**\n * Range-level shortcut for `setCellNumberFormat`. Stamps the same format-code\n * onto every cell in the range; the numFmt pool dedups the code so callers\n * don't pay per-cell pool churn.\n */\nexport function setRangeNumberFormat(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n formatCode: string,\n): void {\n setRangeStyle(wb, ws, range, { numberFormat: formatCode });\n}\n\n/**\n * Range-level shortcut for `setCellProtection`. Stamps the same Protection\n * (locked / hidden) onto every cell in the range. Pass a full `Protection`\n * value or a partial — partials default missing fields to `false` per Excel's\n * `<protection>` semantics.\n *\n * Common usage: `setRangeProtection(wb, ws, 'B2:B100', { locked: false })` to\n * leave just an input column editable when the sheet is protected.\n */\nexport function setRangeProtection(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n protection: Protection | Partial<Protection>,\n): void {\n // Funnel partials through the Protection factory so frozen invariant holds.\n const p: Protection = Object.isFrozen(protection)\n ? (protection as Protection)\n : { locked: protection.locked ?? false, hidden: protection.hidden ?? false };\n setRangeStyle(wb, ws, range, { protection: p });\n}\n\n/**\n * Range-level shortcut for `wrapCellText`. Toggles \"Wrap Text\" on every cell in\n * the range while preserving each cell's existing alignment (horizontal /\n * vertical / textRotation / indent are not touched). Empty cells in the range\n * are materialised so the alignment patch is observable on round-trip.\n */\nexport function setRangeWrapText(wb: Workbook, ws: Worksheet, range: string, on = true): void {\n reserveDefaultXfSlot(wb);\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n for (let r = minRow; r <= maxRow; r++) {\n for (let c = minCol; c <= maxCol; c++) {\n let cell = ws.rows.get(r)?.get(c);\n if (!cell) cell = setCell(ws, r, c);\n wrapCellText(wb, cell, on);\n }\n }\n}\n\n/**\n * Range-level Alignment setter. Two modes:\n *\n * - `mode: 'merge'` (default) — each cell's existing alignment is\n * preserved; the supplied partial overlays it. Use this when you\n * want to set just `horizontal` or `vertical` without wiping the\n * other axes.\n * - `mode: 'replace'` — each cell's alignment is **wholly replaced**\n * by the supplied value. Indent / textRotation / wrapText that\n * weren't supplied are dropped.\n *\n * Empty cells in the range are materialised so the patch is observable on\n * round-trip.\n */\nexport function setRangeAlignment(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n alignment: Partial<Alignment>,\n mode: 'merge' | 'replace' = 'merge',\n): void {\n reserveDefaultXfSlot(wb);\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n if (mode === 'replace') {\n setRangeStyle(wb, ws, range, { alignment: makeAlignment(alignment) });\n return;\n }\n for (let r = minRow; r <= maxRow; r++) {\n for (let c = minCol; c <= maxCol; c++) {\n let cell = ws.rows.get(r)?.get(c);\n if (!cell) cell = setCell(ws, r, c);\n const cur = currentXf(wb.styles, cell).alignment;\n setCellAlignment(wb, cell, mergeAlignment(cur, alignment));\n }\n }\n}\n\n// ---- font presets -------------------------------------------------------\n\nconst mergeFont = (current: Font, patch: Partial<Font>): Font => makeFont({ ...current, ...patch });\n\n/** Toggle bold on a cell. Preserves other font fields. */\nexport function setBold(wb: Workbook, c: Cell, on = true): void {\n setCellFont(wb, c, mergeFont(getCellFont(wb, c), { bold: on }));\n}\n\n/** Toggle italic on a cell. */\nexport function setItalic(wb: Workbook, c: Cell, on = true): void {\n setCellFont(wb, c, mergeFont(getCellFont(wb, c), { italic: on }));\n}\n\n/** Toggle strike-through on a cell. */\nexport function setStrikethrough(wb: Workbook, c: Cell, on = true): void {\n setCellFont(wb, c, mergeFont(getCellFont(wb, c), { strike: on }));\n}\n\n/**\n * Set the underline style. Pass `false` to drop underline; pass `'single' |\n * 'double' | 'singleAccounting' | 'doubleAccounting'` to apply that style; pass\n * `true` for the most common single-line.\n */\nexport function setUnderline(\n wb: Workbook,\n c: Cell,\n style: UnderlineStyle | boolean = 'single',\n): void {\n const cur = getCellFont(wb, c);\n // Strip the existing underline by spreading then overwriting; makeFont\n // ignores `underline: undefined` so passing nothing for the off-case drops it\n // entirely.\n const { underline: _drop, ...rest } = cur;\n if (style === false) {\n setCellFont(wb, c, makeFont(rest));\n return;\n }\n const u = style === true ? 'single' : style;\n setCellFont(wb, c, makeFont({ ...rest, underline: u }));\n}\n\n/** Set the font size in points (e.g. 14). Preserves other fields. */\nexport function setFontSize(wb: Workbook, c: Cell, size: number): void {\n setCellFont(wb, c, mergeFont(getCellFont(wb, c), { size }));\n}\n\n/** Set the font family name (e.g. \"Arial\"). Preserves other fields. */\nexport function setFontName(wb: Workbook, c: Cell, name: string): void {\n setCellFont(wb, c, mergeFont(getCellFont(wb, c), { name }));\n}\n\n/**\n * Set the font color. Accepts a hex string (\"FFAA0033\") or a partial `Color`\n * object (`{ theme: 4, tint: 0.4 }`). Preserves other font fields.\n */\nexport function setFontColor(wb: Workbook, c: Cell, color: string | Partial<Color>): void {\n const colorObj = typeof color === 'string' ? makeColor({ rgb: color }) : makeColor(color);\n setCellFont(wb, c, mergeFont(getCellFont(wb, c), { color: colorObj }));\n}\n\n// ---- alignment presets --------------------------------------------------\n\nconst mergeAlignment = (current: Alignment | undefined, patch: Partial<Alignment>): Alignment => {\n return makeAlignment({ ...current, ...patch });\n};\n\n/**\n * Center a cell horizontally + vertically. Mirrors Excel's \"Merge & Center\" UI\n * button (without the merge — see {@link mergeCells} for that). Preserves any\n * other alignment fields already present.\n */\nexport function centerCell(wb: Workbook, c: Cell): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { horizontal: 'center', vertical: 'center' }));\n}\n\n/** Toggle \"Wrap Text\" on a cell, preserving other alignment fields. */\nexport function wrapCellText(wb: Workbook, c: Cell, wrap = true): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { wrapText: wrap }));\n}\n\n/** Set the horizontal alignment in isolation. */\nexport function alignCellHorizontal(wb: Workbook, c: Cell, horizontal: HorizontalAlignment): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { horizontal }));\n}\n\n/** Set the vertical alignment in isolation. */\nexport function alignCellVertical(wb: Workbook, c: Cell, vertical: VerticalAlignment): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { vertical }));\n}\n\n/**\n * Rotate the cell's text. `degrees` accepts 0..180 (clockwise) or 255 for\n * Excel's \"vertical stacked\" mode. Mirrors the rotate icons in the alignment\n * ribbon.\n */\nexport function rotateCellText(wb: Workbook, c: Cell, degrees: number): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { textRotation: degrees }));\n}\n\n/** Set or clear the indent level (0..255). */\nexport function indentCell(wb: Workbook, c: Cell, levels: number): void {\n const cur = currentXf(wb.styles, c).alignment;\n setCellAlignment(wb, c, mergeAlignment(cur, { indent: levels }));\n}\n\n// ---- format presets -----------------------------------------------------\n//\n// Mirror Excel's \"Format Cells → Number → Category\" panel. Each preset builds\n// the exact format-code Excel ships with, then routes through the existing\n// `setCellNumberFormat` so the dedup pool sees the same string every time.\n\n/**\n * Format a cell as currency. Produces one of:\n * - default → `\"$#,##0.00\"` (US dollar, 2 decimals)\n * - `{ symbol: \"€\" }` → `\"€#,##0.00\"`\n * - `{ symbol: \"¥\", decimals: 0 }` → `\"¥#,##0\"`\n * - `{ accounting: true }` → `\"_-$* #,##0.00_-;-$* #,##0.00_-;_-$* \\\"-\\\"??_-;_-@_-\"`\n * (Excel's \"Accounting\" subtype with right-aligned symbol).\n */\nexport function setCellAsCurrency(\n wb: Workbook,\n c: Cell,\n opts: { symbol?: string; decimals?: number; accounting?: boolean } = {},\n): void {\n const symbol = opts.symbol ?? '$';\n const decimals = opts.decimals ?? 2;\n const decTail = decimals > 0 ? `.${'0'.repeat(decimals)}` : '';\n const code = opts.accounting\n ? `_-${symbol}* #,##0${decTail}_-;-${symbol}* #,##0${decTail}_-;_-${symbol}* \"-\"${'?'.repeat(decimals)}_-;_-@_-`\n : `${symbol}#,##0${decTail}`;\n setCellNumberFormat(wb, c, code);\n}\n\n/**\n * Format a cell as a percentage. `decimals` defaults to 0 → `\"0%\"`; `decimals:\n * 2` → `\"0.00%\"`. The cell value is multiplied by 100 by Excel during display.\n */\nexport function setCellAsPercent(wb: Workbook, c: Cell, decimals = 0): void {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new OpenXmlSchemaError(`setCellAsPercent: decimals must be a non-negative integer; got ${decimals}`);\n }\n const code = decimals === 0 ? '0%' : `0.${'0'.repeat(decimals)}%`;\n setCellNumberFormat(wb, c, code);\n}\n\n/**\n * Format a cell as a date. `format` defaults to Excel's default\n * locale-independent ISO-style date `\"yyyy-mm-dd\"`. Common alternatives:\n * `\"m/d/yyyy\"`, `\"dd-mmm-yy\"`, `\"yyyy-mm-dd hh:mm:ss\"`.\n */\nexport function setCellAsDate(wb: Workbook, c: Cell, format = 'yyyy-mm-dd'): void {\n setCellNumberFormat(wb, c, format);\n}\n\n/**\n * Format a cell as a thousands-separated number. `decimals` defaults to 0 →\n * `\"#,##0\"`; `decimals: 2` → `\"#,##0.00\"`.\n */\nexport function setCellAsNumber(wb: Workbook, c: Cell, decimals = 0): void {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new OpenXmlSchemaError(`setCellAsNumber: decimals must be a non-negative integer; got ${decimals}`);\n }\n const code = decimals === 0 ? '#,##0' : `#,##0.${'0'.repeat(decimals)}`;\n setCellNumberFormat(wb, c, code);\n}\n\n// ---- table-header preset ------------------------------------------------\n\n/**\n * Apply Excel's stock \"table header\" formatting to a range: bold white text on\n * a dark fill, plus a thick bottom border. Override any axis via `opts` — pass\n * `bold: false` to drop the bold, or `fillColor: 'FF305496'` for a different\n * shade. Defaults match Excel's \"Table Style Medium 2\" header row.\n */\nexport function formatAsHeader(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n opts: {\n fillColor?: string | Partial<Color>;\n fontColor?: string | Partial<Color>;\n bold?: boolean;\n bottomBorder?: SideStyle | false;\n bottomBorderColor?: string | Partial<Color>;\n } = {},\n): void {\n const fillColor = opts.fillColor === undefined ? 'FF305496' : typeof opts.fillColor === 'string' ? makeColor({ rgb: opts.fillColor }) : makeColor(opts.fillColor);\n const fontColor = opts.fontColor === undefined ? 'FFFFFFFF' : typeof opts.fontColor === 'string' ? makeColor({ rgb: opts.fontColor }) : makeColor(opts.fontColor);\n const bold = opts.bold ?? true;\n const borderStyle = opts.bottomBorder ?? 'medium';\n const borderColorObj = opts.bottomBorderColor === undefined ? undefined : typeof opts.bottomBorderColor === 'string' ? makeColor({ rgb: opts.bottomBorderColor }) : makeColor(opts.bottomBorderColor);\n\n const fillColorObj = typeof fillColor === 'string' ? makeColor({ rgb: fillColor }) : fillColor;\n const fontColorObj = typeof fontColor === 'string' ? makeColor({ rgb: fontColor }) : fontColor;\n\n const styleOpts: Parameters<typeof setRangeStyle>[3] = {\n font: makeFont({ bold, color: fontColorObj }),\n fill: makePatternFill({ patternType: 'solid', fgColor: fillColorObj }),\n };\n if (borderStyle !== false) {\n const side = makeSide({ style: borderStyle, ...(borderColorObj ? { color: borderColorObj } : {}) });\n styleOpts.border = makeBorder({ bottom: side });\n }\n setRangeStyle(wb, ws, range, styleOpts);\n}\n\n// ---- named / built-in style application --------------------------------\n\n/**\n * Apply a built-in Excel style (\"Heading 1\" / \"Total\" / \"Good\" / \"Bad\" /\n * \"Calculation\" / etc.) to a single cell. Registers the built-in on the\n * Stylesheet (idempotent) and points the cell's xf at it via `xfId` while\n * inheriting the matching font/fill/border/ numFmt ids so the cell renders\n * correctly on its own.\n *\n * Throws when `name` isn't in {@link BUILTIN_NAMED_STYLES}; use {@link\n * applyNamedStyle} for user-registered styles.\n */\nexport function applyBuiltinStyle(wb: Workbook, c: Cell, name: string): void {\n const xfId = ensureBuiltinStyle(wb.styles, name);\n applyNamedStyleByXfId(wb, c, xfId);\n}\n\n/**\n * Apply a NamedStyle that's already registered on the workbook (via\n * `addNamedStyle` or `ensureBuiltinStyle`) to a single cell, by name.\n */\nexport function applyNamedStyle(wb: Workbook, c: Cell, name: string): void {\n const entry = wb.styles._namedStyleByName?.get(name);\n if (entry === undefined) {\n throw new OpenXmlSchemaError(`applyNamedStyle: no named style \"${name}\" registered`);\n }\n applyNamedStyleByXfId(wb, c, entry.xfId);\n}\n\nconst applyNamedStyleByXfId = (wb: Workbook, c: Cell, xfId: number): void => {\n const styleXf = wb.styles.cellStyleXfs[xfId];\n if (!styleXf) {\n throw new OpenXmlSchemaError(`applyNamedStyle: cellStyleXfs[${xfId}] missing`);\n }\n // Excel only renders the cellStyleXf's font / fill / border when the cellXf\n // carries the matching `apply*` flag — even a `xfId` reference alone doesn't\n // make Excel inherit the values. So we copy every component the named style\n // touches *and* set the corresponding apply* flag, mirroring what real Excel\n // writes for `s=` referenced cells using a built-in named style.\n const patch: { -readonly [K in keyof CellXf]?: CellXf[K] } = {\n xfId,\n fontId: styleXf.fontId,\n fillId: styleXf.fillId,\n borderId: styleXf.borderId,\n numFmtId: styleXf.numFmtId,\n applyFont: true,\n applyFill: true,\n applyBorder: true,\n applyNumberFormat: true,\n };\n if (styleXf.alignment !== undefined) {\n patch.alignment = styleXf.alignment;\n patch.applyAlignment = true;\n }\n if (styleXf.protection !== undefined) {\n patch.protection = styleXf.protection;\n patch.applyProtection = true;\n }\n applyXfPatch(wb, c, patch as Partial<CellXf>);\n};\n\n// ---- border presets ----------------------------------------------------\n\n/**\n * Apply the same {@link SideStyle} to all four edges of a single cell. Optional\n * color via hex string or `Color` partial. Equivalent to `setCellBorder(wb, c,\n * makeBorder({ left, right, top, bottom: side }))` with all four sides\n * identical.\n */\nexport function setCellBorderAll(\n wb: Workbook,\n c: Cell,\n opts: { style: SideStyle; color?: string | Partial<Color> } = { style: 'thin' },\n): void {\n const colorObj = opts.color === undefined ? undefined : typeof opts.color === 'string' ? makeColor({ rgb: opts.color }) : makeColor(opts.color);\n const side = makeSide({ style: opts.style, ...(colorObj ? { color: colorObj } : {}) });\n setCellBorder(wb, c, makeBorder({ left: side, right: side, top: side, bottom: side }));\n}\n\n/**\n * Draw an outer border around a rectangular range. Cells on the perimeter\n * receive a partial border (only the edges that face outside the range); inner\n * cells are unaffected unless `inner` is provided, in which case every cell in\n * the range receives a border combining its perimeter edges with the `inner`\n * style for the inside edges.\n */\nexport function setRangeBorderBox(\n wb: Workbook,\n ws: Worksheet,\n range: string,\n opts: { style: SideStyle; color?: string | Partial<Color>; inner?: SideStyle } = { style: 'thin' },\n): void {\n const { minRow, maxRow, minCol, maxCol } = parseRange(range);\n const colorObj = opts.color === undefined ? undefined : typeof opts.color === 'string' ? makeColor({ rgb: opts.color }) : makeColor(opts.color);\n const outer = makeSide({ style: opts.style, ...(colorObj ? { color: colorObj } : {}) });\n const inner =\n opts.inner !== undefined\n ? makeSide({ style: opts.inner, ...(colorObj ? { color: colorObj } : {}) })\n : undefined;\n for (let r = minRow; r <= maxRow; r++) {\n for (let col = minCol; col <= maxCol; col++) {\n const onTop = r === minRow;\n const onBottom = r === maxRow;\n const onLeft = col === minCol;\n const onRight = col === maxCol;\n // Skip cells that wouldn't get any styling (interior cells when no\n // inner).\n if (!inner && !onTop && !onBottom && !onLeft && !onRight) continue;\n const sides: { -readonly [K in keyof Border]?: Border[K] } = {};\n const top = onTop ? outer : inner;\n const bottom = onBottom ? outer : inner;\n const left = onLeft ? outer : inner;\n const right = onRight ? outer : inner;\n if (top !== undefined) sides.top = top;\n if (bottom !== undefined) sides.bottom = bottom;\n if (left !== undefined) sides.left = left;\n if (right !== undefined) sides.right = right;\n let cell = ws.rows.get(r)?.get(col);\n if (!cell) cell = setCell(ws, r, col);\n setCellBorder(wb, cell, makeBorder(sides));\n }\n }\n}\n"],"mappings":";;;AASA,MAAM,oBAAoB,MAAc,UAA4B;CAClE,IAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG,OAAO;CAChF,MAAM,MAAM;CACZ,MAAM,OAAO,OAAO,KAAK,GAAG,CAAC,CAAC,KAAK;CACnC,MAAM,MAA+B,CAAC;CACtC,KAAK,MAAM,KAAK,MAAM,IA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AAA,IACX,SAAS;EAAE,OAAO,KAAK;EAAO,GAAI,WAAW,EAAE,OAAO,SAAS,IAAI,CAAC;CAAG,CAAC,IACxE,KAAA;CACN,KAAK,IAAI,IAAI,QAAQ,KAAK,QAAQ,KAChC,KAAK,IAAI,MAAM,QAAQ,OAAO,QAAQ,OAAO;EAC3C,MAAM,QAAQ,MAAM;EACpB,MAAM,WAAW,MAAM;EACvB,MAAM,SAAS,QAAQ;EACvB,MAAM,UAAU,QAAQ;EAGxB,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,YAAY,CAAC,UAAU,CAAC,SAAS;EAC1D,MAAM,QAAuD,CAAC;EAC9D,MAAM,MAAM,QAAQ,QAAQ;EAC5B,MAAM,SAAS,WAAW,QAAQ;EAClC,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,QAAQ,UAAU,QAAQ;EAChC,IAAI,QAAQ,KAAA,GAAW,MAAM,MAAM;EACnC,IAAI,WAAW,KAAA,GAAW,MAAM,SAAS;EACzC,IAAI,SAAS,KAAA,GAAW,MAAM,OAAO;EACrC,IAAI,UAAU,KAAA,GAAW,MAAM,QAAQ;EACvC,IAAI,OAAO,GAAG,KAAK,IAAI,CAAC,CAAC,EAAE,IAAI,GAAG;EAClC,IAAI,CAAC,MAAM,OAAO,QAAQ,IAAI,GAAG,GAAG;EACpC,cAAc,IAAI,MAAM,WAAW,KAAK,CAAC;CAC3C;AAEJ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"load-BA30X4-M.mjs","names":[],"sources":["../src/styles/stylesheet-reader.ts","../src/io/load.ts"],"sourcesContent":["// xl/styles.xml → Stylesheet reader.\n//\n// The reader preserves slot ordering exactly — cellXfs[3] in the source xlsx\n// must come back as cellXfs[3] in the loaded Workbook because every `<c s=\"3\">`\n// reference depends on the index, not on the value's identity. That rules out\n// the `addFont` / `addCellXf` dedup helpers (which collapse equal values);\n// instead we push raw entries and rebuild the `_*IdByKey` maps at the end so\n// subsequent edits go back through dedup.\n\nimport { fromTree } from '../schema/serialize';\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport { stableStringify } from '../utils/stable-stringify';\nimport { qname, SHEET_MAIN_NS } from '../xml/namespaces';\nimport { parseXml } from '../xml/parser';\nimport { findChild, findChildren, type XmlNode } from '../xml/tree';\nimport { AlignmentSchema } from './alignment.schema';\nimport type { Border } from './borders';\nimport { BorderSchema } from './borders.schema';\nimport type { DifferentialStyle, StylesheetWithDxfs } from './differential';\nimport type { Fill } from './fills';\nimport { fillFromTree } from './fills.schema';\nimport type { Font } from './fonts';\nimport { FontSchema } from './fonts.schema';\nimport type { StylesheetNamedStyle } from './named-styles';\nimport type { NumberFormat } from './numbers';\nimport { NumberFormatSchema } from './numbers.schema';\nimport { ProtectionSchema } from './protection.schema';\nimport { type CellXf, makeStylesheet, type Stylesheet } from './stylesheet';\n\nconst STYLESHEET_TAG = qname(SHEET_MAIN_NS, 'styleSheet');\nconst FONTS_TAG = qname(SHEET_MAIN_NS, 'fonts');\nconst FILLS_TAG = qname(SHEET_MAIN_NS, 'fills');\nconst BORDERS_TAG = qname(SHEET_MAIN_NS, 'borders');\nconst NUMFMTS_TAG = qname(SHEET_MAIN_NS, 'numFmts');\nconst NUMFMT_TAG = qname(SHEET_MAIN_NS, 'numFmt');\nconst CELLXFS_TAG = qname(SHEET_MAIN_NS, 'cellXfs');\nconst CELLSTYLEXFS_TAG = qname(SHEET_MAIN_NS, 'cellStyleXfs');\nconst CELLSTYLES_TAG = qname(SHEET_MAIN_NS, 'cellStyles');\nconst CELLSTYLE_TAG = qname(SHEET_MAIN_NS, 'cellStyle');\nconst DXFS_TAG = qname(SHEET_MAIN_NS, 'dxfs');\nconst DXF_TAG = qname(SHEET_MAIN_NS, 'dxf');\nconst XF_TAG = qname(SHEET_MAIN_NS, 'xf');\nconst FONT_TAG = qname(SHEET_MAIN_NS, 'font');\nconst FILL_TAG = qname(SHEET_MAIN_NS, 'fill');\nconst BORDER_TAG = qname(SHEET_MAIN_NS, 'border');\nconst NUMFMT_INNER_TAG = qname(SHEET_MAIN_NS, 'numFmt');\nconst ALIGNMENT_TAG = qname(SHEET_MAIN_NS, 'alignment');\nconst PROTECTION_TAG = qname(SHEET_MAIN_NS, 'protection');\n\n/**\n * Parse `xl/styles.xml` and return a fully-populated {@link Stylesheet}. Slot\n * ordering is preserved verbatim; the dedup index Maps are rebuilt after the\n * fact so future `addFont` / `addCellXf` calls keep working.\n */\nexport function parseStylesheetXml(bytes: Uint8Array | string): Stylesheet {\n const root = parseXml(bytes);\n if (root.name !== STYLESHEET_TAG) {\n throw new OpenXmlSchemaError(`parseStylesheetXml: root is \"${root.name}\", expected styleSheet`);\n }\n\n // Start from a Stylesheet whose default-pool entries we'll wholesale replace\n // with the XML's actual contents.\n const ss = makeStylesheet();\n ss.fonts.length = 0;\n ss.fills.length = 0;\n ss.borders.length = 0;\n\n for (const fontEl of findInSection(root, FONTS_TAG, FONT_TAG)) {\n ss.fonts.push(fromTree(fontEl, FontSchema));\n }\n for (const fillEl of findInSection(root, FILLS_TAG, FILL_TAG)) {\n ss.fills.push(fillFromTree(fillEl));\n }\n for (const borderEl of findInSection(root, BORDERS_TAG, BORDER_TAG)) {\n ss.borders.push(fromTree(borderEl, BorderSchema));\n }\n\n // numFmts is a Map<id, code>; id is on the element so a sparse Map works.\n for (const numFmtEl of findInSection(root, NUMFMTS_TAG, NUMFMT_TAG)) {\n const nf = parseNumFmt(numFmtEl);\n ss.numFmts.set(nf.numFmtId, nf.formatCode);\n }\n\n for (const xfEl of findInSection(root, CELLSTYLEXFS_TAG, XF_TAG)) {\n ss.cellStyleXfs.push(parseCellXf(xfEl));\n }\n for (const xfEl of findInSection(root, CELLXFS_TAG, XF_TAG)) {\n ss.cellXfs.push(parseCellXf(xfEl));\n }\n\n // cellStyles → ss.namedStyles\n const cellStylesEl = findChild(root, CELLSTYLES_TAG);\n if (cellStylesEl) {\n const named: StylesheetNamedStyle[] = [];\n for (const cs of findChildren(cellStylesEl, CELLSTYLE_TAG)) {\n const name = cs.attrs['name'];\n const xfId = parseIntAttr(cs.attrs['xfId'], 'xfId');\n if (name === undefined || xfId === undefined) continue;\n const entry: StylesheetNamedStyle = {\n name,\n xfId,\n ...(cs.attrs['builtinId'] !== undefined ? { builtinId: parseIntAttr(cs.attrs['builtinId'], 'builtinId') ?? 0 } : {}),\n ...(cs.attrs['iLevel'] !== undefined ? { iLevel: parseIntAttr(cs.attrs['iLevel'], 'iLevel') ?? 0 } : {}),\n ...(parseBoolAttr(cs.attrs['hidden']) === true ? { hidden: true } : {}),\n ...(parseBoolAttr(cs.attrs['customBuiltin']) === true ? { customBuiltin: true } : {}),\n };\n named.push(entry);\n }\n if (named.length > 0) {\n ss.namedStyles = named;\n ss._namedStyleByName = new Map(named.map((n) => [n.name, n]));\n }\n }\n\n // dxfs → ss.dxfs\n const dxfsEl = findChild(root, DXFS_TAG);\n if (dxfsEl) {\n const dxfs: DifferentialStyle[] = [];\n for (const dxfEl of findChildren(dxfsEl, DXF_TAG)) {\n const fontEl = findChild(dxfEl, FONT_TAG);\n const numFmtEl = findChild(dxfEl, NUMFMT_INNER_TAG);\n const fillEl = findChild(dxfEl, FILL_TAG);\n const alignmentEl = findChild(dxfEl, ALIGNMENT_TAG);\n const borderEl = findChild(dxfEl, BORDER_TAG);\n const protectionEl = findChild(dxfEl, PROTECTION_TAG);\n const dxf: DifferentialStyle = {\n ...(fontEl ? { font: fromTree(fontEl, FontSchema) } : {}),\n ...(numFmtEl ? { numFmt: fromTree(numFmtEl, NumberFormatSchema) } : {}),\n ...(fillEl ? { fill: fillFromTree(fillEl) } : {}),\n ...(alignmentEl ? { alignment: fromTree(alignmentEl, AlignmentSchema) } : {}),\n ...(borderEl ? { border: fromTree(borderEl, BorderSchema) } : {}),\n ...(protectionEl ? { protection: fromTree(protectionEl, ProtectionSchema) } : {}),\n };\n dxfs.push(Object.freeze(dxf));\n }\n if (dxfs.length > 0) {\n const w = ss as StylesheetWithDxfs;\n w.dxfs = dxfs;\n w._dxfIdByKey = new Map(dxfs.map((d, i) => [stableStringify(d), i]));\n }\n }\n\n rebuildIndexes(ss);\n return ss;\n}\n\n/** Drill from `<styleSheet>` into a numbered section and yield every matching child. */\nfunction findInSection(root: XmlNode, sectionTag: string, itemTag: string): XmlNode[] {\n const section = findChild(root, sectionTag);\n if (!section) return [];\n return findChildren(section, itemTag);\n}\n\nconst parseNumFmt = (node: XmlNode): NumberFormat => {\n const idAttr = node.attrs['numFmtId'];\n const code = node.attrs['formatCode'];\n if (idAttr === undefined) {\n throw new OpenXmlSchemaError('styles: <numFmt> missing @numFmtId');\n }\n if (code === undefined) {\n throw new OpenXmlSchemaError(`styles: <numFmt numFmtId=\"${idAttr}\"> missing @formatCode`);\n }\n const numFmtId = Number.parseInt(idAttr, 10);\n if (!Number.isInteger(numFmtId) || numFmtId < 0) {\n throw new OpenXmlSchemaError(`styles: <numFmt numFmtId=\"${idAttr}\"> is not a non-negative integer`);\n }\n return { numFmtId, formatCode: code };\n};\n\nconst parseIntAttr = (raw: string | undefined, label: string): number | undefined => {\n if (raw === undefined) return undefined;\n const n = Number.parseInt(raw, 10);\n if (!Number.isInteger(n) || n < 0) {\n throw new OpenXmlSchemaError(`styles: <xf ${label}=\"${raw}\"> is not a non-negative integer`);\n }\n return n;\n};\n\nconst parseBoolAttr = (raw: string | undefined): boolean | undefined => {\n if (raw === undefined) return undefined;\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n};\n\nconst parseCellXf = (node: XmlNode): CellXf => {\n const fontId = parseIntAttr(node.attrs['fontId'], 'fontId') ?? 0;\n const fillId = parseIntAttr(node.attrs['fillId'], 'fillId') ?? 0;\n const borderId = parseIntAttr(node.attrs['borderId'], 'borderId') ?? 0;\n const numFmtId = parseIntAttr(node.attrs['numFmtId'], 'numFmtId') ?? 0;\n const xfId = parseIntAttr(node.attrs['xfId'], 'xfId');\n\n const applyFont = parseBoolAttr(node.attrs['applyFont']);\n const applyFill = parseBoolAttr(node.attrs['applyFill']);\n const applyBorder = parseBoolAttr(node.attrs['applyBorder']);\n const applyNumberFormat = parseBoolAttr(node.attrs['applyNumberFormat']);\n const applyAlignment = parseBoolAttr(node.attrs['applyAlignment']);\n const applyProtection = parseBoolAttr(node.attrs['applyProtection']);\n const pivotButton = parseBoolAttr(node.attrs['pivotButton']);\n const quotePrefix = parseBoolAttr(node.attrs['quotePrefix']);\n\n const alignmentEl = findChild(node, ALIGNMENT_TAG);\n const protectionEl = findChild(node, PROTECTION_TAG);\n\n return {\n fontId,\n fillId,\n borderId,\n numFmtId,\n ...(xfId !== undefined ? { xfId } : {}),\n ...(alignmentEl ? { alignment: fromTree(alignmentEl, AlignmentSchema) } : {}),\n ...(protectionEl ? { protection: fromTree(protectionEl, ProtectionSchema) } : {}),\n ...(applyFont !== undefined ? { applyFont } : {}),\n ...(applyFill !== undefined ? { applyFill } : {}),\n ...(applyBorder !== undefined ? { applyBorder } : {}),\n ...(applyNumberFormat !== undefined ? { applyNumberFormat } : {}),\n ...(applyAlignment !== undefined ? { applyAlignment } : {}),\n ...(applyProtection !== undefined ? { applyProtection } : {}),\n ...(pivotButton !== undefined ? { pivotButton } : {}),\n ...(quotePrefix !== undefined ? { quotePrefix } : {}),\n };\n};\n\n/** Repopulate the `_*IdByKey` maps from the freshly-loaded pool entries. */\nfunction rebuildIndexes(ss: Stylesheet): void {\n ss._fontIdByKey = buildKeyIndex<Font>(ss.fonts);\n ss._fillIdByKey = buildKeyIndex<Fill>(ss.fills);\n ss._borderIdByKey = buildKeyIndex<Border>(ss.borders);\n ss._xfIdByKey = buildKeyIndex<CellXf>(ss.cellXfs);\n ss._styleXfIdByKey = buildKeyIndex<CellXf>(ss.cellStyleXfs);\n ss._numFmtIdByCode = new Map();\n for (const [id, code] of ss.numFmts) ss._numFmtIdByCode.set(code, id);\n}\n\nconst buildKeyIndex = <T>(arr: ReadonlyArray<T>): Map<string, number> => {\n const m = new Map<string, number>();\n for (let i = 0; i < arr.length; i++) {\n const key = stableStringify(arr[i] as T);\n if (!m.has(key)) m.set(key, i);\n }\n return m;\n};\n","// Public `loadWorkbook` entry point.\n//\n// **This is the minimum-skeleton stage**: open zip → parse manifest → resolve\n// workbook part path → parse the `<sheets>` list → for each sheet, allocate an\n// empty Worksheet (title + sheetId + state). Reading the actual cell content /\n// styles / sharedStrings / theme / docProps happens in the next iterations of\n// the loop.\n//\n// The skeleton is enough to round-trip through openpyxl's `genuine/empty.xlsx`\n// fixture (3 empty sheets) and to give the rest of phase 3 a stable scaffolding\n// to layer onto.\n\nimport { findUserShapesRId, parseChartXml } from '../chart/chart-xml';\nimport { isChartExBytes, parseChartExXml } from '../chart/cx/chartex-xml';\nimport { parseUserShapesXml } from '../chart/user-shapes-xml';\nimport { parseChartsheetXml } from '../chartsheet/chartsheet-xml';\nimport { parseDrawingXml } from '../drawing/drawing-xml';\nimport { loadImage } from '../drawing/image';\nimport type { XlsxSource } from '../io/source';\nimport { corePropsFromBytes } from '../packaging/core';\nimport { customPropsFromBytes } from '../packaging/custom';\nimport { extendedPropsFromBytes } from '../packaging/extended';\nimport { manifestFromBytes } from '../packaging/manifest';\nimport { findById, indexRelsById, type Relationship, relsFromBytes } from '../packaging/relationships';\nimport { parseStylesheetXml } from '../styles/stylesheet-reader';\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport type { DefinedName } from '../workbook/defined-names';\nimport { makeDefinedName } from '../workbook/defined-names';\nimport { parseSharedStringsXml, type SharedStringsTable } from '../workbook/shared-strings';\nimport { createWorkbook, type SheetRef, type SheetState, type Workbook } from '../workbook/workbook';\nimport { parseCommentsXml } from '../worksheet/comments-xml';\nimport { parseWorksheetXml } from '../worksheet/reader';\nimport { parseTableXml } from '../worksheet/table-xml';\nimport {\n ARC_APP,\n ARC_CONTENT_TYPES,\n ARC_CORE,\n ARC_CUSTOM,\n ARC_ROOT_RELS,\n ARC_SHARED_STRINGS,\n ARC_STYLE,\n ARC_THEME,\n ARC_WORKBOOK,\n parseQName,\n REL_NS,\n SHEET_MAIN_NS,\n} from '../xml/namespaces';\nimport { parseXml } from '../xml/parser';\nimport { findChild, findChildren, type XmlNode } from '../xml/tree';\nimport type { DecompressionLimits } from '../zip/decompression-guard';\nimport { openZip, type ZipArchive } from '../zip/reader';\n\n/**\n * Options for {@link loadWorkbook}. Earlier drafts exposed `readOnly` /\n * `keepLinks` / `keepVba` / `dataOnly` / `richText` placeholders that the\n * loader silently ignored; those were removed to keep the surface honest.\n * Future toggles land here once their behavior is implemented.\n */\nexport interface LoadOptions {\n /**\n * Decompression-bomb safeguards applied while inflating zip entries.\n * Defaults to limits that fit any legitimate xlsx; pass `false` to disable\n * (only safe for fully trusted sources). See\n * {@link DecompressionLimits} for the individual knobs.\n */\n decompressionLimits?: DecompressionLimits | false;\n}\n\n/** Office Document relationship type — the package-root pointer to `xl/workbook.xml`. */\nconst OFFICE_DOC_REL_TYPE = `${REL_NS}/officeDocument`;\n\n/**\n * Resolve an OPC relationship target against its source part path.\n *\n * - Targets starting with `/` are package-absolute.\n * - Otherwise the target is relative to the source part's parent directory.\n * - `..` segments collapse normally.\n */\nexport function resolveRelTarget(sourcePartPath: string, target: string): string {\n if (target.startsWith('/')) return target.slice(1);\n const lastSlash = sourcePartPath.lastIndexOf('/');\n const parentDir = lastSlash >= 0 ? sourcePartPath.slice(0, lastSlash + 1) : '';\n const joined = parentDir + target;\n return normalizePath(joined);\n}\n\nfunction normalizePath(path: string): string {\n const segments = path.split('/');\n const out: string[] = [];\n for (const seg of segments) {\n if (seg === '' || seg === '.') continue;\n if (seg === '..') {\n // Pop the last accumulated segment when one exists; when `out` is\n // empty (a relative target with more `..` than ancestors) the pop is\n // a no-op so the climb is silently absorbed at the package root. The\n // archive.has() check on the resolved path catches any escape attempt\n // because the entry simply won't exist outside the package — there's\n // no filesystem traversal to worry about, only a missing-entry error.\n out.pop();\n continue;\n }\n out.push(seg);\n }\n return out.join('/');\n}\n\n/** Sibling rels-part path for a given part. `xl/workbook.xml` → `xl/_rels/workbook.xml.rels`. */\nfunction relsPathFor(partPath: string): string {\n const i = partPath.lastIndexOf('/');\n if (i < 0) return `_rels/${partPath}.rels`;\n return `${partPath.slice(0, i)}/_rels/${partPath.slice(i + 1)}.rels`;\n}\n\ninterface SheetEntry {\n /** Display name (`sheet/@name`). */\n name: string;\n /** Workbook-scope sheetId (`sheet/@sheetId`). */\n sheetId: number;\n /** Workbook rels Id (`sheet/@r:id`). */\n rId: string;\n /** Visibility state — defaults to `'visible'` when the attribute is absent. */\n state: SheetState;\n}\n\nconst SHEET_TAG = `{${SHEET_MAIN_NS}}sheet`;\nconst SHEETS_TAG = `{${SHEET_MAIN_NS}}sheets`;\nconst DEFINED_NAMES_TAG = `{${SHEET_MAIN_NS}}definedNames`;\nconst DEFINED_NAME_TAG = `{${SHEET_MAIN_NS}}definedName`;\nconst RID_ATTR = `{${REL_NS}}id`;\n\n/** Extract the `<definedNames>/<definedName>` entries from a parsed `xl/workbook.xml`. */\nfunction parseDefinedNames(workbookRoot: XmlNode): DefinedName[] {\n const wrapper = findChild(workbookRoot, DEFINED_NAMES_TAG);\n if (!wrapper) return [];\n const out: DefinedName[] = [];\n for (const node of findChildren(wrapper, DEFINED_NAME_TAG)) {\n const name = node.attrs['name'];\n if (!name) throw new OpenXmlSchemaError(\"workbook.xml: <definedName> is missing 'name'\");\n const value = node.text ?? '';\n const opts: Partial<DefinedName> & { name: string; value: string } = { name, value };\n const scopeAttr = node.attrs['localSheetId'];\n if (scopeAttr !== undefined) {\n const scope = Number.parseInt(scopeAttr, 10);\n if (Number.isInteger(scope) && scope >= 0) opts.scope = scope;\n }\n if (node.attrs['hidden'] === '1' || node.attrs['hidden'] === 'true') opts.hidden = true;\n if (node.attrs['comment'] !== undefined) opts.comment = node.attrs['comment'];\n out.push(makeDefinedName(opts));\n }\n return out;\n}\n\nconst WORKBOOK_PR_TAG = `{${SHEET_MAIN_NS}}workbookPr`;\nconst WORKBOOK_PROTECTION_TAG = `{${SHEET_MAIN_NS}}workbookProtection`;\nconst BOOK_VIEWS_TAG = `{${SHEET_MAIN_NS}}bookViews`;\nconst WORKBOOK_VIEW_TAG = `{${SHEET_MAIN_NS}}workbookView`;\nconst CUSTOM_WORKBOOK_VIEWS_TAG = `{${SHEET_MAIN_NS}}customWorkbookViews`;\nconst CUSTOM_WORKBOOK_VIEW_TAG = `{${SHEET_MAIN_NS}}customWorkbookView`;\nconst CALC_PR_TAG = `{${SHEET_MAIN_NS}}calcPr`;\nconst FILE_VERSION_TAG = `{${SHEET_MAIN_NS}}fileVersion`;\nconst FILE_SHARING_TAG = `{${SHEET_MAIN_NS}}fileSharing`;\nconst OLE_SIZE_TAG = `{${SHEET_MAIN_NS}}oleSize`;\nconst FILE_RECOVERY_PR_TAG = `{${SHEET_MAIN_NS}}fileRecoveryPr`;\nconst PIVOT_CACHES_TAG = `{${SHEET_MAIN_NS}}pivotCaches`;\nconst PIVOT_CACHE_TAG = `{${SHEET_MAIN_NS}}pivotCache`;\nconst EXTERNAL_REFERENCES_TAG = `{${SHEET_MAIN_NS}}externalReferences`;\nconst EXTERNAL_REFERENCE_TAG = `{${SHEET_MAIN_NS}}externalReference`;\nconst SMART_TAG_PR_TAG = `{${SHEET_MAIN_NS}}smartTagPr`;\nconst SMART_TAG_TYPES_TAG = `{${SHEET_MAIN_NS}}smartTagTypes`;\nconst SMART_TAG_TYPE_TAG = `{${SHEET_MAIN_NS}}smartTagType`;\nconst FUNCTION_GROUPS_TAG = `{${SHEET_MAIN_NS}}functionGroups`;\nconst FUNCTION_GROUP_TAG = `{${SHEET_MAIN_NS}}functionGroup`;\n\n/**\n * Parse the `<workbookPr date1904>` flag. Mac-origin workbooks set\n * `date1904=\"true\"`; everything else uses the Windows 1900 epoch. The value\n * drives Date / Duration cell serial conversion in worksheet/writer.ts and\n * reader.ts.\n */\nfunction parseDate1904(workbookRoot: XmlNode): boolean {\n const pr = findChild(workbookRoot, WORKBOOK_PR_TAG);\n if (!pr) return false;\n const v = pr.attrs['date1904'];\n return v === '1' || v === 'true';\n}\n\n/** Extract the `<sheets>/<sheet>` entries from a parsed `xl/workbook.xml`. */\nexport function parseSheetEntries(workbookRoot: XmlNode): SheetEntry[] {\n const sheets = findChild(workbookRoot, SHEETS_TAG);\n if (!sheets) return [];\n const out: SheetEntry[] = [];\n for (const node of findChildren(sheets, SHEET_TAG)) {\n const name = node.attrs['name'];\n const sheetIdAttr = node.attrs['sheetId'];\n const rId = node.attrs[RID_ATTR];\n if (!name) throw new OpenXmlSchemaError(\"workbook.xml: <sheet> is missing 'name'\");\n if (!sheetIdAttr) throw new OpenXmlSchemaError(`workbook.xml: <sheet name=\"${name}\"> is missing 'sheetId'`);\n if (!rId) throw new OpenXmlSchemaError(`workbook.xml: <sheet name=\"${name}\"> is missing 'r:id'`);\n const sheetId = Number.parseInt(sheetIdAttr, 10);\n if (!Number.isInteger(sheetId) || sheetId < 1) {\n throw new OpenXmlSchemaError(\n `workbook.xml: <sheet name=\"${name}\"> sheetId \"${sheetIdAttr}\" is not a positive integer`,\n );\n }\n const stateAttr = node.attrs['state'];\n let state: SheetState = 'visible';\n if (stateAttr === 'hidden' || stateAttr === 'veryHidden') state = stateAttr;\n out.push({ name, sheetId, rId, state });\n }\n return out;\n}\n\n/**\n * Load a workbook from any {@link XlsxSource}. Currently produces a scaffold\n * Workbook: each Worksheet is empty (no cells / styles / shared strings / theme\n * yet). The next phase-3 iterations layer those in atop the same skeleton.\n */\nexport async function loadWorkbook(source: XlsxSource, opts: LoadOptions = {}): Promise<Workbook> {\n const archive = await openZip(\n source,\n opts.decompressionLimits === undefined ? {} : { decompressionLimits: opts.decompressionLimits },\n );\n try {\n return loadWorkbookFromArchive(archive);\n } finally {\n archive.close();\n }\n}\n\n/** Internal: same as {@link loadWorkbook} but operating on an already-opened archive. */\nfunction loadWorkbookFromArchive(archive: ZipArchive): Workbook {\n // 1. Manifest — resolves which override entries the package declares.\n if (!archive.has(ARC_CONTENT_TYPES)) {\n throw new OpenXmlSchemaError(`loadWorkbook: missing \"${ARC_CONTENT_TYPES}\"`);\n }\n const manifest = manifestFromBytes(archive.read(ARC_CONTENT_TYPES));\n\n // 2. Root rels → resolve the office-document relationship to the workbook part path.\n if (!archive.has(ARC_ROOT_RELS)) {\n throw new OpenXmlSchemaError(`loadWorkbook: missing \"${ARC_ROOT_RELS}\"`);\n }\n const rootRels = relsFromBytes(archive.read(ARC_ROOT_RELS));\n const officeRel = rootRels.rels.find((r) => r.type === OFFICE_DOC_REL_TYPE);\n if (!officeRel) {\n throw new OpenXmlSchemaError('loadWorkbook: root rels missing officeDocument relationship');\n }\n const workbookPath = resolveRelTarget('', officeRel.target);\n if (workbookPath !== ARC_WORKBOOK) {\n // Most xlsx files put the workbook at xl/workbook.xml. We accept any path\n // the rels point at as long as the archive holds it.\n if (!archive.has(workbookPath)) {\n throw new OpenXmlSchemaError(`loadWorkbook: workbook part \"${workbookPath}\" not found in archive`);\n }\n }\n\n // 3. workbook.xml — parse to extract sheet metadata only.\n const wbRoot = parseXml(archive.read(workbookPath));\n if (parseQName(wbRoot.name).local !== 'workbook') {\n throw new OpenXmlSchemaError(`loadWorkbook: ${workbookPath} root is \"${wbRoot.name}\", expected workbook`);\n }\n const sheetEntries = parseSheetEntries(wbRoot);\n const definedNamesFromXml = parseDefinedNames(wbRoot);\n\n // 4. workbook.xml.rels — needed to resolve each sheet's rId to a part path.\n const wbRelsPath = relsPathFor(workbookPath);\n // openpyxl tolerates a missing workbook.xml.rels (it implies no sheets); in\n // practice every Excel file has one. We require it so a malformed package\n // surfaces as an OpenXmlSchemaError, not a silently-empty workbook.\n if (sheetEntries.length > 0 && !archive.has(wbRelsPath)) {\n throw new OpenXmlSchemaError(`loadWorkbook: workbook has sheets but rels part \"${wbRelsPath}\" is missing`);\n }\n const wbRels = archive.has(wbRelsPath) ? relsFromBytes(archive.read(wbRelsPath)) : { rels: [] };\n\n // 4b. sharedStrings.xml — optional. The workbook rels can also point at a\n // non-default location; for the minimum-skeleton stage we look at the\n // canonical `xl/sharedStrings.xml` path first, then fall back to the rels\n // entry if present.\n let sharedStrings: SharedStringsTable | undefined;\n if (archive.has(ARC_SHARED_STRINGS)) {\n sharedStrings = parseSharedStringsXml(archive.read(ARC_SHARED_STRINGS));\n } else {\n const sstRel = wbRels.rels.find((r) => r.type === `${REL_NS}/sharedStrings`);\n if (sstRel) {\n const sstPath = resolveRelTarget(workbookPath, sstRel.target);\n if (archive.has(sstPath)) {\n sharedStrings = parseSharedStringsXml(archive.read(sstPath));\n }\n }\n }\n // The worksheet reader takes plain strings; rich-text SST entries are\n // flattened to their concatenated text body so cell values stay simple.\n // (Rich-text fidelity round-trip on read needs a sst entry → cell-value\n // bridge that produces a rich-text cell; for now Excel re-write still works\n // because we only flatten on read, not on write.)\n const sst: ReadonlyArray<string> = (sharedStrings?.entries ?? []).map((e) =>\n typeof e === 'string' ? e : e.runs.map((r) => r.text).join(''),\n );\n\n // 4c. styles.xml — optional. Same default-or-rels lookup as sst.\n let styles: ReturnType<typeof parseStylesheetXml> | undefined;\n if (archive.has(ARC_STYLE)) {\n styles = parseStylesheetXml(archive.read(ARC_STYLE));\n } else {\n const stylesRel = wbRels.rels.find((r) => r.type === `${REL_NS}/styles`);\n if (stylesRel) {\n const stylesPath = resolveRelTarget(workbookPath, stylesRel.target);\n if (archive.has(stylesPath)) {\n styles = parseStylesheetXml(archive.read(stylesPath));\n }\n }\n }\n\n // 4d. docProps/{core,app,custom}.xml — package-level metadata. Each part is\n // optional; absent ones leave the matching Workbook field undefined. We walk\n // both the canonical path and the root rels so non-default layouts (rare but\n // legal) still resolve.\n const properties = archive.has(ARC_CORE) ? corePropsFromBytes(archive.read(ARC_CORE)) : undefined;\n const appProperties = archive.has(ARC_APP) ? extendedPropsFromBytes(archive.read(ARC_APP)) : undefined;\n const customProperties = archive.has(ARC_CUSTOM) ? customPropsFromBytes(archive.read(ARC_CUSTOM)) : undefined;\n\n // 4e. xl/theme/theme1.xml — kept verbatim. Excel renders with this exact\n // payload; round-tripping the bytes avoids drift.\n const themeXml: Uint8Array | undefined = (() => {\n if (archive.has(ARC_THEME)) return archive.read(ARC_THEME);\n const themeRel = wbRels.rels.find((r) => r.type === `${REL_NS}/theme`);\n if (themeRel) {\n const themePath = resolveRelTarget(workbookPath, themeRel.target);\n if (archive.has(themePath)) return archive.read(themePath);\n }\n return undefined;\n })();\n\n // 5. Build the Workbook. We bypass `addWorksheet` because that allocates\n // sheetIds via `allocateSheetId`; load preserves the IDs from XML.\n const wb = createWorkbook({ date1904: parseDate1904(wbRoot) });\n if (styles) wb.styles = styles;\n if (properties) wb.properties = properties;\n if (appProperties) wb.appProperties = appProperties;\n if (customProperties) wb.customProperties = customProperties;\n if (themeXml) wb.themeXml = themeXml;\n if (definedNamesFromXml.length > 0) wb.definedNames = definedNamesFromXml;\n const seenTitles = new Set<string>();\n const passthroughRoots: string[] = [];\n const vml = makeVmlPartCache(archive);\n for (const entry of sheetEntries) {\n if (seenTitles.has(entry.name)) {\n throw new OpenXmlSchemaError(`loadWorkbook: duplicate sheet name \"${entry.name}\"`);\n }\n seenTitles.add(entry.name);\n const rel = findById(wbRels, entry.rId);\n if (!rel) {\n throw new OpenXmlSchemaError(`loadWorkbook: sheet \"${entry.name}\" rId \"${entry.rId}\" has no matching rels entry`);\n }\n const sheetPath = resolveRelTarget(workbookPath, rel.target);\n if (!archive.has(sheetPath)) {\n throw new OpenXmlSchemaError(`loadWorkbook: sheet part \"${sheetPath}\" not found in archive`);\n }\n const sheetRelsPath = relsPathFor(sheetPath);\n const sheetRels = archive.has(sheetRelsPath) ? relsFromBytes(archive.read(sheetRelsPath)) : undefined;\n // Build an id → rel index once; the loadTable / loadComments / loadDrawing\n // callbacks are invoked once per cross-reference in the worksheet body and\n // a linear find() inside each would be O(rels × refs). Sheets with many\n // hyperlinks / tables / drawings (e.g. dashboard workbooks) make that\n // accumulation visible.\n const sheetRelsById = sheetRels ? indexRelsById(sheetRels) : undefined;\n const loadTable = sheetRelsById\n ? (relId: string) => {\n const tRel = sheetRelsById.get(relId);\n if (!tRel) return undefined;\n const tablePath = resolveRelTarget(sheetPath, tRel.target);\n if (!archive.has(tablePath)) return undefined;\n return parseTableXml(archive.read(tablePath));\n }\n : undefined;\n const loadComments = sheetRelsById\n ? (relId: string) => {\n const cRel = sheetRelsById.get(relId);\n if (!cRel) return undefined;\n const cPath = resolveRelTarget(sheetPath, cRel.target);\n if (!archive.has(cPath)) return undefined;\n return parseCommentsXml(archive.read(cPath));\n }\n : undefined;\n const loadDrawing = sheetRelsById\n ? (relId: string) => {\n const dRel = sheetRelsById.get(relId);\n if (!dRel) return undefined;\n const dPath = resolveRelTarget(sheetPath, dRel.target);\n if (!archive.has(dPath)) return undefined;\n const drawing = parseDrawingXml(archive.read(dPath));\n // Phase-2: resolve drawing-rels to populate chart payloads.\n const dRelsPath = relsPathFor(dPath);\n if (archive.has(dRelsPath)) {\n const dRels = relsFromBytes(archive.read(dRelsPath));\n const dRelsById = indexRelsById(dRels);\n for (const item of drawing.items) {\n if (item.content.kind === 'chart') {\n const chartRId = item.content.chart.rId;\n if (!chartRId) continue;\n const chartRel = dRelsById.get(chartRId);\n if (!chartRel) continue;\n const chartPath = resolveRelTarget(dPath, chartRel.target);\n if (archive.has(chartPath)) {\n const chartBytes = archive.read(chartPath);\n if (isChartExBytes(chartBytes)) {\n item.content.chart.cxSpace = parseChartExXml(chartBytes);\n } else {\n const space = parseChartXml(chartBytes);\n // Resolve <c:userShapes r:id=\"...\"> via the chart's own\n // rels file (xl/charts/_rels/chartN.xml.rels).\n const userShapesRId = findUserShapesRId(chartBytes);\n if (userShapesRId) {\n const chartRelsPath = relsPathFor(chartPath);\n if (archive.has(chartRelsPath)) {\n const chartRelsObj = relsFromBytes(archive.read(chartRelsPath));\n const usRel = indexRelsById(chartRelsObj).get(userShapesRId);\n if (usRel) {\n const usPath = resolveRelTarget(chartPath, usRel.target);\n if (archive.has(usPath)) {\n try {\n space.userShapes = parseUserShapesXml(archive.read(usPath));\n } catch {\n // Tolerate parse failures (Excel sometimes emits\n // chartDrawing parts with namespaces / shapes\n // outside our model).\n }\n }\n }\n }\n }\n item.content.chart.space = space;\n }\n }\n } else if (item.content.kind === 'picture') {\n const picRId = item.content.picture.rId;\n if (!picRId) continue;\n const picRel = dRelsById.get(picRId);\n if (!picRel) continue;\n const imgPath = resolveRelTarget(dPath, picRel.target);\n if (archive.has(imgPath)) {\n try {\n item.content.picture.image = loadImage(archive.read(imgPath));\n } catch {\n // Unknown / unsupported format — leave bytes-less; callers\n // can read via the rId + archive directly if they need the\n // raw payload.\n }\n }\n }\n }\n }\n return drawing;\n }\n : undefined;\n // Distinguish worksheet vs chartsheet by inspecting the workbook-rels\n // entry's relationship type.\n const isChartsheet = rel.type === `${REL_NS}/chartsheet`;\n if (isChartsheet) {\n const chartsheet = parseChartsheetXml(archive.read(sheetPath), entry.name);\n // Inline drawing reference from the chartsheet XML.\n if (sheetRels) {\n // Find the drawing rel and resolve it the same way worksheets do.\n const drawingRel = sheetRels.rels.find((r) => r.type === `${REL_NS}/drawing`);\n if (drawingRel && loadDrawing) {\n const d = loadDrawing(drawingRel.id);\n if (d) chartsheet.drawing = d;\n }\n }\n const ref: SheetRef = {\n kind: 'chartsheet',\n sheet: chartsheet,\n sheetId: entry.sheetId,\n state: entry.state,\n rId: entry.rId,\n };\n wb.sheets.push(ref);\n continue;\n }\n const ws = parseWorksheetXml(archive.read(sheetPath), entry.name, {\n sharedStrings: sst,\n ...(sheetRels ? { rels: sheetRels } : {}),\n ...(loadTable ? { loadTable } : {}),\n ...(loadComments ? { loadComments } : {}),\n ...(loadDrawing ? { loadDrawing } : {}),\n });\n if (sheetRels) {\n const extras = captureSheetRelsExtras(sheetRels, sheetPath, vml);\n if (extras.length > 0) {\n ws.relsExtras = extras;\n // The writer re-emits these rels verbatim, so whatever they point at\n // has to be carried over as passthrough or the output dangles.\n for (const e of extras) {\n if (e.targetMode !== 'External') passthroughRoots.push(resolveRelTarget(sheetPath, e.target));\n }\n }\n }\n // A <legacyDrawing> pointing at the comment VML (or at nothing) has no\n // surviving rel; the writer regenerates the comment link from\n // ws.legacyComments, so re-emitting this rId would dangle.\n if (ws.legacyDrawingRId !== undefined && !ws.relsExtras?.some((e) => e.id === ws.legacyDrawingRId)) {\n delete ws.legacyDrawingRId;\n }\n const ref: SheetRef = {\n kind: 'worksheet',\n sheet: ws,\n sheetId: entry.sheetId,\n state: entry.state,\n rId: entry.rId,\n };\n wb.sheets.push(ref);\n }\n\n captureWorkbookXmlExtras(wbRoot, wb);\n captureWorkbookRelsExtras(wbRels, wb);\n\n // Pass-through: capture parts we don't model (VBA / pivot / activeX / OLE /\n // customUI / customXml / etc.) so re-saving doesn't drop them.\n capturePassthrough(archive, manifest, wb, passthroughRoots, vml);\n return wb;\n}\n\nconst SHEET_MODELED_REL_TYPES: ReadonlySet<string> = new Set([\n `${REL_NS}/hyperlink`,\n `${REL_NS}/table`,\n `${REL_NS}/comments`,\n `${REL_NS}/drawing`,\n]);\nconst VML_DRAWING_REL = `${REL_NS}/vmlDrawing`;\n\n/**\n * Capture per-sheet rels entries that don't match a modeled type. The writer\n * re-emits these verbatim alongside the freshly allocated modeled rels so\n * captured passthrough parts (pivotTable / queryTable / slicer /\n * printerSettings / oleObject / customProperty / threadedComment) remain\n * reachable from the worksheet after a round-trip.\n *\n * `vmlDrawing` rels are split by part content rather than by type: only the\n * comments VML is regenerated (from `ws.legacyComments`), so its rel is\n * dropped; header/footer and form-control VML is re-emitted by its original\n * r:id and rides along as an extra.\n */\nfunction captureSheetRelsExtras(\n sheetRels: import('../packaging/relationships').Relationships,\n sheetPath: string,\n vml: VmlPartCache,\n): Relationship[] {\n const extras: Relationship[] = [];\n for (const rel of sheetRels.rels) {\n if (SHEET_MODELED_REL_TYPES.has(rel.type)) continue;\n if (rel.type === VML_DRAWING_REL && vml.isCommentVml(resolveRelTarget(sheetPath, rel.target))) continue;\n extras.push(rel);\n }\n return extras;\n}\n\n/**\n * Walk top-level children of `<workbook>` and split anything that isn't\n * `<sheets>` or `<definedNames>` into the before/after halves the writer\n * inserts around the modeled elements. Order is preserved within each half so\n * things like `<fileVersion>`, `<workbookPr>`, `<bookViews>`, `<calcPr>`,\n * `<pivotCaches>`, `<extLst>` round-trip in document order.\n */\nfunction captureWorkbookXmlExtras(wbRoot: XmlNode, wb: Workbook): void {\n const beforeSheets: XmlNode[] = [];\n const afterSheets: XmlNode[] = [];\n let seenSheets = false;\n for (const child of wbRoot.children) {\n if (child.name === SHEETS_TAG) {\n seenSheets = true;\n continue;\n }\n if (child.name === DEFINED_NAMES_TAG) continue;\n // Lift <workbookProtection> into the typed workbook field instead of\n // stashing it as a passthrough XmlNode (B5 partial).\n if (child.name === WORKBOOK_PROTECTION_TAG) {\n wb.workbookProtection = parseWorkbookProtection(child);\n continue;\n }\n // Lift <workbookPr> into the typed workbook field. The date1904 attribute\n // is already mirrored onto wb.date1904; everything else stops leaking into\n // bodyExtras.\n if (child.name === WORKBOOK_PR_TAG) {\n const wp = parseWorkbookProperties(child);\n if (wp) wb.workbookProperties = wp;\n continue;\n }\n // Lift <fileSharing> into the typed workbook field.\n if (child.name === FILE_SHARING_TAG) {\n const fs: import('../workbook/file-sharing').FileSharing = {};\n const a = child.attrs;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n const ror = flag(a['readOnlyRecommended']);\n if (ror !== undefined) fs.readOnlyRecommended = ror;\n if (a['userName'] !== undefined) fs.userName = a['userName'];\n if (a['reservationPassword'] !== undefined) fs.reservationPassword = a['reservationPassword'];\n if (a['algorithmName'] !== undefined) fs.algorithmName = a['algorithmName'];\n if (a['hashValue'] !== undefined) fs.hashValue = a['hashValue'];\n if (a['saltValue'] !== undefined) fs.saltValue = a['saltValue'];\n if (a['spinCount'] !== undefined) {\n const n = Number.parseInt(a['spinCount'], 10);\n if (Number.isInteger(n)) fs.spinCount = n;\n }\n if (Object.keys(fs).length > 0) wb.fileSharing = fs;\n continue;\n }\n // Lift <fileVersion> into the typed workbook field.\n if (child.name === FILE_VERSION_TAG) {\n const fv: import('../workbook/file-version').FileVersion = {};\n if (child.attrs['appName'] !== undefined) fv.appName = child.attrs['appName'];\n if (child.attrs['lastEdited'] !== undefined) fv.lastEdited = child.attrs['lastEdited'];\n if (child.attrs['lowestEdited'] !== undefined) fv.lowestEdited = child.attrs['lowestEdited'];\n if (child.attrs['rupBuild'] !== undefined) fv.rupBuild = child.attrs['rupBuild'];\n if (child.attrs['codeName'] !== undefined) fv.codeName = child.attrs['codeName'];\n if (Object.keys(fv).length > 0) wb.fileVersion = fv;\n continue;\n }\n // Lift <bookViews> into the typed workbook field.\n if (child.name === BOOK_VIEWS_TAG) {\n const views: import('../workbook/views').WorkbookView[] = [];\n for (const v of findChildren(child, WORKBOOK_VIEW_TAG)) views.push(parseWorkbookView(v));\n if (views.length > 0) wb.bookViews = views;\n continue;\n }\n // Lift <customWorkbookViews> into the typed workbook field.\n if (child.name === CUSTOM_WORKBOOK_VIEWS_TAG) {\n const cws: import('../workbook/views').CustomWorkbookView[] = [];\n for (const v of findChildren(child, CUSTOM_WORKBOOK_VIEW_TAG)) {\n const parsed = parseCustomWorkbookView(v);\n if (parsed) cws.push(parsed);\n }\n if (cws.length > 0) wb.customWorkbookViews = cws;\n continue;\n }\n // Lift <calcPr> into the typed workbook field.\n if (child.name === CALC_PR_TAG) {\n const cp = parseCalcProperties(child);\n if (cp) wb.calcProperties = cp;\n continue;\n }\n // Lift <oleSize ref=\"…\"/> as a single typed string attribute.\n if (child.name === OLE_SIZE_TAG) {\n const ref = child.attrs['ref'];\n if (ref) wb.oleSize = ref;\n continue;\n }\n // Lift <smartTagPr embed=\"1\" show=\"all\"/>.\n if (child.name === SMART_TAG_PR_TAG) {\n const out: import('../workbook/smart-tags').SmartTagProperties = {};\n const a = child.attrs;\n if (a['embed'] === '1' || a['embed'] === 'true') out.embed = true;\n else if (a['embed'] === '0' || a['embed'] === 'false') out.embed = false;\n if (a['show'] === 'all' || a['show'] === 'noIndicator') out.show = a['show'];\n if (Object.keys(out).length > 0) wb.smartTagPr = out;\n continue;\n }\n // Lift <smartTagTypes><smartTagType .../></smartTagTypes>.\n if (child.name === SMART_TAG_TYPES_TAG) {\n const tags: import('../workbook/smart-tags').SmartTagType[] = [];\n for (const t of findChildren(child, SMART_TAG_TYPE_TAG)) {\n const entry: import('../workbook/smart-tags').SmartTagType = {};\n if (t.attrs['namespaceUri'] !== undefined) entry.namespaceUri = t.attrs['namespaceUri'];\n if (t.attrs['name'] !== undefined) entry.name = t.attrs['name'];\n if (t.attrs['url'] !== undefined) entry.url = t.attrs['url'];\n if (Object.keys(entry).length > 0) tags.push(entry);\n }\n if (tags.length > 0) wb.smartTagTypes = tags;\n continue;\n }\n // Lift <functionGroups builtInGroupCount=…><functionGroup\n // name=…/></functionGroups>.\n if (child.name === FUNCTION_GROUPS_TAG) {\n const fg: import('../workbook/function-groups').FunctionGroups = { groups: [] };\n const bicgRaw = child.attrs['builtInGroupCount'];\n if (bicgRaw !== undefined) {\n const n = Number.parseInt(bicgRaw, 10);\n if (Number.isInteger(n)) fg.builtInGroupCount = n;\n }\n for (const g of findChildren(child, FUNCTION_GROUP_TAG)) {\n const name = g.attrs['name'];\n if (name) fg.groups.push({ name });\n }\n if (fg.groups.length > 0 || fg.builtInGroupCount !== undefined) wb.functionGroups = fg;\n continue;\n }\n // Lift <externalReferences><externalReference\n // r:id=…/></externalReferences>.\n if (child.name === EXTERNAL_REFERENCES_TAG) {\n const refs: Array<{ rId: string }> = [];\n for (const er of findChildren(child, EXTERNAL_REFERENCE_TAG)) {\n const rId = er.attrs[`{${REL_NS}}id`];\n if (rId) refs.push({ rId });\n }\n if (refs.length > 0) wb.externalReferences = refs;\n continue;\n }\n // Lift <pivotCaches><pivotCache cacheId=… r:id=…/></pivotCaches>.\n if (child.name === PIVOT_CACHES_TAG) {\n const caches: Array<{ cacheId: number; rId: string }> = [];\n for (const pc of findChildren(child, PIVOT_CACHE_TAG)) {\n const cacheIdAttr = pc.attrs['cacheId'];\n const rId = pc.attrs[`{${REL_NS}}id`];\n if (cacheIdAttr === undefined || !rId) continue;\n const cacheId = Number.parseInt(cacheIdAttr, 10);\n if (!Number.isInteger(cacheId)) continue;\n caches.push({ cacheId, rId });\n }\n if (caches.length > 0) wb.pivotCaches = caches;\n continue;\n }\n // Lift <fileRecoveryPr> into the typed workbook field.\n if (child.name === FILE_RECOVERY_PR_TAG) {\n const fp: import('../workbook/file-recovery').FileRecoveryProperties = {};\n const a = child.attrs;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n const ar = flag(a['autoRecover']);\n if (ar !== undefined) fp.autoRecover = ar;\n const cs = flag(a['crashSave']);\n if (cs !== undefined) fp.crashSave = cs;\n const del = flag(a['dataExtractLoad']);\n if (del !== undefined) fp.dataExtractLoad = del;\n const rl = flag(a['repairLoad']);\n if (rl !== undefined) fp.repairLoad = rl;\n if (Object.keys(fp).length > 0) wb.fileRecoveryPr = fp;\n continue;\n }\n if (seenSheets) afterSheets.push(child);\n else beforeSheets.push(child);\n }\n if (beforeSheets.length > 0 || afterSheets.length > 0) {\n wb.workbookXmlExtras = { beforeSheets, afterSheets };\n }\n}\n\nconst SHOW_OBJECTS_MODES: ReadonlyArray<import('../workbook/workbook-properties').ShowObjectsMode> = [\n 'all',\n 'placeholders',\n 'none',\n];\nconst UPDATE_LINKS_MODES: ReadonlyArray<import('../workbook/workbook-properties').UpdateLinksMode> = [\n 'userSet',\n 'never',\n 'always',\n];\n\nconst parseWorkbookProperties = (\n node: XmlNode,\n): import('../workbook/workbook-properties').WorkbookProperties | undefined => {\n const out: import('../workbook/workbook-properties').WorkbookProperties = {};\n const a = node.attrs;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n const intAttr = (k: string): number | undefined => {\n if (a[k] === undefined) return undefined;\n const n = Number.parseInt(a[k], 10);\n return Number.isInteger(n) ? n : undefined;\n };\n\n const bools = [\n 'date1904',\n 'dateCompatibility',\n 'showBorderUnselectedTables',\n 'filterPrivacy',\n 'promptedSolutions',\n 'showInkAnnotation',\n 'backupFile',\n 'saveExternalLinkValues',\n 'hidePivotFieldList',\n 'showPivotChartFilter',\n 'allowRefreshQuery',\n 'publishItems',\n 'checkCompatibility',\n 'autoCompressPictures',\n 'refreshAllConnections',\n ] as const satisfies ReadonlyArray<keyof import('../workbook/workbook-properties').WorkbookProperties>;\n for (const k of bools) {\n const v = flag(a[k]);\n if (v !== undefined) out[k] = v;\n }\n\n const showObjects = a['showObjects'];\n if (showObjects && SHOW_OBJECTS_MODES.includes(showObjects as import('../workbook/workbook-properties').ShowObjectsMode)) {\n out.showObjects = showObjects as import('../workbook/workbook-properties').ShowObjectsMode;\n }\n const updateLinks = a['updateLinks'];\n if (updateLinks && UPDATE_LINKS_MODES.includes(updateLinks as import('../workbook/workbook-properties').UpdateLinksMode)) {\n out.updateLinks = updateLinks as import('../workbook/workbook-properties').UpdateLinksMode;\n }\n if (a['codeName'] !== undefined) out.codeName = a['codeName'];\n const dtv = intAttr('defaultThemeVersion');\n if (dtv !== undefined) out.defaultThemeVersion = dtv;\n\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst CALC_MODES: ReadonlyArray<import('../workbook/calc-properties').CalcMode> = [\n 'manual',\n 'auto',\n 'autoNoTable',\n];\nconst REF_MODES: ReadonlyArray<import('../workbook/calc-properties').RefMode> = ['A1', 'R1C1'];\n\nconst parseCalcProperties = (\n node: XmlNode,\n): import('../workbook/calc-properties').CalcProperties | undefined => {\n const out: import('../workbook/calc-properties').CalcProperties = {};\n const a = node.attrs;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n const intAttr = (k: string): number | undefined => {\n if (a[k] === undefined) return undefined;\n const n = Number.parseInt(a[k], 10);\n return Number.isInteger(n) ? n : undefined;\n };\n const floatAttr = (k: string): number | undefined => {\n if (a[k] === undefined) return undefined;\n const n = Number.parseFloat(a[k]);\n return Number.isFinite(n) ? n : undefined;\n };\n\n const calcId = intAttr('calcId');\n if (calcId !== undefined) out.calcId = calcId;\n const calcMode = a['calcMode'];\n if (calcMode && CALC_MODES.includes(calcMode as import('../workbook/calc-properties').CalcMode)) {\n out.calcMode = calcMode as import('../workbook/calc-properties').CalcMode;\n }\n const fcol = flag(a['fullCalcOnLoad']);\n if (fcol !== undefined) out.fullCalcOnLoad = fcol;\n const refMode = a['refMode'];\n if (refMode && REF_MODES.includes(refMode as import('../workbook/calc-properties').RefMode)) {\n out.refMode = refMode as import('../workbook/calc-properties').RefMode;\n }\n const iterate = flag(a['iterate']);\n if (iterate !== undefined) out.iterate = iterate;\n const iterateCount = intAttr('iterateCount');\n if (iterateCount !== undefined) out.iterateCount = iterateCount;\n const iterateDelta = floatAttr('iterateDelta');\n if (iterateDelta !== undefined) out.iterateDelta = iterateDelta;\n const fullPrecision = flag(a['fullPrecision']);\n if (fullPrecision !== undefined) out.fullPrecision = fullPrecision;\n const calcCompleted = flag(a['calcCompleted']);\n if (calcCompleted !== undefined) out.calcCompleted = calcCompleted;\n const calcOnSave = flag(a['calcOnSave']);\n if (calcOnSave !== undefined) out.calcOnSave = calcOnSave;\n const concurrentCalc = flag(a['concurrentCalc']);\n if (concurrentCalc !== undefined) out.concurrentCalc = concurrentCalc;\n const concurrentManualCount = intAttr('concurrentManualCount');\n if (concurrentManualCount !== undefined) out.concurrentManualCount = concurrentManualCount;\n const forceFullCalc = flag(a['forceFullCalc']);\n if (forceFullCalc !== undefined) out.forceFullCalc = forceFullCalc;\n\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst SHOW_COMMENTS_MODES: ReadonlyArray<import('../workbook/views').CustomViewShowComments> = [\n 'commNone',\n 'commIndicator',\n 'commIndAndComment',\n];\nconst SHOW_OBJECTS_CV_MODES: ReadonlyArray<import('../workbook/views').CustomViewShowObjects> = [\n 'all',\n 'placeholders',\n 'none',\n];\n\nconst parseCustomWorkbookView = (\n node: XmlNode,\n): import('../workbook/views').CustomWorkbookView | undefined => {\n const a = node.attrs;\n const name = a['name'];\n const guid = a['guid'];\n if (!name || !guid) return undefined;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n const intAttr = (k: string): number | undefined => {\n if (a[k] === undefined) return undefined;\n const n = Number.parseInt(a[k], 10);\n return Number.isInteger(n) ? n : undefined;\n };\n const ww = intAttr('windowWidth') ?? 0;\n const wh = intAttr('windowHeight') ?? 0;\n const asid = intAttr('activeSheetId') ?? 0;\n const out: import('../workbook/views').CustomWorkbookView = {\n name,\n guid,\n windowWidth: ww,\n windowHeight: wh,\n activeSheetId: asid,\n };\n\n const boolKeys = [\n 'autoUpdate',\n 'changesSavedWin',\n 'onlySync',\n 'personalView',\n 'includePrintSettings',\n 'includeHiddenRowCol',\n 'maximized',\n 'minimized',\n 'showHorizontalScroll',\n 'showVerticalScroll',\n 'showSheetTabs',\n 'showFormulaBar',\n 'showStatusbar',\n ] as const satisfies ReadonlyArray<keyof import('../workbook/views').CustomWorkbookView>;\n for (const k of boolKeys) {\n const v = flag(a[k]);\n if (v !== undefined) out[k] = v;\n }\n const intKeys = [\n 'mergeInterval',\n 'xWindow',\n 'yWindow',\n 'tabRatio',\n ] as const satisfies ReadonlyArray<keyof import('../workbook/views').CustomWorkbookView>;\n for (const k of intKeys) {\n const v = intAttr(k);\n if (v !== undefined) out[k] = v;\n }\n\n const sc = a['showComments'];\n if (sc && SHOW_COMMENTS_MODES.includes(sc as import('../workbook/views').CustomViewShowComments)) {\n out.showComments = sc as import('../workbook/views').CustomViewShowComments;\n }\n const so = a['showObjects'];\n if (so && SHOW_OBJECTS_CV_MODES.includes(so as import('../workbook/views').CustomViewShowObjects)) {\n out.showObjects = so as import('../workbook/views').CustomViewShowObjects;\n }\n return out;\n};\n\nconst VISIBILITIES: ReadonlyArray<import('../workbook/views').WorkbookViewVisibility> = [\n 'visible',\n 'hidden',\n 'veryHidden',\n];\n\nconst parseWorkbookView = (node: XmlNode): import('../workbook/views').WorkbookView => {\n const out: import('../workbook/views').WorkbookView = {};\n const a = node.attrs;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n const intAttr = (k: string): number | undefined => {\n if (a[k] === undefined) return undefined;\n const n = Number.parseInt(a[k], 10);\n return Number.isInteger(n) ? n : undefined;\n };\n\n const visibility = a['visibility'];\n if (visibility && VISIBILITIES.includes(visibility as import('../workbook/views').WorkbookViewVisibility)) {\n out.visibility = visibility as import('../workbook/views').WorkbookViewVisibility;\n }\n const minimized = flag(a['minimized']);\n if (minimized !== undefined) out.minimized = minimized;\n const shScroll = flag(a['showHorizontalScroll']);\n if (shScroll !== undefined) out.showHorizontalScroll = shScroll;\n const svScroll = flag(a['showVerticalScroll']);\n if (svScroll !== undefined) out.showVerticalScroll = svScroll;\n const sst = flag(a['showSheetTabs']);\n if (sst !== undefined) out.showSheetTabs = sst;\n const xWindow = intAttr('xWindow');\n if (xWindow !== undefined) out.xWindow = xWindow;\n const yWindow = intAttr('yWindow');\n if (yWindow !== undefined) out.yWindow = yWindow;\n const ww = intAttr('windowWidth');\n if (ww !== undefined) out.windowWidth = ww;\n const wh = intAttr('windowHeight');\n if (wh !== undefined) out.windowHeight = wh;\n const tr = intAttr('tabRatio');\n if (tr !== undefined) out.tabRatio = tr;\n const fs = intAttr('firstSheet');\n if (fs !== undefined) out.firstSheet = fs;\n const at = intAttr('activeTab');\n if (at !== undefined) out.activeTab = at;\n const adg = flag(a['autoFilterDateGrouping']);\n if (adg !== undefined) out.autoFilterDateGrouping = adg;\n return out;\n};\n\nconst parseWorkbookProtection = (node: XmlNode): import('../workbook/protection').WorkbookProtection => {\n const out: import('../workbook/protection').WorkbookProtection = {};\n const a = node.attrs;\n const flag = (raw: string | undefined): boolean | undefined => {\n if (raw === '1' || raw === 'true') return true;\n if (raw === '0' || raw === 'false') return false;\n return undefined;\n };\n if (a['workbookPassword'] !== undefined) out.workbookPassword = a['workbookPassword'];\n if (a['workbookPasswordCharacterSet'] !== undefined)\n out.workbookPasswordCharacterSet = a['workbookPasswordCharacterSet'];\n if (a['workbookAlgorithmName'] !== undefined) out.workbookAlgorithmName = a['workbookAlgorithmName'];\n if (a['workbookHashValue'] !== undefined) out.workbookHashValue = a['workbookHashValue'];\n if (a['workbookSaltValue'] !== undefined) out.workbookSaltValue = a['workbookSaltValue'];\n if (a['workbookSpinCount'] !== undefined) {\n const n = Number.parseInt(a['workbookSpinCount'], 10);\n if (Number.isInteger(n)) out.workbookSpinCount = n;\n }\n if (a['revisionsPassword'] !== undefined) out.revisionsPassword = a['revisionsPassword'];\n if (a['revisionsPasswordCharacterSet'] !== undefined)\n out.revisionsPasswordCharacterSet = a['revisionsPasswordCharacterSet'];\n if (a['revisionsAlgorithmName'] !== undefined) out.revisionsAlgorithmName = a['revisionsAlgorithmName'];\n if (a['revisionsHashValue'] !== undefined) out.revisionsHashValue = a['revisionsHashValue'];\n if (a['revisionsSaltValue'] !== undefined) out.revisionsSaltValue = a['revisionsSaltValue'];\n if (a['revisionsSpinCount'] !== undefined) {\n const n = Number.parseInt(a['revisionsSpinCount'], 10);\n if (Number.isInteger(n)) out.revisionsSpinCount = n;\n }\n const ls = flag(a['lockStructure']);\n if (ls !== undefined) out.lockStructure = ls;\n const lw = flag(a['lockWindows']);\n if (lw !== undefined) out.lockWindows = lw;\n const lr = flag(a['lockRevision']);\n if (lr !== undefined) out.lockRevision = lr;\n return out;\n};\n\n/**\n * Capture workbook-rels entries that don't match a modeled type so the writer\n * can re-emit them with their original Id (and any captured `<pivotCaches\n * r:id=\"…\"/>` etc. still resolves after a round-trip). Modeled non-sheet rels\n * (sst / styles / theme / vbaProject) keep their original Id via\n * `wb.workbookRelOriginalIds` so the writer can prefer those over freshly\n * allocated ones.\n */\nfunction captureWorkbookRelsExtras(\n wbRels: import('../packaging/relationships').Relationships,\n wb: Workbook,\n): void {\n const SHEET_RELS = new Set([`${REL_NS}/worksheet`, `${REL_NS}/chartsheet`]);\n const original: NonNullable<Workbook['workbookRelOriginalIds']> = {};\n const extras: Array<{ id: string; type: string; target: string }> = [];\n for (const rel of wbRels.rels) {\n if (SHEET_RELS.has(rel.type)) continue;\n if (rel.type === `${REL_NS}/sharedStrings`) {\n original.sharedStrings = rel.id;\n continue;\n }\n if (rel.type === `${REL_NS}/styles`) {\n original.styles = rel.id;\n continue;\n }\n if (rel.type === `${REL_NS}/theme`) {\n original.theme = rel.id;\n continue;\n }\n if (rel.type === `${REL_NS}/vbaProject`) {\n original.vbaProject = rel.id;\n continue;\n }\n extras.push({ id: rel.id, type: rel.type, target: rel.target });\n }\n if (Object.keys(original).length > 0) wb.workbookRelOriginalIds = original;\n if (extras.length > 0) wb.workbookRelsExtras = extras;\n}\n\nconst PASSTHROUGH_PREFIXES: ReadonlyArray<string> = [\n 'xl/activeX/',\n 'xl/ctrlProps/',\n 'xl/embeddings/',\n 'xl/externalLinks/',\n // xl/model/ — Power Pivot data model (`xl/model/item.data` etc.).\n 'xl/model/',\n 'xl/persons/',\n 'xl/pivotCache/',\n 'xl/pivotTables/',\n 'xl/printerSettings/',\n 'xl/queryTables/',\n 'xl/richData/',\n 'xl/slicerCaches/',\n 'xl/slicers/',\n 'xl/threadedComments/',\n 'xl/timelineCaches/',\n 'xl/timelines/',\n 'xl/workbookCache/',\n 'customUI/',\n 'customXml/',\n];\n\n/**\n * Excel emits both form-control VMLs and comment VMLs at\n * `xl/drawings/vmlDrawingN.vml`. Filename alone can't tell them apart, but\n * ECMA-376 §17.18.51 requires comment shapes to carry `<x:ClientData\n * ObjectType=\"Note\">`, so a byte-search for that marker decides which path the\n * file belongs on:\n *\n * - With marker → comment VML; the comments writer regenerates\n * these from `Worksheet.legacyComments`, so we must not capture them as\n * passthrough (would duplicate the entry on save).\n * - Without marker → control / OLE / shape VML; capture as\n * passthrough so form controls survive load → save → load.\n */\nconst COMMENT_VML_MARKER = 'ObjectType=\"Note\"';\n// Latin-1 is a 1-to-1 byte-to-character mapping for the 0–255 range, so a\n// String.indexOf scan on the decoded view returns the same answer as a byte\n// search but takes advantage of V8's native StringPrototypeIndexOf — orders\n// of magnitude faster than the JS loop the previous implementation used on\n// multi-megabyte VML drawings.\nconst LATIN1_DECODER = new TextDecoder('latin1');\n\nconst isVmlDrawing = (path: string): boolean =>\n path.startsWith('xl/drawings/') && path.endsWith('.vml');\n\nconst containsCommentMarker = (bytes: Uint8Array): boolean =>\n LATIN1_DECODER.decode(bytes).includes(COMMENT_VML_MARKER);\n\ninterface VmlPartCache {\n /** Inflated VML bytes, read once per part. */\n read(path: string): Uint8Array;\n /** True when the part at `path` exists and is a comment overlay. */\n isCommentVml(path: string): boolean;\n}\n\n/**\n * Both the per-sheet rels capture and the passthrough sweep need to classify\n * VML parts; share one inflate per part between them.\n */\nconst makeVmlPartCache = (archive: ZipArchive): VmlPartCache => {\n const bytesByPath = new Map<string, Uint8Array>();\n const read = (path: string): Uint8Array => {\n let bytes = bytesByPath.get(path);\n if (bytes === undefined) {\n bytes = archive.read(path);\n bytesByPath.set(path, bytes);\n }\n return bytes;\n };\n return {\n read,\n isCommentVml: (path) => archive.has(path) && containsCommentMarker(read(path)),\n };\n};\n\n/**\n * Top-level xl/*.xml files that aren't modeled but Excel relies on (or\n * harmlessly preserves). Captured by exact path; their content types come\n * through the manifest Override map.\n *\n * - `xl/calcChain.xml` — calculation order hint (Excel rebuilds\n * it on first open if missing, but losing it forces a full recalc).\n * - `xl/connections.xml` — external data connection metadata.\n * - `xl/persons/` — threaded-comment author registry\n * (Excel 365). Captured under the prefix list below.\n * - `xl/metadata.xml` — Excel 365 dynamic-array cell metadata.\n * - `xl/SheetMetadata.xml` — variant casing of the same.\n */\nconst PASSTHROUGH_EXACT_PATHS: ReadonlySet<string> = new Set([\n 'xl/calcChain.xml',\n 'xl/connections.xml',\n 'xl/metadata.xml',\n 'xl/SheetMetadata.xml',\n // docProps/thumbnail.jpeg — workbook preview image Excel renders in the OS\n // file browser. JPEG by default; some files use PNG.\n 'docProps/thumbnail.jpeg',\n 'docProps/thumbnail.jpg',\n 'docProps/thumbnail.png',\n 'docProps/thumbnail.wmf',\n 'docProps/thumbnail.emf',\n]);\n\nconst isPassthroughPath = (path: string, vml: VmlPartCache): boolean => {\n if (PASSTHROUGH_EXACT_PATHS.has(path)) return true;\n if (PASSTHROUGH_PREFIXES.some((p) => path.startsWith(p))) return true;\n // Comment VML is regenerated; control / shape / header-footer VML passes\n // through.\n if (isVmlDrawing(path)) return !vml.isCommentVml(path);\n return false;\n};\n\n/**\n * Walk the archive after the modeled parts are loaded and capture any remaining\n * content into `wb.passthrough`. The dedicated VBA project binaries land on\n * their own slots so the writer can promote the workbook content type to xlsm.\n *\n * `roots` are parts the worksheet writer will reference by their original\n * r:id (see `captureSheetRelsExtras`). Each root is captured together with\n * its own `.rels` file and, transitively, every internal target of those rels\n * — that is what keeps a header/footer VML's image (`vmlDrawingN.vml.rels` →\n * `xl/media/imageN.jpeg`) attached. Passthrough VML parts get the same\n * treatment because form-control VML references images the same way.\n */\nfunction capturePassthrough(\n archive: ZipArchive,\n manifest: import('../packaging/manifest').Manifest,\n wb: Workbook,\n roots: ReadonlyArray<string>,\n vml: VmlPartCache,\n): void {\n const overrides = new Map<string, string>();\n for (const o of manifest.overrides) {\n // Manifest paths are package-absolute (`/xl/...`); strip the leading slash.\n overrides.set(o.partName.replace(/^\\//, ''), o.contentType);\n }\n const defaults = new Map<string, string>();\n for (const d of manifest.defaults) defaults.set(d.ext.toLowerCase(), d.contentType);\n\n const capture = (path: string, bytes: Uint8Array): void => {\n if (!wb.passthrough) wb.passthrough = new Map();\n wb.passthrough.set(path, bytes);\n const ct = overrides.get(path);\n if (ct !== undefined) {\n if (!wb.passthroughContentTypes) wb.passthroughContentTypes = new Map();\n wb.passthroughContentTypes.set(path, ct);\n return;\n }\n // No Override → the part is typed by its extension's Default. Remember it\n // so the writer can re-emit that Default; it only knows the extensions of\n // parts it produces itself.\n const ext = path.slice(path.lastIndexOf('.') + 1).toLowerCase();\n const dct = defaults.get(ext);\n if (dct !== undefined) {\n if (!wb.passthroughDefaults) wb.passthroughDefaults = new Map();\n wb.passthroughDefaults.set(ext, dct);\n }\n };\n\n const closureRoots: string[] = [...roots];\n for (const path of archive.list()) {\n if (path === 'xl/vbaProject.bin') {\n wb.vbaProject = archive.read(path);\n continue;\n }\n if (path === 'xl/vbaProjectSignature.bin') {\n wb.vbaSignature = archive.read(path);\n continue;\n }\n if (!isPassthroughPath(path, vml)) continue;\n if (isVmlDrawing(path)) {\n capture(path, vml.read(path));\n closureRoots.push(path);\n } else {\n capture(path, archive.read(path));\n }\n }\n\n // Breadth-first over rels so a chain like sheet → VML → image is captured\n // whole. `visited` (not `wb.passthrough`) gates the walk because roots\n // captured by the prefix scan above still need their rels followed.\n const visited = new Set<string>();\n // for…of re-reads the array length each step, so targets pushed mid-walk\n // are visited too.\n for (const path of closureRoots) {\n if (visited.has(path) || !archive.has(path)) continue;\n visited.add(path);\n if (!wb.passthrough?.has(path)) capture(path, archive.read(path));\n const relsPath = relsPathFor(path);\n if (!archive.has(relsPath)) continue;\n const relsBytes = archive.read(relsPath);\n capture(relsPath, relsBytes);\n for (const r of relsFromBytes(relsBytes).rels) {\n if (r.targetMode !== 'External') closureRoots.push(resolveRelTarget(path, r.target));\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;AA6BA,MAAM,iBAAiB,MAAM,eAAe,YAAY;AACxD,MAAM,YAAY,MAAM,eAAe,OAAO;AAC9C,MAAM,YAAY,MAAM,eAAe,OAAO;AAC9C,MAAM,cAAc,MAAM,eAAe,SAAS;AAClD,MAAM,cAAc,MAAM,eAAe,SAAS;AAClD,MAAM,aAAa,MAAM,eAAe,Q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a,IAAI,IAAI,GAAG,QAAQ,MAAM,QAAQ,KAAK,IAAI,CAAC;EAChE,MAAM,WAAW,YAAY,IAAI;EACjC,IAAI,CAAC,QAAQ,IAAI,QAAQ,GAAG;EAC5B,MAAM,YAAY,QAAQ,KAAK,QAAQ;EACvC,QAAQ,UAAU,SAAS;EAC3B,KAAK,MAAM,KAAK,cAAc,SAAS,CAAC,CAAC,MACvC,IAAI,EAAE,eAAe,YAAY,aAAa,KAAK,iBAAiB,MAAM,EAAE,MAAM,CAAC;CAEvF;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"parser-nk0Lqmcb.mjs","names":[],"sources":["../src/xml/parser.ts"],"sourcesContent":["// DOM-style XML parser. fast-xml-parser does the lexing, then we walk its\n// preserveOrder tree to:\n// 1. resolve `prefix:local` element + attribute names to Clark notation\n// (`{ns}local`) using a namespace-declaration stack;\n// 2. fold text segments into XmlNode.text for text-only elements;\n// 3. drop XML declarations and processing instructions.\n//\n// DOCTYPE / external entity declarations are rejected outright via a byte-level\n// prescan before the parser ever sees the input — fast-xml-parser does not\n// expand external entities, but we still want the offending document to fail\n// loudly.\n\nimport { XMLParser } from 'fast-xml-parser';\nimport { OpenXmlSchemaError } from '../utils/exceptions';\nimport { qname } from './namespaces';\nimport { el, type XmlNode } from './tree';\n\n// ---- DOCTYPE / DTD prescan --------------------------------------------------\n\nconst decoder = new TextDecoder('utf-8', { fatal: false });\n\nconst decodeForPrescan = (input: Uint8Array | string): string => {\n if (typeof input === 'string') return input;\n return decoder.decode(input);\n};\n\nconst checkForDoctype = (text: string): void => {\n // Strip XML declaration so any subsequent `<!DOCTYPE` is the real thing. The\n // declaration is always the first non-BOM token in well-formed XML.\n const stripped = text.replace(/^/, '');\n if (/<!DOCTYPE\\b/.test(stripped)) {\n throw new OpenXmlSchemaError('DTD declarations are not permitted in OOXML payloads');\n }\n if (/<!ENTITY\\b/.test(stripped)) {\n throw new OpenXmlSchemaError('Entity declarations are not permitted in OOXML payloads');\n }\n};\n\n// ---- fast-xml-parser configuration ------------------------------------------\n\nconst parser = new XMLParser({\n preserveOrder: true,\n ignoreAttributes: false,\n attributeNamePrefix: '',\n attributesGroupName: ':@',\n trimValues: false,\n parseTagValue: false,\n parseAttributeValue: false,\n // OOXML needs the standard XML entities (&amp; / &lt; / &gt; / &quot; /\n // &apos;) expanded; HTML / numeric entities outside that set are not used in\n // SpreadsheetML payloads.\n processEntities: true,\n htmlEntities: false,\n});\n\n// ---- preserveOrder shape ----------------------------------------------------\n\ntype FxpAttrs = Record<string, string>;\ntype FxpEntry = { ':@'?: FxpAttrs } & { [tagOrText: string]: FxpEntry[] | string | FxpAttrs | undefined };\ntype FxpTree = FxpEntry[];\n\nconst ATTR_KEY = ':@';\nconst TEXT_KEY = '#text';\n\n// ---- public API -------------------------------------------------------------\n\n/**\n * Parse a UTF-8 XML payload into an {@link XmlNode} tree. Element and attribute\n * names are returned in Clark notation. Throws {@link OpenXmlSchemaError} on\n * DTD/entity declarations or on multi-root documents.\n */\nexport function parseXml(input: Uint8Array | string): XmlNode {\n const text = decodeForPrescan(input);\n checkForDoctype(text);\n\n let raw: FxpTree;\n try {\n raw = parser.parse(text) as FxpTree;\n } catch (cause) {\n throw new OpenXmlSchemaError('parseXml: failed to parse XML payload', { cause });\n }\n\n // Skip XML declaration, processing instructions and any leading whitespace\n // text nodes.\n const roots: FxpEntry[] = [];\n for (const entry of raw) {\n const tag = elementTag(entry);\n if (tag === undefined) continue; // text-only entry\n if (isProcessingInstruction(tag)) continue; // <?xml …?>, other PIs\n roots.push(entry);\n }\n if (roots.length === 0) {\n throw new OpenXmlSchemaError('parseXml: document has no root element');\n }\n if (roots.length > 1) {\n throw new OpenXmlSchemaError(`parseXml: document has ${roots.length} root elements; expected exactly one`);\n }\n\n const initial: NamespaceStack = { default: '', byPrefix: {} };\n const [root] = roots;\n if (root === undefined) {\n throw new OpenXmlSchemaError('parseXml: no root element');\n }\n return convertElement(root, initial);\n}\n\n// ---- conversion -------------------------------------------------------------\n\ninterface NamespaceStack {\n /** Default namespace URI (xmlns=\"…\"); empty string means no default. */\n readonly default: string;\n /** Map of prefix → namespace URI declared in this scope or any ancestor. */\n readonly byPrefix: Readonly<Record<string, string>>;\n}\n\nconst elementTag = (entry: FxpEntry): string | undefined => {\n for (const k of Object.keys(entry)) {\n if (k === ATTR_KEY) continue;\n return k;\n }\n return undefined;\n};\n\nconst isProcessingInstruction = (tag: string): boolean => tag.startsWith('?');\n\nconst splitPrefixed = (qname0: string): { prefix: string; local: string } => {\n const idx = qname0.indexOf(':');\n if (idx < 0) return { prefix: '', local: qname0 };\n return { prefix: qname0.slice(0, idx), local: qname0.slice(idx + 1) };\n};\n\nconst extendStack = (parent: NamespaceStack, attrs: FxpAttrs | undefined): NamespaceStack => {\n if (attrs === undefined) return parent;\n let nextDefault = parent.default;\n let nextByPrefix: Record<string, string> | undefined;\n for (const [k, v] of Object.entries(attrs)) {\n if (k === 'xmlns') {\n nextDefault = v;\n continue;\n }\n if (k.startsWith('xmlns:')) {\n const prefix = k.slice('xmlns:'.length);\n nextByPrefix ??= { ...parent.byPrefix };\n nextByPrefix[prefix] = v;\n }\n }\n if (nextDefault === parent.default && nextByPrefix === undefined) return parent;\n return {\n default: nextDefault,\n byPrefix: nextByPrefix ?? parent.byPrefix,\n };\n};\n\nconst resolveElementName = (raw: string, stack: NamespaceStack): string => {\n const { prefix, local } = splitPrefixed(raw);\n if (prefix === '') return qname(stack.default, local);\n const ns = stack.byPrefix[prefix];\n if (ns === undefined) {\n throw new OpenXmlSchemaError(`parseXml: undeclared namespace prefix \"${prefix}\" on element <${raw}>`);\n }\n return qname(ns, local);\n};\n\nconst resolveAttrName = (raw: string, stack: NamespaceStack): string => {\n const { prefix, local } = splitPrefixed(raw);\n // Unprefixed attributes do NOT inherit the default namespace (XMLNS spec).\n if (prefix === '') return local;\n if (prefix === 'xml') return qname('http://www.w3.org/XML/1998/namespace', local);\n const ns = stack.byPrefix[prefix];\n if (ns === undefined) {\n throw new OpenXmlSchemaError(`parseXml: undeclared namespace prefix \"${prefix}\" on attribute \"${raw}\"`);\n }\n return qname(ns, local);\n};\n\nconst filterAttrs = (rawAttrs: FxpAttrs | undefined, stack: NamespaceStack): { resolved: Record<string, string> } => {\n const resolved: Record<string, string> = {};\n if (rawAttrs === undefined) return { resolved };\n for (const [k, v] of Object.entries(rawAttrs)) {\n // xmlns / xmlns:* declarations: dropped from the XmlNode attribute table.\n // The serializer rebuilds them from the Clark-notation namespaces it walks,\n // so round-tripping does not require preserving the declarations.\n if (k === 'xmlns' || k.startsWith('xmlns:')) continue;\n resolved[resolveAttrName(k, stack)] = v;\n }\n return { resolved };\n};\n\nconst isWhitespaceOnly = (s: string): boolean => /^\\s*$/.test(s);\n\nconst convertElement = (entry: FxpEntry, parentStack: NamespaceStack): XmlNode => {\n const rawTag = elementTag(entry);\n if (rawTag === undefined) {\n throw new OpenXmlSchemaError('parseXml: encountered an entry with no element tag');\n }\n if (isProcessingInstruction(rawTag)) {\n throw new OpenXmlSchemaError(`parseXml: processing instructions are not supported (saw \"<${rawTag}>\")`);\n }\n\n const rawAttrs = entry[ATTR_KEY] as FxpAttrs | undefined;\n const stack = extendStack(parentStack, rawAttrs);\n\n const { resolved } = filterAttrs(rawAttrs, stack);\n const node = el(resolveElementName(rawTag, stack), resolved);\n\n const childEntries = entry[rawTag] as FxpEntry[] | undefined;\n if (childEntries === undefined || childEntries.length === 0) return node;\n\n const textParts: string[] = [];\n for (const child of childEntries) {\n if (Object.hasOwn(child, TEXT_KEY)) {\n const t = child[TEXT_KEY];\n if (typeof t === 'string') textParts.push(t);\n continue;\n }\n if (textParts.length > 0 && node.children.length === 0) {\n // text accumulated *before* any child element — keep collecting.\n } else if (textParts.length > 0 && node.children.length > 0) {\n const acc = textParts.join('');\n if (!isWhitespaceOnly(acc)) {\n throw new OpenXmlSchemaError(`parseXml: mixed content not supported (text between elements under <${rawTag}>)`);\n }\n // whitespace-only inter-element text: drop.\n textParts.length = 0;\n }\n node.children.push(convertElement(child, stack));\n }\n // Trailing text after the last child element.\n if (textParts.length > 0) {\n const acc = textParts.join('');\n if (node.children.length === 0) {\n // text-only element (the common case): keep as the element's text.\n node.text = acc;\n } else if (!isWhitespaceOnly(acc)) {\n throw new OpenXmlSchemaError(`parseXml: mixed content not supported (trailing text under <${rawTag}>)`);\n }\n }\n return node;\n};\n"],"mappings":";;;;AAmBA,MAAM,UAAU,IAAI,YAAY,SAAS,EAAE,OAAO,MAAM,CAAC;AAEzD,MAAM,oBAAoB,UAAuC;CAC/D,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,QAAQ,OAAO,KAAK;AAC7B;AAEA,MAAM,mBAAmB,SAAuB;CAG9C,MAAM,WAAW,KAAK,QAAQ,MAAM,EAAE;CACtC,IAAI,cAAc,KAAK,QAAQ,GAC7B,MAAM,IAAI,mBAAmB,sDAAsD;CAErF,IAAI,aAAa,KAAK,QAAQ,GAC5B,MAAM,IAAI,mBAAmB,yDAAyD;AAE1F;AAIA,MAAM,SAAS,IAAI,UAAU;CAC3B,eAAe;CACf,kBAAkB;CAClB,qBAAqB;CACrB,qBAAqB;CACrB,YAAY;CACZ,eAAe;CACf,qBAAqB;CAIrB,iBAAiB;CACjB,cAAc;AAChB,CAAC;AAQD,MAAM,WAAW;AACjB,MAAM,WAAW;;;;;;AASjB,SAAgB,SAAS,OAAqC;CAC5D,MAAM,OAAO,iBAAiB,KAAK;CACnC,gBAAgB,IAAI;CAEpB,IAAI;CACJ,IAAI;EACF,MAAM,OAAO,MAAM,IAAI;CACzB,SAAS,OAAO;EACd,MAAM,IAAI,mBAAmB,yCAAyC,EAAE,MAAM,CAAC;CACjF;CAIA,MAAM,QAAoB,CAAC;CAC3B,KAAK,MAAM,SAAS,KAAK;EACvB,MAAM,MAAM,WAAW,KAAK;EAC5B,IAAI,QAAQ,KAAA,GAAW;EACvB,IAAI,wBAAwB,GAAG,GAAG;EAClC,MAAM,KAAK,KAAK;CAClB;CACA,IAAI,MAAM,WA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