odf.js 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import { XMLBuilder, XMLParser } from "fast-xml-parser";
3
3
  import { unzipSync, zipSync } from "fflate";
4
+ import { AlignmentSchema, ColorSchema, colorToRgbHex, rgbHexToColor } from "document-content-model";
4
5
  //#region src/model/node.ts
5
6
  const AttributeSchema = z.object({
6
7
  name: z.string(),
@@ -328,4 +329,1008 @@ function encodePackage(pkg) {
328
329
  return z.encode(packageCodec, pkg);
329
330
  }
330
331
  //#endregion
331
- export { AttributeSchema, BinaryPartSchema, PackageSchema, PartSchema, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, base64ToBytes, buildXml, bytesToBase64, decodePackage, encodePackage, isXmlNode, packageCodec, parsePackage, parseXml, serializePackage, unzipPackage, xmlCodec, zipPackage };
332
+ //#region src/ns.ts
333
+ const ODF_NAMESPACES = Object.freeze({
334
+ office: "urn:oasis:names:tc:opendocument:xmlns:office:1.0",
335
+ style: "urn:oasis:names:tc:opendocument:xmlns:style:1.0",
336
+ text: "urn:oasis:names:tc:opendocument:xmlns:text:1.0",
337
+ table: "urn:oasis:names:tc:opendocument:xmlns:table:1.0",
338
+ draw: "urn:oasis:names:tc:opendocument:xmlns:drawing:1.0",
339
+ fo: "urn:oasis:names:tc:opendocument:xmlns:xsl-fo-compatible:1.0",
340
+ svg: "urn:oasis:names:tc:opendocument:xmlns:svg-compatible:1.0",
341
+ xlink: "http://www.w3.org/1999/xlink",
342
+ dc: "http://purl.org/dc/elements/1.1/",
343
+ meta: "urn:oasis:names:tc:opendocument:xmlns:meta:1.0",
344
+ number: "urn:oasis:names:tc:opendocument:xmlns:datastyle:1.0",
345
+ chart: "urn:oasis:names:tc:opendocument:xmlns:chart:1.0",
346
+ dr3d: "urn:oasis:names:tc:opendocument:xmlns:dr3d:1.0",
347
+ math: "http://www.w3.org/1998/Math/MathML",
348
+ form: "urn:oasis:names:tc:opendocument:xmlns:form:1.0",
349
+ script: "urn:oasis:names:tc:opendocument:xmlns:script:1.0",
350
+ config: "urn:oasis:names:tc:opendocument:xmlns:config:1.0",
351
+ presentation: "urn:oasis:names:tc:opendocument:xmlns:presentation:1.0",
352
+ smil: "urn:oasis:names:tc:opendocument:xmlns:smil-compatible:1.0",
353
+ anim: "urn:oasis:names:tc:opendocument:xmlns:animation:1.0",
354
+ xforms: "http://www.w3.org/2002/xforms",
355
+ xsd: "http://www.w3.org/2001/XMLSchema",
356
+ xsi: "http://www.w3.org/2001/XMLSchema-instance",
357
+ manifest: "urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"
358
+ });
359
+ function xmlnsAttributes(prefixes) {
360
+ const attrs = {};
361
+ for (const prefix of prefixes) attrs[`xmlns:${prefix}`] = ODF_NAMESPACES[prefix];
362
+ return attrs;
363
+ }
364
+ //#endregion
365
+ //#region src/media-type.ts
366
+ const ODF_MEDIA_TYPES = Object.freeze({
367
+ odt: "application/vnd.oasis.opendocument.text",
368
+ ott: "application/vnd.oasis.opendocument.text-template",
369
+ ods: "application/vnd.oasis.opendocument.spreadsheet",
370
+ ots: "application/vnd.oasis.opendocument.spreadsheet-template",
371
+ odp: "application/vnd.oasis.opendocument.presentation",
372
+ otp: "application/vnd.oasis.opendocument.presentation-template",
373
+ odg: "application/vnd.oasis.opendocument.graphics",
374
+ otg: "application/vnd.oasis.opendocument.graphics-template",
375
+ odf: "application/vnd.oasis.opendocument.formula",
376
+ otf: "application/vnd.oasis.opendocument.formula-template",
377
+ odm: "application/vnd.oasis.opendocument.text-master",
378
+ otm: "application/vnd.oasis.opendocument.text-master-template",
379
+ odb: "application/vnd.oasis.opendocument.base"
380
+ });
381
+ function isOdfExtension(extension) {
382
+ return Object.hasOwn(ODF_MEDIA_TYPES, extension);
383
+ }
384
+ function mediaTypeForExtension(extension) {
385
+ const lower = extension.toLowerCase();
386
+ return isOdfExtension(lower) ? ODF_MEDIA_TYPES[lower] : void 0;
387
+ }
388
+ //#endregion
389
+ //#region src/image/sniff.ts
390
+ const PNG_SIGNATURE = [
391
+ 137,
392
+ 80,
393
+ 78,
394
+ 71,
395
+ 13,
396
+ 10,
397
+ 26,
398
+ 10
399
+ ];
400
+ const JPEG_SIGNATURE = [
401
+ 255,
402
+ 216,
403
+ 255
404
+ ];
405
+ function startsWith(bytes, signature) {
406
+ if (bytes.length < signature.length) return false;
407
+ for (let i = 0; i < signature.length; i++) if (bytes[i] !== signature[i]) return false;
408
+ return true;
409
+ }
410
+ function sniffImageFormat(bytes) {
411
+ if (startsWith(bytes, PNG_SIGNATURE)) return "png";
412
+ if (startsWith(bytes, JPEG_SIGNATURE)) return "jpeg";
413
+ }
414
+ //#endregion
415
+ //#region src/mimetype.ts
416
+ function readMimetype(pkg) {
417
+ const part = pkg.parts[MIMETYPE_PART];
418
+ if (part?.kind !== "binary") return;
419
+ return new TextDecoder("utf-8").decode(base64ToBytes(part.base64));
420
+ }
421
+ function writeMimetype(pkg, mediaType) {
422
+ pkg.parts[MIMETYPE_PART] = {
423
+ kind: "binary",
424
+ base64: bytesToBase64(new TextEncoder().encode(mediaType))
425
+ };
426
+ }
427
+ //#endregion
428
+ //#region src/xml/fragment.ts
429
+ function el(tag, attrs = {}, children = []) {
430
+ return {
431
+ type: "element",
432
+ tag,
433
+ attributes: Object.entries(attrs).map(([name, value]) => ({
434
+ name,
435
+ value
436
+ })),
437
+ children
438
+ };
439
+ }
440
+ function txt(value) {
441
+ return {
442
+ type: "text",
443
+ value
444
+ };
445
+ }
446
+ //#endregion
447
+ //#region src/xml/entities.ts
448
+ function encodeXmlText(value) {
449
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
450
+ }
451
+ //#endregion
452
+ //#region src/manifest.ts
453
+ const ManifestEntrySchema = z.object({
454
+ fullPath: z.string(),
455
+ mediaType: z.string(),
456
+ version: z.string().optional()
457
+ });
458
+ const ManifestSchema = z.object({
459
+ version: z.string(),
460
+ entries: z.array(ManifestEntrySchema)
461
+ });
462
+ const ManifestProblemSchema = z.object({
463
+ severity: z.enum(["error", "warning"]),
464
+ message: z.string(),
465
+ path: z.string().optional()
466
+ });
467
+ const DEFAULT_MANIFEST_VERSION = "1.3";
468
+ const STANDARD_XML_PART_NAMES = /* @__PURE__ */ new Set([
469
+ "content.xml",
470
+ "styles.xml",
471
+ "meta.xml",
472
+ "settings.xml"
473
+ ]);
474
+ function findChildElement(nodes, tag) {
475
+ for (const node of nodes) if (node.type === "element" && node.tag === tag) return node;
476
+ }
477
+ function attrValue$1(element, name) {
478
+ return element.attributes.find((attribute) => attribute.name === name)?.value;
479
+ }
480
+ function readManifest(pkg) {
481
+ const part = pkg.parts[MANIFEST_PART];
482
+ if (part?.kind !== "xml") throw new Error(`package has no ${MANIFEST_PART} XML part to read`);
483
+ const root = findChildElement(part.nodes, "manifest:manifest");
484
+ if (root === void 0) throw new Error(`${MANIFEST_PART} has no manifest:manifest root element`);
485
+ const version = attrValue$1(root, "manifest:version");
486
+ if (version === void 0) throw new Error(`${MANIFEST_PART}'s manifest:manifest root is missing the required manifest:version attribute`);
487
+ const entries = [];
488
+ for (const child of root.children) {
489
+ if (child.type !== "element" || child.tag !== "manifest:file-entry") continue;
490
+ const fullPath = attrValue$1(child, "manifest:full-path");
491
+ const mediaType = attrValue$1(child, "manifest:media-type");
492
+ if (fullPath === void 0 || mediaType === void 0) throw new Error(`${MANIFEST_PART} has a manifest:file-entry missing manifest:full-path or manifest:media-type`);
493
+ const entryVersion = attrValue$1(child, "manifest:version");
494
+ entries.push(entryVersion === void 0 ? {
495
+ fullPath,
496
+ mediaType
497
+ } : {
498
+ fullPath,
499
+ mediaType,
500
+ version: entryVersion
501
+ });
502
+ }
503
+ return {
504
+ version,
505
+ entries
506
+ };
507
+ }
508
+ function subdocumentDirectories(partPaths) {
509
+ const dirs = [];
510
+ for (const path of partPaths) if (path.endsWith("/content.xml")) dirs.push(path.slice(0, path.length - 11));
511
+ return dirs;
512
+ }
513
+ function resolvePartMediaType(path, bytes, overrides) {
514
+ const override = overrides?.[path];
515
+ if (override !== void 0) return override;
516
+ const baseName = path.slice(path.lastIndexOf("/") + 1);
517
+ if (STANDARD_XML_PART_NAMES.has(baseName)) return "text/xml";
518
+ const dotIndex = baseName.lastIndexOf(".");
519
+ const extension = dotIndex === -1 ? "" : baseName.slice(dotIndex + 1);
520
+ const byExtension = extension === "" ? void 0 : mediaTypeForExtension(extension);
521
+ if (byExtension !== void 0) return byExtension;
522
+ if (bytes !== void 0) {
523
+ const sniffed = sniffImageFormat(bytes);
524
+ if (sniffed === "png") return "image/png";
525
+ if (sniffed === "jpeg") return "image/jpeg";
526
+ }
527
+ return "";
528
+ }
529
+ function buildManifest(pkg, options = {}) {
530
+ const version = options.version ?? DEFAULT_MANIFEST_VERSION;
531
+ const documentMediaType = options.documentMediaType ?? readMimetype(pkg);
532
+ if (documentMediaType === void 0) throw new Error("buildManifest: package has no \"mimetype\" part and no documentMediaType override was supplied -- the manifest root entry requires a known document media type");
533
+ const entries = [{
534
+ fullPath: "/",
535
+ mediaType: documentMediaType,
536
+ version
537
+ }];
538
+ const partPaths = Object.keys(pkg.parts);
539
+ for (const dir of new Set(subdocumentDirectories(partPaths))) entries.push({
540
+ fullPath: dir,
541
+ mediaType: resolvePartMediaType(dir, void 0, options.mediaTypeOverrides)
542
+ });
543
+ for (const [path, part] of Object.entries(pkg.parts)) {
544
+ if (path === "mimetype" || path === "META-INF/manifest.xml") continue;
545
+ const bytes = part.kind === "binary" ? base64ToBytes(part.base64) : void 0;
546
+ entries.push({
547
+ fullPath: path,
548
+ mediaType: resolvePartMediaType(path, bytes, options.mediaTypeOverrides)
549
+ });
550
+ }
551
+ return {
552
+ version,
553
+ entries
554
+ };
555
+ }
556
+ function buildManifestNodes(manifest) {
557
+ const fileEntries = manifest.entries.map((entry) => {
558
+ const attrs = { "manifest:full-path": encodeXmlText(entry.fullPath) };
559
+ if (entry.version !== void 0) attrs["manifest:version"] = encodeXmlText(entry.version);
560
+ attrs["manifest:media-type"] = encodeXmlText(entry.mediaType);
561
+ return el("manifest:file-entry", attrs);
562
+ });
563
+ return [{
564
+ type: "declaration",
565
+ attributes: [{
566
+ name: "version",
567
+ value: "1.0"
568
+ }, {
569
+ name: "encoding",
570
+ value: "UTF-8"
571
+ }]
572
+ }, el("manifest:manifest", {
573
+ ...xmlnsAttributes(["manifest"]),
574
+ "manifest:version": encodeXmlText(manifest.version)
575
+ }, fileEntries)];
576
+ }
577
+ function writeManifest(pkg, manifest) {
578
+ pkg.parts[MANIFEST_PART] = {
579
+ kind: "xml",
580
+ nodes: buildManifestNodes(manifest)
581
+ };
582
+ }
583
+ function syncManifest(pkg, options) {
584
+ writeManifest(pkg, buildManifest(pkg, options));
585
+ }
586
+ function validateManifest(pkg) {
587
+ const problems = [];
588
+ const manifestPart = pkg.parts[MANIFEST_PART];
589
+ if (manifestPart === void 0) {
590
+ problems.push({
591
+ severity: "error",
592
+ message: `package has no ${MANIFEST_PART} part`
593
+ });
594
+ return problems;
595
+ }
596
+ if (manifestPart.kind !== "xml") {
597
+ problems.push({
598
+ severity: "error",
599
+ message: `${MANIFEST_PART} part is not XML`
600
+ });
601
+ return problems;
602
+ }
603
+ const root = findChildElement(manifestPart.nodes, "manifest:manifest");
604
+ if (root === void 0) {
605
+ problems.push({
606
+ severity: "error",
607
+ message: `${MANIFEST_PART} has no manifest:manifest root element`
608
+ });
609
+ return problems;
610
+ }
611
+ let manifest;
612
+ try {
613
+ manifest = readManifest(pkg);
614
+ } catch (error) {
615
+ problems.push({
616
+ severity: "error",
617
+ message: `failed to parse ${MANIFEST_PART}: ${error instanceof Error ? error.message : String(error)}`
618
+ });
619
+ return problems;
620
+ }
621
+ const rootEntry = manifest.entries.find((entry) => entry.fullPath === "/");
622
+ if (rootEntry === void 0) problems.push({
623
+ severity: "error",
624
+ message: "manifest has no root (\"/\") entry"
625
+ });
626
+ else {
627
+ const documentMediaType = readMimetype(pkg);
628
+ if (documentMediaType !== void 0 && documentMediaType !== rootEntry.mediaType) problems.push({
629
+ severity: "error",
630
+ message: `manifest root entry media type "${rootEntry.mediaType}" does not match the mimetype part's media type "${documentMediaType}"`,
631
+ path: "/"
632
+ });
633
+ }
634
+ const partPaths = new Set(Object.keys(pkg.parts).filter((path) => path !== "mimetype" && path !== "META-INF/manifest.xml"));
635
+ const manifestPaths = new Set(manifest.entries.map((entry) => entry.fullPath));
636
+ for (const entry of manifest.entries) {
637
+ if (entry.fullPath === "/" || entry.fullPath.endsWith("/")) continue;
638
+ if (!partPaths.has(entry.fullPath)) problems.push({
639
+ severity: "warning",
640
+ message: `manifest lists "${entry.fullPath}" but the package has no such part`,
641
+ path: entry.fullPath
642
+ });
643
+ }
644
+ for (const path of partPaths) if (!manifestPaths.has(path)) problems.push({
645
+ severity: "warning",
646
+ message: `package has part "${path}" not listed in the manifest`,
647
+ path
648
+ });
649
+ for (const child of root.children) {
650
+ if (child.type !== "element" || child.tag !== "manifest:file-entry") continue;
651
+ if (!child.children.some((grandchild) => grandchild.type === "element" && grandchild.tag === "manifest:encryption-data")) continue;
652
+ const fullPath = attrValue$1(child, "manifest:full-path");
653
+ if (fullPath === void 0) continue;
654
+ problems.push({
655
+ severity: "warning",
656
+ message: `entry "${fullPath}" carries manifest:encryption-data -- odf.js does not implement ODF encryption/decryption`,
657
+ path: fullPath
658
+ });
659
+ }
660
+ return problems;
661
+ }
662
+ function setDocumentMediaType(pkg, mediaType, version = DEFAULT_MANIFEST_VERSION) {
663
+ writeMimetype(pkg, mediaType);
664
+ const rootEntry = {
665
+ fullPath: "/",
666
+ mediaType,
667
+ version
668
+ };
669
+ if (pkg.parts["META-INF/manifest.xml"] === void 0) {
670
+ writeManifest(pkg, {
671
+ version,
672
+ entries: [rootEntry]
673
+ });
674
+ return;
675
+ }
676
+ const existing = readManifest(pkg);
677
+ const rootIndex = existing.entries.findIndex((entry) => entry.fullPath === "/");
678
+ writeManifest(pkg, {
679
+ version,
680
+ entries: rootIndex === -1 ? [rootEntry, ...existing.entries] : existing.entries.map((entry, index) => index === rootIndex ? rootEntry : entry)
681
+ });
682
+ }
683
+ //#endregion
684
+ //#region src/styles/properties.ts
685
+ const StylePropertiesSchema = z.object({
686
+ bold: z.boolean().optional(),
687
+ italic: z.boolean().optional(),
688
+ underline: z.boolean().optional(),
689
+ strike: z.boolean().optional(),
690
+ fontFamily: z.string().optional(),
691
+ sizePt: z.number().optional(),
692
+ color: ColorSchema.optional(),
693
+ alignment: AlignmentSchema.optional(),
694
+ spacingBeforePt: z.number().optional(),
695
+ spacingAfterPt: z.number().optional(),
696
+ lineSpacing: z.number().optional(),
697
+ indentLeftPt: z.number().optional(),
698
+ indentFirstLinePt: z.number().optional()
699
+ });
700
+ const ATTR = {
701
+ fontWeight: "fo:font-weight",
702
+ fontStyle: "fo:font-style",
703
+ underlineStyle: "style:text-underline-style",
704
+ underlineWidth: "style:text-underline-width",
705
+ underlineColor: "style:text-underline-color",
706
+ lineThroughStyle: "style:text-line-through-style",
707
+ lineThroughType: "style:text-line-through-type",
708
+ fontFamily: "fo:font-family",
709
+ fontSize: "fo:font-size",
710
+ color: "fo:color",
711
+ textAlign: "fo:text-align",
712
+ marginTop: "fo:margin-top",
713
+ marginBottom: "fo:margin-bottom",
714
+ lineHeight: "fo:line-height",
715
+ marginLeft: "fo:margin-left",
716
+ textIndent: "fo:text-indent"
717
+ };
718
+ const TEXT_ATTR_NAMES = /* @__PURE__ */ new Set([
719
+ ATTR.fontWeight,
720
+ ATTR.fontStyle,
721
+ ATTR.underlineStyle,
722
+ ATTR.underlineWidth,
723
+ ATTR.underlineColor,
724
+ ATTR.lineThroughStyle,
725
+ ATTR.lineThroughType,
726
+ ATTR.fontFamily,
727
+ ATTR.fontSize,
728
+ ATTR.color
729
+ ]);
730
+ const PARAGRAPH_ATTR_NAMES = /* @__PURE__ */ new Set([
731
+ ATTR.textAlign,
732
+ ATTR.marginTop,
733
+ ATTR.marginBottom,
734
+ ATTR.lineHeight,
735
+ ATTR.marginLeft,
736
+ ATTR.textIndent
737
+ ]);
738
+ function attributeMap(element) {
739
+ const map = /* @__PURE__ */ new Map();
740
+ for (const attribute of element.attributes) map.set(attribute.name, attribute.value);
741
+ return map;
742
+ }
743
+ const LENGTH_PATTERN = /^(-?(?:\d+(?:\.\d+)?|\.\d+))(cm|mm|in|pt|pc|px)$/;
744
+ function unitToPtFactor(unit) {
745
+ switch (unit) {
746
+ case "pt": return 1;
747
+ case "in": return 72;
748
+ case "cm": return 72 / 2.54;
749
+ case "mm": return 72 / 25.4;
750
+ case "pc": return 12;
751
+ case "px": return .75;
752
+ }
753
+ }
754
+ function isLengthUnit(value) {
755
+ return value === "cm" || value === "mm" || value === "in" || value === "pt" || value === "pc" || value === "px";
756
+ }
757
+ function parseLength(value) {
758
+ const match = LENGTH_PATTERN.exec(value);
759
+ if (match === null) return;
760
+ const numeric = match[1];
761
+ const unit = match[2];
762
+ if (numeric === void 0 || unit === void 0 || !isLengthUnit(unit)) return;
763
+ return Number(numeric) * unitToPtFactor(unit);
764
+ }
765
+ function formatPt(valuePt) {
766
+ return `${valuePt}pt`;
767
+ }
768
+ const PERCENTAGE_PATTERN = /^(-?(?:\d+(?:\.\d+)?|\.\d+))%$/;
769
+ function parsePercentageMultiplier(value) {
770
+ const match = PERCENTAGE_PATTERN.exec(value);
771
+ if (match === null) return;
772
+ const numeric = match[1];
773
+ if (numeric === void 0) return;
774
+ return Number(numeric) / 100;
775
+ }
776
+ function formatPercentageMultiplier(multiplier) {
777
+ return `${multiplier * 100}%`;
778
+ }
779
+ const COLOR_PATTERN = /^#[0-9a-fA-F]{6}$/;
780
+ function parseColor(value) {
781
+ if (!COLOR_PATTERN.test(value)) return;
782
+ return rgbHexToColor(value);
783
+ }
784
+ function formatColor(color) {
785
+ return `#${colorToRgbHex(color)}`;
786
+ }
787
+ function parseLineDecoration(style, companionA, companionAOnValue, companionB, companionBOnValue) {
788
+ if (style === void 0 && companionA === void 0 && companionB === void 0) return;
789
+ if (style === "solid" && (companionA === void 0 || companionA === companionAOnValue) && (companionB === void 0 || companionB === companionBOnValue)) return true;
790
+ if (style === "none" && companionA === void 0 && companionB === void 0) return false;
791
+ return "unknown";
792
+ }
793
+ const RISKY_STYLE_ELEMENT_ATTRS = /* @__PURE__ */ new Set(["style:master-page-name", "style:next-style-name"]);
794
+ function parseTextProperties(element) {
795
+ const attrs = attributeMap(element);
796
+ const properties = {};
797
+ let hasUnknown = false;
798
+ for (const name of attrs.keys()) if (!TEXT_ATTR_NAMES.has(name)) hasUnknown = true;
799
+ const fontWeight = attrs.get(ATTR.fontWeight);
800
+ if (fontWeight === "bold") properties.bold = true;
801
+ else if (fontWeight === "normal") properties.bold = false;
802
+ else if (fontWeight !== void 0) hasUnknown = true;
803
+ const fontStyle = attrs.get(ATTR.fontStyle);
804
+ if (fontStyle === "italic") properties.italic = true;
805
+ else if (fontStyle === "normal") properties.italic = false;
806
+ else if (fontStyle !== void 0) hasUnknown = true;
807
+ const underline = parseLineDecoration(attrs.get(ATTR.underlineStyle), attrs.get(ATTR.underlineWidth), "auto", attrs.get(ATTR.underlineColor), "font-color");
808
+ if (underline === "unknown") hasUnknown = true;
809
+ else if (underline !== void 0) properties.underline = underline;
810
+ const strike = parseLineDecoration(attrs.get(ATTR.lineThroughStyle), attrs.get(ATTR.lineThroughType), "single", void 0, "");
811
+ if (strike === "unknown") hasUnknown = true;
812
+ else if (strike !== void 0) properties.strike = strike;
813
+ const fontFamily = attrs.get(ATTR.fontFamily);
814
+ if (fontFamily !== void 0) properties.fontFamily = fontFamily;
815
+ const fontSize = attrs.get(ATTR.fontSize);
816
+ if (fontSize !== void 0) {
817
+ const pt = parseLength(fontSize);
818
+ if (pt === void 0) hasUnknown = true;
819
+ else properties.sizePt = pt;
820
+ }
821
+ const color = attrs.get(ATTR.color);
822
+ if (color !== void 0) {
823
+ const parsed = parseColor(color);
824
+ if (parsed === void 0) hasUnknown = true;
825
+ else properties.color = parsed;
826
+ }
827
+ return {
828
+ properties,
829
+ hasUnknown
830
+ };
831
+ }
832
+ function parseParagraphProperties(element) {
833
+ const attrs = attributeMap(element);
834
+ const properties = {};
835
+ let hasUnknown = false;
836
+ for (const name of attrs.keys()) if (!PARAGRAPH_ATTR_NAMES.has(name)) hasUnknown = true;
837
+ const textAlign = attrs.get(ATTR.textAlign);
838
+ if (textAlign === "left" || textAlign === "center" || textAlign === "right" || textAlign === "justify") properties.alignment = textAlign;
839
+ else if (textAlign !== void 0) hasUnknown = true;
840
+ const marginTop = attrs.get(ATTR.marginTop);
841
+ if (marginTop !== void 0) {
842
+ const pt = parseLength(marginTop);
843
+ if (pt === void 0) hasUnknown = true;
844
+ else properties.spacingBeforePt = pt;
845
+ }
846
+ const marginBottom = attrs.get(ATTR.marginBottom);
847
+ if (marginBottom !== void 0) {
848
+ const pt = parseLength(marginBottom);
849
+ if (pt === void 0) hasUnknown = true;
850
+ else properties.spacingAfterPt = pt;
851
+ }
852
+ const marginLeft = attrs.get(ATTR.marginLeft);
853
+ if (marginLeft !== void 0) {
854
+ const pt = parseLength(marginLeft);
855
+ if (pt === void 0) hasUnknown = true;
856
+ else properties.indentLeftPt = pt;
857
+ }
858
+ const textIndent = attrs.get(ATTR.textIndent);
859
+ if (textIndent !== void 0) {
860
+ const pt = parseLength(textIndent);
861
+ if (pt === void 0) hasUnknown = true;
862
+ else properties.indentFirstLinePt = pt;
863
+ }
864
+ const lineHeight = attrs.get(ATTR.lineHeight);
865
+ if (lineHeight !== void 0) {
866
+ const multiplier = parsePercentageMultiplier(lineHeight);
867
+ if (multiplier === void 0) hasUnknown = true;
868
+ else properties.lineSpacing = multiplier;
869
+ }
870
+ return {
871
+ properties,
872
+ hasUnknown
873
+ };
874
+ }
875
+ function parseStyleElementProperties(styleElement) {
876
+ let properties = {};
877
+ let hasUnknown = false;
878
+ for (const attribute of styleElement.attributes) if (RISKY_STYLE_ELEMENT_ATTRS.has(attribute.name)) hasUnknown = true;
879
+ for (const child of styleElement.children) {
880
+ if (child.type !== "element") continue;
881
+ if (child.tag === "style:text-properties") {
882
+ const result = parseTextProperties(child);
883
+ properties = {
884
+ ...properties,
885
+ ...result.properties
886
+ };
887
+ if (result.hasUnknown) hasUnknown = true;
888
+ } else if (child.tag === "style:paragraph-properties") {
889
+ const result = parseParagraphProperties(child);
890
+ properties = {
891
+ ...properties,
892
+ ...result.properties
893
+ };
894
+ if (result.hasUnknown) hasUnknown = true;
895
+ } else hasUnknown = true;
896
+ }
897
+ return {
898
+ properties,
899
+ hasUnknown
900
+ };
901
+ }
902
+ function textPropertiesToAttributes(properties) {
903
+ const attributes = [];
904
+ if (properties.bold !== void 0) attributes.push({
905
+ name: ATTR.fontWeight,
906
+ value: properties.bold ? "bold" : "normal"
907
+ });
908
+ if (properties.italic !== void 0) attributes.push({
909
+ name: ATTR.fontStyle,
910
+ value: properties.italic ? "italic" : "normal"
911
+ });
912
+ if (properties.underline !== void 0) if (properties.underline) {
913
+ attributes.push({
914
+ name: ATTR.underlineStyle,
915
+ value: "solid"
916
+ });
917
+ attributes.push({
918
+ name: ATTR.underlineWidth,
919
+ value: "auto"
920
+ });
921
+ attributes.push({
922
+ name: ATTR.underlineColor,
923
+ value: "font-color"
924
+ });
925
+ } else attributes.push({
926
+ name: ATTR.underlineStyle,
927
+ value: "none"
928
+ });
929
+ if (properties.strike !== void 0) if (properties.strike) {
930
+ attributes.push({
931
+ name: ATTR.lineThroughStyle,
932
+ value: "solid"
933
+ });
934
+ attributes.push({
935
+ name: ATTR.lineThroughType,
936
+ value: "single"
937
+ });
938
+ } else attributes.push({
939
+ name: ATTR.lineThroughStyle,
940
+ value: "none"
941
+ });
942
+ if (properties.fontFamily !== void 0) attributes.push({
943
+ name: ATTR.fontFamily,
944
+ value: encodeXmlText(properties.fontFamily)
945
+ });
946
+ if (properties.sizePt !== void 0) attributes.push({
947
+ name: ATTR.fontSize,
948
+ value: formatPt(properties.sizePt)
949
+ });
950
+ if (properties.color !== void 0) attributes.push({
951
+ name: ATTR.color,
952
+ value: formatColor(properties.color)
953
+ });
954
+ return attributes;
955
+ }
956
+ function paragraphPropertiesToAttributes(properties) {
957
+ const attributes = [];
958
+ if (properties.alignment !== void 0) attributes.push({
959
+ name: ATTR.textAlign,
960
+ value: properties.alignment
961
+ });
962
+ if (properties.spacingBeforePt !== void 0) attributes.push({
963
+ name: ATTR.marginTop,
964
+ value: formatPt(properties.spacingBeforePt)
965
+ });
966
+ if (properties.spacingAfterPt !== void 0) attributes.push({
967
+ name: ATTR.marginBottom,
968
+ value: formatPt(properties.spacingAfterPt)
969
+ });
970
+ if (properties.lineSpacing !== void 0) attributes.push({
971
+ name: ATTR.lineHeight,
972
+ value: formatPercentageMultiplier(properties.lineSpacing)
973
+ });
974
+ if (properties.indentLeftPt !== void 0) attributes.push({
975
+ name: ATTR.marginLeft,
976
+ value: formatPt(properties.indentLeftPt)
977
+ });
978
+ if (properties.indentFirstLinePt !== void 0) attributes.push({
979
+ name: ATTR.textIndent,
980
+ value: formatPt(properties.indentFirstLinePt)
981
+ });
982
+ return attributes;
983
+ }
984
+ //#endregion
985
+ //#region src/styles/serialize.ts
986
+ function attributesToRecord(attributes) {
987
+ const record = {};
988
+ for (const attribute of attributes) record[attribute.name] = attribute.value;
989
+ return record;
990
+ }
991
+ function buildStylePropertyElements(properties) {
992
+ const elements = [];
993
+ const paragraphAttributes = paragraphPropertiesToAttributes(properties);
994
+ if (paragraphAttributes.length > 0) elements.push(el("style:paragraph-properties", attributesToRecord(paragraphAttributes)));
995
+ const textAttributes = textPropertiesToAttributes(properties);
996
+ if (textAttributes.length > 0) elements.push(el("style:text-properties", attributesToRecord(textAttributes)));
997
+ return elements;
998
+ }
999
+ function canonicalPropertiesString(properties) {
1000
+ return [...paragraphPropertiesToAttributes(properties), ...textPropertiesToAttributes(properties)].map((attribute) => `${attribute.name}=${attribute.value}`).join("|");
1001
+ }
1002
+ //#endregion
1003
+ //#region src/styles/registry.ts
1004
+ const STYLE_FAMILIES = [
1005
+ "paragraph",
1006
+ "text",
1007
+ "table",
1008
+ "table-column",
1009
+ "table-row",
1010
+ "table-cell",
1011
+ "graphic"
1012
+ ];
1013
+ function isStyleFamily(value) {
1014
+ return value === "paragraph" || value === "text" || value === "table" || value === "table-column" || value === "table-row" || value === "table-cell" || value === "graphic";
1015
+ }
1016
+ const CONTENT_PREFIXES = {
1017
+ paragraph: "P",
1018
+ text: "T",
1019
+ table: "ta",
1020
+ "table-column": "co",
1021
+ "table-row": "ro",
1022
+ "table-cell": "ce",
1023
+ graphic: "fr"
1024
+ };
1025
+ const STYLES_PREFIXES = {
1026
+ paragraph: "PS",
1027
+ text: "TS",
1028
+ table: "taS",
1029
+ "table-column": "coS",
1030
+ "table-row": "roS",
1031
+ "table-cell": "ceS",
1032
+ graphic: "frS"
1033
+ };
1034
+ function prefixesForPart(partPath) {
1035
+ const baseName = partPath.slice(partPath.lastIndexOf("/") + 1);
1036
+ if (baseName === "content.xml") return CONTENT_PREFIXES;
1037
+ if (baseName === "styles.xml") return STYLES_PREFIXES;
1038
+ throw new Error(`StyleRegistry.forPart: expected a part named "content.xml" or "styles.xml" (by base name), got "${partPath}"`);
1039
+ }
1040
+ function emptyFamilySets() {
1041
+ return {
1042
+ paragraph: /* @__PURE__ */ new Set(),
1043
+ text: /* @__PURE__ */ new Set(),
1044
+ table: /* @__PURE__ */ new Set(),
1045
+ "table-column": /* @__PURE__ */ new Set(),
1046
+ "table-row": /* @__PURE__ */ new Set(),
1047
+ "table-cell": /* @__PURE__ */ new Set(),
1048
+ graphic: /* @__PURE__ */ new Set()
1049
+ };
1050
+ }
1051
+ function attrValue(element, name) {
1052
+ return element.attributes.find((attribute) => attribute.name === name)?.value;
1053
+ }
1054
+ function findDirectChild(nodes, tag) {
1055
+ for (const node of nodes) if (node.type === "element" && node.tag === tag) return node;
1056
+ }
1057
+ function findRootElement(nodes) {
1058
+ const root = nodes.find((node) => node.type === "element");
1059
+ if (root === void 0) throw new Error("StyleRegistry: part has no root XML element -- construct the part's minimal root (office:document-content/office:document-styles) before building a StyleRegistry for it");
1060
+ return root;
1061
+ }
1062
+ function ensureAutomaticStyles(root) {
1063
+ const existing = findDirectChild(root.children, "office:automatic-styles");
1064
+ if (existing !== void 0) return existing;
1065
+ const created = el("office:automatic-styles");
1066
+ const insertBeforeTags = /* @__PURE__ */ new Set([
1067
+ "office:body",
1068
+ "office:master-styles",
1069
+ "office:settings"
1070
+ ]);
1071
+ const insertIndex = root.children.findIndex((node) => node.type === "element" && insertBeforeTags.has(node.tag));
1072
+ if (insertIndex === -1) root.children.push(created);
1073
+ else root.children.splice(insertIndex, 0, created);
1074
+ return created;
1075
+ }
1076
+ function reserveStyleNames(container, reserved) {
1077
+ for (const child of container.children) {
1078
+ if (child.type !== "element" || child.tag !== "style:style") continue;
1079
+ const name = attrValue(child, "style:name");
1080
+ const family = attrValue(child, "style:family");
1081
+ if (name === void 0 || family === void 0 || !isStyleFamily(family)) continue;
1082
+ reserved[family].add(name);
1083
+ }
1084
+ }
1085
+ const FINGERPRINT_SEPARATOR = "\0";
1086
+ const NO_PARENT_SENTINEL = "";
1087
+ function computeFingerprint(family, properties, parentStyleName) {
1088
+ const parentComponent = parentStyleName ?? NO_PARENT_SENTINEL;
1089
+ return [
1090
+ family,
1091
+ canonicalPropertiesString(properties),
1092
+ parentComponent
1093
+ ].join(FINGERPRINT_SEPARATOR);
1094
+ }
1095
+ var StyleRegistry = class StyleRegistry {
1096
+ automaticStyles;
1097
+ prefixes;
1098
+ reservedByFamily;
1099
+ knownStyles = /* @__PURE__ */ new Map();
1100
+ fingerprintToName = /* @__PURE__ */ new Map();
1101
+ nameToFingerprint = /* @__PURE__ */ new Map();
1102
+ familyCounters = {
1103
+ paragraph: 1,
1104
+ text: 1,
1105
+ table: 1,
1106
+ "table-column": 1,
1107
+ "table-row": 1,
1108
+ "table-cell": 1,
1109
+ graphic: 1
1110
+ };
1111
+ constructor(automaticStyles, prefixes, reservedByFamily) {
1112
+ this.automaticStyles = automaticStyles;
1113
+ this.prefixes = prefixes;
1114
+ this.reservedByFamily = reservedByFamily;
1115
+ }
1116
+ static forPart(pkg, partPath, options = {}) {
1117
+ const part = pkg.parts[partPath];
1118
+ if (part?.kind !== "xml") throw new Error(`StyleRegistry.forPart: "${partPath}" is not an XML part of the given package`);
1119
+ const prefixes = prefixesForPart(partPath);
1120
+ const root = findRootElement(part.nodes);
1121
+ const automaticStyles = ensureAutomaticStyles(root);
1122
+ const reservedByFamily = emptyFamilySets();
1123
+ const registry = new StyleRegistry(automaticStyles, prefixes, reservedByFamily);
1124
+ for (const child of automaticStyles.children) {
1125
+ if (child.type !== "element" || child.tag !== "style:style") continue;
1126
+ const name = attrValue(child, "style:name");
1127
+ const family = attrValue(child, "style:family");
1128
+ if (name === void 0 || family === void 0 || !isStyleFamily(family)) continue;
1129
+ registry.knownStyles.set(name, child);
1130
+ reservedByFamily[family].add(name);
1131
+ const parsed = parseStyleElementProperties(child);
1132
+ if (!parsed.hasUnknown) {
1133
+ const parentStyleName = attrValue(child, "style:parent-style-name");
1134
+ const fingerprint = computeFingerprint(family, parsed.properties, parentStyleName);
1135
+ if (!registry.fingerprintToName.has(fingerprint)) {
1136
+ registry.fingerprintToName.set(fingerprint, name);
1137
+ registry.nameToFingerprint.set(name, fingerprint);
1138
+ }
1139
+ }
1140
+ }
1141
+ const ownStyles = findDirectChild(root.children, "office:styles");
1142
+ if (ownStyles !== void 0) reserveStyleNames(ownStyles, reservedByFamily);
1143
+ if (options.otherPart !== void 0) {
1144
+ const otherPart = options.otherPart.pkg.parts[options.otherPart.partPath];
1145
+ if (otherPart?.kind === "xml") {
1146
+ const otherRoot = findRootElement(otherPart.nodes);
1147
+ const otherAutomatic = findDirectChild(otherRoot.children, "office:automatic-styles");
1148
+ if (otherAutomatic !== void 0) reserveStyleNames(otherAutomatic, reservedByFamily);
1149
+ const otherStyles = findDirectChild(otherRoot.children, "office:styles");
1150
+ if (otherStyles !== void 0) reserveStyleNames(otherStyles, reservedByFamily);
1151
+ }
1152
+ }
1153
+ if (options.additionalReservedNames !== void 0) for (const family of STYLE_FAMILIES) for (const name of options.additionalReservedNames) reservedByFamily[family].add(name);
1154
+ return registry;
1155
+ }
1156
+ fingerprint(request) {
1157
+ return computeFingerprint(request.family, request.properties, request.parentStyleName);
1158
+ }
1159
+ intern(request) {
1160
+ const fingerprint = this.fingerprint(request);
1161
+ const existingName = this.fingerprintToName.get(fingerprint);
1162
+ if (existingName !== void 0) return existingName;
1163
+ const name = this.mintName(request.family);
1164
+ const attributes = {
1165
+ "style:name": name,
1166
+ "style:family": request.family
1167
+ };
1168
+ if (request.parentStyleName !== void 0) attributes["style:parent-style-name"] = encodeXmlText(request.parentStyleName);
1169
+ const styleElement = el("style:style", attributes, buildStylePropertyElements(request.properties));
1170
+ this.automaticStyles.children.push(styleElement);
1171
+ this.knownStyles.set(name, styleElement);
1172
+ this.reservedByFamily[request.family].add(name);
1173
+ this.fingerprintToName.set(fingerprint, name);
1174
+ this.nameToFingerprint.set(name, fingerprint);
1175
+ return name;
1176
+ }
1177
+ mintName(family) {
1178
+ const prefix = this.prefixes[family];
1179
+ const reserved = this.reservedByFamily[family];
1180
+ let counter = this.familyCounters[family];
1181
+ while (reserved.has(`${prefix}${counter}`)) counter += 1;
1182
+ const name = `${prefix}${counter}`;
1183
+ this.familyCounters[family] = counter + 1;
1184
+ return name;
1185
+ }
1186
+ names() {
1187
+ return [...this.knownStyles.keys()];
1188
+ }
1189
+ gc(referenced) {
1190
+ let removed = 0;
1191
+ for (const [name, element] of [...this.knownStyles]) {
1192
+ if (referenced.has(name)) continue;
1193
+ const index = this.automaticStyles.children.indexOf(element);
1194
+ if (index !== -1) this.automaticStyles.children.splice(index, 1);
1195
+ this.knownStyles.delete(name);
1196
+ const fingerprint = this.nameToFingerprint.get(name);
1197
+ if (fingerprint !== void 0) {
1198
+ this.fingerprintToName.delete(fingerprint);
1199
+ this.nameToFingerprint.delete(name);
1200
+ }
1201
+ removed += 1;
1202
+ }
1203
+ return removed;
1204
+ }
1205
+ };
1206
+ //#endregion
1207
+ //#region src/styles/span.ts
1208
+ function ensureSpan(paragraph, start, end, styleName) {
1209
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start) throw new Error(`ensureSpan: invalid range [${start}, ${end})`);
1210
+ const total = sumLength(paragraph.children);
1211
+ if (end > total) throw new Error(`ensureSpan: range end ${end} exceeds the container's total character length ${total}`);
1212
+ const { before, after: rest } = splitChildrenAt(paragraph.children, start);
1213
+ const { before: middle, after } = splitChildrenAt(rest, end - start);
1214
+ let span;
1215
+ const soleChild = middle.length === 1 ? middle[0] : void 0;
1216
+ if (soleChild?.type === "element" && soleChild.tag === "text:span") {
1217
+ span = soleChild;
1218
+ setStyleName(span, styleName);
1219
+ } else span = el("text:span", { "text:style-name": encodeXmlText(styleName) }, middle);
1220
+ paragraph.children = [
1221
+ ...before,
1222
+ span,
1223
+ ...after
1224
+ ];
1225
+ return span;
1226
+ }
1227
+ function cloneAttributes(attributes) {
1228
+ return attributes.map((attribute) => ({ ...attribute }));
1229
+ }
1230
+ function setStyleName(span, styleName) {
1231
+ const encoded = encodeXmlText(styleName);
1232
+ const existing = span.attributes.find((attribute) => attribute.name === "text:style-name");
1233
+ if (existing !== void 0) {
1234
+ existing.value = encoded;
1235
+ return;
1236
+ }
1237
+ span.attributes.push({
1238
+ name: "text:style-name",
1239
+ value: encoded
1240
+ });
1241
+ }
1242
+ function getSpaceCount(spaceElement) {
1243
+ const raw = spaceElement.attributes.find((attribute) => attribute.name === "text:c")?.value;
1244
+ if (raw === void 0) return 1;
1245
+ const parsed = Number.parseInt(raw, 10);
1246
+ if (!Number.isInteger(parsed) || parsed < 0 || String(parsed) !== raw) throw new Error(`ensureSpan: text:s has a malformed text:c attribute: "${raw}"`);
1247
+ return parsed;
1248
+ }
1249
+ function buildSpaceRun(count) {
1250
+ return count === 1 ? el("text:s") : el("text:s", { "text:c": String(count) });
1251
+ }
1252
+ function measureLength(node) {
1253
+ if (node.type === "text") return node.value.length;
1254
+ if (node.type !== "element") return 0;
1255
+ if (node.tag === "text:s") return getSpaceCount(node);
1256
+ if (node.tag === "text:tab" || node.tag === "text:line-break") return 1;
1257
+ if (node.tag === "text:span") return sumLength(node.children);
1258
+ return 0;
1259
+ }
1260
+ function sumLength(nodes) {
1261
+ let total = 0;
1262
+ for (const node of nodes) total += measureLength(node);
1263
+ return total;
1264
+ }
1265
+ function splitNode(node, offset) {
1266
+ if (node.type === "text") return {
1267
+ left: {
1268
+ type: "text",
1269
+ value: node.value.slice(0, offset)
1270
+ },
1271
+ right: {
1272
+ type: "text",
1273
+ value: node.value.slice(offset)
1274
+ }
1275
+ };
1276
+ if (node.type === "element" && node.tag === "text:s") {
1277
+ const count = getSpaceCount(node);
1278
+ return {
1279
+ left: buildSpaceRun(offset),
1280
+ right: buildSpaceRun(count - offset)
1281
+ };
1282
+ }
1283
+ if (node.type === "element" && node.tag === "text:span") {
1284
+ const inner = splitChildrenAt(node.children, offset);
1285
+ return {
1286
+ left: inner.before.length === 0 ? void 0 : {
1287
+ ...node,
1288
+ attributes: cloneAttributes(node.attributes),
1289
+ children: inner.before
1290
+ },
1291
+ right: inner.after.length === 0 ? void 0 : {
1292
+ ...node,
1293
+ attributes: cloneAttributes(node.attributes),
1294
+ children: inner.after
1295
+ }
1296
+ };
1297
+ }
1298
+ const label = node.type === "element" ? node.tag : node.type;
1299
+ throw new Error(`ensureSpan: cannot split "${label}" at a fractional offset -- this indicates a character-length computation bug, since every node type with length 1 or 0 should never reach this branch`);
1300
+ }
1301
+ function splitChildrenAt(children, offset) {
1302
+ if (offset <= 0) return {
1303
+ before: [],
1304
+ after: [...children]
1305
+ };
1306
+ const before = [];
1307
+ let remaining = offset;
1308
+ for (let index = 0; index < children.length; index += 1) {
1309
+ if (remaining === 0) return {
1310
+ before,
1311
+ after: children.slice(index)
1312
+ };
1313
+ const node = children[index];
1314
+ const length = measureLength(node);
1315
+ if (remaining >= length) {
1316
+ before.push(node);
1317
+ remaining -= length;
1318
+ continue;
1319
+ }
1320
+ const { left, right } = splitNode(node, remaining);
1321
+ const after = [];
1322
+ if (left !== void 0) before.push(left);
1323
+ if (right !== void 0) after.push(right);
1324
+ after.push(...children.slice(index + 1));
1325
+ return {
1326
+ before,
1327
+ after
1328
+ };
1329
+ }
1330
+ return {
1331
+ before,
1332
+ after: []
1333
+ };
1334
+ }
1335
+ //#endregion
1336
+ export { AttributeSchema, BinaryPartSchema, MANIFEST_PART, MIMETYPE_PART, ManifestEntrySchema, ManifestProblemSchema, ManifestSchema, ODF_MEDIA_TYPES, ODF_NAMESPACES, PackageSchema, PartSchema, STYLE_FAMILIES, StylePropertiesSchema, StyleRegistry, XmlCdataSchema, XmlCommentSchema, XmlDeclarationSchema, XmlElementSchema, XmlNodeSchema, XmlPartSchema, XmlPiSchema, XmlTextSchema, base64ToBytes, buildManifest, buildStylePropertyElements, buildXml, bytesToBase64, canonicalPropertiesString, decodePackage, el, encodePackage, encodeXmlText, ensureSpan, formatPercentageMultiplier, formatPt, isXmlNode, mediaTypeForExtension, packageCodec, paragraphPropertiesToAttributes, parseLength, parsePackage, parseParagraphProperties, parseStyleElementProperties, parseTextProperties, parseXml, readManifest, readMimetype, serializePackage, setDocumentMediaType, sniffImageFormat, syncManifest, textPropertiesToAttributes, txt, unzipPackage, validateManifest, writeManifest, writeMimetype, xmlCodec, xmlnsAttributes, zipPackage };