@rahul_dadhich15/archive-kit 0.0.0-stage → 0.1.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/CHANGELOG.md +48 -0
- package/LICENSE +21 -0
- package/README.md +385 -2
- package/dist/gzip/index.cjs +439 -0
- package/dist/gzip/index.cjs.map +1 -0
- package/dist/gzip/index.d.cts +174 -0
- package/dist/gzip/index.d.ts +174 -0
- package/dist/gzip/index.js +424 -0
- package/dist/gzip/index.js.map +1 -0
- package/dist/index.cjs +1320 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +120 -0
- package/dist/index.d.ts +120 -0
- package/dist/index.js +1260 -0
- package/dist/index.js.map +1 -0
- package/dist/types-CY4dTVyZ.d.cts +34 -0
- package/dist/types-CY4dTVyZ.d.ts +34 -0
- package/dist/zip-create/index.cjs +357 -0
- package/dist/zip-create/index.cjs.map +1 -0
- package/dist/zip-create/index.d.cts +120 -0
- package/dist/zip-create/index.d.ts +120 -0
- package/dist/zip-create/index.js +350 -0
- package/dist/zip-create/index.js.map +1 -0
- package/dist/zip-extract/index.cjs +701 -0
- package/dist/zip-extract/index.cjs.map +1 -0
- package/dist/zip-extract/index.d.cts +298 -0
- package/dist/zip-extract/index.d.ts +298 -0
- package/dist/zip-extract/index.js +685 -0
- package/dist/zip-extract/index.js.map +1 -0
- package/package.json +91 -4
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { zip, zipSync } from 'fflate';
|
|
2
|
+
|
|
3
|
+
// src/shared/errors.ts
|
|
4
|
+
var ArchiveKitError = class _ArchiveKitError extends Error {
|
|
5
|
+
code;
|
|
6
|
+
details;
|
|
7
|
+
constructor(code, message, details) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "ArchiveKitError";
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.details = details;
|
|
12
|
+
Object.setPrototypeOf(this, _ArchiveKitError.prototype);
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// src/shared/binary.ts
|
|
17
|
+
async function toUint8Array(input) {
|
|
18
|
+
if (input instanceof Uint8Array) {
|
|
19
|
+
return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
20
|
+
}
|
|
21
|
+
if (input instanceof ArrayBuffer) {
|
|
22
|
+
return new Uint8Array(input);
|
|
23
|
+
}
|
|
24
|
+
if (typeof Blob !== "undefined" && input instanceof Blob) {
|
|
25
|
+
const arrayBuffer = await input.arrayBuffer();
|
|
26
|
+
return new Uint8Array(arrayBuffer);
|
|
27
|
+
}
|
|
28
|
+
throw new ArchiveKitError(
|
|
29
|
+
"INVALID_INPUT",
|
|
30
|
+
"Expected Uint8Array, ArrayBuffer, Blob, or File input"
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
function toUint8ArraySync(input) {
|
|
34
|
+
if (input instanceof Uint8Array) {
|
|
35
|
+
return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);
|
|
36
|
+
}
|
|
37
|
+
if (input instanceof ArrayBuffer) {
|
|
38
|
+
return new Uint8Array(input);
|
|
39
|
+
}
|
|
40
|
+
throw new ArchiveKitError(
|
|
41
|
+
"INVALID_INPUT",
|
|
42
|
+
"Synchronous API requires Uint8Array or ArrayBuffer"
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
var textEncoder = new TextEncoder();
|
|
46
|
+
new TextDecoder("utf-8", { fatal: true });
|
|
47
|
+
function encodeUtf8(text) {
|
|
48
|
+
if (typeof text !== "string") {
|
|
49
|
+
throw new ArchiveKitError("INVALID_INPUT", "Expected string input");
|
|
50
|
+
}
|
|
51
|
+
return textEncoder.encode(text);
|
|
52
|
+
}
|
|
53
|
+
var CRC_TABLE = new Uint32Array(256);
|
|
54
|
+
for (let i = 0; i < 256; i++) {
|
|
55
|
+
let c = i;
|
|
56
|
+
for (let k = 0; k < 8; k++) {
|
|
57
|
+
c = c & 1 ? 3988292384 ^ c >>> 1 : c >>> 1;
|
|
58
|
+
}
|
|
59
|
+
CRC_TABLE[i] = c >>> 0;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/shared/blob.ts
|
|
63
|
+
function createBlob(data, mimeType = "application/octet-stream") {
|
|
64
|
+
if (typeof Blob === "undefined") {
|
|
65
|
+
throw new ArchiveKitError(
|
|
66
|
+
"INVALID_INPUT",
|
|
67
|
+
"Blob API is not available in the current environment"
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
const parts = Array.isArray(data) ? data : [data];
|
|
71
|
+
return new Blob(parts, { type: mimeType });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/shared/path.ts
|
|
75
|
+
function normalizeZipPath(rawPath) {
|
|
76
|
+
if (!rawPath || typeof rawPath !== "string") {
|
|
77
|
+
throw new ArchiveKitError(
|
|
78
|
+
"INVALID_ARCHIVE_PATH",
|
|
79
|
+
"Archive path must be a non-empty string"
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
if (rawPath.includes("\0")) {
|
|
83
|
+
throw new ArchiveKitError(
|
|
84
|
+
"INVALID_ARCHIVE_PATH",
|
|
85
|
+
`Archive path contains NUL byte: "${rawPath}"`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const path = rawPath.replace(/\\/g, "/");
|
|
89
|
+
if (/^[a-zA-Z]:/i.test(path)) {
|
|
90
|
+
throw new ArchiveKitError(
|
|
91
|
+
"INVALID_ARCHIVE_PATH",
|
|
92
|
+
`Absolute Windows drive paths are prohibited: "${rawPath}"`
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
if (path.startsWith("//")) {
|
|
96
|
+
throw new ArchiveKitError(
|
|
97
|
+
"INVALID_ARCHIVE_PATH",
|
|
98
|
+
`UNC network paths are prohibited: "${rawPath}"`
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
if (path.startsWith("/")) {
|
|
102
|
+
throw new ArchiveKitError(
|
|
103
|
+
"INVALID_ARCHIVE_PATH",
|
|
104
|
+
`Absolute root paths are prohibited: "${rawPath}"`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
const isDirectory = path.endsWith("/");
|
|
108
|
+
const segments = path.split("/");
|
|
109
|
+
const cleaned = [];
|
|
110
|
+
for (const seg of segments) {
|
|
111
|
+
if (seg === "" || seg === ".") {
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
if (seg === "..") {
|
|
115
|
+
throw new ArchiveKitError(
|
|
116
|
+
"INVALID_ARCHIVE_PATH",
|
|
117
|
+
`Path traversal ("..") is strictly prohibited (Zip Slip): "${rawPath}"`
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
cleaned.push(seg);
|
|
121
|
+
}
|
|
122
|
+
if (cleaned.length === 0) {
|
|
123
|
+
throw new ArchiveKitError(
|
|
124
|
+
"INVALID_ARCHIVE_PATH",
|
|
125
|
+
`Path resolved to an empty path: "${rawPath}"`
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
const result = cleaned.join("/");
|
|
129
|
+
return isDirectory ? `${result}/` : result;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/shared/validation.ts
|
|
133
|
+
var DEFAULT_SECURITY_LIMITS = {
|
|
134
|
+
maxEntries: 1e4,
|
|
135
|
+
// 250 MB
|
|
136
|
+
maxTotalSize: 1024 * 1024 * 1024};
|
|
137
|
+
function validateCompressionLevel(level) {
|
|
138
|
+
if (level === void 0) return 6;
|
|
139
|
+
if (!Number.isInteger(level) || level < 0 || level > 9) {
|
|
140
|
+
throw new ArchiveKitError(
|
|
141
|
+
"INVALID_INPUT",
|
|
142
|
+
`Compression level must be an integer between 0 and 9, received: ${level}`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
return level;
|
|
146
|
+
}
|
|
147
|
+
function validateEntryCount(count, limit = DEFAULT_SECURITY_LIMITS.maxEntries) {
|
|
148
|
+
if (count > limit) {
|
|
149
|
+
throw new ArchiveKitError(
|
|
150
|
+
"ENTRY_LIMIT_EXCEEDED",
|
|
151
|
+
`Archive entry count (${count}) exceeds the maximum limit of ${limit}`
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function validateTotalDecompressedSize(size, limit = DEFAULT_SECURITY_LIMITS.maxTotalSize) {
|
|
156
|
+
if (size > limit) {
|
|
157
|
+
throw new ArchiveKitError(
|
|
158
|
+
"TOTAL_SIZE_LIMIT_EXCEEDED",
|
|
159
|
+
`Total uncompressed size (${size} bytes) exceeds maximum limit of ${limit} bytes`
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/zip-create/validate-entries.ts
|
|
165
|
+
function getZipCreateOptions(options) {
|
|
166
|
+
const compression = options?.compression ?? "deflate";
|
|
167
|
+
if (compression !== "deflate" && compression !== "store") {
|
|
168
|
+
throw new ArchiveKitError(
|
|
169
|
+
"INVALID_INPUT",
|
|
170
|
+
`Invalid compression mode "${compression}". Must be "deflate" or "store".`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const defaultLevel = compression === "store" ? 0 : 6;
|
|
174
|
+
const level = options?.compressionLevel !== void 0 ? validateCompressionLevel(options.compressionLevel) : defaultLevel;
|
|
175
|
+
return {
|
|
176
|
+
compression,
|
|
177
|
+
compressionLevel: level,
|
|
178
|
+
maxEntries: options?.maxEntries ?? DEFAULT_SECURITY_LIMITS.maxEntries,
|
|
179
|
+
maxTotalInputSize: options?.maxTotalInputSize ?? DEFAULT_SECURITY_LIMITS.maxTotalSize,
|
|
180
|
+
signal: options?.signal,
|
|
181
|
+
comment: options?.comment
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
function validateZipEntries(entries, options) {
|
|
185
|
+
if (!Array.isArray(entries)) {
|
|
186
|
+
throw new ArchiveKitError("INVALID_INPUT", "Entries must be an array");
|
|
187
|
+
}
|
|
188
|
+
const maxEntries = options?.maxEntries ?? DEFAULT_SECURITY_LIMITS.maxEntries;
|
|
189
|
+
validateEntryCount(entries.length, maxEntries);
|
|
190
|
+
const seenPaths = /* @__PURE__ */ new Set();
|
|
191
|
+
for (let i = 0; i < entries.length; i++) {
|
|
192
|
+
const entry = entries[i];
|
|
193
|
+
if (!entry || typeof entry !== "object") {
|
|
194
|
+
throw new ArchiveKitError("INVALID_INPUT", `Entry at index ${i} is not a valid object`);
|
|
195
|
+
}
|
|
196
|
+
if (!entry.path || typeof entry.path !== "string") {
|
|
197
|
+
throw new ArchiveKitError(
|
|
198
|
+
"INVALID_ARCHIVE_PATH",
|
|
199
|
+
`Entry at index ${i} must have a non-empty string path`
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
const normalized = normalizeZipPath(entry.path);
|
|
203
|
+
if (seenPaths.has(normalized)) {
|
|
204
|
+
throw new ArchiveKitError(
|
|
205
|
+
"DUPLICATE_ENTRY",
|
|
206
|
+
`Duplicate archive path detected: "${normalized}"`
|
|
207
|
+
);
|
|
208
|
+
}
|
|
209
|
+
seenPaths.add(normalized);
|
|
210
|
+
if (entry.compressionLevel !== void 0) {
|
|
211
|
+
validateCompressionLevel(entry.compressionLevel);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
async function resolveEntryBytes(entry, signal) {
|
|
216
|
+
if (signal?.aborted) {
|
|
217
|
+
throw new ArchiveKitError("OPERATION_CANCELLED", "ZIP creation was aborted");
|
|
218
|
+
}
|
|
219
|
+
const isDirectory = entry.type === "directory" || entry.path.endsWith("/");
|
|
220
|
+
if (isDirectory || entry.data === void 0 || entry.data === null) {
|
|
221
|
+
return new Uint8Array(0);
|
|
222
|
+
}
|
|
223
|
+
if (typeof entry.data === "string") {
|
|
224
|
+
return encodeUtf8(entry.data);
|
|
225
|
+
}
|
|
226
|
+
return toUint8Array(entry.data);
|
|
227
|
+
}
|
|
228
|
+
function resolveEntryBytesSync(entry) {
|
|
229
|
+
const isDirectory = entry.type === "directory" || entry.path.endsWith("/");
|
|
230
|
+
if (isDirectory || entry.data === void 0 || entry.data === null) {
|
|
231
|
+
return new Uint8Array(0);
|
|
232
|
+
}
|
|
233
|
+
if (typeof entry.data === "string") {
|
|
234
|
+
return encodeUtf8(entry.data);
|
|
235
|
+
}
|
|
236
|
+
return toUint8ArraySync(entry.data);
|
|
237
|
+
}
|
|
238
|
+
function appendZipComment(zipBytes, comment) {
|
|
239
|
+
if (!comment) return zipBytes;
|
|
240
|
+
const commentBytes = encodeUtf8(comment);
|
|
241
|
+
if (commentBytes.length === 0 || commentBytes.length > 65535) return zipBytes;
|
|
242
|
+
const out = new Uint8Array(zipBytes.length + commentBytes.length);
|
|
243
|
+
out.set(zipBytes, 0);
|
|
244
|
+
out[zipBytes.length - 2] = commentBytes.length & 255;
|
|
245
|
+
out[zipBytes.length - 1] = commentBytes.length >> 8 & 255;
|
|
246
|
+
out.set(commentBytes, zipBytes.length);
|
|
247
|
+
return out;
|
|
248
|
+
}
|
|
249
|
+
async function createZip(entries, options) {
|
|
250
|
+
const opts = getZipCreateOptions(options);
|
|
251
|
+
if (opts.signal?.aborted) {
|
|
252
|
+
throw new ArchiveKitError("OPERATION_CANCELLED", "ZIP creation was aborted");
|
|
253
|
+
}
|
|
254
|
+
validateZipEntries(entries, opts);
|
|
255
|
+
const zippable = {};
|
|
256
|
+
let totalInputSize = 0;
|
|
257
|
+
for (const entry of entries) {
|
|
258
|
+
if (opts.signal?.aborted) {
|
|
259
|
+
throw new ArchiveKitError("OPERATION_CANCELLED", "ZIP creation was aborted");
|
|
260
|
+
}
|
|
261
|
+
let normalizedPath = normalizeZipPath(entry.path);
|
|
262
|
+
const isDir = entry.type === "directory" || normalizedPath.endsWith("/");
|
|
263
|
+
if (isDir && !normalizedPath.endsWith("/")) {
|
|
264
|
+
normalizedPath = `${normalizedPath}/`;
|
|
265
|
+
}
|
|
266
|
+
const data = await resolveEntryBytes(entry, opts.signal);
|
|
267
|
+
totalInputSize += data.byteLength;
|
|
268
|
+
validateTotalDecompressedSize(totalInputSize, opts.maxTotalInputSize);
|
|
269
|
+
const level = opts.compression === "store" ? 0 : entry.compressionLevel ?? opts.compressionLevel ?? 6;
|
|
270
|
+
const fileOpts = {
|
|
271
|
+
level,
|
|
272
|
+
mtime: entry.lastModified
|
|
273
|
+
};
|
|
274
|
+
zippable[normalizedPath] = [data, fileOpts];
|
|
275
|
+
}
|
|
276
|
+
return new Promise((resolve, reject) => {
|
|
277
|
+
let completed = false;
|
|
278
|
+
if (opts.signal) {
|
|
279
|
+
opts.signal.addEventListener("abort", () => {
|
|
280
|
+
if (!completed) {
|
|
281
|
+
completed = true;
|
|
282
|
+
reject(new ArchiveKitError("OPERATION_CANCELLED", "ZIP creation was aborted"));
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
zip(zippable, (err, result) => {
|
|
287
|
+
if (completed) return;
|
|
288
|
+
completed = true;
|
|
289
|
+
if (err) {
|
|
290
|
+
reject(
|
|
291
|
+
new ArchiveKitError("INVALID_INPUT", `ZIP creation failed: ${err.message}`, err)
|
|
292
|
+
);
|
|
293
|
+
} else {
|
|
294
|
+
resolve(appendZipComment(result, opts.comment));
|
|
295
|
+
}
|
|
296
|
+
});
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
function createZipSync(entries, options) {
|
|
300
|
+
const opts = getZipCreateOptions(options);
|
|
301
|
+
validateZipEntries(entries, opts);
|
|
302
|
+
const zippable = {};
|
|
303
|
+
let totalInputSize = 0;
|
|
304
|
+
for (const entry of entries) {
|
|
305
|
+
let normalizedPath = normalizeZipPath(entry.path);
|
|
306
|
+
const isDir = entry.type === "directory" || normalizedPath.endsWith("/");
|
|
307
|
+
if (isDir && !normalizedPath.endsWith("/")) {
|
|
308
|
+
normalizedPath = `${normalizedPath}/`;
|
|
309
|
+
}
|
|
310
|
+
const data = resolveEntryBytesSync(entry);
|
|
311
|
+
totalInputSize += data.byteLength;
|
|
312
|
+
validateTotalDecompressedSize(totalInputSize, opts.maxTotalInputSize);
|
|
313
|
+
const level = opts.compression === "store" ? 0 : entry.compressionLevel ?? opts.compressionLevel ?? 6;
|
|
314
|
+
const fileOpts = {
|
|
315
|
+
level,
|
|
316
|
+
mtime: entry.lastModified
|
|
317
|
+
};
|
|
318
|
+
zippable[normalizedPath] = [data, fileOpts];
|
|
319
|
+
}
|
|
320
|
+
try {
|
|
321
|
+
const result = zipSync(zippable);
|
|
322
|
+
return appendZipComment(result, opts.comment);
|
|
323
|
+
} catch (err) {
|
|
324
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
325
|
+
throw new ArchiveKitError("INVALID_INPUT", `ZIP creation failed: ${message}`, err);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
async function createZipBlob(entries, options) {
|
|
329
|
+
const bytes = await createZip(entries, options);
|
|
330
|
+
return createBlob(bytes, "application/zip");
|
|
331
|
+
}
|
|
332
|
+
async function createZipFromFiles(files, options) {
|
|
333
|
+
if (!Array.isArray(files)) {
|
|
334
|
+
throw new ArchiveKitError("INVALID_INPUT", "Expected an array of files");
|
|
335
|
+
}
|
|
336
|
+
const entries = files.map((item) => {
|
|
337
|
+
const file = item instanceof File ? item : item.file;
|
|
338
|
+
const path = item.path || file.webkitRelativePath || file.name;
|
|
339
|
+
return {
|
|
340
|
+
path,
|
|
341
|
+
data: file,
|
|
342
|
+
lastModified: new Date(file.lastModified)
|
|
343
|
+
};
|
|
344
|
+
});
|
|
345
|
+
return createZipBlob(entries, options);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export { createZip, createZipBlob, createZipFromFiles, createZipSync, getZipCreateOptions, validateZipEntries };
|
|
349
|
+
//# sourceMappingURL=index.js.map
|
|
350
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/shared/errors.ts","../../src/shared/binary.ts","../../src/shared/blob.ts","../../src/shared/path.ts","../../src/shared/validation.ts","../../src/zip-create/validate-entries.ts","../../src/zip-create/create-zip.ts"],"names":[],"mapp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AAwB,OAAO,IAAI,GAAG,CAAA;AAAA,EACnF;AACF;AAKA,eAAsB,aAAA,CACpB,SACA,OAAA,EACe;AACf,EAAA,MAAM,KAAA,GAAQ,MAAM,SAAA,CAAU,OAAA,EAAS,OAAO,CAAA;AAC9C,EAAA,OAAO,UAAA,CAAW,OAAO,iBAAiB,CAAA;AAC5C;AAMA,eAAsB,kBAAA,CACpB,OACA,OAAA,EACe;AACf,EAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,KAAK,CAAA,EAAG;AACzB,IAAA,MAAM,IAAI,eAAA,CAAgB,eAAA,EAAiB,4BAA4B,CAAA;AAAA,EACzE;AAEA,EAAA,MAAM,OAAA,GAA2B,KAAA,CAAM,GAAA,CAAI,CAAC,IAAA,KAAS;AACnD,IAAA,MAAM,IAAA,GAAO,IAAA,YAAgB,IAAA,GAAO,IAAA,GAAO,IAAA,CAAK,IAAA;AAEhD,IAAA,MAAM,IAAA,GACH,IAAA,CAA2B,IAAA,IAC3B,IAAA,CAAgD,sBACjD,IAAA,CAAK,IAAA;AAEP,IAAA,OAAO;AAAA,MACL,IAAA;AAAA,MACA,IAAA,EAAM,IAAA;AAAA,MACN,YAAA,EAAc,IAAI,IAAA,CAAK,IAAA,CAAK,YAAY;AAAA,KAC1C;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,aAAA,CAAc,SAAS,OAAO,CAAA;AACvC","file":"index.js","sourcesContent":["import type { ArchiveKitErrorCode } from './types.js';\n\n/**\n * Custom error class for all archive-kit errors with typed codes and details.\n */\nexport class ArchiveKitError extends Error {\n readonly code: ArchiveKitErrorCode;\n readonly details?: unknown;\n\n constructor(code: ArchiveKitErrorCode, message: string, details?: unknown) {\n super(message);\n this.name = 'ArchiveKitError';\n this.code = code;\n this.details = details;\n Object.setPrototypeOf(this, ArchiveKitError.prototype);\n }\n}\n","import { ArchiveKitError } from './errors.js';\nimport type { BinaryInput } from './types.js';\n\n/**\n * Converts any supported binary input into a Uint8Array.\n * Does not mutate caller-owned buffers.\n */\nexport async function toUint8Array(input: BinaryInput): Promise<Uint8Array> {\n if (input instanceof Uint8Array) {\n return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n }\n if (input instanceof ArrayBuffer) {\n return new Uint8Array(input);\n }\n if (typeof Blob !== 'undefined' && input instanceof Blob) {\n const arrayBuffer = await input.arrayBuffer();\n return new Uint8Array(arrayBuffer);\n }\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n 'Expected Uint8Array, ArrayBuffer, Blob, or File input'\n );\n}\n\n/**\n * Synchronous variant for Uint8Array or ArrayBuffer input.\n */\nexport function toUint8ArraySync(input: Uint8Array | ArrayBuffer): Uint8Array {\n if (input instanceof Uint8Array) {\n return new Uint8Array(input.buffer, input.byteOffset, input.byteLength);\n }\n if (input instanceof ArrayBuffer) {\n return new Uint8Array(input);\n }\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n 'Synchronous API requires Uint8Array or ArrayBuffer'\n );\n}\n\n/**\n * Converts Uint8Array or ArrayBuffer to ArrayBuffer.\n */\nexport function toArrayBuffer(input: Uint8Array | ArrayBuffer): ArrayBuffer {\n if (input instanceof ArrayBuffer) {\n return input;\n }\n if (input instanceof Uint8Array) {\n if (input.byteOffset === 0 && input.byteLength === input.buffer.byteLength) {\n return input.buffer as ArrayBuffer;\n }\n return input.buffer.slice(\n input.byteOffset,\n input.byteOffset + input.byteLength\n ) as ArrayBuffer;\n }\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n 'Expected Uint8Array or ArrayBuffer'\n );\n}\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder('utf-8', { fatal: true });\n\n/**\n * Encodes text to UTF-8 bytes using browser-native TextEncoder.\n */\nexport function encodeUtf8(text: string): Uint8Array {\n if (typeof text !== 'string') {\n throw new ArchiveKitError('INVALID_INPUT', 'Expected string input');\n }\n return textEncoder.encode(text);\n}\n\n/**\n * Decodes UTF-8 bytes to text with strict verification (fatal: true).\n * Throws INVALID_INPUT if bytes are not valid UTF-8.\n */\nexport function decodeUtf8(bytes: Uint8Array): string {\n try {\n return textDecoder.decode(bytes);\n } catch (err) {\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n 'Data is not valid UTF-8 text',\n err\n );\n }\n}\n\n/**\n * Concatenates multiple Uint8Arrays efficiently into one buffer.\n */\nexport function concatUint8Arrays(arrays: Uint8Array[]): Uint8Array {\n let totalLength = 0;\n for (let i = 0; i < arrays.length; i++) {\n const arr = arrays[i];\n if (arr) {\n totalLength += arr.length;\n }\n }\n const result = new Uint8Array(totalLength);\n let offset = 0;\n for (let i = 0; i < arrays.length; i++) {\n const arr = arrays[i];\n if (arr) {\n result.set(arr, offset);\n offset += arr.length;\n }\n }\n return result;\n}\n\n/**\n * Compares two Uint8Arrays for byte-for-byte equality.\n */\nexport function compareUint8Arrays(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\n// Precomputed table for IEEE 802.3 CRC-32\nconst CRC_TABLE = new Uint32Array(256);\nfor (let i = 0; i < 256; i++) {\n let c = i;\n for (let k = 0; k < 8; k++) {\n c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);\n }\n CRC_TABLE[i] = c >>> 0;\n}\n\n/**\n * Computes standard 32-bit CRC checksum for verifying ZIP entry integrity.\n */\nexport function computeCrc32(data: Uint8Array): number {\n let crc = 0xffffffff;\n for (let i = 0; i < data.length; i++) {\n const byte = data[i] ?? 0;\n crc = (CRC_TABLE[(crc ^ byte) & 0xff] ?? 0) ^ (crc >>> 8);\n }\n return (crc ^ 0xffffffff) >>> 0;\n}\n","import { ArchiveKitError } from './errors.js';\n\n/**\n * Creates a browser-compatible Blob from Uint8Array or array of chunks.\n */\nexport function createBlob(\n data: Uint8Array | Uint8Array[],\n mimeType = 'application/octet-stream'\n): Blob {\n if (typeof Blob === 'undefined') {\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n 'Blob API is not available in the current environment'\n );\n }\n const parts = Array.isArray(data) ? data : [data];\n return new Blob(parts as BlobPart[], { type: mimeType });\n}\n\n/**\n * Reads a Blob as Uint8Array.\n */\nexport async function readBlobAsUint8Array(blob: Blob): Promise<Uint8Array> {\n const buffer = await blob.arrayBuffer();\n return new Uint8Array(buffer);\n}\n","import { ArchiveKitError } from './errors.js';\n\n/**\n * Normalizes an archive path according to ZIP standards and enforces security:\n * - Converts backslashes to forward slashes.\n * - Rejects NUL characters.\n * - Rejects absolute paths (leading slash, Windows drive letters, UNC paths).\n * - Rejects Zip Slip path traversal ('..' segments).\n * - Removes leading './'.\n * - Preserves trailing slashes for directories.\n */\nexport function normalizeZipPath(rawPath: string): string {\n if (!rawPath || typeof rawPath !== 'string') {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n 'Archive path must be a non-empty string'\n );\n }\n\n // Reject NUL characters\n if (rawPath.includes('\\0')) {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `Archive path contains NUL byte: \"${rawPath}\"`\n );\n }\n\n // Normalize all backslashes to forward slashes\n const path = rawPath.replace(/\\\\/g, '/');\n\n // Check for absolute Windows drive letter (e.g. C:/ or C:\\)\n if (/^[a-zA-Z]:/i.test(path)) {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `Absolute Windows drive paths are prohibited: \"${rawPath}\"`\n );\n }\n\n // Check for UNC path (e.g. //server/share)\n if (path.startsWith('//')) {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `UNC network paths are prohibited: \"${rawPath}\"`\n );\n }\n\n // Check for root-relative absolute path\n if (path.startsWith('/')) {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `Absolute root paths are prohibited: \"${rawPath}\"`\n );\n }\n\n // Preserve directory indicator if original path ended with slash\n const isDirectory = path.endsWith('/');\n\n // Split into segments and validate\n const segments = path.split('/');\n const cleaned: string[] = [];\n\n for (const seg of segments) {\n if (seg === '' || seg === '.') {\n continue;\n }\n if (seg === '..') {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `Path traversal (\"..\") is strictly prohibited (Zip Slip): \"${rawPath}\"`\n );\n }\n cleaned.push(seg);\n }\n\n if (cleaned.length === 0) {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `Path resolved to an empty path: \"${rawPath}\"`\n );\n }\n\n const result = cleaned.join('/');\n return isDirectory ? `${result}/` : result;\n}\n\n/**\n * Checks whether an archive path designates a directory.\n */\nexport function isDirPath(path: string): boolean {\n return path.endsWith('/');\n}\n\n/**\n * Returns the file name component of a path.\n */\nexport function getBaseName(path: string): string {\n const normalized = path.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n const lastSlash = normalized.lastIndexOf('/');\n return lastSlash === -1 ? normalized : normalized.slice(lastSlash + 1);\n}\n\n/**\n * Returns the parent directory path.\n */\nexport function getDirName(path: string): string {\n const normalized = path.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n const lastSlash = normalized.lastIndexOf('/');\n return lastSlash === -1 ? '' : normalized.slice(0, lastSlash);\n}\n","import { ArchiveKitError } from './errors.js';\n\nexport const DEFAULT_SECURITY_LIMITS = {\n maxEntries: 10_000,\n maxEntrySize: 250 * 1024 * 1024, // 250 MB\n maxTotalSize: 1024 * 1024 * 1024, // 1 GB\n maxCompressionRatio: 100, // 100:1 ratio protection against ZIP bombs\n maxInputSize: 1024 * 1024 * 1024 // 1 GB\n} as const;\n\n/**\n * Validates compression level (0-9).\n */\nexport function validateCompressionLevel(level?: number): number {\n if (level === undefined) return 6;\n if (!Number.isInteger(level) || level < 0 || level > 9) {\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n `Compression level must be an integer between 0 and 9, received: ${level}`\n );\n }\n return level;\n}\n\n/**\n * Validates maximum entry count.\n */\nexport function validateEntryCount(count: number, limit: number = DEFAULT_SECURITY_LIMITS.maxEntries): void {\n if (count > limit) {\n throw new ArchiveKitError(\n 'ENTRY_LIMIT_EXCEEDED',\n `Archive entry count (${count}) exceeds the maximum limit of ${limit}`\n );\n }\n}\n\n/**\n * Validates per-entry decompressed size.\n */\nexport function validateDecompressedSize(\n size: number,\n limit: number = DEFAULT_SECURITY_LIMITS.maxEntrySize,\n path?: string\n): void {\n if (size > limit) {\n throw new ArchiveKitError(\n 'FILE_SIZE_LIMIT_EXCEEDED',\n `Entry ${path ? `\"${path}\" ` : ''}decompressed size (${size} bytes) exceeds limit of ${limit} bytes`\n );\n }\n}\n\n/**\n * Validates aggregate decompressed size.\n */\nexport function validateTotalDecompressedSize(\n size: number,\n limit: number = DEFAULT_SECURITY_LIMITS.maxTotalSize\n): void {\n if (size > limit) {\n throw new ArchiveKitError(\n 'TOTAL_SIZE_LIMIT_EXCEEDED',\n `Total uncompressed size (${size} bytes) exceeds maximum limit of ${limit} bytes`\n );\n }\n}\n\n/**\n * Validates compression ratio to prevent ZIP bombs.\n * Only enforced when uncompressed size is greater than 1MB to avoid false alarms on tiny files.\n */\nexport function validateCompressionRatio(\n uncompressed: number,\n compressed: number,\n maxRatio: number = DEFAULT_SECURITY_LIMITS.maxCompressionRatio,\n path?: string\n): void {\n if (uncompressed > 1024 * 1024) {\n const ratio = uncompressed / Math.max(1, compressed);\n if (ratio > maxRatio) {\n throw new ArchiveKitError(\n 'COMPRESSION_RATIO_LIMIT_EXCEEDED',\n `Compression ratio (${ratio.toFixed(1)}:1) for ${path ? `\"${path}\" ` : ''}exceeds safe threshold of ${maxRatio}:1`\n );\n }\n }\n}\n\n/**\n * Calculates compression ratio (compressed / original).\n */\nexport function calculateRatio(compressed: number, original: number): number {\n if (original <= 0) return 1;\n return Number((compressed / original).toFixed(4));\n}\n\n/**\n * Calculates percentage saved: (1 - compressed / original) * 100.\n */\nexport function calculatePercentageSaved(compressed: number, original: number): number {\n if (original <= 0) return 0;\n const saved = (1 - compressed / original) * 100;\n return Math.max(0, Number(saved.toFixed(2)));\n}\n","import {\n ArchiveKitError,\n DEFAULT_SECURITY_LIMITS,\n normalizeZipPath,\n validateCompressionLevel,\n validateEntryCount\n} from '../shared/index.js';\nimport type { ZipCreateOptions, ZipInputEntry } from './types.js';\n\n/**\n * Merges user-provided ZIP creation options with safe production defaults.\n */\nexport function getZipCreateOptions(options?: Partial<ZipCreateOptions>): ZipCreateOptions {\n const compression = options?.compression ?? 'deflate';\n if (compression !== 'deflate' && compression !== 'store') {\n throw new ArchiveKitError(\n 'INVALID_INPUT',\n `Invalid compression mode \"${compression}\". Must be \"deflate\" or \"store\".`\n );\n }\n\n const defaultLevel = compression === 'store' ? 0 : 6;\n const level = options?.compressionLevel !== undefined\n ? validateCompressionLevel(options.compressionLevel)\n : defaultLevel;\n\n return {\n compression,\n compressionLevel: level,\n maxEntries: options?.maxEntries ?? DEFAULT_SECURITY_LIMITS.maxEntries,\n maxTotalInputSize: options?.maxTotalInputSize ?? DEFAULT_SECURITY_LIMITS.maxTotalSize,\n signal: options?.signal,\n comment: options?.comment\n };\n}\n\n/**\n * Validates a list of ZIP input entries:\n * - Checks max entry count.\n * - Normalizes all paths and rejects Zip Slip, NUL bytes, and absolute paths.\n * - Detects and rejects duplicate paths.\n * - Validates per-entry compression levels if set.\n *\n * @throws ArchiveKitError if any entry is invalid or duplicate.\n */\nexport function validateZipEntries(\n entries: ZipInputEntry[],\n options?: ZipCreateOptions\n): void {\n if (!Array.isArray(entries)) {\n throw new ArchiveKitError('INVALID_INPUT', 'Entries must be an array');\n }\n\n const maxEntries = options?.maxEntries ?? DEFAULT_SECURITY_LIMITS.maxEntries;\n validateEntryCount(entries.length, maxEntries);\n\n const seenPaths = new Set<string>();\n\n for (let i = 0; i < entries.length; i++) {\n const entry = entries[i];\n if (!entry || typeof entry !== 'object') {\n throw new ArchiveKitError('INVALID_INPUT', `Entry at index ${i} is not a valid object`);\n }\n\n if (!entry.path || typeof entry.path !== 'string') {\n throw new ArchiveKitError(\n 'INVALID_ARCHIVE_PATH',\n `Entry at index ${i} must have a non-empty string path`\n );\n }\n\n const normalized = normalizeZipPath(entry.path);\n if (seenPaths.has(normalized)) {\n throw new ArchiveKitError(\n 'DUPLICATE_ENTRY',\n `Duplicate archive path detected: \"${normalized}\"`\n );\n }\n seenPaths.add(normalized);\n\n if (entry.compressionLevel !== undefined) {\n validateCompressionLevel(entry.compressionLevel);\n }\n }\n}\n","import { zip, zipSync, type AsyncZippable, type Zippable } from 'fflate';\nimport {\n ArchiveKitError,\n createBlob,\n encodeUtf8,\n normalizeZipPath,\n toUint8Array,\n toUint8ArraySync,\n validateTotalDecompressedSize\n} from '../shared/index.js';\nimport type {\n ZipCreateOptions,\n ZipFileInput,\n ZipInputEntry,\n ZipInputEntrySync\n} from './types.js';\nimport { getZipCreateOptions, validateZipEntries } from './validate-entries.js';\n\nasync function resolveEntryBytes(\n entry: ZipInputEntry,\n signal?: AbortSignal\n): Promise<Uint8Array> {\n if (signal?.aborted) {\n throw new ArchiveKitError('OPERATION_CANCELLED', 'ZIP creation was aborted');\n }\n\n const isDirectory = entry.type === 'directory' || entry.path.endsWith('/');\n if (isDirectory || entry.data === undefined || entry.data === null) {\n return new Uint8Array(0);\n }\n\n if (typeof entry.data === 'string') {\n return encodeUtf8(entry.data);\n }\n\n return toUint8Array(entry.data);\n}\n\nfunction resolveEntryBytesSync(entry: ZipInputEntrySync): Uint8Array {\n const isDirectory = entry.type === 'directory' || entry.path.endsWith('/');\n if (isDirectory || entry.data === undefined || entry.data === null) {\n return new Uint8Array(0);\n }\n\n if (typeof entry.data === 'string') {\n return encodeUtf8(entry.data);\n }\n\n return toUint8ArraySync(entry.data);\n}\n\nfunction appendZipComment(zipBytes: Uint8Array, comment?: string): Uint8Array {\n if (!comment) return zipBytes;\n const commentBytes = encodeUtf8(comment);\n if (commentBytes.length === 0 || commentBytes.length > 65535) return zipBytes;\n const out = new Uint8Array(zipBytes.length + commentBytes.length);\n out.set(zipBytes, 0);\n out[zipBytes.length - 2] = commentBytes.length & 0xff;\n out[zipBytes.length - 1] = (commentBytes.length >> 8) & 0xff;\n out.set(commentBytes, zipBytes.length);\n return out;\n}\n\n/**\n * Creates a ZIP archive Uint8Array asynchronously from a list of input entries.\n *\n * @param entries - Array of files and directories to include.\n * @param options - Configuration options (compression mode, level, limits, cancellation).\n * @returns Resolves to the complete ZIP archive Uint8Array.\n */\nexport async function createZip(\n entries: ZipInputEntry[],\n options?: ZipCreateOptions\n): Promise<Uint8Array> {\n const opts = getZipCreateOptions(options);\n\n if (opts.signal?.aborted) {\n throw new ArchiveKitError('OPERATION_CANCELLED', 'ZIP creation was aborted');\n }\n\n validateZipEntries(entries, opts);\n\n const zippable: AsyncZippable = {};\n let totalInputSize = 0;\n\n for (const entry of entries) {\n if (opts.signal?.aborted) {\n throw new ArchiveKitError('OPERATION_CANCELLED', 'ZIP creation was aborted');\n }\n\n let normalizedPath = normalizeZipPath(entry.path);\n const isDir = entry.type === 'directory' || normalizedPath.endsWith('/');\n if (isDir && !normalizedPath.endsWith('/')) {\n normalizedPath = `${normalizedPath}/`;\n }\n\n const data = await resolveEntryBytes(entry, opts.signal);\n totalInputSize += data.byteLength;\n validateTotalDecompressedSize(totalInputSize, opts.maxTotalInputSize);\n\n const level =\n opts.compression === 'store'\n ? 0\n : (entry.compressionLevel ?? opts.compressionLevel ?? 6);\n\n const fileOpts = {\n level: level as 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9,\n mtime: entry.lastModified\n };\n\n zippable[normalizedPath] = [data, fileOpts];\n }\n\n return new Promise<Uint8Array>((resolve, reject) => {\n let completed = false;\n\n if (opts.signal) {\n opts.signal.addEventListener('abort', () => {\n if (!completed) {\n completed = true;\n reject(new ArchiveKitError('OPERATION_CANCELLED', 'ZIP creation was aborted'));\n }\n });\n }\n\n zip(zippable, (err, result) => {\n if (completed) return;\n completed = true;\n if (err) {\n reject(\n new ArchiveKitError('INVALID_INPUT', `ZIP creation failed: ${err.message}`, err)\n );\n } else {\n resolve(appendZipComment(result, opts.comment));\n }\n });\n });\n}\n\n/**\n * Creates a ZIP archive synchronously for small in-memory workloads.\n *\n * @warning Calling this on large files will block the JavaScript main thread.\n */\nexport function createZipSync(\n entries: ZipInputEntrySync[],\n options?: ZipCreateOptions\n): Uint8Array {\n const opts = getZipCreateOptions(options);\n validateZipEntries(entries as ZipInputEntry[], opts);\n\n const zippable: Zippable = {};\n let totalInputSize = 0;\n\n for (const entry of entries) {\n let normalizedPath = normalizeZipPath(entry.path);\n const isDir = entry.type === 'directory' || normalizedPath.endsWith('/');\n if (isDir && !normalizedPath.endsWith('/')) {\n normalizedPath = `${normalizedPath}/`;\n }\n\n const data = resolveEntryBytesSync(entry);\n totalInputSize += data.byteLength;\n validateTotalDecompressedSize(totalInputSize, opts.maxTotalInputSize);\n\n const level =\n opts.compression === 'store'\n ? 0\n : (entry.compressionLevel ?? opts.compressionLevel ?? 6);\n\n const fileOpts = {\n level: level as 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9,\n mtime: entry.lastModified\n };\n\n zippable[normalizedPath] = [data, fileOpts];\n }\n\n try {\n const result = zipSync(zippable);\n return appendZipComment(result, opts.comment);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n throw new ArchiveKitError('INVALID_INPUT', `ZIP creation failed: ${message}`, err);\n }\n}\n\n/**\n * Creates a ZIP archive and returns it as a browser-compatible Blob.\n */\nexport async function createZipBlob(\n entries: ZipInputEntry[],\n options?: ZipCreateOptions\n): Promise<Blob> {\n const bytes = await createZip(entries, options);\n return createBlob(bytes, 'application/zip');\n}\n\n/**\n * Creates a ZIP archive Blob directly from browser File objects,\n * automatically handling folder selection via webkitRelativePath.\n */\nexport async function createZipFromFiles(\n files: ZipFileInput[],\n options?: ZipCreateOptions\n): Promise<Blob> {\n if (!Array.isArray(files)) {\n throw new ArchiveKitError('INVALID_INPUT', 'Expected an array of files');\n }\n\n const entries: ZipInputEntry[] = files.map((item) => {\n const file = item instanceof File ? item : item.file;\n // Support webkitRelativePath for directory uploads or custom path\n const path =\n (item as { path?: string }).path ||\n (file as File & { webkitRelativePath?: string }).webkitRelativePath ||\n file.name;\n\n return {\n path,\n data: file,\n lastModified: new Date(file.lastModified)\n };\n });\n\n return createZipBlob(entries, options);\n}\n"]}
|