ooxml.js 2.4.0 → 2.5.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 (138) hide show
  1. package/README.md +40 -2
  2. package/dist/codec.cjs +28 -0
  3. package/dist/codec.d.cts +72 -0
  4. package/dist/codec.d.ts +72 -0
  5. package/dist/codec.js +24 -0
  6. package/dist/compact.cjs +162 -0
  7. package/dist/compact.d.cts +70 -0
  8. package/dist/compact.d.ts +70 -0
  9. package/dist/compact.js +152 -0
  10. package/dist/image/sniff.cjs +28 -0
  11. package/dist/image/sniff.d.cts +5 -0
  12. package/dist/image/sniff.d.ts +5 -0
  13. package/dist/image/sniff.js +27 -0
  14. package/dist/index.cjs +83 -3025
  15. package/dist/index.d.cts +22 -527
  16. package/dist/index.d.ts +22 -527
  17. package/dist/index.js +22 -2964
  18. package/dist/model/node.cjs +67 -0
  19. package/dist/model/node.d.cts +2 -0
  20. package/dist/model/node.d.ts +2 -0
  21. package/dist/model/node.js +58 -0
  22. package/dist/model/package.cjs +19 -0
  23. package/dist/model/package.d.cts +2 -0
  24. package/dist/model/package.d.ts +2 -0
  25. package/dist/model/package.js +15 -0
  26. package/dist/node-CkBWRjNR.d.cts +83 -0
  27. package/dist/node-CkBWRjNR.d.ts +83 -0
  28. package/dist/package-BUojjTXf.d.ts +114 -0
  29. package/dist/package-L24lkba-.d.cts +114 -0
  30. package/dist/package-io/read.cjs +33 -0
  31. package/dist/package-io/read.d.cts +5 -0
  32. package/dist/package-io/read.d.ts +5 -0
  33. package/dist/package-io/read.js +32 -0
  34. package/dist/package-io/write.cjs +18 -0
  35. package/dist/package-io/write.d.cts +5 -0
  36. package/dist/package-io/write.d.ts +5 -0
  37. package/dist/package-io/write.js +17 -0
  38. package/dist/typed/docx/read.cjs +332 -0
  39. package/dist/typed/docx/read.d.cts +52 -0
  40. package/dist/typed/docx/read.d.ts +52 -0
  41. package/dist/typed/docx/read.js +328 -0
  42. package/dist/typed/docx/styles.cjs +148 -0
  43. package/dist/typed/docx/styles.d.cts +29 -0
  44. package/dist/typed/docx/styles.d.ts +29 -0
  45. package/dist/typed/docx/styles.js +146 -0
  46. package/dist/typed/pptx/inherit.cjs +96 -0
  47. package/dist/typed/pptx/inherit.d.cts +30 -0
  48. package/dist/typed/pptx/inherit.d.ts +30 -0
  49. package/dist/typed/pptx/inherit.js +90 -0
  50. package/dist/typed/pptx/read.cjs +364 -0
  51. package/dist/typed/pptx/read.d.cts +44 -0
  52. package/dist/typed/pptx/read.d.ts +44 -0
  53. package/dist/typed/pptx/read.js +362 -0
  54. package/dist/typed/shared/color.cjs +85 -0
  55. package/dist/typed/shared/color.d.cts +9 -0
  56. package/dist/typed/shared/color.d.ts +9 -0
  57. package/dist/typed/shared/color.js +84 -0
  58. package/dist/typed/shared/drawingml.cjs +191 -0
  59. package/dist/typed/shared/drawingml.d.cts +40 -0
  60. package/dist/typed/shared/drawingml.d.ts +40 -0
  61. package/dist/typed/shared/drawingml.js +180 -0
  62. package/dist/typed/shared/metadata.cjs +44 -0
  63. package/dist/typed/shared/metadata.d.cts +16 -0
  64. package/dist/typed/shared/metadata.d.ts +16 -0
  65. package/dist/typed/shared/metadata.js +42 -0
  66. package/dist/typed/shared/source-path.cjs +18 -0
  67. package/dist/typed/shared/source-path.d.cts +5 -0
  68. package/dist/typed/shared/source-path.d.ts +5 -0
  69. package/dist/typed/shared/source-path.js +17 -0
  70. package/dist/typed/shared/units.cjs +55 -0
  71. package/dist/typed/shared/units.d.cts +20 -0
  72. package/dist/typed/shared/units.d.ts +20 -0
  73. package/dist/typed/shared/units.js +38 -0
  74. package/dist/typed/util.cjs +85 -0
  75. package/dist/typed/util.d.cts +18 -0
  76. package/dist/typed/util.d.ts +18 -0
  77. package/dist/typed/util.js +77 -0
  78. package/dist/typed/xlsx/a1.cjs +64 -0
  79. package/dist/typed/xlsx/a1.d.cts +19 -0
  80. package/dist/typed/xlsx/a1.d.ts +19 -0
  81. package/dist/typed/xlsx/a1.js +58 -0
  82. package/dist/typed/xlsx/build.cjs +456 -0
  83. package/dist/typed/xlsx/build.d.cts +6 -0
  84. package/dist/typed/xlsx/build.d.ts +6 -0
  85. package/dist/typed/xlsx/build.js +455 -0
  86. package/dist/typed/xlsx/content.cjs +257 -0
  87. package/dist/typed/xlsx/content.d.cts +6 -0
  88. package/dist/typed/xlsx/content.d.ts +6 -0
  89. package/dist/typed/xlsx/content.js +256 -0
  90. package/dist/typed/xlsx/defined-names.cjs +90 -0
  91. package/dist/typed/xlsx/defined-names.d.cts +20 -0
  92. package/dist/typed/xlsx/defined-names.d.ts +20 -0
  93. package/dist/typed/xlsx/defined-names.js +83 -0
  94. package/dist/typed/xlsx/print-settings.cjs +116 -0
  95. package/dist/typed/xlsx/print-settings.d.cts +8 -0
  96. package/dist/typed/xlsx/print-settings.d.ts +8 -0
  97. package/dist/typed/xlsx/print-settings.js +114 -0
  98. package/dist/typed/xlsx/shared-strings.cjs +35 -0
  99. package/dist/typed/xlsx/shared-strings.d.cts +12 -0
  100. package/dist/typed/xlsx/shared-strings.d.ts +12 -0
  101. package/dist/typed/xlsx/shared-strings.js +33 -0
  102. package/dist/typed/xlsx/units.cjs +21 -0
  103. package/dist/typed/xlsx/units.d.cts +8 -0
  104. package/dist/typed/xlsx/units.d.ts +8 -0
  105. package/dist/typed/xlsx/units.js +16 -0
  106. package/dist/typed/xlsx/util.cjs +53 -0
  107. package/dist/typed/xlsx/util.d.cts +10 -0
  108. package/dist/typed/xlsx/util.d.ts +10 -0
  109. package/dist/typed/xlsx/util.js +47 -0
  110. package/dist/typed/xlsx.cjs +140 -0
  111. package/dist/typed/xlsx.d.cts +43 -0
  112. package/dist/typed/xlsx.d.ts +43 -0
  113. package/dist/typed/xlsx.js +135 -0
  114. package/dist/util/base64.cjs +48 -0
  115. package/dist/util/base64.d.cts +5 -0
  116. package/dist/util/base64.d.ts +5 -0
  117. package/dist/util/base64.js +46 -0
  118. package/dist/xml/build.cjs +46 -0
  119. package/dist/xml/build.d.cts +5 -0
  120. package/dist/xml/build.d.ts +5 -0
  121. package/dist/xml/build.js +46 -0
  122. package/dist/xml/entities.cjs +7 -0
  123. package/dist/xml/entities.d.cts +4 -0
  124. package/dist/xml/entities.d.ts +4 -0
  125. package/dist/xml/entities.js +6 -0
  126. package/dist/xml/fragment.cjs +22 -0
  127. package/dist/xml/fragment.d.cts +6 -0
  128. package/dist/xml/fragment.d.ts +6 -0
  129. package/dist/xml/fragment.js +20 -0
  130. package/dist/xml/parse.cjs +88 -0
  131. package/dist/xml/parse.d.cts +5 -0
  132. package/dist/xml/parse.d.ts +5 -0
  133. package/dist/xml/parse.js +88 -0
  134. package/dist/zip.cjs +12 -0
  135. package/dist/zip.d.cts +5 -0
  136. package/dist/zip.d.ts +5 -0
  137. package/dist/zip.js +10 -0
  138. package/package.json +9 -1
package/dist/index.cjs CHANGED
@@ -1,2976 +1,34 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- let zod = require("zod");
3
- let fast_xml_parser = require("fast-xml-parser");
4
- let fflate = require("fflate");
2
+ const require_model_node = require("./model/node.cjs");
3
+ const require_model_package = require("./model/package.cjs");
4
+ const require_util_base64 = require("./util/base64.cjs");
5
+ const require_xml_parse = require("./xml/parse.cjs");
6
+ const require_zip = require("./zip.cjs");
7
+ const require_package_io_read = require("./package-io/read.cjs");
8
+ const require_xml_build = require("./xml/build.cjs");
9
+ const require_package_io_write = require("./package-io/write.cjs");
10
+ const require_codec = require("./codec.cjs");
11
+ const require_compact = require("./compact.cjs");
12
+ const require_xml_fragment = require("./xml/fragment.cjs");
13
+ const require_xml_entities = require("./xml/entities.cjs");
14
+ const require_typed_util = require("./typed/util.cjs");
15
+ const require_typed_shared_color = require("./typed/shared/color.cjs");
16
+ const require_typed_shared_metadata = require("./typed/shared/metadata.cjs");
17
+ const require_image_sniff = require("./image/sniff.cjs");
18
+ const require_typed_docx_read = require("./typed/docx/read.cjs");
19
+ const require_typed_pptx_read = require("./typed/pptx/read.cjs");
20
+ const require_typed_xlsx = require("./typed/xlsx.cjs");
21
+ const require_typed_xlsx_content = require("./typed/xlsx/content.cjs");
22
+ const require_typed_xlsx_build = require("./typed/xlsx/build.cjs");
5
23
  let document_schema_js = require("document-schema.js");
6
- //#region src/model/node.ts
7
- const AttributeSchema = zod.z.object({
8
- name: zod.z.string(),
9
- value: zod.z.string()
10
- });
11
- const XmlTextSchema = zod.z.object({
12
- type: zod.z.literal("text"),
13
- value: zod.z.string()
14
- });
15
- const XmlCdataSchema = zod.z.object({
16
- type: zod.z.literal("cdata"),
17
- value: zod.z.string()
18
- });
19
- const XmlCommentSchema = zod.z.object({
20
- type: zod.z.literal("comment"),
21
- value: zod.z.string()
22
- });
23
- const XmlDeclarationSchema = zod.z.object({
24
- type: zod.z.literal("declaration"),
25
- attributes: zod.z.array(AttributeSchema)
26
- });
27
- const XmlPiSchema = zod.z.object({
28
- type: zod.z.literal("pi"),
29
- target: zod.z.string(),
30
- content: zod.z.string()
31
- });
32
- function isRecord$1(value) {
33
- return typeof value === "object" && value !== null && !Array.isArray(value);
34
- }
35
- function isAttribute(value) {
36
- return isRecord$1(value) && typeof value.name === "string" && typeof value.value === "string";
37
- }
38
- function isXmlNode(value) {
39
- if (!isRecord$1(value)) return false;
40
- const t = value.type;
41
- if (t === "text" || t === "cdata" || t === "comment") return typeof value.value === "string";
42
- if (t === "declaration") return Array.isArray(value.attributes) && value.attributes.every(isAttribute);
43
- if (t === "pi") return typeof value.target === "string" && typeof value.content === "string";
44
- if (t === "element") return typeof value.tag === "string" && Array.isArray(value.attributes) && value.attributes.every(isAttribute) && Array.isArray(value.children) && value.children.every(isXmlNode);
45
- return false;
46
- }
47
- const XmlElementSchema = zod.z.object({
48
- type: zod.z.literal("element"),
49
- tag: zod.z.string(),
50
- attributes: zod.z.array(AttributeSchema),
51
- children: zod.z.array(zod.z.custom(isXmlNode))
52
- });
53
- const XmlNodeSchema = zod.z.discriminatedUnion("type", [
54
- XmlTextSchema,
55
- XmlCdataSchema,
56
- XmlCommentSchema,
57
- XmlDeclarationSchema,
58
- XmlPiSchema,
59
- XmlElementSchema
60
- ]);
61
- //#endregion
62
- //#region src/model/package.ts
63
- const XmlPartSchema = zod.z.object({
64
- kind: zod.z.literal("xml"),
65
- nodes: zod.z.array(XmlNodeSchema)
66
- });
67
- const BinaryPartSchema = zod.z.object({
68
- kind: zod.z.literal("binary"),
69
- base64: zod.z.string()
70
- });
71
- const PartSchema = zod.z.discriminatedUnion("kind", [XmlPartSchema, BinaryPartSchema]);
72
- const PackageSchema = zod.z.object({ parts: zod.z.record(zod.z.string(), PartSchema) });
73
- //#endregion
74
- //#region src/util/base64.ts
75
- const TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
76
- const DECODE = (() => {
77
- const map = (/* @__PURE__ */ new Uint8Array(256)).fill(255);
78
- for (let i = 0; i < 64; i = i + 1) map[TABLE.charCodeAt(i)] = i;
79
- return map;
80
- })();
81
- function bytesToBase64(bytes) {
82
- let out = "";
83
- const len = bytes.length;
84
- for (let i = 0; i < len; i = i + 3) {
85
- const b0 = bytes[i];
86
- const b1 = i + 1 < len ? bytes[i + 1] : 0;
87
- const b2 = i + 2 < len ? bytes[i + 2] : 0;
88
- out += TABLE[b0 >> 2];
89
- out += TABLE[(b0 & 3) << 4 | b1 >> 4];
90
- out += i + 1 < len ? TABLE[(b1 & 15) << 2 | b2 >> 6] : "=";
91
- out += i + 2 < len ? TABLE[b2 & 63] : "=";
92
- }
93
- return out;
94
- }
95
- function base64ToBytes(b64) {
96
- const clean = b64.replace(/[^A-Za-z0-9+/=]/g, "");
97
- const len = clean.length;
98
- const out = new Uint8Array(len * 3 / 4 | 0);
99
- let p = 0;
100
- for (let i = 0; i < len; i = i + 4) {
101
- const c0 = DECODE[clean.charCodeAt(i)];
102
- const c1 = DECODE[clean.charCodeAt(i + 1)];
103
- const c2 = clean.charCodeAt(i + 2);
104
- const c3 = clean.charCodeAt(i + 3);
105
- if (c0 === 255 || c1 === 255) throw new Error("invalid base64 input");
106
- out[p++] = c0 << 2 | c1 >> 4;
107
- if (c2 !== 61) {
108
- const d2 = DECODE[c2];
109
- out[p++] = (c1 & 15) << 4 | d2 >> 2;
110
- if (c3 !== 61) {
111
- const d3 = DECODE[c3];
112
- out[p++] = (d2 & 3) << 6 | d3;
113
- }
114
- }
115
- }
116
- return out.subarray(0, p);
117
- }
118
- //#endregion
119
- //#region src/xml/parse.ts
120
- const PARSER = new fast_xml_parser.XMLParser({
121
- preserveOrder: true,
122
- attributeNamePrefix: "@_",
123
- ignoreAttributes: false,
124
- textNodeName: "#text",
125
- cdataPropName: "__cdata",
126
- commentPropName: "__comment",
127
- processEntities: false,
128
- parseTagValue: false,
129
- trimValues: false
130
- });
131
- function parseXml(xml) {
132
- return parseNodes(PARSER.parse(xml));
133
- }
134
- function isRecord(value) {
135
- return typeof value === "object" && value !== null && !Array.isArray(value);
136
- }
137
- function isUnknownArray$1(value) {
138
- return Array.isArray(value);
139
- }
140
- function asString(value) {
141
- if (typeof value !== "string") throw new Error(`expected string while parsing XML, got ${typeof value}`);
142
- return value;
143
- }
144
- function parseNodes(raw) {
145
- if (!isUnknownArray$1(raw)) throw new Error("fast-xml-parser output was not an ordered array");
146
- return raw.map(parseNode);
147
- }
148
- function parseNode(raw) {
149
- if (!isRecord(raw)) throw new Error("fast-xml-parser node was not an object");
150
- let tagKey;
151
- for (const key of Object.keys(raw)) if (key !== ":@") {
152
- if (tagKey !== void 0) throw new Error("XML node had multiple tag keys");
153
- tagKey = key;
154
- }
155
- if (tagKey === void 0) throw new Error("XML node had no tag key");
156
- const attributes = parseAttributes(raw[":@"]);
157
- if (tagKey === "#text") return {
158
- type: "text",
159
- value: asString(raw["#text"])
160
- };
161
- if (tagKey === "__comment") return {
162
- type: "comment",
163
- value: scalarText(raw.__comment)
164
- };
165
- if (tagKey === "__cdata") return {
166
- type: "cdata",
167
- value: scalarText(raw.__cdata)
168
- };
169
- if (tagKey === "?xml") return {
170
- type: "declaration",
171
- attributes
172
- };
173
- if (tagKey.startsWith("?")) return {
174
- type: "pi",
175
- target: tagKey.slice(1),
176
- content: scalarText(raw[tagKey])
177
- };
178
- return {
179
- type: "element",
180
- tag: tagKey,
181
- attributes,
182
- children: parseNodes(raw[tagKey])
183
- };
184
- }
185
- function parseAttributes(raw) {
186
- if (raw === void 0) return [];
187
- if (!isRecord(raw)) throw new Error("XML attributes were not an object");
188
- const attrs = [];
189
- for (const key of Object.keys(raw)) {
190
- if (!key.startsWith("@_")) throw new Error(`unexpected attribute key without @_ prefix: ${key}`);
191
- attrs.push({
192
- name: key.slice(2),
193
- value: asString(raw[key])
194
- });
195
- }
196
- return attrs;
197
- }
198
- function scalarText(raw) {
199
- if (!isUnknownArray$1(raw) || raw.length === 0) throw new Error("expected a scalar-text wrapper array");
200
- const first = raw[0];
201
- if (!isRecord(first)) throw new Error("scalar-text wrapper was not an object");
202
- return asString(first["#text"]);
203
- }
204
- //#endregion
205
- //#region src/zip.ts
206
- function unzipPackage(bytes) {
207
- return (0, fflate.unzipSync)(bytes);
208
- }
209
- function zipPackage(parts) {
210
- return (0, fflate.zipSync)(parts);
211
- }
212
- //#endregion
213
- //#region src/package-io/read.ts
214
- function parsePackage(bytes) {
215
- const entries = unzipPackage(bytes);
216
- const parts = {};
217
- for (const [path, partBytes] of Object.entries(entries)) if (looksLikeXml(partBytes)) parts[path] = {
218
- kind: "xml",
219
- nodes: parseXml(new TextDecoder("utf-8").decode(partBytes))
220
- };
221
- else parts[path] = {
222
- kind: "binary",
223
- base64: bytesToBase64(partBytes)
224
- };
225
- return { parts };
226
- }
227
- function looksLikeXml(bytes) {
228
- let i = 0;
229
- if (bytes.length >= 3 && bytes[0] === 239 && bytes[1] === 187 && bytes[2] === 191) i = 3;
230
- while (i < bytes.length) {
231
- const b = bytes[i];
232
- if (b === 32 || b === 9 || b === 10 || b === 13) {
233
- i = i + 1;
234
- continue;
235
- }
236
- return b === 60;
237
- }
238
- return false;
239
- }
240
- //#endregion
241
- //#region src/xml/build.ts
242
- const BUILDER = new fast_xml_parser.XMLBuilder({
243
- preserveOrder: true,
244
- attributeNamePrefix: "@_",
245
- ignoreAttributes: false,
246
- textNodeName: "#text",
247
- cdataPropName: "__cdata",
248
- commentPropName: "__comment",
249
- processEntities: false,
250
- format: false,
251
- suppressEmptyNode: false
252
- });
253
- function buildXml(nodes) {
254
- const out = BUILDER.build(toOrdered(nodes));
255
- if (typeof out !== "string") throw new Error("XMLBuilder did not return a string");
256
- return out;
257
- }
258
- function toOrdered(nodes) {
259
- return nodes.map(toOrderedNode);
260
- }
261
- function attrsObject(attributes) {
262
- const obj = {};
263
- for (const a of attributes) obj[`@_${a.name}`] = a.value;
264
- return obj;
265
- }
266
- function toOrderedNode(node) {
267
- switch (node.type) {
268
- case "text": return { "#text": node.value };
269
- case "comment": return { __comment: [{ "#text": node.value }] };
270
- case "cdata": return { __cdata: [{ "#text": node.value }] };
271
- case "pi": return { [`?${node.target}`]: [{ "#text": node.content }] };
272
- case "declaration": return {
273
- "?xml": [{ "#text": "" }],
274
- ":@": attrsObject(node.attributes)
275
- };
276
- case "element": {
277
- const obj = { [node.tag]: toOrdered(node.children) };
278
- const attrs = attrsObject(node.attributes);
279
- if (Object.keys(attrs).length > 0) obj[":@"] = attrs;
280
- return obj;
281
- }
282
- }
283
- }
284
- //#endregion
285
- //#region src/package-io/write.ts
286
- function serializePackage(pkg) {
287
- const entries = {};
288
- for (const [path, part] of Object.entries(pkg.parts)) entries[path] = partToBytes(part);
289
- return zipPackage(entries);
290
- }
291
- function partToBytes(part) {
292
- switch (part.kind) {
293
- case "xml": return new TextEncoder().encode(buildXml(part.nodes));
294
- case "binary": return base64ToBytes(part.base64);
295
- }
296
- }
297
- //#endregion
298
- //#region src/codec.ts
299
- const xmlCodec = zod.z.codec(zod.z.string(), zod.z.array(XmlNodeSchema), {
300
- decode: (xml) => parseXml(xml),
301
- encode: (nodes) => buildXml(nodes)
302
- });
303
- const packageCodec = zod.z.codec(zod.z.instanceof(Uint8Array), PackageSchema, {
304
- decode: (bytes) => parsePackage(bytes),
305
- encode: (pkg) => serializePackage(pkg)
306
- });
307
- function decodePackage(bytes) {
308
- return zod.z.decode(packageCodec, bytes);
309
- }
310
- function encodePackage(pkg) {
311
- return zod.z.encode(packageCodec, pkg);
312
- }
313
- //#endregion
314
- //#region src/xml/fragment.ts
315
- function el(tag, attrs = {}, children = []) {
316
- return {
317
- type: "element",
318
- tag,
319
- attributes: Object.entries(attrs).map(([name, value]) => ({
320
- name,
321
- value
322
- })),
323
- children
324
- };
325
- }
326
- function txt(value) {
327
- return {
328
- type: "text",
329
- value
330
- };
331
- }
332
- //#endregion
333
- //#region src/xml/entities.ts
334
- function encodeXmlText(value) {
335
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
336
- }
337
- //#endregion
338
- //#region src/typed/util.ts
339
- function* walk(nodes) {
340
- for (const node of nodes) {
341
- yield node;
342
- if (node.type === "element") yield* walk(node.children);
343
- }
344
- }
345
- function elementsWithTag(nodes, tag) {
346
- const out = [];
347
- for (const node of walk(nodes)) if (node.type === "element" && node.tag === tag) out.push(node);
348
- return out;
349
- }
350
- function childrenWithTag(element, tag) {
351
- const out = [];
352
- for (const child of element.children) if (child.type === "element" && child.tag === tag) out.push(child);
353
- return out;
354
- }
355
- function attr(element, name) {
356
- for (const a of element.attributes) if (a.name === name) return a.value;
357
- }
358
- function rootElement(part) {
359
- if (part?.kind !== "xml") return;
360
- for (const node of part.nodes) if (node.type === "element") return node;
361
- }
362
- function decodeEntities(value) {
363
- return value.replace(/&(?:amp|lt|gt|quot|apos);/g, (entity) => {
364
- switch (entity) {
365
- case "&amp;": return "&";
366
- case "&lt;": return "<";
367
- case "&gt;": return ">";
368
- case "&quot;": return "\"";
369
- case "&apos;": return "'";
370
- default: return entity;
371
- }
372
- });
373
- }
374
- function textContent(element) {
375
- let text = "";
376
- for (const node of walk(element.children)) if (node.type === "text" || node.type === "cdata") text += node.value;
377
- return decodeEntities(text);
378
- }
379
- function relsPathFor(partPath) {
380
- const lastSlash = partPath.lastIndexOf("/");
381
- return `${lastSlash === -1 ? "" : partPath.slice(0, lastSlash)}/_rels/${lastSlash === -1 ? partPath : partPath.slice(lastSlash + 1)}.rels`;
382
- }
383
- function resolveRelTarget$1(partPath, target) {
384
- if (target.startsWith("/")) return target.slice(1);
385
- const lastSlash = partPath.lastIndexOf("/");
386
- const baseDir = lastSlash === -1 ? "" : partPath.slice(0, lastSlash);
387
- const resolved = [];
388
- for (const segment of `${baseDir}/${target}`.split("/")) {
389
- if (segment === "" || segment === ".") continue;
390
- if (segment === "..") resolved.pop();
391
- else resolved.push(segment);
392
- }
393
- return resolved.join("/");
394
- }
395
- function resolveRelationships(pkg, partPath) {
396
- const map = /* @__PURE__ */ new Map();
397
- const rels = rootElement(pkg.parts[relsPathFor(partPath)]);
398
- if (rels === void 0) return map;
399
- for (const rel of childrenWithTag(rels, "Relationship")) {
400
- const id = attr(rel, "Id");
401
- const type = attr(rel, "Type");
402
- const target = attr(rel, "Target");
403
- if (id === void 0 || type === void 0 || target === void 0) continue;
404
- const targetMode = attr(rel, "TargetMode");
405
- map.set(id, {
406
- type,
407
- target: targetMode === "External" ? target : resolveRelTarget$1(partPath, target),
408
- targetMode
409
- });
410
- }
411
- return map;
412
- }
413
- //#endregion
414
- //#region src/compact.ts
415
- function isUnknownArray(value) {
416
- return Array.isArray(value);
417
- }
418
- function isCompactAttrPairs(value) {
419
- return isUnknownArray(value) && value.every((v) => typeof v === "number");
420
- }
421
- function isCompactXmlNode(value) {
422
- if (!isUnknownArray(value)) return false;
423
- const code = value[0];
424
- if (code === 1 || code === 2 || code === 3) return value.length === 2 && typeof value[1] === "number";
425
- if (code === 4) return value.length === 2 && isCompactAttrPairs(value[1]);
426
- if (code === 5) return value.length === 3 && typeof value[1] === "number" && typeof value[2] === "number";
427
- if (code === 0) return value.length === 4 && typeof value[1] === "number" && isCompactAttrPairs(value[2]) && Array.isArray(value[3]) && value[3].every(isCompactXmlNode);
428
- return false;
429
- }
430
- const CompactXmlNodeSchema = zod.z.custom(isCompactXmlNode);
431
- const CompactPartSchema = zod.z.union([zod.z.array(CompactXmlNodeSchema), zod.z.number()]);
432
- const CompactPackageSchema = zod.z.object({
433
- s: zod.z.array(zod.z.string()),
434
- p: zod.z.record(zod.z.string(), CompactPartSchema)
435
- });
436
- var StringTable = class {
437
- indices = /* @__PURE__ */ new Map();
438
- strings = [];
439
- intern(value) {
440
- const existing = this.indices.get(value);
441
- if (existing !== void 0) return existing;
442
- const index = this.strings.length;
443
- this.indices.set(value, index);
444
- this.strings.push(value);
445
- return index;
446
- }
447
- };
448
- function encodeAttrs(attributes, table) {
449
- const pairs = [];
450
- for (const attribute of attributes) pairs.push(table.intern(attribute.name), table.intern(attribute.value));
451
- return pairs;
452
- }
453
- function encodeNode(node, table) {
454
- switch (node.type) {
455
- case "text": return [1, table.intern(node.value)];
456
- case "cdata": return [2, table.intern(node.value)];
457
- case "comment": return [3, table.intern(node.value)];
458
- case "declaration": return [4, encodeAttrs(node.attributes, table)];
459
- case "pi": return [
460
- 5,
461
- table.intern(node.target),
462
- table.intern(node.content)
463
- ];
464
- case "element": return [
465
- 0,
466
- table.intern(node.tag),
467
- encodeAttrs(node.attributes, table),
468
- node.children.map((child) => encodeNode(child, table))
469
- ];
470
- }
471
- }
472
- function packageToCompact(pkg) {
473
- const table = new StringTable();
474
- const p = {};
475
- for (const [path, part] of Object.entries(pkg.parts)) p[path] = part.kind === "binary" ? table.intern(part.base64) : part.nodes.map((node) => encodeNode(node, table));
476
- return {
477
- s: table.strings,
478
- p
479
- };
480
- }
481
- function stringAt(strings, index) {
482
- const value = strings[index];
483
- if (value === void 0) throw new Error(`fromCompact: string table index ${index} is out of range`);
484
- return value;
485
- }
486
- function decodeAttrs(pairs, strings) {
487
- const attributes = [];
488
- for (let i = 0; i < pairs.length; i += 2) {
489
- const nameIdx = pairs[i];
490
- const valueIdx = pairs[i + 1];
491
- if (nameIdx === void 0 || valueIdx === void 0) throw new Error("fromCompact: attribute index pairs array has odd length");
492
- attributes.push({
493
- name: stringAt(strings, nameIdx),
494
- value: stringAt(strings, valueIdx)
495
- });
496
- }
497
- return attributes;
498
- }
499
- function decodeNode(node, strings) {
500
- switch (node[0]) {
501
- case 1: return {
502
- type: "text",
503
- value: stringAt(strings, node[1])
504
- };
505
- case 2: return {
506
- type: "cdata",
507
- value: stringAt(strings, node[1])
508
- };
509
- case 3: return {
510
- type: "comment",
511
- value: stringAt(strings, node[1])
512
- };
513
- case 4: return {
514
- type: "declaration",
515
- attributes: decodeAttrs(node[1], strings)
516
- };
517
- case 5: return {
518
- type: "pi",
519
- target: stringAt(strings, node[1]),
520
- content: stringAt(strings, node[2])
521
- };
522
- case 0: return {
523
- type: "element",
524
- tag: stringAt(strings, node[1]),
525
- attributes: decodeAttrs(node[2], strings),
526
- children: node[3].map((child) => decodeNode(child, strings))
527
- };
528
- }
529
- }
530
- function compactToPackage(cpkg) {
531
- const parts = {};
532
- for (const [path, part] of Object.entries(cpkg.p)) parts[path] = typeof part === "number" ? {
533
- kind: "binary",
534
- base64: stringAt(cpkg.s, part)
535
- } : {
536
- kind: "xml",
537
- nodes: part.map((node) => decodeNode(node, cpkg.s))
538
- };
539
- return { parts };
540
- }
541
- const compactCodec = zod.z.codec(PackageSchema, CompactPackageSchema, {
542
- decode: (pkg) => packageToCompact(pkg),
543
- encode: (cpkg) => compactToPackage(cpkg)
544
- });
545
- function toCompact(pkg) {
546
- return zod.z.decode(compactCodec, pkg);
547
- }
548
- function fromCompact(cpkg) {
549
- return zod.z.encode(compactCodec, cpkg);
550
- }
551
- const compactPackageCodec = zod.z.codec(zod.z.instanceof(Uint8Array), CompactPackageSchema, {
552
- decode: (bytes) => toCompact(decodePackage(bytes)),
553
- encode: (cpkg) => encodePackage(fromCompact(cpkg))
554
- });
555
- function decodeCompactPackage(bytes) {
556
- return zod.z.decode(compactPackageCodec, bytes);
557
- }
558
- function encodeCompactPackage(cpkg) {
559
- return zod.z.encode(compactPackageCodec, cpkg);
560
- }
561
- //#endregion
562
- //#region src/typed/shared/color.ts
563
- const OOXML_PERCENT_SCALE = 1e5;
564
- function clamp01(x) {
565
- return Math.max(0, Math.min(1, x));
566
- }
567
- function srgbToLinear(c) {
568
- return c <= .04045 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
569
- }
570
- function linearToSrgb(c) {
571
- return c <= .0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - .055;
572
- }
573
- function applyShadeOrTint(color, kind, value) {
574
- const pct = value / OOXML_PERCENT_SCALE;
575
- const transform = kind === "shade" ? (linear) => linear * pct : (linear) => 1 - (1 - linear) * pct;
576
- return {
577
- r: clamp01(linearToSrgb(transform(srgbToLinear(color.r)))),
578
- g: clamp01(linearToSrgb(transform(srgbToLinear(color.g)))),
579
- b: clamp01(linearToSrgb(transform(srgbToLinear(color.b))))
580
- };
581
- }
582
- function rgbToHsl(color) {
583
- const { r, g, b } = color;
584
- const max = Math.max(r, g, b);
585
- const min = Math.min(r, g, b);
586
- const l = (max + min) / 2;
587
- if (max === min) return {
588
- h: 0,
589
- s: 0,
590
- l
591
- };
592
- const d = max - min;
593
- const s = l > .5 ? d / (2 - max - min) : d / (max + min);
594
- let h;
595
- if (max === r) h = (g - b) / d + (g < b ? 6 : 0);
596
- else if (max === g) h = (b - r) / d + 2;
597
- else h = (r - g) / d + 4;
598
- return {
599
- h: h * 60,
600
- s,
601
- l
602
- };
603
- }
604
- function hueToRgbComponent(p, q, hue) {
605
- let t = hue;
606
- if (t < 0) t += 1;
607
- if (t > 1) t -= 1;
608
- if (t < 1 / 6) return p + (q - p) * 6 * t;
609
- if (t < 1 / 2) return q;
610
- if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
611
- return p;
612
- }
613
- function hslToRgb(hsl) {
614
- const { h, s, l } = hsl;
615
- if (s === 0) return {
616
- r: l,
617
- g: l,
618
- b: l
619
- };
620
- const q = l < .5 ? l * (1 + s) : l + s - l * s;
621
- const p = 2 * l - q;
622
- const hk = h / 360;
623
- return {
624
- r: clamp01(hueToRgbComponent(p, q, hk + 1 / 3)),
625
- g: clamp01(hueToRgbComponent(p, q, hk)),
626
- b: clamp01(hueToRgbComponent(p, q, hk - 1 / 3))
627
- };
628
- }
629
- function applyLumModOrOff(color, kind, value) {
630
- const hsl = rgbToHsl(color);
631
- const pct = value / OOXML_PERCENT_SCALE;
632
- const l = clamp01(kind === "lumMod" ? hsl.l * pct : hsl.l + pct);
633
- return hslToRgb({
634
- ...hsl,
635
- l
636
- });
637
- }
638
- function applyColorTransforms(base, transforms) {
639
- let color = base;
640
- for (const t of transforms) if (t.kind === "shade" || t.kind === "tint") color = applyShadeOrTint(color, t.kind, t.value);
641
- for (const t of transforms) if (t.kind === "lumMod" || t.kind === "lumOff") color = applyLumModOrOff(color, t.kind, t.value);
642
- return color;
643
- }
644
- //#endregion
645
- //#region src/typed/shared/metadata.ts
646
- const DocumentMetadataSchema = zod.z.object({
647
- title: zod.z.string().optional(),
648
- author: zod.z.string().optional(),
649
- subject: zod.z.string().optional(),
650
- keywords: zod.z.array(zod.z.string()).optional(),
651
- creator: zod.z.string().optional(),
652
- createdIso: zod.z.string().optional(),
653
- modifiedIso: zod.z.string().optional()
654
- });
655
- const CORE_PROPERTIES_PATH = "docProps/core.xml";
656
- const APP_PROPERTIES_PATH = "docProps/app.xml";
657
- function firstElementText(root, tag) {
658
- if (root === void 0) return;
659
- const element = childrenWithTag(root, tag)[0];
660
- if (element === void 0) return;
661
- const text = textContent(element);
662
- return text.length > 0 ? text : void 0;
663
- }
664
- function readKeywords(core) {
665
- const raw = firstElementText(core, "cp:keywords");
666
- if (raw === void 0) return;
667
- const parts = raw.split(",").map((part) => part.trim()).filter((part) => part.length > 0);
668
- return parts.length > 0 ? parts : void 0;
669
- }
670
- function readCoreProperties(pkg) {
671
- const core = rootElement(pkg.parts[CORE_PROPERTIES_PATH]);
672
- const app = rootElement(pkg.parts[APP_PROPERTIES_PATH]);
673
- return {
674
- title: firstElementText(core, "dc:title"),
675
- author: firstElementText(core, "dc:creator"),
676
- subject: firstElementText(core, "dc:subject"),
677
- keywords: readKeywords(core),
678
- creator: firstElementText(app, "Application"),
679
- createdIso: firstElementText(core, "dcterms:created"),
680
- modifiedIso: firstElementText(core, "dcterms:modified")
681
- };
682
- }
683
- //#endregion
684
- //#region src/image/sniff.ts
685
- const PNG_SIGNATURE = [
686
- 137,
687
- 80,
688
- 78,
689
- 71,
690
- 13,
691
- 10,
692
- 26,
693
- 10
694
- ];
695
- const JPEG_SIGNATURE = [
696
- 255,
697
- 216,
698
- 255
699
- ];
700
- function startsWith(bytes, signature) {
701
- if (bytes.length < signature.length) return false;
702
- for (let i = 0; i < signature.length; i++) if (bytes[i] !== signature[i]) return false;
703
- return true;
704
- }
705
- function sniffImageFormat(bytes) {
706
- if (startsWith(bytes, PNG_SIGNATURE)) return "png";
707
- if (startsWith(bytes, JPEG_SIGNATURE)) return "jpeg";
708
- }
709
- const EMU_PER_POINT = 914400 / 72;
710
- function emuToPt(emu) {
711
- return emu / EMU_PER_POINT;
712
- }
713
- function twipsToPt(twips) {
714
- return twips / 20;
715
- }
716
- function halfPointsToPt(halfPoints) {
717
- return halfPoints / 2;
718
- }
719
- function drawingMlFontSizeToPt(hundredths) {
720
- return hundredths / 100;
721
- }
722
- function lineUnitsToMultiplier(lineUnits) {
723
- return lineUnits / 240;
724
- }
725
- //#endregion
726
- //#region src/typed/shared/drawingml.ts
727
- const ROTATION_UNITS_PER_DEGREE = 6e4;
728
- function readXfrm(xfrm) {
729
- if (xfrm === void 0) return;
730
- const off = childrenWithTag(xfrm, "a:off")[0];
731
- const ext = childrenWithTag(xfrm, "a:ext")[0];
732
- if (off === void 0 || ext === void 0) return;
733
- const x = attr(off, "x");
734
- const y = attr(off, "y");
735
- const cx = attr(ext, "cx");
736
- const cy = attr(ext, "cy");
737
- if (x === void 0 || y === void 0 || cx === void 0 || cy === void 0) return;
738
- const rot = attr(xfrm, "rot");
739
- return {
740
- xPt: emuToPt(Number(x)),
741
- yPt: emuToPt(Number(y)),
742
- widthPt: emuToPt(Number(cx)),
743
- heightPt: emuToPt(Number(cy)),
744
- rotationDeg: rot === void 0 ? 0 : Number(rot) / ROTATION_UNITS_PER_DEGREE,
745
- flipH: attr(xfrm, "flipH") === "1",
746
- flipV: attr(xfrm, "flipV") === "1"
747
- };
748
- }
749
- const CLR_SCHEME_SLOTS = [
750
- "dk1",
751
- "lt1",
752
- "dk2",
753
- "lt2",
754
- "accent1",
755
- "accent2",
756
- "accent3",
757
- "accent4",
758
- "accent5",
759
- "accent6",
760
- "hlink",
761
- "folHlink"
762
- ];
763
- function readThemeSlotColor(colorEl) {
764
- if (colorEl.tag === "a:srgbClr") {
765
- const val = attr(colorEl, "val");
766
- return val === void 0 ? void 0 : (0, document_schema_js.rgbHexToColor)(val);
767
- }
768
- if (colorEl.tag === "a:sysClr") {
769
- const lastClr = attr(colorEl, "lastClr");
770
- if (lastClr !== void 0) return (0, document_schema_js.rgbHexToColor)(lastClr);
771
- return attr(colorEl, "val") === "window" ? {
772
- r: 1,
773
- g: 1,
774
- b: 1
775
- } : {
776
- r: 0,
777
- g: 0,
778
- b: 0
779
- };
780
- }
781
- }
782
- function readClrScheme(clrSchemeEl) {
783
- const map = /* @__PURE__ */ new Map();
784
- for (const slot of CLR_SCHEME_SLOTS) {
785
- const wrapper = childrenWithTag(clrSchemeEl, `a:${slot}`)[0];
786
- if (wrapper === void 0) continue;
787
- const colorEl = wrapper.children.find((c) => c.type === "element");
788
- if (colorEl === void 0) continue;
789
- const color = readThemeSlotColor(colorEl);
790
- if (color !== void 0) map.set(slot, color);
791
- }
792
- return map;
793
- }
794
- function readSchemeFont(fontSchemeEl, tag) {
795
- if (fontSchemeEl === void 0) return;
796
- const fontEl = childrenWithTag(fontSchemeEl, tag)[0];
797
- const latin = fontEl === void 0 ? void 0 : childrenWithTag(fontEl, "a:latin")[0];
798
- return latin === void 0 ? void 0 : attr(latin, "typeface");
799
- }
800
- const DEFAULT_THEME_FONT = "Calibri";
801
- const EMPTY_THEME = {
802
- colorScheme: /* @__PURE__ */ new Map(),
803
- majorFont: DEFAULT_THEME_FONT,
804
- minorFont: DEFAULT_THEME_FONT
805
- };
806
- function readTheme(themeRoot) {
807
- const clrSchemeEl = elementsWithTag([themeRoot], "a:clrScheme")[0];
808
- const colorScheme = clrSchemeEl === void 0 ? /* @__PURE__ */ new Map() : readClrScheme(clrSchemeEl);
809
- const fontSchemeEl = elementsWithTag([themeRoot], "a:fontScheme")[0];
810
- return {
811
- colorScheme,
812
- majorFont: readSchemeFont(fontSchemeEl, "a:majorFont") ?? DEFAULT_THEME_FONT,
813
- minorFont: readSchemeFont(fontSchemeEl, "a:minorFont") ?? DEFAULT_THEME_FONT
814
- };
815
- }
816
- function resolveThemeFontReference(typeface, theme) {
817
- if (typeface === "+mj-lt") return theme.majorFont;
818
- if (typeface === "+mn-lt") return theme.minorFont;
819
- return typeface;
820
- }
821
- function readColorMap(clrMapEl) {
822
- const map = /* @__PURE__ */ new Map();
823
- if (clrMapEl === void 0) return map;
824
- for (const a of clrMapEl.attributes) map.set(a.name, a.value);
825
- return map;
826
- }
827
- function resolveSchemeColorSlot(schemeVal, colorMap) {
828
- return colorMap.get(schemeVal) ?? schemeVal;
829
- }
830
- const COLOR_TRANSFORM_TAGS = /* @__PURE__ */ new Map([
831
- ["a:shade", "shade"],
832
- ["a:tint", "tint"],
833
- ["a:lumMod", "lumMod"],
834
- ["a:lumOff", "lumOff"]
835
- ]);
836
- function readColorTransforms(container) {
837
- const transforms = [];
838
- for (const child of container.children) {
839
- if (child.type !== "element") continue;
840
- const kind = COLOR_TRANSFORM_TAGS.get(child.tag);
841
- if (kind === void 0) continue;
842
- const val = attr(child, "val");
843
- if (val === void 0) continue;
844
- transforms.push({
845
- kind,
846
- value: Number(val)
847
- });
848
- }
849
- return transforms;
850
- }
851
- function readSchemeColor(schemeClrEl, colorMap, theme) {
852
- const val = attr(schemeClrEl, "val");
853
- if (val === void 0) return;
854
- const base = theme.colorScheme.get(resolveSchemeColorSlot(val, colorMap));
855
- return base === void 0 ? void 0 : applyColorTransforms(base, readColorTransforms(schemeClrEl));
856
- }
857
- function readSrgbColor(srgbClrEl) {
858
- const val = attr(srgbClrEl, "val");
859
- return val === void 0 ? void 0 : applyColorTransforms((0, document_schema_js.rgbHexToColor)(val), readColorTransforms(srgbClrEl));
860
- }
861
- function readSolidFillColor(solidFillEl, colorMap, theme) {
862
- if (solidFillEl === void 0) return;
863
- const schemeClr = childrenWithTag(solidFillEl, "a:schemeClr")[0];
864
- if (schemeClr !== void 0) return readSchemeColor(schemeClr, colorMap, theme);
865
- const srgbClr = childrenWithTag(solidFillEl, "a:srgbClr")[0];
866
- return srgbClr === void 0 ? void 0 : readSrgbColor(srgbClr);
867
- }
868
- function readGroupXfrm(xfrm) {
869
- const base = readXfrm(xfrm);
870
- if (base === void 0 || xfrm === void 0) return;
871
- const chOff = childrenWithTag(xfrm, "a:chOff")[0];
872
- const chExt = childrenWithTag(xfrm, "a:chExt")[0];
873
- if (chOff === void 0 || chExt === void 0) return;
874
- const cx = attr(chOff, "x");
875
- const cy = attr(chOff, "y");
876
- const ccx = attr(chExt, "cx");
877
- const ccy = attr(chExt, "cy");
878
- if (cx === void 0 || cy === void 0 || ccx === void 0 || ccy === void 0) return;
879
- return {
880
- offXPt: base.xPt,
881
- offYPt: base.yPt,
882
- extWidthPt: base.widthPt,
883
- extHeightPt: base.heightPt,
884
- childOffXPt: emuToPt(Number(cx)),
885
- childOffYPt: emuToPt(Number(cy)),
886
- childExtWidthPt: emuToPt(Number(ccx)),
887
- childExtHeightPt: emuToPt(Number(ccy))
888
- };
889
- }
890
- function applyGroupTransform(group, childFrame) {
891
- const scaleX = group.childExtWidthPt === 0 ? 1 : group.extWidthPt / group.childExtWidthPt;
892
- const scaleY = group.childExtHeightPt === 0 ? 1 : group.extHeightPt / group.childExtHeightPt;
893
- return {
894
- xPt: group.offXPt + (childFrame.xPt - group.childOffXPt) * scaleX,
895
- yPt: group.offYPt + (childFrame.yPt - group.childOffYPt) * scaleY,
896
- widthPt: childFrame.widthPt * scaleX,
897
- heightPt: childFrame.heightPt * scaleY
898
- };
899
- }
900
- //#endregion
901
- //#region src/typed/shared/source-path.ts
902
- function assignSourcePaths(blocks, prefix) {
903
- blocks.forEach((block, blockIndex) => {
904
- const blockPath = `${prefix}.blocks[${blockIndex}]`;
905
- block.sourcePath = blockPath;
906
- if (block.kind === "paragraph") block.runs.forEach((run, runIndex) => {
907
- run.sourcePath = `${blockPath}.runs[${runIndex}]`;
908
- });
909
- else if (block.kind === "table") block.rows.forEach((row, rowIndex) => {
910
- row.cells.forEach((cell, cellIndex) => {
911
- assignSourcePaths(cell.blocks, `${blockPath}.rows[${rowIndex}].cells[${cellIndex}]`);
912
- });
913
- });
914
- });
915
- }
916
- //#endregion
917
- //#region src/typed/docx/styles.ts
918
- function mergeParagraphLayer(base, layer) {
919
- return {
920
- alignment: layer.alignment ?? base.alignment,
921
- spacingBeforePt: layer.spacingBeforePt ?? base.spacingBeforePt,
922
- spacingAfterPt: layer.spacingAfterPt ?? base.spacingAfterPt,
923
- lineSpacing: layer.lineSpacing ?? base.lineSpacing,
924
- indentLeftPt: layer.indentLeftPt ?? base.indentLeftPt,
925
- indentFirstLinePt: layer.indentFirstLinePt ?? base.indentFirstLinePt
926
- };
927
- }
928
- function mergeRunLayer(base, layer) {
929
- return {
930
- bold: layer.bold ?? base.bold,
931
- italic: layer.italic ?? base.italic,
932
- underline: layer.underline ?? base.underline,
933
- strike: layer.strike ?? base.strike,
934
- fontFamily: layer.fontFamily ?? base.fontFamily,
935
- sizePt: layer.sizePt ?? base.sizePt,
936
- color: layer.color ?? base.color
937
- };
938
- }
939
- function readToggle$1(el) {
940
- if (el === void 0) return;
941
- const val = attr(el, "w:val");
942
- return val === void 0 || val !== "0" && val !== "false" && val !== "off";
943
- }
944
- function readUnderline(u) {
945
- if (u === void 0) return;
946
- const val = attr(u, "w:val");
947
- return val !== void 0 && val !== "none";
948
- }
949
- function readRunColor(colorEl) {
950
- if (colorEl === void 0) return;
951
- const val = attr(colorEl, "w:val");
952
- return val === void 0 || val === "auto" ? void 0 : (0, document_schema_js.rgbHexToColor)(val);
953
- }
954
- function readRunFontFamily(rFonts, theme) {
955
- if (rFonts === void 0) return;
956
- const ascii = attr(rFonts, "w:ascii");
957
- if (ascii !== void 0) return ascii;
958
- const asciiTheme = attr(rFonts, "w:asciiTheme");
959
- if (asciiTheme === "majorHAnsi" || asciiTheme === "majorAscii") return theme.majorFont;
960
- if (asciiTheme === "minorHAnsi" || asciiTheme === "minorAscii") return theme.minorFont;
961
- }
962
- function readRunPropertiesLayer(rPr, theme) {
963
- if (rPr === void 0) return {};
964
- const sz = childrenWithTag(rPr, "w:sz")[0];
965
- const szVal = sz === void 0 ? void 0 : attr(sz, "w:val");
966
- return {
967
- bold: readToggle$1(childrenWithTag(rPr, "w:b")[0]),
968
- italic: readToggle$1(childrenWithTag(rPr, "w:i")[0]),
969
- underline: readUnderline(childrenWithTag(rPr, "w:u")[0]),
970
- strike: readToggle$1(childrenWithTag(rPr, "w:strike")[0]),
971
- fontFamily: readRunFontFamily(childrenWithTag(rPr, "w:rFonts")[0], theme),
972
- sizePt: szVal === void 0 ? void 0 : halfPointsToPt(Number(szVal)),
973
- color: readRunColor(childrenWithTag(rPr, "w:color")[0])
974
- };
975
- }
976
- function readAlignment$1(jc) {
977
- const val = jc === void 0 ? void 0 : attr(jc, "w:val");
978
- if (val === "left" || val === "start") return "left";
979
- if (val === "center") return "center";
980
- if (val === "right" || val === "end") return "right";
981
- if (val === "both" || val === "distribute") return "justify";
982
- }
983
- function readParagraphPropertiesLayer(pPr) {
984
- if (pPr === void 0) return {};
985
- const spacing = childrenWithTag(pPr, "w:spacing")[0];
986
- const before = spacing === void 0 ? void 0 : attr(spacing, "w:before");
987
- const after = spacing === void 0 ? void 0 : attr(spacing, "w:after");
988
- const line = spacing === void 0 ? void 0 : attr(spacing, "w:line");
989
- const lineRule = spacing === void 0 ? void 0 : attr(spacing, "w:lineRule");
990
- const ind = childrenWithTag(pPr, "w:ind")[0];
991
- const left = ind === void 0 ? void 0 : attr(ind, "w:left") ?? attr(ind, "w:start");
992
- const firstLine = ind === void 0 ? void 0 : attr(ind, "w:firstLine");
993
- const hanging = ind === void 0 ? void 0 : attr(ind, "w:hanging");
994
- return {
995
- alignment: readAlignment$1(childrenWithTag(pPr, "w:jc")[0]),
996
- spacingBeforePt: before === void 0 ? void 0 : twipsToPt(Number(before)),
997
- spacingAfterPt: after === void 0 ? void 0 : twipsToPt(Number(after)),
998
- lineSpacing: line === void 0 || lineRule === "exact" || lineRule === "atLeast" ? void 0 : lineUnitsToMultiplier(Number(line)),
999
- indentLeftPt: left === void 0 ? void 0 : twipsToPt(Number(left)),
1000
- indentFirstLinePt: firstLine !== void 0 ? twipsToPt(Number(firstLine)) : hanging !== void 0 ? -twipsToPt(Number(hanging)) : void 0
1001
- };
1002
- }
1003
- function findStyle(stylesRoot, styleId, type) {
1004
- return elementsWithTag([stylesRoot], "w:style").find((s) => attr(s, "w:type") === type && attr(s, "w:styleId") === styleId);
1005
- }
1006
- function findDefaultStyle(stylesRoot, type) {
1007
- return elementsWithTag([stylesRoot], "w:style").find((s) => attr(s, "w:type") === type && attr(s, "w:default") === "1");
1008
- }
1009
- function resolveBasedOnChain(stylesRoot, styleId, type) {
1010
- const chain = [];
1011
- const visited = /* @__PURE__ */ new Set();
1012
- let currentId = styleId;
1013
- while (currentId !== void 0 && !visited.has(currentId)) {
1014
- visited.add(currentId);
1015
- const style = findStyle(stylesRoot, currentId, type);
1016
- if (style === void 0) break;
1017
- chain.unshift(style);
1018
- const basedOn = childrenWithTag(style, "w:basedOn")[0];
1019
- currentId = basedOn === void 0 ? void 0 : attr(basedOn, "w:val");
1020
- }
1021
- return chain;
1022
- }
1023
- function docDefaultsElement(stylesRoot, wrapperTag, innerTag) {
1024
- const docDefaults = stylesRoot === void 0 ? void 0 : childrenWithTag(stylesRoot, "w:docDefaults")[0];
1025
- const wrapper = docDefaults === void 0 ? void 0 : childrenWithTag(docDefaults, wrapperTag)[0];
1026
- return wrapper === void 0 ? void 0 : childrenWithTag(wrapper, innerTag)[0];
1027
- }
1028
- function resolveParagraphProperties(paragraph, context) {
1029
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1030
- const pStyleEl = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pStyle")[0];
1031
- const styleId = pStyleEl === void 0 ? void 0 : attr(pStyleEl, "w:val");
1032
- let resolved = readParagraphPropertiesLayer(docDefaultsElement(context.stylesRoot, "w:pPrDefault", "w:pPr"));
1033
- if (context.stylesRoot !== void 0) {
1034
- const defaultStyle = findDefaultStyle(context.stylesRoot, "paragraph");
1035
- if (defaultStyle !== void 0) resolved = mergeParagraphLayer(resolved, readParagraphPropertiesLayer(childrenWithTag(defaultStyle, "w:pPr")[0]));
1036
- if (styleId !== void 0) for (const style of resolveBasedOnChain(context.stylesRoot, styleId, "paragraph")) resolved = mergeParagraphLayer(resolved, readParagraphPropertiesLayer(childrenWithTag(style, "w:pPr")[0]));
1037
- }
1038
- return mergeParagraphLayer(resolved, readParagraphPropertiesLayer(pPr));
1039
- }
1040
- function resolveRunProperties(run, paragraph, context) {
1041
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1042
- const pStyleEl = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pStyle")[0];
1043
- const pStyleId = pStyleEl === void 0 ? void 0 : attr(pStyleEl, "w:val");
1044
- let resolved = readRunPropertiesLayer(docDefaultsElement(context.stylesRoot, "w:rPrDefault", "w:rPr"), context.theme);
1045
- if (context.stylesRoot !== void 0) {
1046
- const defaultStyle = findDefaultStyle(context.stylesRoot, "paragraph");
1047
- if (defaultStyle !== void 0) resolved = mergeRunLayer(resolved, readRunPropertiesLayer(childrenWithTag(defaultStyle, "w:rPr")[0], context.theme));
1048
- if (pStyleId !== void 0) for (const style of resolveBasedOnChain(context.stylesRoot, pStyleId, "paragraph")) resolved = mergeRunLayer(resolved, readRunPropertiesLayer(childrenWithTag(style, "w:rPr")[0], context.theme));
1049
- }
1050
- const paragraphMarkRPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:rPr")[0];
1051
- resolved = mergeRunLayer(resolved, readRunPropertiesLayer(paragraphMarkRPr, context.theme));
1052
- const rPr = childrenWithTag(run, "w:rPr")[0];
1053
- const rStyleEl = rPr === void 0 ? void 0 : childrenWithTag(rPr, "w:rStyle")[0];
1054
- const rStyleId = rStyleEl === void 0 ? void 0 : attr(rStyleEl, "w:val");
1055
- if (context.stylesRoot !== void 0 && rStyleId !== void 0) for (const style of resolveBasedOnChain(context.stylesRoot, rStyleId, "character")) resolved = mergeRunLayer(resolved, readRunPropertiesLayer(childrenWithTag(style, "w:rPr")[0], context.theme));
1056
- return mergeRunLayer(resolved, readRunPropertiesLayer(rPr, context.theme));
1057
- }
1058
- //#endregion
1059
- //#region src/typed/docx/read.ts
1060
- const CommentSchema = zod.z.object({
1061
- author: zod.z.string().optional(),
1062
- text: zod.z.string()
1063
- });
1064
- const FootnoteSchema = zod.z.object({
1065
- type: zod.z.string().optional(),
1066
- text: zod.z.string()
1067
- });
1068
- const DocxDocumentSchema = zod.z.object({
1069
- metadata: DocumentMetadataSchema,
1070
- sections: zod.z.array(document_schema_js.ContentSectionSchema),
1071
- comments: zod.z.array(CommentSchema),
1072
- footnotes: zod.z.array(FootnoteSchema),
1073
- headers: zod.z.array(zod.z.string()),
1074
- footers: zod.z.array(zod.z.string())
1075
- });
1076
- const DOCUMENT_PART_PATH = "word/document.xml";
1077
- const STYLES_PART_PATH = "word/styles.xml";
1078
- const THEME_REL_SUFFIX$1 = "/theme";
1079
- const DEFAULT_MARGIN_PT = 72;
1080
- const DEFAULT_MARGINS$1 = {
1081
- topPt: DEFAULT_MARGIN_PT,
1082
- rightPt: DEFAULT_MARGIN_PT,
1083
- bottomPt: DEFAULT_MARGIN_PT,
1084
- leftPt: DEFAULT_MARGIN_PT
1085
- };
1086
- function readPageSize$1(sectPr) {
1087
- const pgSz = childrenWithTag(sectPr, "w:pgSz")[0];
1088
- const w = pgSz === void 0 ? void 0 : attr(pgSz, "w:w");
1089
- const h = pgSz === void 0 ? void 0 : attr(pgSz, "w:h");
1090
- return w === void 0 || h === void 0 ? document_schema_js.PAGE_SIZE_LETTER : {
1091
- widthPt: twipsToPt(Number(w)),
1092
- heightPt: twipsToPt(Number(h))
1093
- };
1094
- }
1095
- function readMargins$1(sectPr) {
1096
- const pgMar = childrenWithTag(sectPr, "w:pgMar")[0];
1097
- if (pgMar === void 0) return DEFAULT_MARGINS$1;
1098
- const top = attr(pgMar, "w:top");
1099
- const right = attr(pgMar, "w:right");
1100
- const bottom = attr(pgMar, "w:bottom");
1101
- const left = attr(pgMar, "w:left");
1102
- return {
1103
- topPt: top === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(top)),
1104
- rightPt: right === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(right)),
1105
- bottomPt: bottom === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(bottom)),
1106
- leftPt: left === void 0 ? DEFAULT_MARGIN_PT : twipsToPt(Number(left))
1107
- };
1108
- }
1109
- function readListMembership(pPr) {
1110
- const numPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:numPr")[0];
1111
- if (numPr === void 0) return;
1112
- const numIdEl = childrenWithTag(numPr, "w:numId")[0];
1113
- const numId = numIdEl === void 0 ? void 0 : attr(numIdEl, "w:val");
1114
- if (numId === void 0) return;
1115
- const ilvlEl = childrenWithTag(numPr, "w:ilvl")[0];
1116
- const ilvlVal = ilvlEl === void 0 ? void 0 : attr(ilvlEl, "w:val");
1117
- return {
1118
- numId,
1119
- level: ilvlVal === void 0 ? 0 : Number(ilvlVal)
1120
- };
1121
- }
1122
- function readToggle(el) {
1123
- if (el === void 0) return false;
1124
- const val = attr(el, "w:val");
1125
- return val === void 0 || val !== "0" && val !== "false" && val !== "off";
1126
- }
1127
- function hasPageBreakBefore(paragraph) {
1128
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1129
- return readToggle(pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pageBreakBefore")[0]);
1130
- }
1131
- function readRunText(run) {
1132
- let text = "";
1133
- for (const child of run.children) {
1134
- if (child.type !== "element") continue;
1135
- if (child.tag === "w:t") text += textContent(child);
1136
- else if (child.tag === "w:tab") text += " ";
1137
- else if (child.tag === "w:br" || child.tag === "w:cr") text += "\n";
1138
- }
1139
- return text;
1140
- }
1141
- function readRun$1(run, paragraph, context) {
1142
- const props = resolveRunProperties(run, paragraph, context);
1143
- return {
1144
- text: readRunText(run),
1145
- bold: props.bold,
1146
- italic: props.italic,
1147
- underline: props.underline,
1148
- strike: props.strike,
1149
- fontFamily: props.fontFamily,
1150
- sizePt: props.sizePt,
1151
- color: props.color
1152
- };
1153
- }
1154
- function readParagraphRuns(paragraph, context, rels) {
1155
- const runs = [];
1156
- let fieldState = "none";
1157
- function walk(nodes, hyperlinkTarget) {
1158
- for (const node of nodes) {
1159
- if (node.type !== "element") continue;
1160
- if (node.tag === "w:r") {
1161
- const fldChar = childrenWithTag(node, "w:fldChar")[0];
1162
- if (fldChar !== void 0) {
1163
- const type = attr(fldChar, "w:fldCharType");
1164
- if (type === "begin") fieldState = "code";
1165
- else if (type === "separate") fieldState = "result";
1166
- else if (type === "end") fieldState = "none";
1167
- continue;
1168
- }
1169
- if (fieldState === "code") continue;
1170
- const run = readRun$1(node, paragraph, context);
1171
- runs.push(hyperlinkTarget === void 0 ? run : {
1172
- ...run,
1173
- hyperlink: hyperlinkTarget
1174
- });
1175
- } else if (node.tag === "w:fldSimple") walk(node.children, hyperlinkTarget);
1176
- else if (node.tag === "w:hyperlink") {
1177
- const rId = attr(node, "r:id");
1178
- const target = rId === void 0 ? void 0 : rels.get(rId)?.target;
1179
- walk(node.children, target ?? hyperlinkTarget);
1180
- } else if (node.tag === "w:ins") walk(node.children, hyperlinkTarget);
1181
- }
1182
- }
1183
- walk(paragraph.children, void 0);
1184
- return runs;
1185
- }
1186
- function readParagraph$1(paragraph, context, rels) {
1187
- const pPr = childrenWithTag(paragraph, "w:pPr")[0];
1188
- const pStyleEl = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:pStyle")[0];
1189
- const props = resolveParagraphProperties(paragraph, context);
1190
- return {
1191
- kind: "paragraph",
1192
- runs: readParagraphRuns(paragraph, context, rels),
1193
- styleId: pStyleEl === void 0 ? void 0 : attr(pStyleEl, "w:val"),
1194
- alignment: props.alignment,
1195
- list: readListMembership(pPr),
1196
- spacingBeforePt: props.spacingBeforePt,
1197
- spacingAfterPt: props.spacingAfterPt,
1198
- lineSpacing: props.lineSpacing,
1199
- indentLeftPt: props.indentLeftPt,
1200
- indentFirstLinePt: props.indentFirstLinePt
1201
- };
1202
- }
1203
- function readCellShading(tcPr) {
1204
- const shd = tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "w:shd")[0];
1205
- const fill = shd === void 0 ? void 0 : attr(shd, "w:fill");
1206
- return fill === void 0 || fill === "auto" || fill === "none" ? void 0 : (0, document_schema_js.rgbHexToColor)(fill);
1207
- }
1208
- function readRawCell(tc, context, rels) {
1209
- const tcPr = childrenWithTag(tc, "w:tcPr")[0];
1210
- const gridSpanEl = tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "w:gridSpan")[0];
1211
- const gridSpanVal = gridSpanEl === void 0 ? void 0 : attr(gridSpanEl, "w:val");
1212
- const vMerge = tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "w:vMerge")[0];
1213
- const vMergeVal = vMerge === void 0 ? void 0 : attr(vMerge, "w:val") ?? "continue";
1214
- return {
1215
- gridSpan: gridSpanVal === void 0 ? 1 : Number(gridSpanVal),
1216
- isVMergeContinuation: vMergeVal === "continue",
1217
- background: readCellShading(tcPr),
1218
- blocks: readBodyBlocks(tc.children, context, rels)
1219
- };
1220
- }
1221
- function readTable$1(tbl, context, rels) {
1222
- const tblGrid = childrenWithTag(tbl, "w:tblGrid")[0];
1223
- const columnWidthsPt = tblGrid === void 0 ? [] : childrenWithTag(tblGrid, "w:gridCol").map((col) => twipsToPt(Number(attr(col, "w:w") ?? "0")));
1224
- const rawRows = childrenWithTag(tbl, "w:tr").map((tr) => childrenWithTag(tr, "w:tc").map((tc) => readRawCell(tc, context, rels)));
1225
- const rowColumnIndices = rawRows.map((row) => {
1226
- const indices = [];
1227
- let col = 0;
1228
- for (const cell of row) {
1229
- indices.push(col);
1230
- col += cell.gridSpan;
1231
- }
1232
- return indices;
1233
- });
1234
- return {
1235
- kind: "table",
1236
- columnWidthsPt,
1237
- rows: rawRows.map((row, rowIndex) => ({ cells: row.map((cell, cellIndex) => {
1238
- if (cell.isVMergeContinuation) return { blocks: [] };
1239
- const colIndex = rowColumnIndices[rowIndex][cellIndex];
1240
- let rowSpan = 1;
1241
- for (let r = rowIndex + 1; r < rawRows.length; r++) {
1242
- const matchIndex = rowColumnIndices[r].indexOf(colIndex);
1243
- if (!(matchIndex === -1 ? void 0 : rawRows[r][matchIndex])?.isVMergeContinuation) break;
1244
- rowSpan++;
1245
- }
1246
- return {
1247
- blocks: cell.blocks,
1248
- colSpan: cell.gridSpan > 1 ? cell.gridSpan : void 0,
1249
- rowSpan: rowSpan > 1 ? rowSpan : void 0,
1250
- background: cell.background
1251
- };
1252
- }) }))
1253
- };
1254
- }
1255
- function readBodyBlocks(nodes, context, rels) {
1256
- const blocks = [];
1257
- for (const node of nodes) {
1258
- if (node.type !== "element") continue;
1259
- if (node.tag === "w:p") {
1260
- if (hasPageBreakBefore(node)) blocks.push({ kind: "pageBreak" });
1261
- blocks.push(readParagraph$1(node, context, rels));
1262
- } else if (node.tag === "w:tbl") blocks.push(readTable$1(node, context, rels));
1263
- else if (node.tag === "w:sdt") {
1264
- const sdtContent = childrenWithTag(node, "w:sdtContent")[0];
1265
- if (sdtContent !== void 0) blocks.push(...readBodyBlocks(sdtContent.children, context, rels));
1266
- } else if (node.tag === "w:ins") blocks.push(...readBodyBlocks(node.children, context, rels));
1267
- else if (node.tag === "mc:AlternateContent") {
1268
- const target = childrenWithTag(node, "mc:Fallback")[0] ?? childrenWithTag(node, "mc:Choice")[0];
1269
- if (target !== void 0) blocks.push(...readBodyBlocks(target.children, context, rels));
1270
- }
1271
- }
1272
- return blocks;
1273
- }
1274
- function readSections(body, context, rels) {
1275
- const sections = [];
1276
- let currentBlocks = [];
1277
- for (const node of body.children) {
1278
- if (node.type !== "element") continue;
1279
- if (node.tag === "w:sectPr") {
1280
- sections.push({
1281
- pageSize: readPageSize$1(node),
1282
- margins: readMargins$1(node),
1283
- blocks: currentBlocks
1284
- });
1285
- currentBlocks = [];
1286
- continue;
1287
- }
1288
- if (node.tag === "w:p") {
1289
- const pPr = childrenWithTag(node, "w:pPr")[0];
1290
- const sectPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "w:sectPr")[0];
1291
- if (hasPageBreakBefore(node)) currentBlocks.push({ kind: "pageBreak" });
1292
- currentBlocks.push(readParagraph$1(node, context, rels));
1293
- if (sectPr !== void 0) {
1294
- sections.push({
1295
- pageSize: readPageSize$1(sectPr),
1296
- margins: readMargins$1(sectPr),
1297
- blocks: currentBlocks
1298
- });
1299
- currentBlocks = [];
1300
- }
1301
- continue;
1302
- }
1303
- currentBlocks.push(...readBodyBlocks([node], context, rels));
1304
- }
1305
- if (currentBlocks.length > 0 || sections.length === 0) sections.push({
1306
- pageSize: document_schema_js.PAGE_SIZE_LETTER,
1307
- margins: DEFAULT_MARGINS$1,
1308
- blocks: currentBlocks
1309
- });
1310
- sections.forEach((section, sectionIndex) => assignSourcePaths(section.blocks, `sections[${sectionIndex}]`));
1311
- return sections;
1312
- }
1313
- function readDocumentTheme(pkg, docRels) {
1314
- for (const rel of docRels.values()) if (rel.type.endsWith(THEME_REL_SUFFIX$1)) {
1315
- const themeRoot = rootElement(pkg.parts[rel.target]);
1316
- if (themeRoot !== void 0) return readTheme(themeRoot);
1317
- }
1318
- return EMPTY_THEME;
1319
- }
1320
- function readComment(comment) {
1321
- const author = attr(comment, "w:author");
1322
- const result = { text: elementsWithTag(comment.children, "w:t").map(textContent).join("") };
1323
- if (author !== void 0) result.author = author;
1324
- return result;
1325
- }
1326
- function readFootnote(footnote) {
1327
- const type = attr(footnote, "w:type");
1328
- const result = { text: elementsWithTag(footnote.children, "w:t").map(textContent).join("") };
1329
- if (type !== void 0) result.type = type;
1330
- return result;
1331
- }
1332
- function readComments(pkg) {
1333
- const root = rootElement(pkg.parts["word/comments.xml"]);
1334
- if (root === void 0) return [];
1335
- return childrenWithTag(root, "w:comment").map(readComment);
1336
- }
1337
- function readFootnotes(pkg) {
1338
- const root = rootElement(pkg.parts["word/footnotes.xml"]);
1339
- if (root === void 0) return [];
1340
- const out = [];
1341
- for (const fn of childrenWithTag(root, "w:footnote")) {
1342
- const type = attr(fn, "w:type");
1343
- if (type === "separator" || type === "continuationSeparator") continue;
1344
- out.push(readFootnote(fn));
1345
- }
1346
- return out;
1347
- }
1348
- function readHeaderFooterText(pkg, prefix) {
1349
- const out = [];
1350
- for (const path of Object.keys(pkg.parts)) {
1351
- if (!path.startsWith(prefix) || !path.endsWith(".xml")) continue;
1352
- const part = pkg.parts[path];
1353
- if (part?.kind !== "xml") continue;
1354
- out.push(elementsWithTag(part.nodes, "w:t").map(textContent).join(""));
1355
- }
1356
- return out;
1357
- }
1358
- function readDocx(pkg) {
1359
- const documentRoot = rootElement(pkg.parts[DOCUMENT_PART_PATH]);
1360
- if (documentRoot === void 0) throw new Error(`readDocx: package has no ${DOCUMENT_PART_PATH} part`);
1361
- const body = childrenWithTag(documentRoot, "w:body")[0];
1362
- if (body === void 0) throw new Error(`readDocx: ${DOCUMENT_PART_PATH} has no w:body element`);
1363
- const docRels = resolveRelationships(pkg, DOCUMENT_PART_PATH);
1364
- const context = {
1365
- stylesRoot: rootElement(pkg.parts[STYLES_PART_PATH]),
1366
- theme: readDocumentTheme(pkg, docRels)
1367
- };
1368
- return {
1369
- metadata: readCoreProperties(pkg),
1370
- sections: readSections(body, context, docRels),
1371
- comments: readComments(pkg),
1372
- footnotes: readFootnotes(pkg),
1373
- headers: readHeaderFooterText(pkg, "word/header"),
1374
- footers: readHeaderFooterText(pkg, "word/footer")
1375
- };
1376
- }
1377
- //#endregion
1378
- //#region src/typed/pptx/inherit.ts
1379
- const SLIDE_LAYOUT_REL_SUFFIX = "/slideLayout";
1380
- const SLIDE_MASTER_REL_SUFFIX = "/slideMaster";
1381
- const THEME_REL_SUFFIX = "/theme";
1382
- function findRelTarget(pkg, partPath, typeSuffix) {
1383
- for (const rel of resolveRelationships(pkg, partPath).values()) if (rel.type.endsWith(typeSuffix)) return rel.target;
1384
- }
1385
- function resolveSlideInheritance(pkg, slidePath) {
1386
- const layoutPath = findRelTarget(pkg, slidePath, SLIDE_LAYOUT_REL_SUFFIX);
1387
- const layoutRoot = layoutPath === void 0 ? void 0 : rootElement(pkg.parts[layoutPath]);
1388
- const masterPath = layoutPath === void 0 ? void 0 : findRelTarget(pkg, layoutPath, SLIDE_MASTER_REL_SUFFIX);
1389
- const masterRoot = masterPath === void 0 ? void 0 : rootElement(pkg.parts[masterPath]);
1390
- const themePath = masterPath === void 0 ? void 0 : findRelTarget(pkg, masterPath, THEME_REL_SUFFIX);
1391
- const themeRoot = themePath === void 0 ? void 0 : rootElement(pkg.parts[themePath]);
1392
- return {
1393
- layoutRoot,
1394
- masterRoot,
1395
- theme: themeRoot === void 0 ? EMPTY_THEME : readTheme(themeRoot),
1396
- colorMap: readColorMap(masterRoot === void 0 ? void 0 : childrenWithTag(masterRoot, "p:clrMap")[0])
1397
- };
1398
- }
1399
- const TYPE_NORMALIZATION = /* @__PURE__ */ new Map([["ctrTitle", "title"], ["subTitle", "body"]]);
1400
- function normalizePlaceholderType(type) {
1401
- return type === void 0 ? void 0 : TYPE_NORMALIZATION.get(type) ?? type;
1402
- }
1403
- function readPlaceholderKey(shape) {
1404
- const ph = elementsWithTag([shape], "p:ph")[0];
1405
- return ph === void 0 ? void 0 : {
1406
- type: attr(ph, "type"),
1407
- idx: attr(ph, "idx")
1408
- };
1409
- }
1410
- function shapesOf(root) {
1411
- return root === void 0 ? [] : elementsWithTag([root], "p:sp");
1412
- }
1413
- function findMatchingPlaceholder(root, key) {
1414
- const shapes = shapesOf(root);
1415
- if (key.idx !== void 0) {
1416
- const byIdx = shapes.find((shape) => readPlaceholderKey(shape)?.idx === key.idx);
1417
- if (byIdx !== void 0) return byIdx;
1418
- }
1419
- const normalizedTarget = normalizePlaceholderType(key.type);
1420
- if (normalizedTarget === void 0) return;
1421
- return shapes.find((shape) => normalizePlaceholderType(readPlaceholderKey(shape)?.type) === normalizedTarget);
1422
- }
1423
- function shapeXfrm(shape) {
1424
- if (shape === void 0) return;
1425
- const spPr = childrenWithTag(shape, "p:spPr")[0];
1426
- return spPr === void 0 ? void 0 : readXfrm(childrenWithTag(spPr, "a:xfrm")[0]);
1427
- }
1428
- function resolvePlaceholderXfrm(key, context) {
1429
- return shapeXfrm(findMatchingPlaceholder(context.layoutRoot, key)) ?? shapeXfrm(findMatchingPlaceholder(context.masterRoot, key));
1430
- }
1431
- function readRunPropertiesFromElement(rPr, context) {
1432
- const sz = attr(rPr, "sz");
1433
- const latin = childrenWithTag(rPr, "a:latin")[0];
1434
- const typeface = latin === void 0 ? void 0 : attr(latin, "typeface");
1435
- const solidFill = childrenWithTag(rPr, "a:solidFill")[0];
1436
- const bold = attr(rPr, "b");
1437
- const italic = attr(rPr, "i");
1438
- return {
1439
- fontFamily: typeface === void 0 ? void 0 : resolveThemeFontReference(typeface, context.theme),
1440
- sizePt: sz === void 0 ? void 0 : drawingMlFontSizeToPt(Number(sz)),
1441
- bold: bold === void 0 ? void 0 : bold === "1",
1442
- italic: italic === void 0 ? void 0 : italic === "1",
1443
- color: readSolidFillColor(solidFill, context.colorMap, context.theme)
1444
- };
1445
- }
1446
- function txStyleTagFor(placeholderType) {
1447
- const normalized = normalizePlaceholderType(placeholderType);
1448
- if (normalized === "title") return "p:titleStyle";
1449
- if (normalized === "body") return "p:bodyStyle";
1450
- return "p:otherStyle";
1451
- }
1452
- function levelTag(level) {
1453
- return `a:lvl${Math.min(Math.max(level, 0), 8) + 1}pPr`;
1454
- }
1455
- function resolveDefaultRunProperties(placeholderType, level, context) {
1456
- if (context.masterRoot === void 0) return {};
1457
- const txStyles = childrenWithTag(context.masterRoot, "p:txStyles")[0];
1458
- const styleEl = txStyles === void 0 ? void 0 : childrenWithTag(txStyles, txStyleTagFor(placeholderType))[0];
1459
- const lvlPPr = styleEl === void 0 ? void 0 : childrenWithTag(styleEl, levelTag(level))[0];
1460
- const defRPr = lvlPPr === void 0 ? void 0 : childrenWithTag(lvlPPr, "a:defRPr")[0];
1461
- return defRPr === void 0 ? {} : readRunPropertiesFromElement(defRPr, context);
1462
- }
1463
- //#endregion
1464
- //#region src/typed/pptx/read.ts
1465
- const PptxDocumentSchema = zod.z.object({
1466
- metadata: DocumentMetadataSchema,
1467
- slides: zod.z.array(document_schema_js.ContentSlideSchema)
1468
- });
1469
- const PRESENTATION_PATH = "ppt/presentation.xml";
1470
- const TABLE_GRAPHIC_URI = "http://schemas.openxmlformats.org/drawingml/2006/table";
1471
- function readSlideSize(presentationRoot) {
1472
- const sldSz = presentationRoot === void 0 ? void 0 : childrenWithTag(presentationRoot, "p:sldSz")[0];
1473
- const cx = sldSz === void 0 ? void 0 : attr(sldSz, "cx");
1474
- const cy = sldSz === void 0 ? void 0 : attr(sldSz, "cy");
1475
- return cx === void 0 || cy === void 0 ? document_schema_js.SLIDE_SIZE_WIDESCREEN : {
1476
- widthPt: emuToPt(Number(cx)),
1477
- heightPt: emuToPt(Number(cy))
1478
- };
1479
- }
1480
- function readSlidePathsInOrder(pkg, presentationRoot) {
1481
- if (presentationRoot === void 0) return [];
1482
- const sldIdLst = childrenWithTag(presentationRoot, "p:sldIdLst")[0];
1483
- if (sldIdLst === void 0) return [];
1484
- const presentationRels = resolveRelationships(pkg, PRESENTATION_PATH);
1485
- const paths = [];
1486
- for (const sldId of childrenWithTag(sldIdLst, "p:sldId")) {
1487
- const rId = attr(sldId, "r:id");
1488
- const rel = rId === void 0 ? void 0 : presentationRels.get(rId);
1489
- if (rel !== void 0) paths.push(rel.target);
1490
- }
1491
- return paths;
1492
- }
1493
- function shapeName(shape) {
1494
- const cNvPr = elementsWithTag([shape], "p:cNvPr")[0];
1495
- return cNvPr === void 0 ? void 0 : attr(cNvPr, "name");
1496
- }
1497
- function mergeRunProperties(base, override) {
1498
- return {
1499
- fontFamily: override.fontFamily ?? base.fontFamily,
1500
- sizePt: override.sizePt ?? base.sizePt,
1501
- bold: override.bold ?? base.bold,
1502
- italic: override.italic ?? base.italic,
1503
- color: override.color ?? base.color
1504
- };
1505
- }
1506
- function isUnderlined(rPr) {
1507
- if (rPr === void 0) return;
1508
- const u = attr(rPr, "u");
1509
- return u === void 0 ? void 0 : u !== "none";
1510
- }
1511
- function isStrikethrough(rPr) {
1512
- if (rPr === void 0) return;
1513
- const strike = attr(rPr, "strike");
1514
- return strike === void 0 ? void 0 : strike !== "noStrike";
1515
- }
1516
- function readHyperlink(rPr, slideRels) {
1517
- if (rPr === void 0) return;
1518
- const hlink = childrenWithTag(rPr, "a:hlinkClick")[0];
1519
- const rId = hlink === void 0 ? void 0 : attr(hlink, "r:id");
1520
- const rel = rId === void 0 ? void 0 : slideRels.get(rId);
1521
- return rel?.targetMode === "External" ? rel.target : void 0;
1522
- }
1523
- function readRun(runEl, cascadeBase, context, slideRels) {
1524
- const rPr = childrenWithTag(runEl, "a:rPr")[0];
1525
- const merged = mergeRunProperties(cascadeBase, rPr === void 0 ? {} : readRunPropertiesFromElement(rPr, context));
1526
- const tEl = childrenWithTag(runEl, "a:t")[0];
1527
- return {
1528
- text: tEl === void 0 ? "" : textContent(tEl),
1529
- bold: merged.bold,
1530
- italic: merged.italic,
1531
- underline: isUnderlined(rPr),
1532
- strike: isStrikethrough(rPr),
1533
- fontFamily: merged.fontFamily,
1534
- sizePt: merged.sizePt,
1535
- color: merged.color,
1536
- hyperlink: readHyperlink(rPr, slideRels)
1537
- };
1538
- }
1539
- function readAlignment(algn) {
1540
- if (algn === "l") return "left";
1541
- if (algn === "ctr") return "center";
1542
- if (algn === "r") return "right";
1543
- if (algn === "just" || algn === "justLow") return "justify";
1544
- }
1545
- function readAbsoluteSpacingPt(spc) {
1546
- if (spc === void 0) return;
1547
- const pts = childrenWithTag(spc, "a:spcPts")[0];
1548
- const val = pts === void 0 ? void 0 : attr(pts, "val");
1549
- return val === void 0 ? void 0 : drawingMlFontSizeToPt(Number(val));
1550
- }
1551
- function readLineSpacingMultiplier(pPr) {
1552
- const lnSpc = pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:lnSpc")[0];
1553
- const pct = lnSpc === void 0 ? void 0 : childrenWithTag(lnSpc, "a:spcPct")[0];
1554
- const val = pct === void 0 ? void 0 : attr(pct, "val");
1555
- return val === void 0 ? void 0 : Number(val) / 1e5;
1556
- }
1557
- function readParagraph(pEl, placeholderType, context, slideRels) {
1558
- const pPr = childrenWithTag(pEl, "a:pPr")[0];
1559
- const masterDefaults = resolveDefaultRunProperties(placeholderType, pPr === void 0 ? 0 : Number(attr(pPr, "lvl") ?? "0"), context);
1560
- const pPrDefRPr = pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:defRPr")[0];
1561
- const paragraphDefaults = pPrDefRPr === void 0 ? masterDefaults : mergeRunProperties(masterDefaults, readRunPropertiesFromElement(pPrDefRPr, context));
1562
- const runs = [];
1563
- for (const child of pEl.children) {
1564
- if (child.type !== "element") continue;
1565
- if (child.tag === "a:r" || child.tag === "a:fld") runs.push(readRun(child, paragraphDefaults, context, slideRels));
1566
- else if (child.tag === "a:br") runs.push({ text: "\n" });
1567
- }
1568
- const marL = pPr === void 0 ? void 0 : attr(pPr, "marL");
1569
- const indent = pPr === void 0 ? void 0 : attr(pPr, "indent");
1570
- return {
1571
- kind: "paragraph",
1572
- runs,
1573
- alignment: pPr === void 0 ? void 0 : readAlignment(attr(pPr, "algn")),
1574
- spacingBeforePt: readAbsoluteSpacingPt(pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:spcBef")[0]),
1575
- spacingAfterPt: readAbsoluteSpacingPt(pPr === void 0 ? void 0 : childrenWithTag(pPr, "a:spcAft")[0]),
1576
- lineSpacing: readLineSpacingMultiplier(pPr),
1577
- indentLeftPt: marL === void 0 ? void 0 : emuToPt(Number(marL)),
1578
- indentFirstLinePt: indent === void 0 ? void 0 : emuToPt(Number(indent))
1579
- };
1580
- }
1581
- function textBodyParagraphs(txBody, placeholderType, context, slideRels) {
1582
- return txBody === void 0 ? [] : childrenWithTag(txBody, "a:p").map((p) => readParagraph(p, placeholderType, context, slideRels));
1583
- }
1584
- const DEFAULT_INSET_LEFT_RIGHT_EMU = 91440;
1585
- const DEFAULT_INSET_TOP_BOTTOM_EMU = 45720;
1586
- const NO_TEXT_BODY_EXTRAS = {
1587
- insetLeftPt: 0,
1588
- insetTopPt: 0,
1589
- insetRightPt: 0,
1590
- insetBottomPt: 0,
1591
- fontScale: void 0,
1592
- lineSpacingReduction: void 0
1593
- };
1594
- function readShapeTextExtras(txBody) {
1595
- if (txBody === void 0) return NO_TEXT_BODY_EXTRAS;
1596
- const bodyPr = childrenWithTag(txBody, "a:bodyPr")[0];
1597
- const lIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "lIns");
1598
- const tIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "tIns");
1599
- const rIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "rIns");
1600
- const bIns = bodyPr === void 0 ? void 0 : attr(bodyPr, "bIns");
1601
- const normAutofit = bodyPr === void 0 ? void 0 : childrenWithTag(bodyPr, "a:normAutofit")[0];
1602
- const fontScale = normAutofit === void 0 ? void 0 : attr(normAutofit, "fontScale");
1603
- const lnSpcReduction = normAutofit === void 0 ? void 0 : attr(normAutofit, "lnSpcReduction");
1604
- return {
1605
- insetLeftPt: emuToPt(lIns === void 0 ? DEFAULT_INSET_LEFT_RIGHT_EMU : Number(lIns)),
1606
- insetTopPt: emuToPt(tIns === void 0 ? DEFAULT_INSET_TOP_BOTTOM_EMU : Number(tIns)),
1607
- insetRightPt: emuToPt(rIns === void 0 ? DEFAULT_INSET_LEFT_RIGHT_EMU : Number(rIns)),
1608
- insetBottomPt: emuToPt(bIns === void 0 ? DEFAULT_INSET_TOP_BOTTOM_EMU : Number(bIns)),
1609
- fontScale: fontScale === void 0 ? void 0 : Number(fontScale) / 1e5,
1610
- lineSpacingReduction: lnSpcReduction === void 0 ? void 0 : Number(lnSpcReduction) / 1e5
1611
- };
1612
- }
1613
- function resolveShapeFrame(shape, context, parentTransform) {
1614
- const key = readPlaceholderKey(shape);
1615
- const spPr = childrenWithTag(shape, "p:spPr")[0];
1616
- const xfrm = (spPr === void 0 ? void 0 : readXfrm(childrenWithTag(spPr, "a:xfrm")[0])) ?? (key === void 0 ? void 0 : resolvePlaceholderXfrm(key, context));
1617
- if (xfrm === void 0) return;
1618
- const localFrame = {
1619
- xPt: xfrm.xPt,
1620
- yPt: xfrm.yPt,
1621
- widthPt: xfrm.widthPt,
1622
- heightPt: xfrm.heightPt
1623
- };
1624
- return {
1625
- frame: parentTransform === void 0 ? localFrame : applyGroupTransform(parentTransform, localFrame),
1626
- rotationDeg: xfrm.rotationDeg === 0 ? void 0 : xfrm.rotationDeg
1627
- };
1628
- }
1629
- function readSpShape(sp, context, slideRels, parentTransform) {
1630
- const resolved = resolveShapeFrame(sp, context, parentTransform);
1631
- if (resolved === void 0) return;
1632
- const key = readPlaceholderKey(sp);
1633
- const txBody = childrenWithTag(sp, "p:txBody")[0];
1634
- const blocks = textBodyParagraphs(txBody, key?.type, context, slideRels);
1635
- const extras = readShapeTextExtras(txBody);
1636
- return {
1637
- name: shapeName(sp),
1638
- frame: resolved.frame,
1639
- rotationDeg: resolved.rotationDeg,
1640
- ...extras,
1641
- blocks
1642
- };
1643
- }
1644
- function readPicShape(pic, context, slideRels, pkg, parentTransform) {
1645
- const resolved = resolveShapeFrame(pic, context, parentTransform);
1646
- if (resolved === void 0) return;
1647
- const blipFill = childrenWithTag(pic, "p:blipFill")[0];
1648
- const blip = blipFill === void 0 ? void 0 : childrenWithTag(blipFill, "a:blip")[0];
1649
- const rId = blip === void 0 ? void 0 : attr(blip, "r:embed");
1650
- const rel = rId === void 0 ? void 0 : slideRels.get(rId);
1651
- const mediaPart = rel === void 0 ? void 0 : pkg.parts[rel.target];
1652
- const blocks = [];
1653
- if (mediaPart?.kind === "binary") {
1654
- const format = sniffImageFormat(base64ToBytes(mediaPart.base64));
1655
- if (format !== void 0) {
1656
- const image = {
1657
- kind: "image",
1658
- format,
1659
- base64: mediaPart.base64,
1660
- widthPt: resolved.frame.widthPt,
1661
- heightPt: resolved.frame.heightPt
1662
- };
1663
- blocks.push(image);
1664
- }
1665
- }
1666
- return {
1667
- name: shapeName(pic),
1668
- frame: resolved.frame,
1669
- rotationDeg: resolved.rotationDeg,
1670
- ...NO_TEXT_BODY_EXTRAS,
1671
- blocks
1672
- };
1673
- }
1674
- function readTableCell(tc, context, slideRels) {
1675
- const hMerge = attr(tc, "hMerge");
1676
- const vMerge = attr(tc, "vMerge");
1677
- if (hMerge === "1" || vMerge === "1") return { blocks: [] };
1678
- const tcPr = childrenWithTag(tc, "a:tcPr")[0];
1679
- const background = readSolidFillColor(tcPr === void 0 ? void 0 : childrenWithTag(tcPr, "a:solidFill")[0], context.colorMap, context.theme);
1680
- const txBody = childrenWithTag(tc, "a:txBody")[0];
1681
- const gridSpan = attr(tc, "gridSpan");
1682
- const rowSpan = attr(tc, "rowSpan");
1683
- return {
1684
- blocks: textBodyParagraphs(txBody, void 0, context, slideRels),
1685
- colSpan: gridSpan === void 0 ? void 0 : Number(gridSpan),
1686
- rowSpan: rowSpan === void 0 ? void 0 : Number(rowSpan),
1687
- background
1688
- };
1689
- }
1690
- function readTable(tbl, context, slideRels) {
1691
- const tblGrid = childrenWithTag(tbl, "a:tblGrid")[0];
1692
- const columnWidthsPt = tblGrid === void 0 ? [] : childrenWithTag(tblGrid, "a:gridCol").map((col) => emuToPt(Number(attr(col, "w") ?? "0")));
1693
- return {
1694
- kind: "table",
1695
- rows: childrenWithTag(tbl, "a:tr").map((tr) => {
1696
- const h = attr(tr, "h");
1697
- return {
1698
- cells: childrenWithTag(tr, "a:tc").map((tc) => readTableCell(tc, context, slideRels)),
1699
- heightPt: h === void 0 ? void 0 : emuToPt(Number(h))
1700
- };
1701
- }),
1702
- columnWidthsPt
1703
- };
1704
- }
1705
- function readGraphicFrameShape(gf, context, slideRels, parentTransform) {
1706
- const xfrm = readXfrm(childrenWithTag(gf, "p:xfrm")[0]);
1707
- if (xfrm === void 0) return;
1708
- const localFrame = {
1709
- xPt: xfrm.xPt,
1710
- yPt: xfrm.yPt,
1711
- widthPt: xfrm.widthPt,
1712
- heightPt: xfrm.heightPt
1713
- };
1714
- const frame = parentTransform === void 0 ? localFrame : applyGroupTransform(parentTransform, localFrame);
1715
- const rotationDeg = xfrm.rotationDeg === 0 ? void 0 : xfrm.rotationDeg;
1716
- const graphic = childrenWithTag(gf, "a:graphic")[0];
1717
- const graphicData = graphic === void 0 ? void 0 : childrenWithTag(graphic, "a:graphicData")[0];
1718
- const tbl = (graphicData === void 0 ? void 0 : attr(graphicData, "uri")) === TABLE_GRAPHIC_URI && graphicData !== void 0 ? childrenWithTag(graphicData, "a:tbl")[0] : void 0;
1719
- const blocks = tbl === void 0 ? [] : [readTable(tbl, context, slideRels)];
1720
- return {
1721
- name: shapeName(gf),
1722
- frame,
1723
- rotationDeg,
1724
- ...NO_TEXT_BODY_EXTRAS,
1725
- blocks
1726
- };
1727
- }
1728
- function walkShapeTreeChildren(children, parentTransform, context, slideRels, pkg, out) {
1729
- for (const node of children) {
1730
- if (node.type !== "element") continue;
1731
- if (node.tag === "p:sp") {
1732
- const shape = readSpShape(node, context, slideRels, parentTransform);
1733
- if (shape !== void 0) out.push(shape);
1734
- } else if (node.tag === "p:pic") {
1735
- const shape = readPicShape(node, context, slideRels, pkg, parentTransform);
1736
- if (shape !== void 0) out.push(shape);
1737
- } else if (node.tag === "p:graphicFrame") {
1738
- const shape = readGraphicFrameShape(node, context, slideRels, parentTransform);
1739
- if (shape !== void 0) out.push(shape);
1740
- } else if (node.tag === "p:grpSp") {
1741
- const grpSpPr = childrenWithTag(node, "p:grpSpPr")[0];
1742
- const composed = composeGroupTransform(readGroupXfrm(grpSpPr === void 0 ? void 0 : childrenWithTag(grpSpPr, "a:xfrm")[0]), parentTransform);
1743
- walkShapeTreeChildren(node.children, composed, context, slideRels, pkg, out);
1744
- }
1745
- }
1746
- }
1747
- function composeGroupTransform(own, parent) {
1748
- if (own === void 0) return;
1749
- if (parent === void 0) return own;
1750
- const absolute = applyGroupTransform(parent, {
1751
- xPt: own.offXPt,
1752
- yPt: own.offYPt,
1753
- widthPt: own.extWidthPt,
1754
- heightPt: own.extHeightPt
1755
- });
1756
- return {
1757
- ...own,
1758
- offXPt: absolute.xPt,
1759
- offYPt: absolute.yPt,
1760
- extWidthPt: absolute.widthPt,
1761
- extHeightPt: absolute.heightPt
1762
- };
1763
- }
1764
- const NOTES_SLIDE_REL_SUFFIX = "/notesSlide";
1765
- function readNotes(pkg, slidePath) {
1766
- let notesPath;
1767
- for (const rel of resolveRelationships(pkg, slidePath).values()) if (rel.type.endsWith(NOTES_SLIDE_REL_SUFFIX)) {
1768
- notesPath = rel.target;
1769
- break;
1770
- }
1771
- if (notesPath === void 0) return "";
1772
- const notesRoot = rootElement(pkg.parts[notesPath]);
1773
- if (notesRoot === void 0) return "";
1774
- const bodyShape = elementsWithTag([notesRoot], "p:sp").find((shape) => {
1775
- const key = readPlaceholderKey(shape);
1776
- return key !== void 0 && (key.type === void 0 || key.type === "body");
1777
- });
1778
- if (bodyShape !== void 0) {
1779
- const txBody = childrenWithTag(bodyShape, "p:txBody")[0];
1780
- if (txBody !== void 0) return elementsWithTag(txBody.children, "a:t").map(textContent).join("");
1781
- }
1782
- return elementsWithTag([notesRoot], "a:t").map(textContent).join("");
1783
- }
1784
- function readSlide(pkg, slidePath, size) {
1785
- const slideRoot = rootElement(pkg.parts[slidePath]);
1786
- const context = resolveSlideInheritance(pkg, slidePath);
1787
- const slideRels = resolveRelationships(pkg, slidePath);
1788
- const cSld = slideRoot === void 0 ? void 0 : childrenWithTag(slideRoot, "p:cSld")[0];
1789
- const spTree = cSld === void 0 ? void 0 : childrenWithTag(cSld, "p:spTree")[0];
1790
- const shapes = [];
1791
- if (spTree !== void 0) walkShapeTreeChildren(spTree.children, void 0, context, slideRels, pkg, shapes);
1792
- return {
1793
- size,
1794
- shapes,
1795
- notes: readNotes(pkg, slidePath)
1796
- };
1797
- }
1798
- function readPptx(pkg) {
1799
- const presentationRoot = rootElement(pkg.parts[PRESENTATION_PATH]);
1800
- const size = readSlideSize(presentationRoot);
1801
- const slides = readSlidePathsInOrder(pkg, presentationRoot).map((slidePath) => readSlide(pkg, slidePath, size));
1802
- slides.forEach((slide, slideIndex) => {
1803
- slide.shapes.forEach((shape, shapeIndex) => {
1804
- const shapePath = `slides[${slideIndex}].shapes[${shapeIndex}]`;
1805
- shape.sourcePath = shapePath;
1806
- assignSourcePaths(shape.blocks, shapePath);
1807
- });
1808
- });
1809
- return {
1810
- metadata: readCoreProperties(pkg),
1811
- slides
1812
- };
1813
- }
1814
- //#endregion
1815
- //#region src/typed/xlsx/shared-strings.ts
1816
- function loadSharedStrings(pkg) {
1817
- const root = rootElement(pkg.parts["xl/sharedStrings.xml"]);
1818
- if (root === void 0) return [];
1819
- const strings = [];
1820
- for (const si of childrenWithTag(root, "si")) {
1821
- let value = "";
1822
- for (const t of elementsWithTag(si.children, "t")) value += textContent(t);
1823
- strings.push(value);
1824
- }
1825
- return strings;
1826
- }
1827
- var SharedStringTable = class {
1828
- indexByValue = /* @__PURE__ */ new Map();
1829
- values = [];
1830
- intern(value) {
1831
- const existing = this.indexByValue.get(value);
1832
- if (existing !== void 0) return existing;
1833
- const index = this.values.length;
1834
- this.indexByValue.set(value, index);
1835
- this.values.push(value);
1836
- return index;
1837
- }
1838
- entries() {
1839
- return this.values;
1840
- }
1841
- get size() {
1842
- return this.values.length;
1843
- }
1844
- };
1845
- //#endregion
1846
- //#region src/typed/xlsx.ts
1847
- const XlsxCellSchema = zod.z.object({
1848
- reference: zod.z.string(),
1849
- value: zod.z.string(),
1850
- formula: zod.z.string().optional()
1851
- });
1852
- const XlsxSheetSchema = zod.z.object({
1853
- name: zod.z.string(),
1854
- cells: zod.z.array(XlsxCellSchema),
1855
- mergedRanges: zod.z.array(zod.z.string())
1856
- });
1857
- const DefinedNameSchema = zod.z.object({
1858
- name: zod.z.string(),
1859
- refersTo: zod.z.string()
1860
- });
1861
- const XlsxWorkbookSchema = zod.z.object({
1862
- sheets: zod.z.array(XlsxSheetSchema),
1863
- definedNames: zod.z.array(DefinedNameSchema)
1864
- });
1865
- const SHEET_PATH_RE = /^xl\/worksheets\/sheet(\d+)\.xml$/;
1866
- function resolveRelTarget(target) {
1867
- if (target.startsWith("/")) return target.slice(1);
1868
- return `xl/${target}`;
1869
- }
1870
- function relTargets(pkg) {
1871
- const map = /* @__PURE__ */ new Map();
1872
- const rels = rootElement(pkg.parts["xl/_rels/workbook.xml.rels"]);
1873
- if (rels === void 0) return map;
1874
- for (const rel of childrenWithTag(rels, "Relationship")) {
1875
- const id = attr(rel, "Id");
1876
- const target = attr(rel, "Target");
1877
- if (id !== void 0 && target !== void 0) map.set(id, resolveRelTarget(target));
1878
- }
1879
- return map;
1880
- }
1881
- function resolveSheetNames(pkg) {
1882
- const names = /* @__PURE__ */ new Map();
1883
- const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
1884
- if (workbook === void 0) return names;
1885
- const targets = relTargets(pkg);
1886
- for (const sheet of elementsWithTag(workbook.children, "sheet")) {
1887
- const name = attr(sheet, "name");
1888
- const rid = attr(sheet, "r:id");
1889
- if (name !== void 0 && rid !== void 0) {
1890
- const partName = targets.get(rid);
1891
- if (partName !== void 0) names.set(partName, name);
1892
- }
1893
- }
1894
- return names;
1895
- }
1896
- function readDefinedNames(pkg) {
1897
- const names = [];
1898
- const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
1899
- if (workbook === void 0) return names;
1900
- for (const container of elementsWithTag(workbook.children, "definedNames")) for (const definedName of childrenWithTag(container, "definedName")) {
1901
- const name = attr(definedName, "name");
1902
- if (name === void 0) continue;
1903
- names.push({
1904
- name,
1905
- refersTo: textContent(definedName)
1906
- });
1907
- }
1908
- return names;
1909
- }
1910
- function sheetNumberOf(path) {
1911
- const match = SHEET_PATH_RE.exec(path);
1912
- const digits = match === null ? void 0 : match[1];
1913
- if (digits === void 0) return;
1914
- return Number.parseInt(digits, 10);
1915
- }
1916
- function readCell$1(cell, sharedStrings) {
1917
- const reference = attr(cell, "r");
1918
- if (reference === void 0) return;
1919
- const valueEl = childrenWithTag(cell, "v")[0];
1920
- if (valueEl === void 0) return;
1921
- const raw = textContent(valueEl);
1922
- let value;
1923
- if (attr(cell, "t") === "s") {
1924
- const index = Number.parseInt(raw, 10);
1925
- value = Number.isInteger(index) ? sharedStrings[index] : void 0;
1926
- } else value = raw;
1927
- if (value === void 0) return;
1928
- const projected = {
1929
- reference,
1930
- value
1931
- };
1932
- const formulaEl = childrenWithTag(cell, "f")[0];
1933
- if (formulaEl !== void 0) projected.formula = textContent(formulaEl);
1934
- return projected;
1935
- }
1936
- function readCells$1(worksheet, sharedStrings) {
1937
- const cells = [];
1938
- for (const row of elementsWithTag(worksheet.children, "row")) for (const cell of childrenWithTag(row, "c")) {
1939
- const projected = readCell$1(cell, sharedStrings);
1940
- if (projected !== void 0) cells.push(projected);
1941
- }
1942
- return cells;
1943
- }
1944
- function readMergedRanges(worksheet) {
1945
- const ranges = [];
1946
- for (const mergeCells of elementsWithTag(worksheet.children, "mergeCells")) for (const mergeCell of childrenWithTag(mergeCells, "mergeCell")) {
1947
- const ref = attr(mergeCell, "ref");
1948
- if (ref !== void 0) ranges.push(ref);
1949
- }
1950
- return ranges;
1951
- }
1952
- function readXlsx(pkg) {
1953
- const sharedStrings = loadSharedStrings(pkg);
1954
- const names = resolveSheetNames(pkg);
1955
- const definedNames = readDefinedNames(pkg);
1956
- const worksheets = Object.keys(pkg.parts).map((path) => ({
1957
- path,
1958
- number: sheetNumberOf(path)
1959
- })).filter((entry) => entry.number !== void 0).sort((a, b) => a.number - b.number);
1960
- const sheets = [];
1961
- for (const { path, number } of worksheets) {
1962
- const root = rootElement(pkg.parts[path]);
1963
- if (root === void 0) continue;
1964
- const name = names.get(path) ?? `Sheet${number}`;
1965
- sheets.push({
1966
- name,
1967
- cells: readCells$1(root, sharedStrings),
1968
- mergedRanges: readMergedRanges(root)
1969
- });
1970
- }
1971
- return {
1972
- sheets,
1973
- definedNames
1974
- };
1975
- }
1976
- //#endregion
1977
- //#region src/typed/xlsx/a1.ts
1978
- const CELL_REFERENCE_RE = /^([A-Za-z]+)(\d+)$/;
1979
- function columnLettersToIndex(letters) {
1980
- if (letters.length === 0) return;
1981
- let index = 0;
1982
- for (const ch of letters.toUpperCase()) {
1983
- const code = ch.charCodeAt(0);
1984
- if (code < 65 || code > 90) return;
1985
- index = index * 26 + (code - 64);
1986
- }
1987
- return index - 1;
1988
- }
1989
- function columnIndexToLetters(index) {
1990
- let remaining = index + 1;
1991
- let letters = "";
1992
- while (remaining > 0) {
1993
- const digit = (remaining - 1) % 26;
1994
- letters = String.fromCharCode(65 + digit) + letters;
1995
- remaining = Math.trunc((remaining - 1) / 26);
1996
- }
1997
- return letters;
1998
- }
1999
- function parseCellReference(ref) {
2000
- const match = CELL_REFERENCE_RE.exec(ref);
2001
- if (match === null) return;
2002
- const letters = match[1];
2003
- const digits = match[2];
2004
- if (letters === void 0 || digits === void 0) return;
2005
- const column = columnLettersToIndex(letters);
2006
- const rowNumber = Number.parseInt(digits, 10);
2007
- if (column === void 0 || !Number.isInteger(rowNumber) || rowNumber < 1) return;
2008
- return {
2009
- row: rowNumber - 1,
2010
- column
2011
- };
2012
- }
2013
- function cellReference(row, column) {
2014
- return `${columnIndexToLetters(column)}${row + 1}`;
2015
- }
2016
- function parseRangeReference(ref) {
2017
- const separatorIndex = ref.indexOf(":");
2018
- const startRaw = separatorIndex === -1 ? ref : ref.slice(0, separatorIndex);
2019
- const endRaw = separatorIndex === -1 ? ref : ref.slice(separatorIndex + 1);
2020
- const start = parseCellReference(startRaw);
2021
- const end = parseCellReference(endRaw);
2022
- if (start === void 0 || end === void 0) return;
2023
- return {
2024
- startRow: Math.min(start.row, end.row),
2025
- startColumn: Math.min(start.column, end.column),
2026
- endRow: Math.max(start.row, end.row),
2027
- endColumn: Math.max(start.column, end.column)
2028
- };
2029
- }
2030
- function rangeReference(range) {
2031
- return `${cellReference(range.startRow, range.startColumn)}:${cellReference(range.endRow, range.endColumn)}`;
2032
- }
2033
- //#endregion
2034
- //#region src/typed/xlsx/defined-names.ts
2035
- const XLNM_PRINT_AREA = "_xlnm.Print_Area";
2036
- const XLNM_PRINT_TITLES = "_xlnm.Print_Titles";
2037
- function readDefinedNamesBySheet(pkg) {
2038
- const map = /* @__PURE__ */ new Map();
2039
- const workbook = rootElement(pkg.parts["xl/workbook.xml"]);
2040
- if (workbook === void 0) return map;
2041
- const container = childrenWithTag(workbook, "definedNames")[0];
2042
- if (container === void 0) return map;
2043
- for (const definedName of childrenWithTag(container, "definedName")) {
2044
- const name = attr(definedName, "name");
2045
- const localSheetIdRaw = attr(definedName, "localSheetId");
2046
- if (name === void 0 || localSheetIdRaw === void 0) continue;
2047
- if (name !== "_xlnm.Print_Area" && name !== "_xlnm.Print_Titles") continue;
2048
- const sheetIndex = Number.parseInt(localSheetIdRaw, 10);
2049
- if (!Number.isInteger(sheetIndex) || sheetIndex < 0) continue;
2050
- const value = textContent(definedName);
2051
- const existing = map.get(sheetIndex) ?? {};
2052
- if (name === "_xlnm.Print_Area") existing.printArea = value;
2053
- else existing.printTitles = value;
2054
- map.set(sheetIndex, existing);
2055
- }
2056
- return map;
2057
- }
2058
- function stripSheetPrefix(segment) {
2059
- const bang = segment.lastIndexOf("!");
2060
- return bang === -1 ? segment : segment.slice(bang + 1);
2061
- }
2062
- function parsePrintAreaValue(value) {
2063
- const first = value.split(",")[0]?.trim();
2064
- if (first === void 0 || first.length === 0) return;
2065
- return parseRangeReference(stripSheetPrefix(first).replace(/\$/g, ""));
2066
- }
2067
- function parsePrintTitlesValue(value) {
2068
- const result = {};
2069
- for (const rawSegment of value.split(",")) {
2070
- const segment = stripSheetPrefix(rawSegment.trim()).replace(/\$/g, "");
2071
- const separatorIndex = segment.indexOf(":");
2072
- if (separatorIndex === -1) continue;
2073
- const startSpec = segment.slice(0, separatorIndex);
2074
- const endSpec = segment.slice(separatorIndex + 1);
2075
- if (/^[A-Za-z]+$/.test(startSpec) && /^[A-Za-z]+$/.test(endSpec)) {
2076
- const start = columnLettersToIndex(startSpec);
2077
- const end = columnLettersToIndex(endSpec);
2078
- if (start !== void 0 && end !== void 0) result.repeatColumns = {
2079
- start: Math.min(start, end),
2080
- end: Math.max(start, end)
2081
- };
2082
- } else if (/^\d+$/.test(startSpec) && /^\d+$/.test(endSpec)) {
2083
- const start = Number.parseInt(startSpec, 10) - 1;
2084
- const end = Number.parseInt(endSpec, 10) - 1;
2085
- result.repeatRows = {
2086
- start: Math.min(start, end),
2087
- end: Math.max(start, end)
2088
- };
2089
- }
2090
- }
2091
- return result;
2092
- }
2093
- function quoteSheetNameIfNeeded(sheetName) {
2094
- if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(sheetName)) return sheetName;
2095
- return `'${sheetName.replace(/'/g, "''")}'`;
2096
- }
2097
- function buildPrintAreaValue(sheetName, range) {
2098
- const dollared = rangeReference({
2099
- startRow: range.startRow,
2100
- startColumn: range.startColumn,
2101
- endRow: range.endRow,
2102
- endColumn: range.endColumn
2103
- }).replace(/([A-Z]+)(\d+)/g, "$$$1$$$2");
2104
- return `${quoteSheetNameIfNeeded(sheetName)}!${dollared}`;
2105
- }
2106
- function buildPrintTitlesValue(sheetName, repeatRows, repeatColumns) {
2107
- const quotedName = quoteSheetNameIfNeeded(sheetName);
2108
- const segments = [];
2109
- if (repeatColumns !== void 0) segments.push(`${quotedName}!$${columnIndexToLetters(repeatColumns.start)}:$${columnIndexToLetters(repeatColumns.end)}`);
2110
- if (repeatRows !== void 0) segments.push(`${quotedName}!$${repeatRows.start + 1}:$${repeatRows.end + 1}`);
2111
- return segments.length > 0 ? segments.join(",") : void 0;
2112
- }
2113
- //#endregion
2114
- //#region src/typed/xlsx/util.ts
2115
- function readXmlBool(value) {
2116
- return value === "1" || value === "true";
2117
- }
2118
- function writeXmlBool(value) {
2119
- return value ? "true" : "false";
2120
- }
2121
- const UNIVERSAL_MEASURE_RE = /^(-?\d+(?:\.\d+)?)(mm|cm|in|pt|pc|pi)$/;
2122
- function parseUniversalMeasureToPt(value) {
2123
- const match = UNIVERSAL_MEASURE_RE.exec(value.trim());
2124
- if (match === null) return;
2125
- const amountRaw = match[1];
2126
- const unit = match[2];
2127
- if (amountRaw === void 0 || unit === void 0) return;
2128
- const amount = Number(amountRaw);
2129
- switch (unit) {
2130
- case "mm": return amount / 25.4 * 72;
2131
- case "cm": return amount / 2.54 * 72;
2132
- case "in": return amount * 72;
2133
- case "pt": return amount;
2134
- case "pc":
2135
- case "pi": return amount * 12;
2136
- default: return;
2137
- }
2138
- }
2139
- function ptToUniversalMeasure(pt) {
2140
- return `${(pt / 72 * 2.54).toFixed(2)}cm`;
2141
- }
2142
- const PAPER_SIZE_BY_CODE = {
2143
- "1": document_schema_js.PAGE_SIZE_LETTER,
2144
- "9": document_schema_js.PAGE_SIZE_A4
2145
- };
2146
- function paperSizeCodeToPageSize(code) {
2147
- return PAPER_SIZE_BY_CODE[code];
2148
- }
2149
- const PAPER_SIZE_TOLERANCE_PT = .5;
2150
- function approximatelyEquals(a, b) {
2151
- return Math.abs(a - b) <= PAPER_SIZE_TOLERANCE_PT;
2152
- }
2153
- function pageSizeToPaperSizeCode(pageSize) {
2154
- if (approximatelyEquals(pageSize.widthPt, document_schema_js.PAGE_SIZE_LETTER.widthPt) && approximatelyEquals(pageSize.heightPt, document_schema_js.PAGE_SIZE_LETTER.heightPt)) return "1";
2155
- if (approximatelyEquals(pageSize.widthPt, document_schema_js.PAGE_SIZE_A4.widthPt) && approximatelyEquals(pageSize.heightPt, document_schema_js.PAGE_SIZE_A4.heightPt)) return "9";
2156
- }
2157
- //#endregion
2158
- //#region src/typed/xlsx/print-settings.ts
2159
- const DEFAULT_MARGINS = {
2160
- topPt: .75 * 72,
2161
- rightPt: .7 * 72,
2162
- bottomPt: .75 * 72,
2163
- leftPt: .7 * 72
2164
- };
2165
- const DEFAULT_HEADER_FOOTER_MARGIN_PT = .3 * 72;
2166
- const DEFAULT_FIT_TO_PAGES = 1;
2167
- function applyOrientation(pageSize, pageSetup) {
2168
- if ((pageSetup === void 0 ? void 0 : attr(pageSetup, "orientation")) !== "landscape") return pageSize;
2169
- return {
2170
- widthPt: pageSize.heightPt,
2171
- heightPt: pageSize.widthPt
2172
- };
2173
- }
2174
- function readPageSize(pageSetup) {
2175
- if (pageSetup === void 0) return document_schema_js.PAGE_SIZE_LETTER;
2176
- const paperSize = attr(pageSetup, "paperSize");
2177
- const byCode = paperSize === void 0 ? void 0 : paperSizeCodeToPageSize(paperSize);
2178
- if (byCode !== void 0) return applyOrientation(byCode, pageSetup);
2179
- const paperWidth = attr(pageSetup, "paperWidth");
2180
- const paperHeight = attr(pageSetup, "paperHeight");
2181
- const widthPt = paperWidth === void 0 ? void 0 : parseUniversalMeasureToPt(paperWidth);
2182
- const heightPt = paperHeight === void 0 ? void 0 : parseUniversalMeasureToPt(paperHeight);
2183
- return widthPt === void 0 || heightPt === void 0 ? document_schema_js.PAGE_SIZE_LETTER : applyOrientation({
2184
- widthPt,
2185
- heightPt
2186
- }, pageSetup);
2187
- }
2188
- function readMargins(pageMargins) {
2189
- if (pageMargins === void 0) return DEFAULT_MARGINS;
2190
- const top = attr(pageMargins, "top");
2191
- const right = attr(pageMargins, "right");
2192
- const bottom = attr(pageMargins, "bottom");
2193
- const left = attr(pageMargins, "left");
2194
- return {
2195
- topPt: top === void 0 ? DEFAULT_MARGINS.topPt : Number(top) * 72,
2196
- rightPt: right === void 0 ? DEFAULT_MARGINS.rightPt : Number(right) * 72,
2197
- bottomPt: bottom === void 0 ? DEFAULT_MARGINS.bottomPt : Number(bottom) * 72,
2198
- leftPt: left === void 0 ? DEFAULT_MARGINS.leftPt : Number(left) * 72
2199
- };
2200
- }
2201
- function readPageOrder(pageSetup) {
2202
- return (pageSetup === void 0 ? void 0 : attr(pageSetup, "pageOrder")) === "overThenDown" ? "overThenDown" : "downThenOver";
2203
- }
2204
- function readManualBreaks(worksheet) {
2205
- const rowBreaksEl = childrenWithTag(worksheet, "rowBreaks")[0];
2206
- const colBreaksEl = childrenWithTag(worksheet, "colBreaks")[0];
2207
- const rows = rowBreaksEl === void 0 ? [] : readBreakIndices(rowBreaksEl);
2208
- const columns = colBreaksEl === void 0 ? [] : readBreakIndices(colBreaksEl);
2209
- return rows.length > 0 || columns.length > 0 ? {
2210
- rows,
2211
- columns
2212
- } : void 0;
2213
- }
2214
- function readBreakIndices(container) {
2215
- const indices = [];
2216
- for (const brk of childrenWithTag(container, "brk")) {
2217
- const id = attr(brk, "id");
2218
- const index = id === void 0 ? void 0 : Number.parseInt(id, 10);
2219
- if (index !== void 0 && Number.isInteger(index) && index >= 0) indices.push(index);
2220
- }
2221
- return indices;
2222
- }
2223
- function readPrintSettings(worksheet, sheetIndex, definedNamesBySheet) {
2224
- const sheetPr = childrenWithTag(worksheet, "sheetPr")[0];
2225
- const pageSetUpPr = sheetPr === void 0 ? void 0 : childrenWithTag(sheetPr, "pageSetUpPr")[0];
2226
- const fitToPage = readXmlBool(pageSetUpPr === void 0 ? void 0 : attr(pageSetUpPr, "fitToPage"));
2227
- const pageSetup = childrenWithTag(worksheet, "pageSetup")[0];
2228
- const pageMargins = childrenWithTag(worksheet, "pageMargins")[0];
2229
- const printOptions = childrenWithTag(worksheet, "printOptions")[0];
2230
- const manualBreaks = readManualBreaks(worksheet);
2231
- const definedNames = definedNamesBySheet.get(sheetIndex);
2232
- const settings = {
2233
- pageSize: readPageSize(pageSetup),
2234
- margins: readMargins(pageMargins),
2235
- gridlines: readXmlBool(printOptions === void 0 ? void 0 : attr(printOptions, "gridLines")),
2236
- headers: readXmlBool(printOptions === void 0 ? void 0 : attr(printOptions, "headings")),
2237
- pageOrder: readPageOrder(pageSetup)
2238
- };
2239
- if (fitToPage) {
2240
- const fitToWidthRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "fitToWidth");
2241
- const fitToHeightRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "fitToHeight");
2242
- settings.fitToPages = {
2243
- width: fitToWidthRaw === void 0 ? DEFAULT_FIT_TO_PAGES : Number(fitToWidthRaw),
2244
- height: fitToHeightRaw === void 0 ? DEFAULT_FIT_TO_PAGES : Number(fitToHeightRaw)
2245
- };
2246
- } else {
2247
- const scaleRaw = pageSetup === void 0 ? void 0 : attr(pageSetup, "scale");
2248
- if (scaleRaw !== void 0) {
2249
- const scale = Number(scaleRaw);
2250
- if (Number.isFinite(scale)) settings.scale = scale;
2251
- }
2252
- }
2253
- if (manualBreaks !== void 0) settings.manualBreaks = manualBreaks;
2254
- if (definedNames?.printArea !== void 0) {
2255
- const range = parsePrintAreaValue(definedNames.printArea);
2256
- if (range !== void 0) settings.printRange = range;
2257
- }
2258
- if (definedNames?.printTitles !== void 0) {
2259
- const titles = parsePrintTitlesValue(definedNames.printTitles);
2260
- if (titles.repeatRows !== void 0) settings.repeatRows = titles.repeatRows;
2261
- if (titles.repeatColumns !== void 0) settings.repeatColumns = titles.repeatColumns;
2262
- }
2263
- return settings;
2264
- }
2265
- function columnWidthCharsToPt(width) {
2266
- const digitWidthAllowance = Math.trunc(128 / 7);
2267
- return Math.trunc((256 * width + digitWidthAllowance) / 256 * 7) / 96 * 72;
2268
- }
2269
- function ptToColumnWidthChars(widthPt) {
2270
- const pixels = widthPt / 72 * 96;
2271
- const digitWidthAllowance = Math.trunc(128 / 7);
2272
- return pixels / 7 - digitWidthAllowance / 256;
2273
- }
2274
- //#endregion
2275
- //#region src/typed/xlsx/content.ts
2276
- const WORKBOOK_PATH = "xl/workbook.xml";
2277
- function resolveSheetEntries(pkg) {
2278
- const workbook = rootElement(pkg.parts[WORKBOOK_PATH]);
2279
- if (workbook === void 0) return [];
2280
- const sheetsEl = childrenWithTag(workbook, "sheets")[0];
2281
- if (sheetsEl === void 0) return [];
2282
- const rels = resolveRelationships(pkg, WORKBOOK_PATH);
2283
- const entries = [];
2284
- for (const sheet of childrenWithTag(sheetsEl, "sheet")) {
2285
- const name = attr(sheet, "name");
2286
- const rId = attr(sheet, "r:id");
2287
- const rel = rId === void 0 ? void 0 : rels.get(rId);
2288
- if (name !== void 0 && rel !== void 0) entries.push({
2289
- name,
2290
- path: rel.target
2291
- });
2292
- }
2293
- return entries;
2294
- }
2295
- function sheetFormatDefaultRowHeightPt(worksheet) {
2296
- const sheetFormatPr = childrenWithTag(worksheet, "sheetFormatPr")[0];
2297
- const raw = sheetFormatPr === void 0 ? void 0 : attr(sheetFormatPr, "defaultRowHeight");
2298
- if (raw === void 0) return 15;
2299
- const parsed = Number(raw);
2300
- return Number.isFinite(parsed) ? parsed : 15;
2301
- }
2302
- function readColumns(worksheet) {
2303
- const colsEl = childrenWithTag(worksheet, "cols")[0];
2304
- if (colsEl === void 0) return [];
2305
- const columns = [];
2306
- for (const col of childrenWithTag(colsEl, "col")) {
2307
- const minRaw = attr(col, "min");
2308
- const min = minRaw === void 0 ? void 0 : Number.parseInt(minRaw, 10);
2309
- if (min === void 0 || !Number.isInteger(min) || min < 1) continue;
2310
- const widthRaw = attr(col, "width");
2311
- const widthPt = widthRaw === void 0 ? 0 : columnWidthCharsToPt(Number(widthRaw));
2312
- const column = {
2313
- index: min - 1,
2314
- widthPt: Number.isFinite(widthPt) ? widthPt : 0
2315
- };
2316
- if (readXmlBool(attr(col, "hidden"))) column.hidden = true;
2317
- columns.push(column);
2318
- }
2319
- return columns;
2320
- }
2321
- function readRows(worksheet) {
2322
- const sheetData = childrenWithTag(worksheet, "sheetData")[0];
2323
- if (sheetData === void 0) return [];
2324
- const fallbackHeightPt = sheetFormatDefaultRowHeightPt(worksheet);
2325
- const rows = [];
2326
- for (const row of childrenWithTag(sheetData, "row")) {
2327
- const rRaw = attr(row, "r");
2328
- const rowNumber = rRaw === void 0 ? void 0 : Number.parseInt(rRaw, 10);
2329
- if (rowNumber === void 0 || !Number.isInteger(rowNumber) || rowNumber < 1) continue;
2330
- const htRaw = attr(row, "ht");
2331
- const heightPt = htRaw === void 0 ? fallbackHeightPt : Number(htRaw);
2332
- const contentRow = {
2333
- index: rowNumber - 1,
2334
- heightPt: Number.isFinite(heightPt) ? heightPt : fallbackHeightPt
2335
- };
2336
- if (readXmlBool(attr(row, "hidden"))) contentRow.hidden = true;
2337
- rows.push(contentRow);
2338
- }
2339
- return rows;
2340
- }
2341
- function readInlineOrSharedStringText(container) {
2342
- let value = "";
2343
- for (const t of elementsWithTag(container.children, "t")) value += textContent(t);
2344
- return value;
2345
- }
2346
- function deriveDisplayText(value) {
2347
- switch (value.kind) {
2348
- case "number": return String(value.value);
2349
- case "boolean": return value.value ? "TRUE" : "FALSE";
2350
- case "string":
2351
- case "error":
2352
- case "date":
2353
- case "time": return value.value;
2354
- case "percentage":
2355
- case "currency": return String(value.value);
2356
- case "empty": return "";
2357
- }
2358
- }
2359
- function readCellValue(cell, sharedStrings) {
2360
- const type = attr(cell, "t");
2361
- if (type === "inlineStr") {
2362
- const is = childrenWithTag(cell, "is")[0];
2363
- const text = is === void 0 ? void 0 : readInlineOrSharedStringText(is);
2364
- return text === void 0 ? void 0 : {
2365
- value: {
2366
- kind: "string",
2367
- value: text
2368
- },
2369
- displayText: text
2370
- };
2371
- }
2372
- const valueEl = childrenWithTag(cell, "v")[0];
2373
- const raw = valueEl === void 0 ? void 0 : textContent(valueEl);
2374
- if (raw === void 0) return;
2375
- if (type === "s") {
2376
- const index = Number.parseInt(raw, 10);
2377
- const text = Number.isInteger(index) ? sharedStrings[index] : void 0;
2378
- return text === void 0 ? void 0 : {
2379
- value: {
2380
- kind: "string",
2381
- value: text
2382
- },
2383
- displayText: text
2384
- };
2385
- }
2386
- if (type === "str") return {
2387
- value: {
2388
- kind: "string",
2389
- value: raw
2390
- },
2391
- displayText: raw
2392
- };
2393
- if (type === "b") {
2394
- const value = {
2395
- kind: "boolean",
2396
- value: raw === "1" || raw.toLowerCase() === "true"
2397
- };
2398
- return {
2399
- value,
2400
- displayText: deriveDisplayText(value)
2401
- };
2402
- }
2403
- if (type === "e") return {
2404
- value: {
2405
- kind: "error",
2406
- value: raw
2407
- },
2408
- displayText: raw
2409
- };
2410
- if (type === "d") return {
2411
- value: {
2412
- kind: "date",
2413
- value: raw
2414
- },
2415
- displayText: raw
2416
- };
2417
- const num = Number(raw);
2418
- if (Number.isNaN(num)) return;
2419
- const value = {
2420
- kind: "number",
2421
- value: num
2422
- };
2423
- return {
2424
- value,
2425
- displayText: deriveDisplayText(value)
2426
- };
2427
- }
2428
- function readCell(cell, sharedStrings) {
2429
- const reference = attr(cell, "r");
2430
- const position = reference === void 0 ? void 0 : parseCellReference(reference);
2431
- if (position === void 0) return;
2432
- const formulaEl = childrenWithTag(cell, "f")[0];
2433
- const formula = formulaEl === void 0 ? void 0 : textContent(formulaEl);
2434
- const resolved = readCellValue(cell, sharedStrings);
2435
- if (resolved === void 0) {
2436
- if (formula === void 0) return;
2437
- return {
2438
- row: position.row,
2439
- column: position.column,
2440
- value: { kind: "empty" },
2441
- formula,
2442
- displayText: ""
2443
- };
2444
- }
2445
- const cellEntry = {
2446
- row: position.row,
2447
- column: position.column,
2448
- value: resolved.value,
2449
- displayText: resolved.displayText
2450
- };
2451
- if (formula !== void 0) cellEntry.formula = formula;
2452
- return cellEntry;
2453
- }
2454
- function applyMergedRanges(worksheet, cells) {
2455
- const mergeCellsEl = childrenWithTag(worksheet, "mergeCells")[0];
2456
- if (mergeCellsEl === void 0) return;
2457
- const byPosition = /* @__PURE__ */ new Map();
2458
- for (const cell of cells) byPosition.set(`${cell.row}:${cell.column}`, cell);
2459
- for (const mergeCell of childrenWithTag(mergeCellsEl, "mergeCell")) {
2460
- const ref = attr(mergeCell, "ref");
2461
- const range = ref === void 0 ? void 0 : parseRangeReference(ref);
2462
- if (range === void 0) continue;
2463
- const anchor = byPosition.get(`${range.startRow}:${range.startColumn}`);
2464
- if (anchor === void 0) continue;
2465
- const colSpan = range.endColumn - range.startColumn + 1;
2466
- const rowSpan = range.endRow - range.startRow + 1;
2467
- if (colSpan > 1) anchor.colSpan = colSpan;
2468
- if (rowSpan > 1) anchor.rowSpan = rowSpan;
2469
- }
2470
- }
2471
- function readCells(worksheet, sharedStrings) {
2472
- const sheetData = childrenWithTag(worksheet, "sheetData")[0];
2473
- if (sheetData === void 0) return [];
2474
- const cells = [];
2475
- for (const row of childrenWithTag(sheetData, "row")) for (const cell of childrenWithTag(row, "c")) {
2476
- const read = readCell(cell, sharedStrings);
2477
- if (read !== void 0) cells.push(read);
2478
- }
2479
- applyMergedRanges(worksheet, cells);
2480
- return cells;
2481
- }
2482
- function readSheet(pkg, entry, sheetIndex, sharedStrings, definedNamesBySheet) {
2483
- const worksheet = rootElement(pkg.parts[entry.path]);
2484
- if (worksheet === void 0) return {
2485
- name: entry.name,
2486
- cells: [],
2487
- columns: [],
2488
- rows: [],
2489
- images: [],
2490
- printSettings: readPrintSettings(fallbackEmptyWorksheet(), sheetIndex, definedNamesBySheet)
2491
- };
2492
- return {
2493
- name: entry.name,
2494
- cells: readCells(worksheet, sharedStrings),
2495
- columns: readColumns(worksheet),
2496
- rows: readRows(worksheet),
2497
- images: [],
2498
- printSettings: readPrintSettings(worksheet, sheetIndex, definedNamesBySheet)
2499
- };
2500
- }
2501
- function fallbackEmptyWorksheet() {
2502
- return {
2503
- type: "element",
2504
- tag: "worksheet",
2505
- attributes: [],
2506
- children: []
2507
- };
2508
- }
2509
- function readXlsxContent(pkg) {
2510
- const sharedStrings = loadSharedStrings(pkg);
2511
- const definedNamesBySheet = readDefinedNamesBySheet(pkg);
2512
- const sheets = resolveSheetEntries(pkg).map((entry, sheetIndex) => readSheet(pkg, entry, sheetIndex, sharedStrings, definedNamesBySheet));
2513
- return {
2514
- kind: "spreadsheet",
2515
- formatVersion: document_schema_js.CONTENT_FORMAT_VERSION,
2516
- metadata: readCoreProperties(pkg),
2517
- sheets
2518
- };
2519
- }
2520
- //#endregion
2521
- //#region src/typed/xlsx/build.ts
2522
- const SML_NS = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
2523
- const REL_NS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
2524
- const PKG_RELS_NS = "http://schemas.openxmlformats.org/package/2006/relationships";
2525
- const CONTENT_TYPES_NS = "http://schemas.openxmlformats.org/package/2006/content-types";
2526
- const CORE_PROPS_NS = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
2527
- const DC_NS = "http://purl.org/dc/elements/1.1/";
2528
- const DCTERMS_NS = "http://purl.org/dc/terms/";
2529
- const XSI_NS = "http://www.w3.org/2001/XMLSchema-instance";
2530
- const EXTENDED_PROPS_NS = "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties";
2531
- const CT_WORKBOOK = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
2532
- const CT_STYLES = "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml";
2533
- const CT_SHARED_STRINGS = "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml";
2534
- const CT_WORKSHEET = "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml";
2535
- const CT_CORE_PROPS = "application/vnd.openxmlformats-package.core-properties+xml";
2536
- const CT_EXTENDED_PROPS = "application/vnd.openxmlformats-officedocument.extended-properties+xml";
2537
- const REL_OFFICE_DOCUMENT = `${REL_NS}/officeDocument`;
2538
- const REL_CORE_PROPS = `${PKG_RELS_NS}/metadata/core-properties`;
2539
- const REL_EXTENDED_PROPS = `${REL_NS}/extended-properties`;
2540
- const REL_WORKSHEET = `${REL_NS}/worksheet`;
2541
- const REL_STYLES = `${REL_NS}/styles`;
2542
- const REL_SHARED_STRINGS = `${REL_NS}/sharedStrings`;
2543
- const MAX_COLUMN_INDEX = 16383;
2544
- const MAX_ROW_INDEX = 1048575;
2545
- function xmlDeclaration() {
2546
- return {
2547
- type: "declaration",
2548
- attributes: [
2549
- {
2550
- name: "version",
2551
- value: "1.0"
2552
- },
2553
- {
2554
- name: "encoding",
2555
- value: "UTF-8"
2556
- },
2557
- {
2558
- name: "standalone",
2559
- value: "yes"
2560
- }
2561
- ]
2562
- };
2563
- }
2564
- function xmlPart(root) {
2565
- return {
2566
- kind: "xml",
2567
- nodes: [xmlDeclaration(), root]
2568
- };
2569
- }
2570
- function buildContentTypesPart(sheetCount) {
2571
- const overrides = [
2572
- el("Override", {
2573
- PartName: "/xl/workbook.xml",
2574
- ContentType: CT_WORKBOOK
2575
- }),
2576
- el("Override", {
2577
- PartName: "/xl/styles.xml",
2578
- ContentType: CT_STYLES
2579
- }),
2580
- el("Override", {
2581
- PartName: "/xl/sharedStrings.xml",
2582
- ContentType: CT_SHARED_STRINGS
2583
- })
2584
- ];
2585
- for (let index = 0; index < sheetCount; index++) overrides.push(el("Override", {
2586
- PartName: `/xl/worksheets/sheet${index + 1}.xml`,
2587
- ContentType: CT_WORKSHEET
2588
- }));
2589
- overrides.push(el("Override", {
2590
- PartName: "/docProps/core.xml",
2591
- ContentType: CT_CORE_PROPS
2592
- }));
2593
- overrides.push(el("Override", {
2594
- PartName: "/docProps/app.xml",
2595
- ContentType: CT_EXTENDED_PROPS
2596
- }));
2597
- return xmlPart(el("Types", { xmlns: CONTENT_TYPES_NS }, [
2598
- el("Default", {
2599
- Extension: "rels",
2600
- ContentType: "application/vnd.openxmlformats-package.relationships+xml"
2601
- }),
2602
- el("Default", {
2603
- Extension: "xml",
2604
- ContentType: "application/xml"
2605
- }),
2606
- ...overrides
2607
- ]));
2608
- }
2609
- function buildPackageRelsPart() {
2610
- return xmlPart(el("Relationships", { xmlns: PKG_RELS_NS }, [
2611
- el("Relationship", {
2612
- Id: "rId1",
2613
- Type: REL_OFFICE_DOCUMENT,
2614
- Target: "xl/workbook.xml"
2615
- }),
2616
- el("Relationship", {
2617
- Id: "rId2",
2618
- Type: REL_CORE_PROPS,
2619
- Target: "docProps/core.xml"
2620
- }),
2621
- el("Relationship", {
2622
- Id: "rId3",
2623
- Type: REL_EXTENDED_PROPS,
2624
- Target: "docProps/app.xml"
2625
- })
2626
- ]));
2627
- }
2628
- function worksheetRelId(sheetIndex) {
2629
- return `rId${sheetIndex + 1}`;
2630
- }
2631
- function buildWorkbookRelsPart(sheetCount) {
2632
- const relationships = [];
2633
- for (let index = 0; index < sheetCount; index++) relationships.push(el("Relationship", {
2634
- Id: worksheetRelId(index),
2635
- Type: REL_WORKSHEET,
2636
- Target: `worksheets/sheet${index + 1}.xml`
2637
- }));
2638
- relationships.push(el("Relationship", {
2639
- Id: `rId${sheetCount + 1}`,
2640
- Type: REL_STYLES,
2641
- Target: "styles.xml"
2642
- }));
2643
- relationships.push(el("Relationship", {
2644
- Id: `rId${sheetCount + 2}`,
2645
- Type: REL_SHARED_STRINGS,
2646
- Target: "sharedStrings.xml"
2647
- }));
2648
- return xmlPart(el("Relationships", { xmlns: PKG_RELS_NS }, relationships));
2649
- }
2650
- function buildDefinedNameElements(sheets) {
2651
- const elements = [];
2652
- sheets.forEach((sheet, sheetIndex) => {
2653
- const { printRange, repeatRows, repeatColumns } = sheet.printSettings;
2654
- if (printRange !== void 0) {
2655
- const value = buildPrintAreaValue(sheet.name, printRange);
2656
- elements.push(el("definedName", {
2657
- name: XLNM_PRINT_AREA,
2658
- localSheetId: String(sheetIndex)
2659
- }, [txt(encodeXmlText(value))]));
2660
- }
2661
- if (repeatRows !== void 0 || repeatColumns !== void 0) {
2662
- const value = buildPrintTitlesValue(sheet.name, repeatRows, repeatColumns);
2663
- if (value !== void 0) elements.push(el("definedName", {
2664
- name: XLNM_PRINT_TITLES,
2665
- localSheetId: String(sheetIndex)
2666
- }, [txt(encodeXmlText(value))]));
2667
- }
2668
- });
2669
- return elements;
2670
- }
2671
- function buildWorkbookPart(sheets) {
2672
- const children = [el("sheets", {}, sheets.map((sheet, index) => el("sheet", {
2673
- name: encodeXmlText(sheet.name),
2674
- sheetId: String(index + 1),
2675
- "r:id": worksheetRelId(index)
2676
- })))];
2677
- const definedNameElements = buildDefinedNameElements(sheets);
2678
- if (definedNameElements.length > 0) children.push(el("definedNames", {}, definedNameElements));
2679
- return xmlPart(el("workbook", {
2680
- xmlns: SML_NS,
2681
- "xmlns:r": REL_NS
2682
- }, children));
2683
- }
2684
- function buildSharedStringsPart(sharedStrings) {
2685
- const entries = sharedStrings.entries();
2686
- const siElements = entries.map((value) => el("si", {}, [el("t", { "xml:space": "preserve" }, [txt(encodeXmlText(value))])]));
2687
- return xmlPart(el("sst", {
2688
- xmlns: SML_NS,
2689
- count: String(entries.length),
2690
- uniqueCount: String(entries.length)
2691
- }, siElements));
2692
- }
2693
- function buildStylesPart() {
2694
- return xmlPart(el("styleSheet", { xmlns: SML_NS }, [
2695
- el("fonts", { count: "1" }, [el("font", {}, [el("sz", { val: "11" }), el("name", { val: "Calibri" })])]),
2696
- el("fills", { count: "2" }, [el("fill", {}, [el("patternFill", { patternType: "none" })]), el("fill", {}, [el("patternFill", { patternType: "gray125" })])]),
2697
- el("borders", { count: "1" }, [el("border", {}, [
2698
- el("left"),
2699
- el("right"),
2700
- el("top"),
2701
- el("bottom"),
2702
- el("diagonal")
2703
- ])]),
2704
- el("cellStyleXfs", { count: "1" }, [el("xf", {
2705
- numFmtId: "0",
2706
- fontId: "0",
2707
- fillId: "0",
2708
- borderId: "0"
2709
- })]),
2710
- el("cellXfs", { count: "1" }, [el("xf", {
2711
- numFmtId: "0",
2712
- fontId: "0",
2713
- fillId: "0",
2714
- borderId: "0",
2715
- xfId: "0"
2716
- })]),
2717
- el("cellStyles", { count: "1" }, [el("cellStyle", {
2718
- name: "Normal",
2719
- xfId: "0",
2720
- builtinId: "0"
2721
- })])
2722
- ]));
2723
- }
2724
- function buildCorePropertiesPart(metadata) {
2725
- const children = [];
2726
- if (metadata.title !== void 0) children.push(el("dc:title", {}, [txt(encodeXmlText(metadata.title))]));
2727
- if (metadata.author !== void 0) children.push(el("dc:creator", {}, [txt(encodeXmlText(metadata.author))]));
2728
- if (metadata.subject !== void 0) children.push(el("dc:subject", {}, [txt(encodeXmlText(metadata.subject))]));
2729
- if (metadata.keywords !== void 0 && metadata.keywords.length > 0) children.push(el("cp:keywords", {}, [txt(encodeXmlText(metadata.keywords.join(", ")))]));
2730
- if (metadata.createdIso !== void 0) children.push(el("dcterms:created", { "xsi:type": "dcterms:W3CDTF" }, [txt(encodeXmlText(metadata.createdIso))]));
2731
- if (metadata.modifiedIso !== void 0) children.push(el("dcterms:modified", { "xsi:type": "dcterms:W3CDTF" }, [txt(encodeXmlText(metadata.modifiedIso))]));
2732
- return xmlPart(el("cp:coreProperties", {
2733
- "xmlns:cp": CORE_PROPS_NS,
2734
- "xmlns:dc": DC_NS,
2735
- "xmlns:dcterms": DCTERMS_NS,
2736
- "xmlns:xsi": XSI_NS
2737
- }, children));
2738
- }
2739
- function buildAppPropertiesPart(metadata) {
2740
- const children = [];
2741
- if (metadata.creator !== void 0) children.push(el("Application", {}, [txt(encodeXmlText(metadata.creator))]));
2742
- return xmlPart(el("Properties", { xmlns: EXTENDED_PROPS_NS }, children));
2743
- }
2744
- function computeDimension(sheet) {
2745
- let maxRow = 0;
2746
- let maxColumn = 0;
2747
- let hasAny = false;
2748
- for (const cell of sheet.cells) {
2749
- hasAny = true;
2750
- maxRow = Math.max(maxRow, cell.row);
2751
- maxColumn = Math.max(maxColumn, cell.column);
2752
- }
2753
- for (const column of sheet.columns) {
2754
- hasAny = true;
2755
- maxColumn = Math.max(maxColumn, column.index);
2756
- }
2757
- for (const row of sheet.rows) {
2758
- hasAny = true;
2759
- maxRow = Math.max(maxRow, row.index);
2760
- }
2761
- return hasAny ? rangeReference({
2762
- startRow: 0,
2763
- startColumn: 0,
2764
- endRow: maxRow,
2765
- endColumn: maxColumn
2766
- }) : "A1";
2767
- }
2768
- function buildColsElement(columns) {
2769
- if (columns.length === 0) return;
2770
- return el("cols", {}, columns.map((column) => {
2771
- const attrs = {
2772
- min: String(column.index + 1),
2773
- max: String(column.index + 1),
2774
- width: ptToColumnWidthChars(column.widthPt).toFixed(2),
2775
- customWidth: "true"
2776
- };
2777
- if (column.hidden === true) attrs.hidden = "true";
2778
- return el("col", attrs);
2779
- }));
2780
- }
2781
- function renderCellValue(value, isFormulaResult, sharedStrings) {
2782
- switch (value.kind) {
2783
- case "string":
2784
- if (isFormulaResult) return {
2785
- type: "str",
2786
- content: encodeXmlText(value.value)
2787
- };
2788
- return {
2789
- type: "s",
2790
- content: String(sharedStrings.intern(value.value))
2791
- };
2792
- case "number":
2793
- case "percentage":
2794
- case "currency": return { content: String(value.value) };
2795
- case "boolean": return {
2796
- type: "b",
2797
- content: value.value ? "1" : "0"
2798
- };
2799
- case "date":
2800
- case "time": return {
2801
- type: "d",
2802
- content: encodeXmlText(value.value)
2803
- };
2804
- case "error": return {
2805
- type: "e",
2806
- content: encodeXmlText(value.value)
2807
- };
2808
- case "empty": return;
2809
- }
2810
- }
2811
- function buildCellElement(cell, sharedStrings) {
2812
- const attrs = {
2813
- r: cellReference(cell.row, cell.column),
2814
- s: "0"
2815
- };
2816
- const children = [];
2817
- if (cell.formula !== void 0) children.push(el("f", {}, [txt(encodeXmlText(cell.formula))]));
2818
- const rendered = renderCellValue(cell.value, cell.formula !== void 0, sharedStrings);
2819
- if (rendered !== void 0) {
2820
- if (rendered.type !== void 0) attrs.t = rendered.type;
2821
- children.push(el("v", {}, [txt(rendered.content)]));
2822
- }
2823
- return el("c", attrs, children);
2824
- }
2825
- function buildSheetDataElement(sheet, sharedStrings) {
2826
- const cellsByRow = /* @__PURE__ */ new Map();
2827
- for (const cell of sheet.cells) {
2828
- const existing = cellsByRow.get(cell.row);
2829
- if (existing === void 0) cellsByRow.set(cell.row, [cell]);
2830
- else existing.push(cell);
2831
- }
2832
- const rowInfoByIndex = /* @__PURE__ */ new Map();
2833
- for (const row of sheet.rows) rowInfoByIndex.set(row.index, row);
2834
- return el("sheetData", {}, Array.from(/* @__PURE__ */ new Set([...cellsByRow.keys(), ...rowInfoByIndex.keys()])).sort((a, b) => a - b).map((rowIndex) => {
2835
- const cells = (cellsByRow.get(rowIndex) ?? []).slice().sort((a, b) => a.column - b.column);
2836
- const rowInfo = rowInfoByIndex.get(rowIndex);
2837
- const attrs = { r: String(rowIndex + 1) };
2838
- if (rowInfo !== void 0) {
2839
- attrs.ht = String(rowInfo.heightPt);
2840
- attrs.customHeight = "true";
2841
- if (rowInfo.hidden === true) attrs.hidden = "true";
2842
- }
2843
- return el("row", attrs, cells.map((cell) => buildCellElement(cell, sharedStrings)));
2844
- }));
2845
- }
2846
- function buildMergeCellsElement(cells) {
2847
- const merges = cells.filter((cell) => (cell.colSpan ?? 1) > 1 || (cell.rowSpan ?? 1) > 1);
2848
- if (merges.length === 0) return;
2849
- const mergeCellElements = merges.map((cell) => {
2850
- const endRow = cell.row + (cell.rowSpan ?? 1) - 1;
2851
- const endColumn = cell.column + (cell.colSpan ?? 1) - 1;
2852
- return el("mergeCell", { ref: rangeReference({
2853
- startRow: cell.row,
2854
- startColumn: cell.column,
2855
- endRow,
2856
- endColumn
2857
- }) });
2858
- });
2859
- return el("mergeCells", { count: String(mergeCellElements.length) }, mergeCellElements);
2860
- }
2861
- function buildSheetPrElement(settings) {
2862
- return el("sheetPr", {}, [el("pageSetUpPr", { fitToPage: writeXmlBool(settings.fitToPages !== void 0) })]);
2863
- }
2864
- function buildPrintOptionsElement(settings) {
2865
- return el("printOptions", {
2866
- gridLines: writeXmlBool(settings.gridlines),
2867
- headings: writeXmlBool(settings.headers)
2868
- });
2869
- }
2870
- function ptToInches(pt) {
2871
- return String(pt / 72);
2872
- }
2873
- function buildPageMarginsElement(settings) {
2874
- const margins = settings.margins;
2875
- return el("pageMargins", {
2876
- left: ptToInches(margins.leftPt),
2877
- right: ptToInches(margins.rightPt),
2878
- top: ptToInches(margins.topPt),
2879
- bottom: ptToInches(margins.bottomPt),
2880
- header: ptToInches(DEFAULT_HEADER_FOOTER_MARGIN_PT),
2881
- footer: ptToInches(DEFAULT_HEADER_FOOTER_MARGIN_PT)
2882
- });
2883
- }
2884
- function buildPageSetupElement(settings) {
2885
- const attrs = {};
2886
- const paperCode = pageSizeToPaperSizeCode(settings.pageSize);
2887
- if (paperCode !== void 0) attrs.paperSize = paperCode;
2888
- else {
2889
- attrs.paperWidth = ptToUniversalMeasure(settings.pageSize.widthPt);
2890
- attrs.paperHeight = ptToUniversalMeasure(settings.pageSize.heightPt);
2891
- }
2892
- attrs.scale = String(settings.scale ?? 100);
2893
- attrs.fitToWidth = String(settings.fitToPages?.width ?? 1);
2894
- attrs.fitToHeight = String(settings.fitToPages?.height ?? 1);
2895
- attrs.pageOrder = settings.pageOrder;
2896
- attrs.orientation = settings.pageSize.widthPt > settings.pageSize.heightPt ? "landscape" : "portrait";
2897
- return el("pageSetup", attrs);
2898
- }
2899
- function buildBreaksElements(settings) {
2900
- const manualBreaks = settings.manualBreaks;
2901
- if (manualBreaks === void 0) return {};
2902
- const result = {};
2903
- if (manualBreaks.rows.length > 0) {
2904
- const breaks = manualBreaks.rows.map((id) => el("brk", {
2905
- id: String(id),
2906
- min: "0",
2907
- max: String(MAX_COLUMN_INDEX),
2908
- man: "1"
2909
- }));
2910
- result.rowBreaks = el("rowBreaks", {
2911
- count: String(breaks.length),
2912
- manualBreakCount: String(breaks.length)
2913
- }, breaks);
2914
- }
2915
- if (manualBreaks.columns.length > 0) {
2916
- const breaks = manualBreaks.columns.map((id) => el("brk", {
2917
- id: String(id),
2918
- min: "0",
2919
- max: String(MAX_ROW_INDEX),
2920
- man: "1"
2921
- }));
2922
- result.colBreaks = el("colBreaks", {
2923
- count: String(breaks.length),
2924
- manualBreakCount: String(breaks.length)
2925
- }, breaks);
2926
- }
2927
- return result;
2928
- }
2929
- function buildWorksheetPart(sheet, sharedStrings) {
2930
- const children = [buildSheetPrElement(sheet.printSettings), el("dimension", { ref: computeDimension(sheet) })];
2931
- const colsElement = buildColsElement(sheet.columns);
2932
- if (colsElement !== void 0) children.push(colsElement);
2933
- children.push(buildSheetDataElement(sheet, sharedStrings));
2934
- const mergeCellsElement = buildMergeCellsElement(sheet.cells);
2935
- if (mergeCellsElement !== void 0) children.push(mergeCellsElement);
2936
- children.push(buildPrintOptionsElement(sheet.printSettings), buildPageMarginsElement(sheet.printSettings), buildPageSetupElement(sheet.printSettings));
2937
- const { rowBreaks, colBreaks } = buildBreaksElements(sheet.printSettings);
2938
- if (rowBreaks !== void 0) children.push(rowBreaks);
2939
- if (colBreaks !== void 0) children.push(colBreaks);
2940
- return xmlPart(el("worksheet", {
2941
- xmlns: SML_NS,
2942
- "xmlns:r": REL_NS
2943
- }, children));
2944
- }
2945
- function buildXlsxPackage(document) {
2946
- if (document.kind !== "spreadsheet") throw new Error(`buildXlsxPackage: expected a ContentDocument of kind "spreadsheet", got "${document.kind}"`);
2947
- const sheets = document.sheets;
2948
- const sharedStrings = new SharedStringTable();
2949
- const worksheetParts = sheets.map((sheet) => buildWorksheetPart(sheet, sharedStrings));
2950
- const parts = {
2951
- "[Content_Types].xml": buildContentTypesPart(sheets.length),
2952
- "_rels/.rels": buildPackageRelsPart(),
2953
- "xl/workbook.xml": buildWorkbookPart(sheets),
2954
- "xl/_rels/workbook.xml.rels": buildWorkbookRelsPart(sheets.length),
2955
- "xl/styles.xml": buildStylesPart(),
2956
- "xl/sharedStrings.xml": buildSharedStringsPart(sharedStrings),
2957
- "docProps/core.xml": buildCorePropertiesPart(document.metadata),
2958
- "docProps/app.xml": buildAppPropertiesPart(document.metadata)
2959
- };
2960
- worksheetParts.forEach((part, index) => {
2961
- parts[`xl/worksheets/sheet${index + 1}.xml`] = part;
2962
- });
2963
- return { parts };
2964
- }
2965
- //#endregion
2966
24
  Object.defineProperty(exports, "AlignmentSchema", {
2967
25
  enumerable: true,
2968
26
  get: function() {
2969
27
  return document_schema_js.AlignmentSchema;
2970
28
  }
2971
29
  });
2972
- exports.AttributeSchema = AttributeSchema;
2973
- exports.BinaryPartSchema = BinaryPartSchema;
30
+ exports.AttributeSchema = require_model_node.AttributeSchema;
31
+ exports.BinaryPartSchema = require_model_package.BinaryPartSchema;
2974
32
  Object.defineProperty(exports, "BoxSchema", {
2975
33
  enumerable: true,
2976
34
  get: function() {
@@ -2995,10 +53,10 @@ Object.defineProperty(exports, "ColorSchema", {
2995
53
  return document_schema_js.ColorSchema;
2996
54
  }
2997
55
  });
2998
- exports.CommentSchema = CommentSchema;
2999
- exports.CompactPackageSchema = CompactPackageSchema;
3000
- exports.CompactPartSchema = CompactPartSchema;
3001
- exports.CompactXmlNodeSchema = CompactXmlNodeSchema;
56
+ exports.CommentSchema = require_typed_docx_read.CommentSchema;
57
+ exports.CompactPackageSchema = require_compact.CompactPackageSchema;
58
+ exports.CompactPartSchema = require_compact.CompactPartSchema;
59
+ exports.CompactXmlNodeSchema = require_compact.CompactXmlNodeSchema;
3002
60
  Object.defineProperty(exports, "ContentBlockSchema", {
3003
61
  enumerable: true,
3004
62
  get: function() {
@@ -3131,10 +189,10 @@ Object.defineProperty(exports, "ContentTableSchema", {
3131
189
  return document_schema_js.ContentTableSchema;
3132
190
  }
3133
191
  });
3134
- exports.DefinedNameSchema = DefinedNameSchema;
3135
- exports.DocumentMetadataSchema = DocumentMetadataSchema;
3136
- exports.DocxDocumentSchema = DocxDocumentSchema;
3137
- exports.FootnoteSchema = FootnoteSchema;
192
+ exports.DefinedNameSchema = require_typed_xlsx.DefinedNameSchema;
193
+ exports.DocumentMetadataSchema = require_typed_shared_metadata.DocumentMetadataSchema;
194
+ exports.DocxDocumentSchema = require_typed_docx_read.DocxDocumentSchema;
195
+ exports.FootnoteSchema = require_typed_docx_read.FootnoteSchema;
3138
196
  Object.defineProperty(exports, "MarginsSchema", {
3139
197
  enumerable: true,
3140
198
  get: function() {
@@ -3153,15 +211,15 @@ Object.defineProperty(exports, "PAGE_SIZE_LETTER", {
3153
211
  return document_schema_js.PAGE_SIZE_LETTER;
3154
212
  }
3155
213
  });
3156
- exports.PackageSchema = PackageSchema;
214
+ exports.PackageSchema = require_model_package.PackageSchema;
3157
215
  Object.defineProperty(exports, "PageSizeSchema", {
3158
216
  enumerable: true,
3159
217
  get: function() {
3160
218
  return document_schema_js.PageSizeSchema;
3161
219
  }
3162
220
  });
3163
- exports.PartSchema = PartSchema;
3164
- exports.PptxDocumentSchema = PptxDocumentSchema;
221
+ exports.PartSchema = require_model_package.PartSchema;
222
+ exports.PptxDocumentSchema = require_typed_pptx_read.PptxDocumentSchema;
3165
223
  Object.defineProperty(exports, "SLIDE_SIZE_STANDARD", {
3166
224
  enumerable: true,
3167
225
  get: function() {
@@ -3174,70 +232,70 @@ Object.defineProperty(exports, "SLIDE_SIZE_WIDESCREEN", {
3174
232
  return document_schema_js.SLIDE_SIZE_WIDESCREEN;
3175
233
  }
3176
234
  });
3177
- exports.XlsxCellSchema = XlsxCellSchema;
3178
- exports.XlsxSheetSchema = XlsxSheetSchema;
3179
- exports.XlsxWorkbookSchema = XlsxWorkbookSchema;
3180
- exports.XmlCdataSchema = XmlCdataSchema;
3181
- exports.XmlCommentSchema = XmlCommentSchema;
3182
- exports.XmlDeclarationSchema = XmlDeclarationSchema;
3183
- exports.XmlElementSchema = XmlElementSchema;
3184
- exports.XmlNodeSchema = XmlNodeSchema;
3185
- exports.XmlPartSchema = XmlPartSchema;
3186
- exports.XmlPiSchema = XmlPiSchema;
3187
- exports.XmlTextSchema = XmlTextSchema;
3188
- exports.applyColorTransforms = applyColorTransforms;
3189
- exports.attr = attr;
3190
- exports.base64ToBytes = base64ToBytes;
3191
- exports.buildXlsxPackage = buildXlsxPackage;
3192
- exports.buildXml = buildXml;
3193
- exports.bytesToBase64 = bytesToBase64;
3194
- exports.childrenWithTag = childrenWithTag;
235
+ exports.XlsxCellSchema = require_typed_xlsx.XlsxCellSchema;
236
+ exports.XlsxSheetSchema = require_typed_xlsx.XlsxSheetSchema;
237
+ exports.XlsxWorkbookSchema = require_typed_xlsx.XlsxWorkbookSchema;
238
+ exports.XmlCdataSchema = require_model_node.XmlCdataSchema;
239
+ exports.XmlCommentSchema = require_model_node.XmlCommentSchema;
240
+ exports.XmlDeclarationSchema = require_model_node.XmlDeclarationSchema;
241
+ exports.XmlElementSchema = require_model_node.XmlElementSchema;
242
+ exports.XmlNodeSchema = require_model_node.XmlNodeSchema;
243
+ exports.XmlPartSchema = require_model_package.XmlPartSchema;
244
+ exports.XmlPiSchema = require_model_node.XmlPiSchema;
245
+ exports.XmlTextSchema = require_model_node.XmlTextSchema;
246
+ exports.applyColorTransforms = require_typed_shared_color.applyColorTransforms;
247
+ exports.attr = require_typed_util.attr;
248
+ exports.base64ToBytes = require_util_base64.base64ToBytes;
249
+ exports.buildXlsxPackage = require_typed_xlsx_build.buildXlsxPackage;
250
+ exports.buildXml = require_xml_build.buildXml;
251
+ exports.bytesToBase64 = require_util_base64.bytesToBase64;
252
+ exports.childrenWithTag = require_typed_util.childrenWithTag;
3195
253
  Object.defineProperty(exports, "colorToRgbHex", {
3196
254
  enumerable: true,
3197
255
  get: function() {
3198
256
  return document_schema_js.colorToRgbHex;
3199
257
  }
3200
258
  });
3201
- exports.compactCodec = compactCodec;
3202
- exports.compactPackageCodec = compactPackageCodec;
3203
- exports.decodeCompactPackage = decodeCompactPackage;
3204
- exports.decodeEntities = decodeEntities;
3205
- exports.decodePackage = decodePackage;
3206
- exports.el = el;
3207
- exports.elementsWithTag = elementsWithTag;
3208
- exports.encodeCompactPackage = encodeCompactPackage;
3209
- exports.encodePackage = encodePackage;
3210
- exports.encodeXmlText = encodeXmlText;
3211
- exports.fromCompact = fromCompact;
3212
- exports.isCompactXmlNode = isCompactXmlNode;
259
+ exports.compactCodec = require_compact.compactCodec;
260
+ exports.compactPackageCodec = require_compact.compactPackageCodec;
261
+ exports.decodeCompactPackage = require_compact.decodeCompactPackage;
262
+ exports.decodeEntities = require_typed_util.decodeEntities;
263
+ exports.decodePackage = require_codec.decodePackage;
264
+ exports.el = require_xml_fragment.el;
265
+ exports.elementsWithTag = require_typed_util.elementsWithTag;
266
+ exports.encodeCompactPackage = require_compact.encodeCompactPackage;
267
+ exports.encodePackage = require_codec.encodePackage;
268
+ exports.encodeXmlText = require_xml_entities.encodeXmlText;
269
+ exports.fromCompact = require_compact.fromCompact;
270
+ exports.isCompactXmlNode = require_compact.isCompactXmlNode;
3213
271
  Object.defineProperty(exports, "isContentBlock", {
3214
272
  enumerable: true,
3215
273
  get: function() {
3216
274
  return document_schema_js.isContentBlock;
3217
275
  }
3218
276
  });
3219
- exports.isXmlNode = isXmlNode;
3220
- exports.packageCodec = packageCodec;
3221
- exports.parsePackage = parsePackage;
3222
- exports.parseXml = parseXml;
3223
- exports.readDocx = readDocx;
3224
- exports.readPptx = readPptx;
3225
- exports.readXlsx = readXlsx;
3226
- exports.readXlsxContent = readXlsxContent;
3227
- exports.resolveRelationships = resolveRelationships;
277
+ exports.isXmlNode = require_model_node.isXmlNode;
278
+ exports.packageCodec = require_codec.packageCodec;
279
+ exports.parsePackage = require_package_io_read.parsePackage;
280
+ exports.parseXml = require_xml_parse.parseXml;
281
+ exports.readDocx = require_typed_docx_read.readDocx;
282
+ exports.readPptx = require_typed_pptx_read.readPptx;
283
+ exports.readXlsx = require_typed_xlsx.readXlsx;
284
+ exports.readXlsxContent = require_typed_xlsx_content.readXlsxContent;
285
+ exports.resolveRelationships = require_typed_util.resolveRelationships;
3228
286
  Object.defineProperty(exports, "rgbHexToColor", {
3229
287
  enumerable: true,
3230
288
  get: function() {
3231
289
  return document_schema_js.rgbHexToColor;
3232
290
  }
3233
291
  });
3234
- exports.rootElement = rootElement;
3235
- exports.serializePackage = serializePackage;
3236
- exports.sniffImageFormat = sniffImageFormat;
3237
- exports.textContent = textContent;
3238
- exports.toCompact = toCompact;
3239
- exports.txt = txt;
3240
- exports.unzipPackage = unzipPackage;
3241
- exports.walk = walk;
3242
- exports.xmlCodec = xmlCodec;
3243
- exports.zipPackage = zipPackage;
292
+ exports.rootElement = require_typed_util.rootElement;
293
+ exports.serializePackage = require_package_io_write.serializePackage;
294
+ exports.sniffImageFormat = require_image_sniff.sniffImageFormat;
295
+ exports.textContent = require_typed_util.textContent;
296
+ exports.toCompact = require_compact.toCompact;
297
+ exports.txt = require_xml_fragment.txt;
298
+ exports.unzipPackage = require_zip.unzipPackage;
299
+ exports.walk = require_typed_util.walk;
300
+ exports.xmlCodec = require_codec.xmlCodec;
301
+ exports.zipPackage = require_zip.zipPackage;