@stll/docx-core 0.39.2 → 0.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/archive-yBR7X-Qc.js +456 -0
- package/dist/errors-Dm3jsb5q.d.ts +57 -0
- package/dist/format-DXPXB02u.js +378 -0
- package/dist/index.d.ts +0 -7
- package/dist/index.js +106 -193
- package/dist/zip/archive.d.ts +114 -0
- package/dist/zip/archive.js +3 -0
- package/dist/zip/stream.d.ts +30 -0
- package/dist/zip/stream.js +117 -0
- package/package.json +10 -6
- package/dist/zip/writeZipPart.d.ts +0 -10
- package/dist/zip/writeZipPart.js +0 -16
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import { T as borderStyleToken, Z as headingOutlineLevel, _t as isCanonicallyEmptyParagraphFormatting, ct as paragraphNumberingReferenceId, d as isNoteReferenceId, f as isOoxmlSymbolCharacter, gt as finalizeParagraphFormatting, k as statesNoBorder, lt as paragraphNumberingSlots, ot as paragraphNumberingLevel, r as DOCX_CONFORMANCE_CLASSES, s as MAX_REVISION_ID, st as paragraphNumberingReference, vt as setDocumentBodyComments } from "./document-NtScxyHH.js";
|
|
2
2
|
import { i as serializeSequenceChildren } from "./sequenceChildren-CrMcryEF.js";
|
|
3
|
-
import {
|
|
3
|
+
import { _ as ZipError } from "./format-DXPXB02u.js";
|
|
4
|
+
import { t as ZipArchive } from "./archive-yBR7X-Qc.js";
|
|
4
5
|
import { a as hasIllegalXmlCharacters, i as escapeXmlText, n as sanitizeMarkdownHref, o as sanitizeXmlCharacters, r as escapeXmlAttribute, t as sanitizeExternalUrl } from "./href-ogmJmncc.js";
|
|
5
6
|
import { Result, TaggedError, panic } from "better-result";
|
|
6
|
-
import JSZip from "jszip";
|
|
7
|
-
import { decodeText, encodeUtf8 } from "@stll/utf8-boundaries";
|
|
8
7
|
import { XMLParser, XMLValidator } from "fast-xml-parser";
|
|
8
|
+
import { decodeText } from "@stll/utf8-boundaries";
|
|
9
9
|
import { ENTITY_ACTION, EntityDecoder } from "@nodable/entities";
|
|
10
10
|
import { Marked } from "marked";
|
|
11
11
|
// src/serialize/numericIds.ts
|
|
@@ -360,62 +360,22 @@ const APP_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><P
|
|
|
360
360
|
* not the other way round.
|
|
361
361
|
*/
|
|
362
362
|
const serializeDocumentToDocx = async (document, options = {}) => {
|
|
363
|
-
const zip = new
|
|
363
|
+
const zip = new ZipArchive();
|
|
364
364
|
const hasNumbering = hasNumberingDefinitions(document.package.numbering);
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
});
|
|
380
|
-
writeZipPart({
|
|
381
|
-
zip,
|
|
382
|
-
path: "docProps/core.xml",
|
|
383
|
-
data: encodeUtf8(serializeCoreProperties(document))
|
|
384
|
-
});
|
|
385
|
-
writeZipPart({
|
|
386
|
-
zip,
|
|
387
|
-
path: "word/document.xml",
|
|
388
|
-
data: encodeUtf8(serializeDocumentXml(document))
|
|
389
|
-
});
|
|
390
|
-
writeZipPart({
|
|
391
|
-
zip,
|
|
392
|
-
path: "word/styles.xml",
|
|
393
|
-
data: encodeUtf8(serializeStyles(document.package.styles))
|
|
394
|
-
});
|
|
395
|
-
if (hasNumbering) writeZipPart({
|
|
396
|
-
zip,
|
|
397
|
-
path: "word/numbering.xml",
|
|
398
|
-
data: encodeUtf8(serializeNumbering(document.package.numbering))
|
|
399
|
-
});
|
|
400
|
-
writeZipPart({
|
|
401
|
-
zip,
|
|
402
|
-
path: `word/${DEFAULT_FOOTER_PART_NAME}`,
|
|
403
|
-
data: encodeUtf8(buildFooterXml(options.language))
|
|
404
|
-
});
|
|
405
|
-
writeZipPart({
|
|
406
|
-
zip,
|
|
407
|
-
path: "word/_rels/document.xml.rels",
|
|
408
|
-
data: encodeUtf8(documentRelsXml(hasNumbering))
|
|
409
|
-
});
|
|
410
|
-
for (const [path, file] of Object.entries(zip.files)) {
|
|
411
|
-
if (file.dir || !path.endsWith(".xml")) continue;
|
|
412
|
-
assertValidOoxmlNumericIds(await file.async("uint8array").then((bytes) => decodeText(bytes, { ignoreBOM: true })), path);
|
|
413
|
-
}
|
|
414
|
-
return await zip.generateAsync({
|
|
415
|
-
type: "arraybuffer",
|
|
416
|
-
compression: "DEFLATE",
|
|
417
|
-
compressionOptions: { level: 6 }
|
|
418
|
-
});
|
|
365
|
+
zip.set("[Content_Types].xml", contentTypesXml(hasNumbering));
|
|
366
|
+
zip.set("_rels/.rels", ROOT_RELS_XML);
|
|
367
|
+
zip.set("docProps/app.xml", APP_XML);
|
|
368
|
+
zip.set("docProps/core.xml", serializeCoreProperties(document));
|
|
369
|
+
zip.set("word/document.xml", serializeDocumentXml(document));
|
|
370
|
+
zip.set("word/styles.xml", serializeStyles(document.package.styles));
|
|
371
|
+
if (hasNumbering) zip.set("word/numbering.xml", serializeNumbering(document.package.numbering));
|
|
372
|
+
zip.set(`word/${DEFAULT_FOOTER_PART_NAME}`, buildFooterXml(options.language));
|
|
373
|
+
zip.set("word/_rels/document.xml.rels", documentRelsXml(hasNumbering));
|
|
374
|
+
for (const entry of zip.entries()) {
|
|
375
|
+
if (!entry.path.endsWith(".xml")) continue;
|
|
376
|
+
assertValidOoxmlNumericIds(await entry.text(), entry.path);
|
|
377
|
+
}
|
|
378
|
+
return (await zip.generate()).buffer;
|
|
419
379
|
};
|
|
420
380
|
const hasNumberingDefinitions = (numbering) => (numbering?.abstractNums.length ?? 0) > 0 || (numbering?.nums.length ?? 0) > 0;
|
|
421
381
|
const serializeDocumentXml = (document) => {
|
|
@@ -1038,14 +998,6 @@ const packageXmlParser = new XMLParser({
|
|
|
1038
998
|
processEntities: false,
|
|
1039
999
|
ignoreDeclaration: true
|
|
1040
1000
|
});
|
|
1041
|
-
const getDeclaredUncompressedSize = (file) => {
|
|
1042
|
-
const metadata = file._data;
|
|
1043
|
-
return typeof metadata?.uncompressedSize === "number" ? metadata.uncompressedSize : null;
|
|
1044
|
-
};
|
|
1045
|
-
const getCompressedSize = (file) => {
|
|
1046
|
-
const metadata = file._data;
|
|
1047
|
-
return typeof metadata?.compressedSize === "number" ? metadata.compressedSize : null;
|
|
1048
|
-
};
|
|
1049
1001
|
const RATIO_BOUNDED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1050
1002
|
"xml",
|
|
1051
1003
|
"rels",
|
|
@@ -1058,106 +1010,79 @@ const RATIO_BOUNDED_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
|
1058
1010
|
"rtf"
|
|
1059
1011
|
]);
|
|
1060
1012
|
const isRatioBoundedPart = (path) => RATIO_BOUNDED_EXTENSIONS.has(path.slice(path.lastIndexOf(".") + 1).toLowerCase());
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
offset = bytes.indexOf(80, offset + 1);
|
|
1076
|
-
}
|
|
1077
|
-
return count;
|
|
1078
|
-
};
|
|
1079
|
-
const concatChunks = (chunks, totalBytes) => {
|
|
1080
|
-
const merged = new Uint8Array(totalBytes);
|
|
1081
|
-
let offset = 0;
|
|
1082
|
-
for (const chunk of chunks) {
|
|
1083
|
-
merged.set(chunk, offset);
|
|
1084
|
-
offset += chunk.length;
|
|
1013
|
+
/** The archive refusal `validateDocxPackage` reports for a read limit. */
|
|
1014
|
+
const archiveBoundsMessage = (error) => {
|
|
1015
|
+
const entry = error.path === void 0 ? "" : ` entry "${error.path}"`;
|
|
1016
|
+
switch (error.reason) {
|
|
1017
|
+
case "too-many-entries": return `Generated DOCX holds more than ${VALIDATE_DOCX_MAX_ENTRIES} archive entries.`;
|
|
1018
|
+
case "entry-too-large": return `Generated DOCX${entry} declares more than ${VALIDATE_DOCX_MAX_ENTRY_BYTES} uncompressed bytes.`;
|
|
1019
|
+
case "total-too-large": return `Generated DOCX declares more than ${VALIDATE_DOCX_MAX_TOTAL_BYTES} cumulative uncompressed bytes.`;
|
|
1020
|
+
case "compression-ratio": return error.path === void 0 ? `Generated DOCX declares more than ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO} uncompressed bytes per archive byte.` : `Generated DOCX${entry} declares more than ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO} uncompressed bytes per compressed byte.`;
|
|
1021
|
+
case "declared-size-exceeded": return `Generated DOCX${entry} inflates past its declared size.`;
|
|
1022
|
+
case "corrupt-entry": return `Generated DOCX${entry} does not match its declared size and checksum.`;
|
|
1023
|
+
case "malformed":
|
|
1024
|
+
case "unsupported":
|
|
1025
|
+
case "invalid-entry-name":
|
|
1026
|
+
case "duplicate-entry": return null;
|
|
1085
1027
|
}
|
|
1086
|
-
return merged;
|
|
1087
1028
|
};
|
|
1088
1029
|
/**
|
|
1089
|
-
*
|
|
1090
|
-
*
|
|
1091
|
-
* with its declared size only after inflating all of it, so the declared
|
|
1092
|
-
* size alone does not bound the allocation.
|
|
1030
|
+
* Read one XML part, refusing it from its declared size before inflating.
|
|
1031
|
+
* Inflation itself stops at the declared size.
|
|
1093
1032
|
*/
|
|
1094
|
-
const
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
const stop = (error) => {
|
|
1103
|
-
settled = true;
|
|
1104
|
-
stream.pause();
|
|
1105
|
-
resolve({
|
|
1106
|
-
ok: false,
|
|
1107
|
-
error
|
|
1108
|
-
});
|
|
1109
|
-
};
|
|
1110
|
-
stream.on("data", (chunk) => {
|
|
1111
|
-
if (settled) return;
|
|
1112
|
-
entryBytes += chunk.length;
|
|
1113
|
-
if (declaredBytes !== null && entryBytes > declaredBytes) {
|
|
1114
|
-
stop(`Generated DOCX entry "${entry.name}" inflates past its declared size.`);
|
|
1115
|
-
return;
|
|
1116
|
-
}
|
|
1117
|
-
if (exceedsCompressionRatio(entryBytes, compressedBytes)) {
|
|
1118
|
-
stop(`Generated DOCX entry "${entry.name}" exceeds the ${VALIDATE_DOCX_MAX_COMPRESSION_RATIO}:1 compression ratio limit.`);
|
|
1119
|
-
return;
|
|
1120
|
-
}
|
|
1121
|
-
if (entryBytes > maxBytes) {
|
|
1122
|
-
stop(`Generated DOCX ${entry.name} exceeds the ${maxBytes}-byte limit.`);
|
|
1123
|
-
return;
|
|
1124
|
-
}
|
|
1125
|
-
chunks.push(chunk);
|
|
1126
|
-
}).on("end", () => {
|
|
1127
|
-
if (settled) return;
|
|
1128
|
-
settled = true;
|
|
1129
|
-
resolve({
|
|
1130
|
-
ok: true,
|
|
1131
|
-
bytes: concatChunks(chunks, entryBytes)
|
|
1132
|
-
});
|
|
1133
|
-
}).on("error", (error) => {
|
|
1134
|
-
if (settled) return;
|
|
1135
|
-
settled = true;
|
|
1136
|
-
reject(error);
|
|
1137
|
-
}).resume();
|
|
1033
|
+
const readXmlPart = async (entry, maxBytes) => {
|
|
1034
|
+
if (entry.size > maxBytes) return {
|
|
1035
|
+
ok: false,
|
|
1036
|
+
error: `Generated DOCX ${entry.path} declares ${entry.size} uncompressed bytes, over the ${maxBytes}-byte limit.`
|
|
1037
|
+
};
|
|
1038
|
+
const bytes = await Result.tryPromise({
|
|
1039
|
+
try: async () => await entry.bytes(),
|
|
1040
|
+
catch: (cause) => cause
|
|
1138
1041
|
});
|
|
1042
|
+
if (Result.isOk(bytes)) return {
|
|
1043
|
+
ok: true,
|
|
1044
|
+
text: decodeText(bytes.value)
|
|
1045
|
+
};
|
|
1046
|
+
const error = bytes.error;
|
|
1047
|
+
if (!(error instanceof ZipError)) throw error;
|
|
1048
|
+
return {
|
|
1049
|
+
ok: false,
|
|
1050
|
+
error: archiveBoundsMessage(error) ?? error.message
|
|
1051
|
+
};
|
|
1139
1052
|
};
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
if (
|
|
1160
|
-
|
|
1053
|
+
const openArchive = async (bytes) => {
|
|
1054
|
+
const read = await Result.tryPromise({
|
|
1055
|
+
try: async () => await ZipArchive.read(bytes, {
|
|
1056
|
+
limits: {
|
|
1057
|
+
maxEntries: VALIDATE_DOCX_MAX_ENTRIES,
|
|
1058
|
+
maxEntryBytes: VALIDATE_DOCX_MAX_ENTRY_BYTES,
|
|
1059
|
+
maxTotalBytes: VALIDATE_DOCX_MAX_TOTAL_BYTES,
|
|
1060
|
+
maxCompressionRatio: VALIDATE_DOCX_MAX_COMPRESSION_RATIO,
|
|
1061
|
+
compressionRatioGraceBytes: VALIDATE_DOCX_COMPRESSION_RATIO_GRACE_BYTES
|
|
1062
|
+
},
|
|
1063
|
+
isCompressionRatioExempt: (path) => !isRatioBoundedPart(path)
|
|
1064
|
+
}),
|
|
1065
|
+
catch: (cause) => cause
|
|
1066
|
+
});
|
|
1067
|
+
if (Result.isOk(read)) return {
|
|
1068
|
+
ok: true,
|
|
1069
|
+
zip: read.value
|
|
1070
|
+
};
|
|
1071
|
+
const error = read.error;
|
|
1072
|
+
if (!(error instanceof ZipError)) throw error;
|
|
1073
|
+
const bounds = archiveBoundsMessage(error);
|
|
1074
|
+
return {
|
|
1075
|
+
ok: false,
|
|
1076
|
+
result: bounds === null ? {
|
|
1077
|
+
valid: false,
|
|
1078
|
+
code: DOCX_PACKAGE_ISSUE_CODES.InvalidArchive,
|
|
1079
|
+
error: error.message
|
|
1080
|
+
} : {
|
|
1081
|
+
valid: false,
|
|
1082
|
+
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1083
|
+
error: bounds
|
|
1084
|
+
}
|
|
1085
|
+
};
|
|
1161
1086
|
};
|
|
1162
1087
|
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1163
1088
|
const elementName = (node) => Object.keys(node).find((key) => key !== ":@" && !key.startsWith("?")) ?? null;
|
|
@@ -1192,57 +1117,46 @@ const validateDocumentXml = (xml) => {
|
|
|
1192
1117
|
const validateDocxPackage = async (buffer) => {
|
|
1193
1118
|
try {
|
|
1194
1119
|
const archiveBytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
error: `Generated DOCX holds more than ${VALIDATE_DOCX_MAX_ENTRIES} archive entries.`
|
|
1199
|
-
};
|
|
1200
|
-
const zip = await JSZip.loadAsync(buffer);
|
|
1201
|
-
const boundsError = checkDocxArchiveBounds(zip, archiveBytes.byteLength);
|
|
1202
|
-
if (boundsError) return {
|
|
1203
|
-
valid: false,
|
|
1204
|
-
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1205
|
-
error: boundsError
|
|
1206
|
-
};
|
|
1120
|
+
const opened = await openArchive(archiveBytes);
|
|
1121
|
+
if (!opened.ok) return opened.result;
|
|
1122
|
+
const { zip } = opened;
|
|
1207
1123
|
for (const requiredPath of [
|
|
1208
1124
|
"[Content_Types].xml",
|
|
1209
1125
|
"_rels/.rels",
|
|
1210
1126
|
"word/document.xml"
|
|
1211
|
-
]) if (!zip.
|
|
1127
|
+
]) if (!zip.has(requiredPath)) return {
|
|
1212
1128
|
valid: false,
|
|
1213
1129
|
code: DOCX_PACKAGE_ISSUE_CODES.MissingPackagePart,
|
|
1214
1130
|
error: `Generated DOCX is missing required package part: ${requiredPath}`
|
|
1215
1131
|
};
|
|
1216
|
-
const documentPart = zip.
|
|
1217
|
-
|
|
1218
|
-
if (declaredDocumentBytes !== null && declaredDocumentBytes > VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) return {
|
|
1132
|
+
const documentPart = zip.entry("word/document.xml");
|
|
1133
|
+
if (documentPart !== void 0 && documentPart.size > VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) return {
|
|
1219
1134
|
valid: false,
|
|
1220
1135
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1221
|
-
error: `Generated DOCX word/document.xml declares ${
|
|
1136
|
+
error: `Generated DOCX word/document.xml declares ${documentPart.size} uncompressed bytes, over the ${VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES}-byte limit.`
|
|
1222
1137
|
};
|
|
1223
|
-
const documentRead = documentPart ? await
|
|
1138
|
+
const documentRead = documentPart ? await readXmlPart(documentPart, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) : void 0;
|
|
1224
1139
|
if (documentRead !== void 0 && !documentRead.ok) return {
|
|
1225
1140
|
valid: false,
|
|
1226
1141
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1227
1142
|
error: documentRead.error
|
|
1228
1143
|
};
|
|
1229
|
-
const
|
|
1230
|
-
const documentXml = documentBytes ? decodeText(documentBytes) : void 0;
|
|
1144
|
+
const documentXml = documentRead?.text;
|
|
1231
1145
|
const documentError = documentXml ? validateDocumentXml(documentXml) : "Generated DOCX has no word/document.xml root document.";
|
|
1232
1146
|
if (documentError) return {
|
|
1233
1147
|
valid: false,
|
|
1234
1148
|
code: DOCX_PACKAGE_ISSUE_CODES.InvalidDocumentRoot,
|
|
1235
1149
|
error: documentError
|
|
1236
1150
|
};
|
|
1237
|
-
const documentRelsPart = zip.
|
|
1238
|
-
const documentRelsRead = documentRelsPart ? await
|
|
1151
|
+
const documentRelsPart = zip.entry("word/_rels/document.xml.rels");
|
|
1152
|
+
const documentRelsRead = documentRelsPart ? await readXmlPart(documentRelsPart, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES) : void 0;
|
|
1239
1153
|
if (documentRelsRead !== void 0 && !documentRelsRead.ok) return {
|
|
1240
1154
|
valid: false,
|
|
1241
1155
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1242
1156
|
error: documentRelsRead.error
|
|
1243
1157
|
};
|
|
1244
|
-
const documentRelsXml = documentRelsRead
|
|
1245
|
-
if (documentRelsXml?.includes("/relationships/numbering") && !zip.
|
|
1158
|
+
const documentRelsXml = documentRelsRead?.text;
|
|
1159
|
+
if (documentRelsXml?.includes("/relationships/numbering") && !zip.has("word/numbering.xml")) return {
|
|
1246
1160
|
valid: false,
|
|
1247
1161
|
code: DOCX_PACKAGE_ISSUE_CODES.MissingNumberingPart,
|
|
1248
1162
|
error: "Generated DOCX references numbering.xml but does not include it."
|
|
@@ -1251,27 +1165,26 @@ const validateDocxPackage = async (buffer) => {
|
|
|
1251
1165
|
if (documentXml) parts.set("word/document.xml", documentXml);
|
|
1252
1166
|
if (documentRelsXml) parts.set("word/_rels/document.xml.rels", documentRelsXml);
|
|
1253
1167
|
const paths = /* @__PURE__ */ new Set();
|
|
1254
|
-
for (const entry of
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
let xml = parts.get(entry.name);
|
|
1168
|
+
for (const entry of zip.entries()) {
|
|
1169
|
+
paths.add(entry.path);
|
|
1170
|
+
if (!entry.path.endsWith(".xml") && !entry.path.endsWith(".rels")) continue;
|
|
1171
|
+
let xml = parts.get(entry.path);
|
|
1259
1172
|
if (xml === void 0) {
|
|
1260
|
-
const read = await
|
|
1173
|
+
const read = await readXmlPart(entry, VALIDATE_DOCX_MAX_DOCUMENT_XML_BYTES);
|
|
1261
1174
|
if (!read.ok) return {
|
|
1262
1175
|
valid: false,
|
|
1263
1176
|
code: DOCX_PACKAGE_ISSUE_CODES.ArchiveBoundsExceeded,
|
|
1264
1177
|
error: read.error
|
|
1265
1178
|
};
|
|
1266
|
-
xml =
|
|
1179
|
+
xml = read.text;
|
|
1267
1180
|
}
|
|
1268
1181
|
const issue = validateSchemaAttributes(xml);
|
|
1269
1182
|
if (issue) return {
|
|
1270
1183
|
valid: false,
|
|
1271
1184
|
code: DOCX_PACKAGE_ISSUE_CODES.InvalidSchemaAttribute,
|
|
1272
|
-
error: `${entry.
|
|
1185
|
+
error: `${entry.path}: ${issue}`
|
|
1273
1186
|
};
|
|
1274
|
-
parts.set(entry.
|
|
1187
|
+
parts.set(entry.path, xml);
|
|
1275
1188
|
}
|
|
1276
1189
|
const graphIssue = validatePackageGraph(parts, paths);
|
|
1277
1190
|
if (graphIssue) return {
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { a as ZipCodec, i as InflateOutcome, n as ZipErrorReason, r as InflateExpectation, t as ZipError } from "../errors-Dm3jsb5q.js";
|
|
2
|
+
import { Result } from "better-result";
|
|
3
|
+
/** The compression an entry is written with. */
|
|
4
|
+
type ZipCompression = "store" | "deflate";
|
|
5
|
+
/** Whether `path` is a relative, forward-slash name with no `..` segment. */
|
|
6
|
+
export declare const isSafeZipPath: (path: string) => boolean;
|
|
7
|
+
/** Bounds a read enforces. Every byte limit counts inflated bytes. */
|
|
8
|
+
type ZipReadLimits = {
|
|
9
|
+
/** Records the central directory may hold, directories included. */
|
|
10
|
+
readonly maxEntries: number;
|
|
11
|
+
/** Inflated bytes one entry may declare. */
|
|
12
|
+
readonly maxEntryBytes: number;
|
|
13
|
+
/** Inflated bytes all entries together may declare. */
|
|
14
|
+
readonly maxTotalBytes: number;
|
|
15
|
+
/**
|
|
16
|
+
* Inflated bytes per compressed byte, for each entry and for the archive
|
|
17
|
+
* as a whole. Sizes under `compressionRatioGraceBytes` are exempt: a small
|
|
18
|
+
* part can compress extremely well without costing anything to hold.
|
|
19
|
+
*/
|
|
20
|
+
readonly maxCompressionRatio: number;
|
|
21
|
+
readonly compressionRatioGraceBytes: number;
|
|
22
|
+
};
|
|
23
|
+
/**
|
|
24
|
+
* Defaults sized for office packages. A DEFLATE stream tops out near 1032:1;
|
|
25
|
+
* markup in real documents stays under 75:1.
|
|
26
|
+
*/
|
|
27
|
+
export declare const ZIP_DEFAULT_READ_LIMITS: ZipReadLimits;
|
|
28
|
+
/** Entry content. Text is written as UTF-8. */
|
|
29
|
+
export type ZipEntryData = string | Uint8Array | ArrayBuffer;
|
|
30
|
+
/** How {@link ZipArchive.set} writes one entry. */
|
|
31
|
+
export type ZipEntryOptions = {
|
|
32
|
+
/** Overrides the archive-wide compression passed to `generate`. */
|
|
33
|
+
readonly compression?: ZipCompression;
|
|
34
|
+
/** Overrides the archive-wide DEFLATE level passed to `generate`. */
|
|
35
|
+
readonly level?: number;
|
|
36
|
+
/** Entry timestamp; defaults to 2000-01-01T00:00Z for reproducible output. */
|
|
37
|
+
readonly modified?: Date;
|
|
38
|
+
};
|
|
39
|
+
/** How {@link ZipArchive.read} bounds an archive. */
|
|
40
|
+
export type ZipReadOptions = {
|
|
41
|
+
/** Limits to apply; omitted fields take {@link ZIP_DEFAULT_READ_LIMITS}. */
|
|
42
|
+
readonly limits?: Partial<ZipReadLimits>;
|
|
43
|
+
/**
|
|
44
|
+
* Entries the per-entry compression-ratio cap skips, such as binary parts
|
|
45
|
+
* that legitimately compress like a run of one byte. They still count
|
|
46
|
+
* toward the archive-wide ratio and every byte limit.
|
|
47
|
+
*/
|
|
48
|
+
readonly isCompressionRatioExempt?: (path: string) => boolean;
|
|
49
|
+
/** DEFLATE implementation; defaults to the platform's. */
|
|
50
|
+
readonly codec?: ZipCodec;
|
|
51
|
+
};
|
|
52
|
+
/** How {@link ZipArchive.generate} writes new and replaced entries. */
|
|
53
|
+
export type ZipGenerateOptions = {
|
|
54
|
+
/** Defaults to `"deflate"`. Entries passed through keep their compression. */
|
|
55
|
+
readonly compression?: ZipCompression;
|
|
56
|
+
/** DEFLATE level 0-9; defaults to 6. */
|
|
57
|
+
readonly level?: number;
|
|
58
|
+
/** Timestamp for every entry, replacing the ones read or set. */
|
|
59
|
+
readonly modified?: Date;
|
|
60
|
+
};
|
|
61
|
+
/** One entry of a {@link ZipArchive}. */
|
|
62
|
+
export type ZipEntry = {
|
|
63
|
+
/** Entry name, a relative forward-slash path. */
|
|
64
|
+
readonly path: string;
|
|
65
|
+
/** Inflated size in bytes. */
|
|
66
|
+
readonly size: number;
|
|
67
|
+
/** Entry timestamp, read as UTC with two seconds of resolution. */
|
|
68
|
+
readonly modified: Date;
|
|
69
|
+
/**
|
|
70
|
+
* The entry's bytes. A read entry inflates at most its declared size and
|
|
71
|
+
* must match its CRC-32; anything else rejects with a {@link ZipError}.
|
|
72
|
+
*/
|
|
73
|
+
readonly bytes: () => Promise<Uint8Array<ArrayBuffer>>;
|
|
74
|
+
/** The entry decoded as UTF-8, keeping any byte-order mark. */
|
|
75
|
+
readonly text: () => Promise<string>;
|
|
76
|
+
/** The entry's bytes in an `ArrayBuffer` of exactly their length. */
|
|
77
|
+
readonly arrayBuffer: () => Promise<ArrayBuffer>;
|
|
78
|
+
};
|
|
79
|
+
/** An editable, bounded, in-memory ZIP archive. */
|
|
80
|
+
export declare class ZipArchive {
|
|
81
|
+
#private;
|
|
82
|
+
constructor(options?: {
|
|
83
|
+
readonly codec?: ZipCodec;
|
|
84
|
+
});
|
|
85
|
+
/**
|
|
86
|
+
* Read an archive. Rejects with a {@link ZipError} when the archive is
|
|
87
|
+
* malformed or exceeds a limit; entries inflate later, on demand. The
|
|
88
|
+
* archive keeps a reference to `input`, which must not change afterwards.
|
|
89
|
+
*/
|
|
90
|
+
static read(input: Uint8Array | ArrayBuffer, options?: ZipReadOptions): Promise<ZipArchive>;
|
|
91
|
+
/** Entry names in archive order. */
|
|
92
|
+
paths(): string[];
|
|
93
|
+
/** Entries in archive order. */
|
|
94
|
+
entries(): ZipEntry[];
|
|
95
|
+
/** Whether an entry named `path` exists. */
|
|
96
|
+
has(path: string): boolean;
|
|
97
|
+
/** The entry named `path`, or `undefined`. */
|
|
98
|
+
entry(path: string): ZipEntry | undefined;
|
|
99
|
+
/**
|
|
100
|
+
* Add or replace one entry. A replaced entry keeps its position. No parent
|
|
101
|
+
* directory entries are created.
|
|
102
|
+
*/
|
|
103
|
+
set(path: string, data: ZipEntryData, options?: ZipEntryOptions): void;
|
|
104
|
+
/**
|
|
105
|
+
* An independent copy: later edits to either archive leave the other
|
|
106
|
+
* unchanged. Entry content is shared, never copied, since it is immutable.
|
|
107
|
+
*/
|
|
108
|
+
clone(): ZipArchive;
|
|
109
|
+
/** Remove an entry; returns whether it existed. */
|
|
110
|
+
delete(path: string): boolean;
|
|
111
|
+
/** Write the archive. Entries read and not replaced keep their bytes. */
|
|
112
|
+
generate({ compression, level, modified }?: ZipGenerateOptions): Promise<Uint8Array<ArrayBuffer>>;
|
|
113
|
+
}
|
|
114
|
+
export { type InflateExpectation, type InflateOutcome, type ZipCodec, type ZipCompression, ZipError, type ZipErrorReason, type ZipReadLimits };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { a as ZipCodec, n as ZipErrorReason, t as ZipError } from "../errors-Dm3jsb5q.js";
|
|
2
|
+
/** Content of one streamed entry. */
|
|
3
|
+
export type ZipStreamData = string | Uint8Array | AsyncIterable<Uint8Array> | Iterable<Uint8Array>;
|
|
4
|
+
/**
|
|
5
|
+
* One entry of a streamed archive. A path ending in `/` is a directory entry
|
|
6
|
+
* and takes no data.
|
|
7
|
+
*/
|
|
8
|
+
export type ZipStreamEntry = {
|
|
9
|
+
readonly path: string;
|
|
10
|
+
readonly data?: ZipStreamData;
|
|
11
|
+
/** Entry timestamp; defaults to 2000-01-01T00:00Z. */
|
|
12
|
+
readonly modified?: Date;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* The archive bytes for `entries`, produced as they are consumed. Entries
|
|
16
|
+
* are pulled one at a time, so a source that opens a download per entry
|
|
17
|
+
* opens it only when the archive reaches it.
|
|
18
|
+
*/
|
|
19
|
+
export declare function zipStream(entries: AsyncIterable<ZipStreamEntry> | Iterable<ZipStreamEntry>, { codec }?: {
|
|
20
|
+
readonly codec?: ZipCodec;
|
|
21
|
+
}): AsyncGenerator<Uint8Array>;
|
|
22
|
+
/**
|
|
23
|
+
* {@link zipStream} as a `ReadableStream`. The stream pulls the next chunk
|
|
24
|
+
* only when its consumer asks, so a slow consumer slows the sources rather
|
|
25
|
+
* than buffering them.
|
|
26
|
+
*/
|
|
27
|
+
export declare const createZipStream: (entries: AsyncIterable<ZipStreamEntry> | Iterable<ZipStreamEntry>, options?: {
|
|
28
|
+
readonly codec?: ZipCodec;
|
|
29
|
+
}) => ReadableStream<Uint8Array>;
|
|
30
|
+
export { ZipError, type ZipErrorReason };
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { _ as ZipError, d as encodeEndOfCentralDirectory, f as encodeEntryName, g as toDosDateTime, h as isSafeZipPath, l as encodeCentralHeader, p as encodeLocalHeader, r as FIXED_DOS_DATE_TIME, u as encodeDataDescriptor, y as platformZipCodec } from "../format-DXPXB02u.js";
|
|
2
|
+
import { encodeUtf8 } from "@stll/utf8-boundaries";
|
|
3
|
+
// src/zip/stream.ts
|
|
4
|
+
/**
|
|
5
|
+
* A streaming ZIP writer for archives too large to hold in memory.
|
|
6
|
+
*
|
|
7
|
+
* Entries are stored, not compressed, and their bytes flow straight from the
|
|
8
|
+
* input to the output: each entry's CRC-32 and size are counted as it passes
|
|
9
|
+
* and written in a data descriptor after it, and Zip64 records are used when
|
|
10
|
+
* a size, an offset or the entry count outgrows the classic fields. Memory
|
|
11
|
+
* holds one chunk at a time plus one small central-directory record per
|
|
12
|
+
* entry.
|
|
13
|
+
*/
|
|
14
|
+
async function* entryChunks(data) {
|
|
15
|
+
if (data === void 0) return;
|
|
16
|
+
if (typeof data === "string") {
|
|
17
|
+
yield encodeUtf8(data);
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (data instanceof Uint8Array) {
|
|
21
|
+
yield data;
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
yield* data;
|
|
25
|
+
}
|
|
26
|
+
const invalidName = (path) => new ZipError({
|
|
27
|
+
message: "Archive entry name must be a relative path",
|
|
28
|
+
reason: "invalid-entry-name",
|
|
29
|
+
path
|
|
30
|
+
});
|
|
31
|
+
/**
|
|
32
|
+
* The archive bytes for `entries`, produced as they are consumed. Entries
|
|
33
|
+
* are pulled one at a time, so a source that opens a download per entry
|
|
34
|
+
* opens it only when the archive reaches it.
|
|
35
|
+
*/
|
|
36
|
+
async function* zipStream(entries, { codec = platformZipCodec() } = {}) {
|
|
37
|
+
const centralHeaders = [];
|
|
38
|
+
const names = /* @__PURE__ */ new Set();
|
|
39
|
+
let offset = 0;
|
|
40
|
+
for await (const { path, data, modified } of entries) {
|
|
41
|
+
if (!isSafeZipPath(path)) throw invalidName(path);
|
|
42
|
+
if (names.has(path)) throw new ZipError({
|
|
43
|
+
message: "Archive names an entry twice",
|
|
44
|
+
reason: "duplicate-entry",
|
|
45
|
+
path
|
|
46
|
+
});
|
|
47
|
+
names.add(path);
|
|
48
|
+
const directory = path.endsWith("/");
|
|
49
|
+
if (directory && data !== void 0) throw invalidName(path);
|
|
50
|
+
const name = encodeEntryName(path);
|
|
51
|
+
const header = {
|
|
52
|
+
name: name.bytes,
|
|
53
|
+
flags: name.flags | 8,
|
|
54
|
+
method: 0,
|
|
55
|
+
dateTime: modified === void 0 ? FIXED_DOS_DATE_TIME : toDosDateTime(modified),
|
|
56
|
+
crc32: 0,
|
|
57
|
+
compressedSize: 0,
|
|
58
|
+
uncompressedSize: 0,
|
|
59
|
+
directory
|
|
60
|
+
};
|
|
61
|
+
const localOffset = offset;
|
|
62
|
+
const local = encodeLocalHeader(header);
|
|
63
|
+
yield local;
|
|
64
|
+
offset += local.byteLength;
|
|
65
|
+
let crc32 = 0;
|
|
66
|
+
let size = 0;
|
|
67
|
+
for await (const chunk of entryChunks(data)) {
|
|
68
|
+
if (chunk.byteLength === 0) continue;
|
|
69
|
+
crc32 = codec.crc32(chunk, crc32);
|
|
70
|
+
size += chunk.byteLength;
|
|
71
|
+
yield chunk;
|
|
72
|
+
}
|
|
73
|
+
offset += size;
|
|
74
|
+
const record = {
|
|
75
|
+
...header,
|
|
76
|
+
crc32,
|
|
77
|
+
compressedSize: size,
|
|
78
|
+
uncompressedSize: size
|
|
79
|
+
};
|
|
80
|
+
const descriptor = encodeDataDescriptor(record);
|
|
81
|
+
yield descriptor;
|
|
82
|
+
offset += descriptor.byteLength;
|
|
83
|
+
centralHeaders.push(encodeCentralHeader(record, localOffset));
|
|
84
|
+
}
|
|
85
|
+
let directorySize = 0;
|
|
86
|
+
for (const header of centralHeaders) {
|
|
87
|
+
yield header;
|
|
88
|
+
directorySize += header.byteLength;
|
|
89
|
+
}
|
|
90
|
+
yield encodeEndOfCentralDirectory({
|
|
91
|
+
entryCount: centralHeaders.length,
|
|
92
|
+
offset,
|
|
93
|
+
size: directorySize
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* {@link zipStream} as a `ReadableStream`. The stream pulls the next chunk
|
|
98
|
+
* only when its consumer asks, so a slow consumer slows the sources rather
|
|
99
|
+
* than buffering them.
|
|
100
|
+
*/
|
|
101
|
+
const createZipStream = (entries, options = {}) => {
|
|
102
|
+
const chunks = zipStream(entries, options);
|
|
103
|
+
return new ReadableStream({
|
|
104
|
+
pull: async (controller) => {
|
|
105
|
+
const { done, value } = await chunks.next();
|
|
106
|
+
if (done) {
|
|
107
|
+
controller.close();
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
controller.enqueue(value);
|
|
111
|
+
},
|
|
112
|
+
cancel: async () => {
|
|
113
|
+
await chunks.return(void 0);
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
export { ZipError, createZipStream, zipStream };
|