bagit-node 1.0.0 → 1.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 +9 -0
- package/README.md +26 -8
- package/dist/cjs/util.d.ts +1 -1
- package/dist/cjs/util.js +1 -1
- package/dist/cjs/util.js.map +1 -1
- package/dist/cjs/zip.d.ts +4 -2
- package/dist/cjs/zip.d.ts.map +1 -1
- package/dist/cjs/zip.js +79 -44
- package/dist/cjs/zip.js.map +1 -1
- package/dist/esm/util.d.ts +1 -1
- package/dist/esm/util.js +1 -1
- package/dist/esm/util.js.map +1 -1
- package/dist/esm/zip.d.ts +4 -2
- package/dist/esm/zip.d.ts.map +1 -1
- package/dist/esm/zip.js +79 -44
- package/dist/esm/zip.js.map +1 -1
- package/package.json +2 -1
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 1.1.0
|
|
4
|
+
|
|
5
|
+
- Add `BagZipOptions.tagFiles` for lazy root and nested tag files across all streaming ZIP APIs. Accepts synchronous or asynchronous iterables of `BagZipEntry`.
|
|
6
|
+
- Stream and hash tag bytes with backpressure, include checksums in every configured tagmanifest, and preserve payload counts and progress semantics.
|
|
7
|
+
- Reject unsafe paths, duplicates, Unicode normalization conflicts, generated-file conflicts, and file/directory collisions.
|
|
8
|
+
- Destroy active readable sources on cancellation, including sources waiting for bytes; preserve manifest cleanup and atomic file output.
|
|
9
|
+
- Document direct S3/Ceph streaming with root `metadata.json` and fresh sources for retries. Preserve ESM, CommonJS, and TypeScript support.
|
package/README.md
CHANGED
|
@@ -41,7 +41,7 @@ await bag.validate();
|
|
|
41
41
|
|
|
42
42
|
This moves the folder's existing contents into `data/`, preserves directory permissions, and writes `bagit.txt`, `bag-info.txt`, payload manifests, and tag manifests. An existing `data/` becomes `data/data/`, matching Python. Empty payloads receive empty manifests and remain valid. The function never changes the process working directory.
|
|
43
43
|
|
|
44
|
-
`Bagging-Date` defaults to the local calendar date. `Bag-Software-Agent` defaults to `bagit-node v1.
|
|
44
|
+
`Bagging-Date` defaults to the local calendar date. `Bag-Software-Agent` defaults to `bagit-node v1.1.0`. Both may be overridden. `Payload-Oxum` is always calculated from the payload. New bags use UTF-8.
|
|
45
45
|
|
|
46
46
|
## Open, inspect, validate, and save
|
|
47
47
|
|
|
@@ -132,24 +132,36 @@ await folderToBagZip('/exports/source', createWriteStream('/exports/source.bag.z
|
|
|
132
132
|
|
|
133
133
|
`folderToBagitZip` is an alias for `folderToBagZip`.
|
|
134
134
|
|
|
135
|
-
Each source file is opened once. Its bytes pass through incremental hashing, ZIP deflate compression, and the output stream with backpressure.
|
|
135
|
+
Each source file is opened once. Its bytes pass through incremental hashing, ZIP deflate compression, and the output stream with backpressure. Checksums cover the original bytes before compression. Custom tag files, when supplied, follow payload entries, then payload manifests, bag metadata, and tag manifests. ZIP64 supports files and offsets above 4 GiB and more than 65,535 entries.
|
|
136
136
|
|
|
137
|
-
Payloads and the complete ZIP are never buffered or staged by the streaming APIs.
|
|
137
|
+
Payloads, custom tag files, and the complete ZIP are never buffered or staged by the streaming APIs. Payload manifests are spooled to temporary files, removed on completion, cancellation, or failure. Memory holds stream buffers, ZIP central directory metadata, and filenames/checksums for duplicate checks and tag manifests; it grows with the number of entries, not their byte sizes. `tempDirectory` selects the spool location and must be outside a folder source. Directory exports preserve empty directories, ZIP timestamps, and Unix modes. `mtime` sets a fixed ZIP timestamp for reproducible exports. Yazl automatically uses ZIP64 when needed, so small archives remain compatible with ordinary ZIP readers.
|
|
138
138
|
|
|
139
139
|
Source changes detected while a file is read cause export to fail. Keep sources stable during export: this is not a filesystem snapshot. Symlinks resolving outside the source are rejected, and folder export rejects directory symlinks. Custom source iterables must honor cancellation during their own pending I/O.
|
|
140
140
|
|
|
141
141
|
## Pipe directly to Ceph / S3 multipart upload
|
|
142
142
|
|
|
143
|
-
`
|
|
143
|
+
`createBagZipStreamFromEntries` returns a standard Node `Readable`, suitable for your existing multipart uploader. Use `tagFiles` to keep an application's `metadata.json` at the bag root while streaming lazy payloads directly to S3 or Ceph. For example, if your application already uses the AWS SDK:
|
|
144
144
|
|
|
145
145
|
```ts
|
|
146
|
-
import {
|
|
146
|
+
import { Readable } from 'node:stream';
|
|
147
|
+
import { createBagZipStreamFromEntries } from 'bagit-node';
|
|
147
148
|
import { Upload } from '@aws-sdk/lib-storage'; // application dependency, not a bagit-node dependency
|
|
148
149
|
|
|
149
150
|
const controller = new AbortController();
|
|
150
|
-
const
|
|
151
|
+
const metadata = { id: 'collection-123', description: 'Export metadata' };
|
|
152
|
+
const payloadEntries = [
|
|
153
|
+
{ path: 'images/original.tif', open: () => openOriginalImageStream() }, // application source
|
|
154
|
+
];
|
|
155
|
+
const body = createBagZipStreamFromEntries(payloadEntries, {
|
|
151
156
|
signal: controller.signal,
|
|
152
157
|
checksums: ['sha256', 'sha512'],
|
|
158
|
+
bagInfo: { 'Contact-Name': 'Exporter' },
|
|
159
|
+
tagFiles: [
|
|
160
|
+
{
|
|
161
|
+
path: 'metadata.json', // relative to the bag root
|
|
162
|
+
open: () => Readable.from([Buffer.from(JSON.stringify(metadata), 'utf8')]),
|
|
163
|
+
},
|
|
164
|
+
],
|
|
153
165
|
});
|
|
154
166
|
|
|
155
167
|
const upload = new Upload({
|
|
@@ -173,7 +185,9 @@ try {
|
|
|
173
185
|
}
|
|
174
186
|
```
|
|
175
187
|
|
|
176
|
-
|
|
188
|
+
This writes `data/images/original.tif`, root `metadata.json`, `bagit.txt`, `bag-info.txt`, payload manifests, and tag manifests. For a folder source, pass the same options to `createBagZipStream('/exports/source', options)`.
|
|
189
|
+
|
|
190
|
+
The uploader's queue adds its own multipart buffers. A content length is not known before streaming. The stream emits source, compression, and filesystem errors; use an error-aware consumer such as `pipeline` or your multipart uploader. A consumed stream cannot be replayed. To retry or generate a temporary ZIP fallback, call the export API again with fresh payload and tag-file iterables, and have every `open()` return a fresh stream or iterable. Recreate async generators for each attempt and keep sources stable across retries.
|
|
177
191
|
|
|
178
192
|
## Build a ZIP directly from application sources
|
|
179
193
|
|
|
@@ -200,10 +214,14 @@ const body = createBagZipStreamFromEntries(entries(), {
|
|
|
200
214
|
// Pass body to your multipart uploader or pipeline(body, destination).
|
|
201
215
|
```
|
|
202
216
|
|
|
203
|
-
`open()` is called lazily, once per entry, and returns a `Readable`, iterable, or async iterable of `Uint8Array`/`Buffer` chunks, or a promise for one.
|
|
217
|
+
`open()` is called lazily, once per entry, and returns a `Readable`, iterable, or async iterable of `Uint8Array`/`Buffer` chunks, or a promise for one. Payloads and custom tag files are read sequentially, one source at a time, with backpressure. Source lengths need not be known. Entries may set `mtime`, `mode`, and `directory: true` (with `open: () => []`) for empty directories. Progress callbacks are awaited after each completed payload; tag files do not trigger them.
|
|
218
|
+
|
|
219
|
+
`BagZipOptions.tagFiles?: Iterable<BagZipEntry> | AsyncIterable<BagZipEntry>` is supported by `createBagZipStreamFromEntries`, `createBagZipStream`, `folderToBagZip`, and its `folderToBagitZip` alias. Tag paths are relative to the bag root, support nested names such as `metadata/description.json`, and receive the optional `bagName` prefix in the ZIP. Every configured tagmanifest records their original-byte checksums. They are excluded from payload manifests, payload byte/file totals, and `Payload-Oxum`. Root `metadata.json` can coexist with payload `data/metadata.json`. Omitting `tagFiles` preserves the existing layout and behavior.
|
|
204
220
|
|
|
205
221
|
Archive paths must be relative POSIX paths. Absolute paths, traversal, backslashes, duplicate paths, Unicode normalization collisions, and file/directory conflicts are rejected. CR/LF filenames are encoded in manifests. Literal `%0A`/`%0D` in names and trailing whitespace that cannot round-trip through Python's manifest parser are rejected by ZIP export.
|
|
206
222
|
|
|
223
|
+
Custom tag paths follow the same rules and cannot occupy `data/`, `bagit.txt`, `bag-info.txt`, or root `manifest-*.txt` / `tagmanifest-*.txt` paths, including their descendants. Leading whitespace or `*` in a tag path is also rejected because manifest parsers strip it. Tag manifests never list themselves or other tag manifests. Cancellation or failure destroys active readable sources and removes temporary manifests. Application iterables must honor cancellation during their own pending I/O.
|
|
224
|
+
|
|
207
225
|
## Compatibility and verification
|
|
208
226
|
|
|
209
227
|
The reference is pinned at [`4bd2713`](https://github.com/LibraryOfCongress/bagit-python/tree/4bd2713cedbe1f8e634567c20ef0dded9622011d). Test-only upstream files and fixtures are included under `test/vendor/` and excluded from npm packages.
|
package/dist/cjs/util.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type Hash } from 'node:crypto';
|
|
2
2
|
import type { BagInfo, BagInfoInput, Checksums } from './types.js';
|
|
3
|
-
export declare const VERSION = "1.
|
|
3
|
+
export declare const VERSION = "1.1.0";
|
|
4
4
|
export declare const DEFAULT_CHECKSUMS: readonly string[];
|
|
5
5
|
export declare const HASH_BLOCK_SIZE: number;
|
|
6
6
|
export declare const BAG_DECLARATION = "BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n";
|
package/dist/cjs/util.js
CHANGED
|
@@ -26,7 +26,7 @@ const node_fs_1 = require("node:fs");
|
|
|
26
26
|
const promises_1 = require("node:fs/promises");
|
|
27
27
|
const node_path_1 = require("node:path");
|
|
28
28
|
const errors_js_1 = require("./errors.js");
|
|
29
|
-
exports.VERSION = '1.
|
|
29
|
+
exports.VERSION = '1.1.0';
|
|
30
30
|
exports.DEFAULT_CHECKSUMS = Object.freeze(['sha256', 'sha512']);
|
|
31
31
|
exports.HASH_BLOCK_SIZE = 512 * 1024;
|
|
32
32
|
exports.BAG_DECLARATION = 'BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n';
|
package/dist/cjs/util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";;;AAyBA,gCAQC;AACD,sCAEC;AACD,kCAEC;AACD,4BAaC;AACD,sDAGC;AAED,4EAQC;AAQD,8BAQC;AACD,oCAMC;AAQD,0CAKC;AACD,wCAEC;AACD,gCAgBC;AACD,sCAKC;A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AAE,CAAC,CAAC;YAAC,CAAC;YACxC,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,GAAG,IAAI,CAAC;gBAAC,OAAO,GAAG,KAAK,CAAC;YAAC,CAAC;QACnD,CAAC;IACH,CAAC,CAAC,CAAC,CAAC;IACJ,IAAI,MAAM;QAAE,MAAM,OAAO,CAAC;IAC1B,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createHash, type Hash } from 'node:crypto';\nimport { createReadStream, existsSync, readdirSync, realpathSync, statSync, constants, accessSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';\nimport { BagError, BagValidationError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\n\nexport const VERSION = '1.0.0';\nexport const DEFAULT_CHECKSUMS: readonly string[] = Object.freeze(['sha256', 'sha512']);\nexport const HASH_BLOCK_SIZE = 512 * 1024;\nexport const BAG_DECLARATION = 'BagIt-Version: 1.0\\nTag-File-Character-Encoding: UTF-8\\n';\nexport const STANDARD_BAG_INFO_HEADERS: readonly string[] = Object.freeze([\n 'Source-Organization', 'Organization-Address', 'Contact-Name', 'Contact-Phone', 'Contact-Email',\n 'External-Description', 'External-Identifier', 'Bag-Size', 'Bag-Group-Identifier', 'Bag-Count',\n 'Internal-Sender-Identifier', 'Internal-Sender-Description', 'BagIt-Profile-Identifier',\n]);\n// Python's guaranteed fixed-length algorithms, mapped to OpenSSL names where necessary.\nconst HASH_NAMES: Record<string, string> = {\n blake2b: 'blake2b512', blake2s: 'blake2s256',\n sha3_224: 'sha3-224', sha3_256: 'sha3-256', sha3_384: 'sha3-384', sha3_512: 'sha3-512',\n};\nexport const CHECKSUM_ALGOS: readonly string[] = Object.freeze([\n 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',\n 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'blake2b', 'blake2s',\n]);\nexport function getHashers(algorithms: readonly string[]): Record<string, Hash> {\n const result: Record<string, Hash> = Object.create(null);\n for (const alg of algorithms) {\n if (!CHECKSUM_ALGOS.includes(alg)) continue;\n try { result[alg] = createHash(HASH_NAMES[alg] ?? alg); } catch { /* unavailable in this OpenSSL build */ }\n }\n if (!Object.keys(result).length) throw new BagError('Unable to continue: no supported checksum algorithms were requested');\n return result;\n}\nexport function algorithmsFor(algorithms: readonly string[] = DEFAULT_CHECKSUMS): string[] {\n return Object.keys(getHashers(algorithms));\n}\nexport function digestBytes(bytes: Uint8Array, algorithms: readonly string[]): Checksums {\n return Object.fromEntries(Object.entries(getHashers(algorithms)).map(([a, h]) => [a, h.update(bytes).digest('hex')]));\n}\nexport async function hashFile(path: string, algorithms: readonly string[], signal?: AbortSignal): Promise<{ hashes: Checksums; bytes: bigint }> {\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n try {\n for await (const block of createReadStream(path, { highWaterMark: HASH_BLOCK_SIZE, signal })) {\n bytes += BigInt(block.length);\n for (const hash of Object.values(hashers)) hash.update(block);\n }\n } catch (error) {\n signal?.throwIfAborted();\n throw new BagValidationError(`Could not read ${path}: ${String(error)}`, [], { cause: error });\n }\n return { hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])), bytes };\n}\nexport async function generateManifestLines(filename: string, algorithms: readonly string[] = DEFAULT_CHECKSUMS, signal?: AbortSignal): Promise<[algorithm: string, digest: string, filename: string, bytes: bigint][]> {\n const { hashes, bytes } = await hashFile(filename, algorithms, signal);\n return Object.entries(hashes).map(([algorithm, digest]) => [algorithm, digest, filename, bytes]);\n}\nexport const normalizeUnicode = (s: string): string => s.normalize('NFC');\nexport function buildUnicodeNormalizedLookupDict(filenames: Iterable<string>): Record<string, string> {\n const result: Record<string, string> = Object.create(null);\n for (const filename of filenames) {\n const normalized = normalizeUnicode(filename);\n if (Object.hasOwn(result, normalized)) throw new FileNormalizationConflict(filename, result[normalized]!);\n result[normalized] = filename;\n }\n return result;\n}\nexport const encodeFilename = (s: string): string => s.replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\nexport const decodeFilename = (s: string): string => s.replace(/%0d/gi, '\\r').replace(/%0a/gi, '\\n');\nexport const posixPath = (s: string): string => s.split(sep).join('/');\nexport const isFile = (p: string): boolean => { try { return statSync(p).isFile(); } catch { return false; } };\nexport const isDirectory = (p: string): boolean => { try { return statSync(p).isDirectory(); } catch { return false; } };\n\n/** Match os.walk: sorted files at each level, then sorted directories; do not follow directory symlinks. */\nexport function* walkFiles(root: string, prefix = ''): Generator<string> {\n if (!isDirectory(root)) return;\n const entries = readdirSync(root, { withFileTypes: true }).sort((a, b) => compareNames(a.name, b.name));\n for (const e of entries) {\n const p = join(root, e.name);\n if (e.isFile() || (e.isSymbolicLink() && !isDirectory(p))) yield prefix + e.name;\n }\n for (const e of entries) if (e.isDirectory()) yield* walkFiles(join(root, e.name), `${prefix}${e.name}/`);\n}\nexport function compareNames(a: string, b: string): number {\n // Python sorts Unicode code points, whereas JavaScript's default sort uses UTF-16 code units.\n const ac = Array.from(a, c => c.codePointAt(0)!);\n const bc = Array.from(b, c => c.codePointAt(0)!);\n for (let i = 0; i < Math.min(ac.length, bc.length); i++) if (ac[i] !== bc[i]) return ac[i]! - bc[i]!;\n return ac.length - bc.length;\n}\nfunction canonicalMissingPath(path: string): string {\n if (existsSync(path)) return realpathSync(path);\n const parent = dirname(path);\n if (parent === path) return path;\n // realpath still detects symlinks in the existing part of an absent fetch target.\n return join(canonicalMissingPath(parent), relative(parent, path));\n}\nexport function pathIsDangerous(root: string, filename: string): boolean {\n if (!filename || filename.includes('\\0') || isAbsolute(filename) || win32.isAbsolute(filename) || filename.startsWith('~')) return true;\n const actual = canonicalMissingPath(resolve(root, filename));\n const rel = relative(realpathSync(root), actual);\n return rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel);\n}\nexport function assertSafePath(root: string, filename: string, context = 'manifest'): void {\n if (pathIsDangerous(root, filename)) throw new BagError(`Path \"${filename}\" in ${context} is unsafe`);\n}\nexport function decodeText(bytes: Uint8Array, encoding = 'utf-8'): string {\n let label = encodingLabel(encoding);\n if (label === 'utf-16') {\n if (bytes[0] === 0xfe && bytes[1] === 0xff) label = 'utf-16be';\n else if (bytes[0] === 0xff && bytes[1] === 0xfe) label = 'utf-16le';\n else if (bytes.length) throw new BagValidationError('UTF-16 tag file must begin with a byte-order mark');\n }\n if (label === 'utf-8-sig') return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n if (label === 'ascii' || label === 'us-ascii') {\n if (bytes.some(b => b > 127)) throw new BagValidationError('Non-ASCII byte in ASCII tag file');\n return Buffer.from(bytes).toString('ascii');\n }\n // TextDecoder maps ISO-8859-1 to Windows-1252; Python uses the actual ISO mapping.\n if (['latin-1', 'latin1', 'iso-8859-1'].includes(label)) return Buffer.from(bytes).toString('latin1');\n try { return new TextDecoder(label, { fatal: true }).decode(bytes); }\n catch (e) { throw new BagValidationError(`Cannot decode tag file as ${encoding}`, [], { cause: e }); }\n}\nexport function checkEncoding(encoding: string): void {\n const label = encodingLabel(encoding);\n if (['utf-8-sig', 'latin-1'].includes(label)) return;\n try { new TextDecoder(label); }\n catch { throw new BagValidationError(`Unsupported encoding: ${encoding}`); }\n}\nexport function encodeText(text: string, encoding = 'utf-8'): Buffer {\n const label = encodingLabel(encoding);\n if (['utf-8', 'utf8', 'utf-8-sig'].includes(label)) {\n const bytes = Buffer.from(text, 'utf8');\n return label === 'utf-8-sig' ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), bytes]) : bytes;\n }\n if (['utf-16', 'utf-16le', 'utf-16-le', 'utf16le'].includes(label)) {\n const bytes = Buffer.from(text, 'utf16le');\n return label === 'utf-16' ? Buffer.concat([Buffer.from([0xff, 0xfe]), bytes]) : bytes;\n }\n if (['utf-16be', 'utf-16-be'].includes(label)) return Buffer.from(text, 'utf16le').swap16();\n const table = new Map<string, number>();\n for (let b = 0; b < 256; b++) {\n try { const c = decodeText(Uint8Array.of(b), encoding); if (c.length === 1 && !table.has(c)) table.set(c, b); } catch { /* invalid single byte */ }\n }\n const bytes: number[] = [];\n for (const c of text) {\n const b = table.get(c);\n if (b === undefined) throw new BagError(`Cannot encode character ${JSON.stringify(c)} as ${encoding}`);\n bytes.push(b);\n }\n return Buffer.from(bytes);\n}\nfunction encodingLabel(encoding: string): string {\n const label = encoding.toLowerCase().replace(/_/g, '-');\n return ({ utf8: 'utf-8', utf16: 'utf-16', utf16le: 'utf-16le', utf16be: 'utf-16be', 'utf-16-le': 'utf-16le', 'utf-16-be': 'utf-16be' } as Record<string, string>)[label] ?? label;\n}\nexport function parseTagFile(text: string, filename = 'tag file'): BagInfo {\n const result: BagInfo = Object.create(null);\n let key: string | undefined;\n let value = '';\n const emit = (): void => {\n if (!key) return;\n const v = value.trim();\n const prev = result[key];\n result[key] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [prev, v];\n };\n for (const line of text.replace(/\\r\\n?/g, '\\n').match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n if (!line.trim()) continue;\n if (/^\\s/.test(line) && key !== undefined) value += line;\n else {\n emit();\n const colon = line.indexOf(':');\n if (colon < 0) throw new BagValidationError(`${filename} contains invalid tag: ${line.trim()}`);\n key = line.slice(0, colon).trim();\n value = line.slice(colon + 1);\n }\n }\n emit();\n return result;\n}\nexport function serializeTagFile(info: BagInfoInput): string {\n let result = '';\n for (const key of Object.keys(info).sort(compareNames)) {\n if (!key || /[\\r\\n:]/.test(key)) throw new BagError(`Invalid metadata field name: ${key}`);\n const values = Array.isArray(info[key]) ? info[key] : [info[key]];\n for (const value of values!) result += `${key}: ${String(value).replace(/[\\r\\n]/g, '')}\\n`;\n }\n return result;\n}\nexport function makeBagInfo(info: BagInfoInput | undefined, bytes: bigint, files: number): BagInfo {\n const date = new Date();\n const today = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;\n return parseTagFile(serializeTagFile({\n 'Bagging-Date': today,\n 'Bag-Software-Agent': `bagit-node v${VERSION}`,\n ...info,\n 'Payload-Oxum': `${bytes}.${files}`,\n }));\n}\nexport async function loadTagFile(path: string, encoding = 'utf-8'): Promise<BagInfo> {\n return parseTagFile(decodeText(await readFile(path), encoding), path);\n}\nexport function checkPermissions(root: string, saving = false): void {\n try { accessSync(root, constants.R_OK | constants.W_OK | constants.X_OK); }\n catch {\n throw new BagError(saving ? `Cannot save bag to non-existent or inaccessible directory ${root}` : 'Missing permissions to move all files and directories');\n }\n const dirs = [root];\n const files: string[] = [];\n // Finish the write check before reporting unreadable descendants, matching Python.\n for (let i = 0; i < dirs.length; i++) {\n const dir = dirs[i]!;\n try { accessSync(dir, constants.W_OK); }\n catch { throw new BagError('Missing permissions to move all files and directories'); }\n let entries;\n try { entries = readdirSync(dir, { withFileTypes: true }); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n for (const e of entries) {\n if (e.isDirectory()) dirs.push(join(dir, e.name));\n else files.push(join(dir, e.name));\n }\n }\n for (const p of [...dirs, ...files]) {\n try { accessSync(p, constants.R_OK); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n }\n}\nexport function checkConcurrency(concurrency = 1): number {\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer');\n return concurrency;\n}\nexport async function mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (value: T) => Promise<R>): Promise<R[]> {\n const result: R[] = new Array(items.length);\n let next = 0;\n let failure: unknown;\n let failed = false;\n await Promise.all(Array.from({ length: Math.min(checkConcurrency(concurrency), items.length) }, async () => {\n while (!failed) {\n const i = next++;\n if (i >= items.length) return;\n try { result[i] = await fn(items[i]!); }\n catch (error) { failed = true; failure = error; }\n }\n }));\n if (failed) throw failure;\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":";;;AAyBA,gCAQC;AACD,sCAEC;AACD,kC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AAC,MAAM;gBAAE,OAAO;YAC9B,IAAI,CAAC;gBAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC;YAAC,CAAC;YACxC,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,GAAG,IAAI,CAAC;gBAAC,OAAO,GAAG,KAAK,CAAC;YAAC,CAAC;QACnD,CAAC;IACH,CAAC,CAAC,CAAC,CAAC;IACJ,IAAI,MAAM;QAAE,MAAM,OAAO,CAAC;IAC1B,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createHash, type Hash } from 'node:crypto';\nimport { createReadStream, existsSync, readdirSync, realpathSync, statSync, constants, accessSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';\nimport { BagError, BagValidationError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\n\nexport const VERSION = '1.1.0';\nexport const DEFAULT_CHECKSUMS: readonly string[] = Object.freeze(['sha256', 'sha512']);\nexport const HASH_BLOCK_SIZE = 512 * 1024;\nexport const BAG_DECLARATION = 'BagIt-Version: 1.0\\nTag-File-Character-Encoding: UTF-8\\n';\nexport const STANDARD_BAG_INFO_HEADERS: readonly string[] = Object.freeze([\n 'Source-Organization', 'Organization-Address', 'Contact-Name', 'Contact-Phone', 'Contact-Email',\n 'External-Description', 'External-Identifier', 'Bag-Size', 'Bag-Group-Identifier', 'Bag-Count',\n 'Internal-Sender-Identifier', 'Internal-Sender-Description', 'BagIt-Profile-Identifier',\n]);\n// Python's guaranteed fixed-length algorithms, mapped to OpenSSL names where necessary.\nconst HASH_NAMES: Record<string, string> = {\n blake2b: 'blake2b512', blake2s: 'blake2s256',\n sha3_224: 'sha3-224', sha3_256: 'sha3-256', sha3_384: 'sha3-384', sha3_512: 'sha3-512',\n};\nexport const CHECKSUM_ALGOS: readonly string[] = Object.freeze([\n 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',\n 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'blake2b', 'blake2s',\n]);\nexport function getHashers(algorithms: readonly string[]): Record<string, Hash> {\n const result: Record<string, Hash> = Object.create(null);\n for (const alg of algorithms) {\n if (!CHECKSUM_ALGOS.includes(alg)) continue;\n try { result[alg] = createHash(HASH_NAMES[alg] ?? alg); } catch { /* unavailable in this OpenSSL build */ }\n }\n if (!Object.keys(result).length) throw new BagError('Unable to continue: no supported checksum algorithms were requested');\n return result;\n}\nexport function algorithmsFor(algorithms: readonly string[] = DEFAULT_CHECKSUMS): string[] {\n return Object.keys(getHashers(algorithms));\n}\nexport function digestBytes(bytes: Uint8Array, algorithms: readonly string[]): Checksums {\n return Object.fromEntries(Object.entries(getHashers(algorithms)).map(([a, h]) => [a, h.update(bytes).digest('hex')]));\n}\nexport async function hashFile(path: string, algorithms: readonly string[], signal?: AbortSignal): Promise<{ hashes: Checksums; bytes: bigint }> {\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n try {\n for await (const block of createReadStream(path, { highWaterMark: HASH_BLOCK_SIZE, signal })) {\n bytes += BigInt(block.length);\n for (const hash of Object.values(hashers)) hash.update(block);\n }\n } catch (error) {\n signal?.throwIfAborted();\n throw new BagValidationError(`Could not read ${path}: ${String(error)}`, [], { cause: error });\n }\n return { hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])), bytes };\n}\nexport async function generateManifestLines(filename: string, algorithms: readonly string[] = DEFAULT_CHECKSUMS, signal?: AbortSignal): Promise<[algorithm: string, digest: string, filename: string, bytes: bigint][]> {\n const { hashes, bytes } = await hashFile(filename, algorithms, signal);\n return Object.entries(hashes).map(([algorithm, digest]) => [algorithm, digest, filename, bytes]);\n}\nexport const normalizeUnicode = (s: string): string => s.normalize('NFC');\nexport function buildUnicodeNormalizedLookupDict(filenames: Iterable<string>): Record<string, string> {\n const result: Record<string, string> = Object.create(null);\n for (const filename of filenames) {\n const normalized = normalizeUnicode(filename);\n if (Object.hasOwn(result, normalized)) throw new FileNormalizationConflict(filename, result[normalized]!);\n result[normalized] = filename;\n }\n return result;\n}\nexport const encodeFilename = (s: string): string => s.replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\nexport const decodeFilename = (s: string): string => s.replace(/%0d/gi, '\\r').replace(/%0a/gi, '\\n');\nexport const posixPath = (s: string): string => s.split(sep).join('/');\nexport const isFile = (p: string): boolean => { try { return statSync(p).isFile(); } catch { return false; } };\nexport const isDirectory = (p: string): boolean => { try { return statSync(p).isDirectory(); } catch { return false; } };\n\n/** Match os.walk: sorted files at each level, then sorted directories; do not follow directory symlinks. */\nexport function* walkFiles(root: string, prefix = ''): Generator<string> {\n if (!isDirectory(root)) return;\n const entries = readdirSync(root, { withFileTypes: true }).sort((a, b) => compareNames(a.name, b.name));\n for (const e of entries) {\n const p = join(root, e.name);\n if (e.isFile() || (e.isSymbolicLink() && !isDirectory(p))) yield prefix + e.name;\n }\n for (const e of entries) if (e.isDirectory()) yield* walkFiles(join(root, e.name), `${prefix}${e.name}/`);\n}\nexport function compareNames(a: string, b: string): number {\n // Python sorts Unicode code points, whereas JavaScript's default sort uses UTF-16 code units.\n const ac = Array.from(a, c => c.codePointAt(0)!);\n const bc = Array.from(b, c => c.codePointAt(0)!);\n for (let i = 0; i < Math.min(ac.length, bc.length); i++) if (ac[i] !== bc[i]) return ac[i]! - bc[i]!;\n return ac.length - bc.length;\n}\nfunction canonicalMissingPath(path: string): string {\n if (existsSync(path)) return realpathSync(path);\n const parent = dirname(path);\n if (parent === path) return path;\n // realpath still detects symlinks in the existing part of an absent fetch target.\n return join(canonicalMissingPath(parent), relative(parent, path));\n}\nexport function pathIsDangerous(root: string, filename: string): boolean {\n if (!filename || filename.includes('\\0') || isAbsolute(filename) || win32.isAbsolute(filename) || filename.startsWith('~')) return true;\n const actual = canonicalMissingPath(resolve(root, filename));\n const rel = relative(realpathSync(root), actual);\n return rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel);\n}\nexport function assertSafePath(root: string, filename: string, context = 'manifest'): void {\n if (pathIsDangerous(root, filename)) throw new BagError(`Path \"${filename}\" in ${context} is unsafe`);\n}\nexport function decodeText(bytes: Uint8Array, encoding = 'utf-8'): string {\n let label = encodingLabel(encoding);\n if (label === 'utf-16') {\n if (bytes[0] === 0xfe && bytes[1] === 0xff) label = 'utf-16be';\n else if (bytes[0] === 0xff && bytes[1] === 0xfe) label = 'utf-16le';\n else if (bytes.length) throw new BagValidationError('UTF-16 tag file must begin with a byte-order mark');\n }\n if (label === 'utf-8-sig') return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n if (label === 'ascii' || label === 'us-ascii') {\n if (bytes.some(b => b > 127)) throw new BagValidationError('Non-ASCII byte in ASCII tag file');\n return Buffer.from(bytes).toString('ascii');\n }\n // TextDecoder maps ISO-8859-1 to Windows-1252; Python uses the actual ISO mapping.\n if (['latin-1', 'latin1', 'iso-8859-1'].includes(label)) return Buffer.from(bytes).toString('latin1');\n try { return new TextDecoder(label, { fatal: true }).decode(bytes); }\n catch (e) { throw new BagValidationError(`Cannot decode tag file as ${encoding}`, [], { cause: e }); }\n}\nexport function checkEncoding(encoding: string): void {\n const label = encodingLabel(encoding);\n if (['utf-8-sig', 'latin-1'].includes(label)) return;\n try { new TextDecoder(label); }\n catch { throw new BagValidationError(`Unsupported encoding: ${encoding}`); }\n}\nexport function encodeText(text: string, encoding = 'utf-8'): Buffer {\n const label = encodingLabel(encoding);\n if (['utf-8', 'utf8', 'utf-8-sig'].includes(label)) {\n const bytes = Buffer.from(text, 'utf8');\n return label === 'utf-8-sig' ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), bytes]) : bytes;\n }\n if (['utf-16', 'utf-16le', 'utf-16-le', 'utf16le'].includes(label)) {\n const bytes = Buffer.from(text, 'utf16le');\n return label === 'utf-16' ? Buffer.concat([Buffer.from([0xff, 0xfe]), bytes]) : bytes;\n }\n if (['utf-16be', 'utf-16-be'].includes(label)) return Buffer.from(text, 'utf16le').swap16();\n const table = new Map<string, number>();\n for (let b = 0; b < 256; b++) {\n try { const c = decodeText(Uint8Array.of(b), encoding); if (c.length === 1 && !table.has(c)) table.set(c, b); } catch { /* invalid single byte */ }\n }\n const bytes: number[] = [];\n for (const c of text) {\n const b = table.get(c);\n if (b === undefined) throw new BagError(`Cannot encode character ${JSON.stringify(c)} as ${encoding}`);\n bytes.push(b);\n }\n return Buffer.from(bytes);\n}\nfunction encodingLabel(encoding: string): string {\n const label = encoding.toLowerCase().replace(/_/g, '-');\n return ({ utf8: 'utf-8', utf16: 'utf-16', utf16le: 'utf-16le', utf16be: 'utf-16be', 'utf-16-le': 'utf-16le', 'utf-16-be': 'utf-16be' } as Record<string, string>)[label] ?? label;\n}\nexport function parseTagFile(text: string, filename = 'tag file'): BagInfo {\n const result: BagInfo = Object.create(null);\n let key: string | undefined;\n let value = '';\n const emit = (): void => {\n if (!key) return;\n const v = value.trim();\n const prev = result[key];\n result[key] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [prev, v];\n };\n for (const line of text.replace(/\\r\\n?/g, '\\n').match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n if (!line.trim()) continue;\n if (/^\\s/.test(line) && key !== undefined) value += line;\n else {\n emit();\n const colon = line.indexOf(':');\n if (colon < 0) throw new BagValidationError(`${filename} contains invalid tag: ${line.trim()}`);\n key = line.slice(0, colon).trim();\n value = line.slice(colon + 1);\n }\n }\n emit();\n return result;\n}\nexport function serializeTagFile(info: BagInfoInput): string {\n let result = '';\n for (const key of Object.keys(info).sort(compareNames)) {\n if (!key || /[\\r\\n:]/.test(key)) throw new BagError(`Invalid metadata field name: ${key}`);\n const values = Array.isArray(info[key]) ? info[key] : [info[key]];\n for (const value of values!) result += `${key}: ${String(value).replace(/[\\r\\n]/g, '')}\\n`;\n }\n return result;\n}\nexport function makeBagInfo(info: BagInfoInput | undefined, bytes: bigint, files: number): BagInfo {\n const date = new Date();\n const today = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;\n return parseTagFile(serializeTagFile({\n 'Bagging-Date': today,\n 'Bag-Software-Agent': `bagit-node v${VERSION}`,\n ...info,\n 'Payload-Oxum': `${bytes}.${files}`,\n }));\n}\nexport async function loadTagFile(path: string, encoding = 'utf-8'): Promise<BagInfo> {\n return parseTagFile(decodeText(await readFile(path), encoding), path);\n}\nexport function checkPermissions(root: string, saving = false): void {\n try { accessSync(root, constants.R_OK | constants.W_OK | constants.X_OK); }\n catch {\n throw new BagError(saving ? `Cannot save bag to non-existent or inaccessible directory ${root}` : 'Missing permissions to move all files and directories');\n }\n const dirs = [root];\n const files: string[] = [];\n // Finish the write check before reporting unreadable descendants, matching Python.\n for (let i = 0; i < dirs.length; i++) {\n const dir = dirs[i]!;\n try { accessSync(dir, constants.W_OK); }\n catch { throw new BagError('Missing permissions to move all files and directories'); }\n let entries;\n try { entries = readdirSync(dir, { withFileTypes: true }); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n for (const e of entries) {\n if (e.isDirectory()) dirs.push(join(dir, e.name));\n else files.push(join(dir, e.name));\n }\n }\n for (const p of [...dirs, ...files]) {\n try { accessSync(p, constants.R_OK); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n }\n}\nexport function checkConcurrency(concurrency = 1): number {\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer');\n return concurrency;\n}\nexport async function mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (value: T) => Promise<R>): Promise<R[]> {\n const result: R[] = new Array(items.length);\n let next = 0;\n let failure: unknown;\n let failed = false;\n await Promise.all(Array.from({ length: Math.min(checkConcurrency(concurrency), items.length) }, async () => {\n while (!failed) {\n const i = next++;\n if (i >= items.length) return;\n try { result[i] = await fn(items[i]!); }\n catch (error) { failed = true; failure = error; }\n }\n }));\n if (failed) throw failure;\n return result;\n}\n"]}
|
package/dist/cjs/zip.d.ts
CHANGED
|
@@ -5,9 +5,11 @@ export interface BagZipOptions {
|
|
|
5
5
|
checksums?: readonly string[];
|
|
6
6
|
/** An optional directory containing the entire bag inside the archive. Default: archive root. */
|
|
7
7
|
bagName?: string;
|
|
8
|
+
/** Lazy custom tag files, with paths relative to the bag root. Use fresh iterables and sources for retries. */
|
|
9
|
+
tagFiles?: Iterable<BagZipEntry> | AsyncIterable<BagZipEntry>;
|
|
8
10
|
/** Deflate level 0–9; default 6. */
|
|
9
11
|
compressionLevel?: number;
|
|
10
|
-
/** Temporary directory for manifests; payloads are never staged. */
|
|
12
|
+
/** Temporary directory for payload manifests; payloads and custom tag files are never staged. */
|
|
11
13
|
tempDirectory?: string;
|
|
12
14
|
signal?: AbortSignal;
|
|
13
15
|
/** Fixed ZIP modification time for reproducible archives. */
|
|
@@ -28,7 +30,7 @@ export interface BagZipResult {
|
|
|
28
30
|
payloadFiles: number;
|
|
29
31
|
bagInfo: BagInfo;
|
|
30
32
|
}
|
|
31
|
-
/** Sources are opened lazily, one at a time.
|
|
33
|
+
/** Sources are opened lazily, one at a time. Payload paths are relative to data/; tagFiles paths are relative to the bag root. */
|
|
32
34
|
export interface BagZipEntry {
|
|
33
35
|
path: string;
|
|
34
36
|
/** Preserve an empty directory. Its open() function is ignored. */
|
package/dist/cjs/zip.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zip.d.ts","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAQtD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAMnE,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,iGAAiG;IAC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kI;AAClI,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,CAAC;IACb,mEAAmE;IACnE,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,IAAI,EAAE,MAAM,QAAQ,GAAG,aAAa,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,OAAO,CAAC,QAAQ,GAAG,aAAa,CAAC,UAAU,CAAC,GAAG,QAAQ,CAAC,UAAU,CAAC,CAAC,CAAC;IAC/I,KAAK,CAAC,EAAE,IAAI,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AA8QD,6FAA6F;AAC7F,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,GAAE,aAAkB,GAAG,QAAQ,CAG3F;AAED,uGAAuG;AACvG,wBAAgB,6BAA6B,CAAC,OAAO,EAAE,aAAa,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,GAAE,aAAkB,GAAG,QAAQ,CAGhJ;AAED,sHAAsH;AACtH,wBAAsB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,QAAQ,EAAE,OAAO,GAAE,aAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CA2B1I;AAED,eAAO,MAAM,gBAAgB,uBAAiB,CAAC"}
|
package/dist/cjs/zip.js
CHANGED
|
@@ -36,6 +36,32 @@ function validatePayloadPath(path) {
|
|
|
36
36
|
if (/\s$/.test((0, util_js_1.encodeFilename)(path)))
|
|
37
37
|
throw new errors_js_1.BagError(`BagIt cannot represent trailing whitespace unambiguously: ${JSON.stringify(path)}`);
|
|
38
38
|
}
|
|
39
|
+
function entryRegistry(kind, reservedFiles = []) {
|
|
40
|
+
const seen = new Map();
|
|
41
|
+
const directories = new Set();
|
|
42
|
+
const files = new Set(reservedFiles);
|
|
43
|
+
return entry => {
|
|
44
|
+
validatePayloadPath(entry.path);
|
|
45
|
+
const normalized = (0, util_js_1.normalizeUnicode)(entry.path);
|
|
46
|
+
const previous = seen.get(normalized);
|
|
47
|
+
if (previous !== undefined)
|
|
48
|
+
throw new errors_js_1.FileNormalizationConflict(entry.path, previous);
|
|
49
|
+
if (files.has(normalized) || (!entry.directory && directories.has(normalized)))
|
|
50
|
+
throw new errors_js_1.BagError(`Conflicting ${kind} file and directory: ${entry.path}`);
|
|
51
|
+
const parts = normalized.split('/');
|
|
52
|
+
for (let i = 1; i < parts.length; i++) {
|
|
53
|
+
const parent = parts.slice(0, i).join('/');
|
|
54
|
+
if (files.has(parent))
|
|
55
|
+
throw new errors_js_1.BagError(`Conflicting ${kind} paths: ${parent} and ${entry.path}`);
|
|
56
|
+
directories.add(parent);
|
|
57
|
+
}
|
|
58
|
+
seen.set(normalized, entry.path);
|
|
59
|
+
if (entry.directory)
|
|
60
|
+
directories.add(normalized);
|
|
61
|
+
else
|
|
62
|
+
files.add(normalized);
|
|
63
|
+
};
|
|
64
|
+
}
|
|
39
65
|
async function* folderEntries(directory, options) {
|
|
40
66
|
const root = (0, node_path_1.resolve)(directory);
|
|
41
67
|
if (!(0, util_js_1.isDirectory)(root))
|
|
@@ -159,6 +185,37 @@ async function* archiveContent(entries, options, state) {
|
|
|
159
185
|
signal.throwIfAborted();
|
|
160
186
|
zip.addEmptyDirectory(name, { mtime: options.mtime ?? mtime ?? new Date(), mode });
|
|
161
187
|
}
|
|
188
|
+
async function addSource(entry, name) {
|
|
189
|
+
const hashers = (0, util_js_1.getHashers)(algorithms);
|
|
190
|
+
let bytes = 0n;
|
|
191
|
+
async function* hashed() {
|
|
192
|
+
signal.throwIfAborted();
|
|
193
|
+
const source = await entry.open();
|
|
194
|
+
const destroy = () => {
|
|
195
|
+
if (source instanceof node_stream_1.Readable)
|
|
196
|
+
source.destroy();
|
|
197
|
+
};
|
|
198
|
+
signal.addEventListener('abort', destroy, { once: true });
|
|
199
|
+
try {
|
|
200
|
+
signal.throwIfAborted();
|
|
201
|
+
for await (const chunk of source) {
|
|
202
|
+
signal.throwIfAborted();
|
|
203
|
+
if (!(chunk instanceof Uint8Array))
|
|
204
|
+
throw new TypeError('ZIP sources must produce Uint8Array or Buffer chunks');
|
|
205
|
+
bytes += BigInt(chunk.length);
|
|
206
|
+
for (const h of Object.values(hashers))
|
|
207
|
+
h.update(chunk);
|
|
208
|
+
yield chunk;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
finally {
|
|
212
|
+
signal.removeEventListener('abort', destroy);
|
|
213
|
+
destroy();
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
await addEntry(name, hashed(), entry.mtime, entry.mode);
|
|
217
|
+
return { bytes, hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])) };
|
|
218
|
+
}
|
|
162
219
|
const produce = async () => {
|
|
163
220
|
const manifests = new Map();
|
|
164
221
|
for (const a of algorithms) {
|
|
@@ -168,59 +225,18 @@ async function* archiveContent(entries, options, state) {
|
|
|
168
225
|
manifests.set(a, { path, handle });
|
|
169
226
|
}
|
|
170
227
|
const prefix = options.bagName ? `${options.bagName}/` : '';
|
|
171
|
-
const
|
|
172
|
-
const directories = new Set();
|
|
173
|
-
const files = new Set();
|
|
228
|
+
const registerPayload = entryRegistry('payload');
|
|
174
229
|
let totalBytes = 0n;
|
|
175
230
|
let totalFiles = 0;
|
|
176
231
|
addDirectory(`${prefix}data/`);
|
|
177
232
|
for await (const entry of entries) {
|
|
178
233
|
signal.throwIfAborted();
|
|
179
|
-
|
|
180
|
-
const normalized = (0, util_js_1.normalizeUnicode)(entry.path);
|
|
181
|
-
const previous = seen.get(normalized);
|
|
182
|
-
if (previous !== undefined)
|
|
183
|
-
throw new errors_js_1.FileNormalizationConflict(entry.path, previous);
|
|
184
|
-
if (!entry.directory && directories.has(normalized))
|
|
185
|
-
throw new errors_js_1.BagError(`Conflicting payload file and directory: ${entry.path}`);
|
|
186
|
-
const parts = normalized.split('/');
|
|
187
|
-
for (let i = 1; i < parts.length; i++) {
|
|
188
|
-
const parent = parts.slice(0, i).join('/');
|
|
189
|
-
if (files.has(parent))
|
|
190
|
-
throw new errors_js_1.BagError(`Conflicting payload paths: ${parent} and ${entry.path}`);
|
|
191
|
-
directories.add(parent);
|
|
192
|
-
}
|
|
193
|
-
if (entry.directory && files.has(normalized))
|
|
194
|
-
throw new errors_js_1.BagError(`Conflicting payload file and directory: ${entry.path}`);
|
|
195
|
-
seen.set(normalized, entry.path);
|
|
234
|
+
registerPayload(entry);
|
|
196
235
|
if (entry.directory) {
|
|
197
|
-
directories.add(normalized);
|
|
198
236
|
addDirectory(`${prefix}data/${entry.path}/`, entry.mtime, entry.mode);
|
|
199
237
|
continue;
|
|
200
238
|
}
|
|
201
|
-
|
|
202
|
-
const hashers = (0, util_js_1.getHashers)(algorithms);
|
|
203
|
-
let bytes = 0n;
|
|
204
|
-
async function* hashed() {
|
|
205
|
-
const source = await entry.open();
|
|
206
|
-
try {
|
|
207
|
-
for await (const chunk of source) {
|
|
208
|
-
signal.throwIfAborted();
|
|
209
|
-
if (!(chunk instanceof Uint8Array))
|
|
210
|
-
throw new TypeError('Payload sources must produce Uint8Array or Buffer chunks');
|
|
211
|
-
bytes += BigInt(chunk.length);
|
|
212
|
-
for (const h of Object.values(hashers))
|
|
213
|
-
h.update(chunk);
|
|
214
|
-
yield chunk;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
finally {
|
|
218
|
-
if (source instanceof node_stream_1.Readable)
|
|
219
|
-
source.destroy();
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
await addEntry(`${prefix}data/${entry.path}`, hashed(), entry.mtime, entry.mode);
|
|
223
|
-
const hashes = Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')]));
|
|
239
|
+
const { bytes, hashes } = await addSource(entry, `${prefix}data/${entry.path}`);
|
|
224
240
|
for (const a of algorithms)
|
|
225
241
|
await manifests.get(a).handle.writeFile(`${hashes[a]} ${(0, util_js_1.encodeFilename)(`data/${entry.path}`)}\n`);
|
|
226
242
|
totalBytes += bytes;
|
|
@@ -228,6 +244,25 @@ async function* archiveContent(entries, options, state) {
|
|
|
228
244
|
await options.onProgress?.({ path: entry.path, bytes, hashes, totalBytes, totalFiles });
|
|
229
245
|
}
|
|
230
246
|
const tags = [];
|
|
247
|
+
const registerTag = entryRegistry('tag', ['bagit.txt', 'bag-info.txt', 'data']);
|
|
248
|
+
for await (const entry of options.tagFiles ?? []) {
|
|
249
|
+
signal.throwIfAborted();
|
|
250
|
+
// Unlike payload paths (which start with data/), root tags can begin with
|
|
251
|
+
// whitespace or checksum-tool binary markers that manifest parsers strip.
|
|
252
|
+
if (/^[\s*]/.test((0, util_js_1.encodeFilename)(entry.path)))
|
|
253
|
+
throw new errors_js_1.BagError(`Ambiguous BagIt tag filename: ${JSON.stringify(entry.path)}`);
|
|
254
|
+
// Reserve manifest namespaces, including algorithms not selected for this export.
|
|
255
|
+
const root = (0, util_js_1.normalizeUnicode)(entry.path).split('/')[0];
|
|
256
|
+
if (/^(?:tagmanifest|manifest)-.*\.txt$/.test(root))
|
|
257
|
+
throw new errors_js_1.BagError(`Reserved tag-file path: ${entry.path}`);
|
|
258
|
+
registerTag(entry);
|
|
259
|
+
if (entry.directory)
|
|
260
|
+
addDirectory(`${prefix}${entry.path}/`, entry.mtime, entry.mode);
|
|
261
|
+
else {
|
|
262
|
+
const { hashes } = await addSource(entry, prefix + entry.path);
|
|
263
|
+
tags.push({ name: entry.path, hashes });
|
|
264
|
+
}
|
|
265
|
+
}
|
|
231
266
|
for (const a of algorithms) {
|
|
232
267
|
const manifest = manifests.get(a);
|
|
233
268
|
await manifest.handle.close();
|
package/dist/cjs/zip.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zip.js","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":";;;AA0RA,gDAGC;AAGD,sEAGC;AAGD,wCA2BC;AAjUD,6CAAsD;AACtD,mDAA0D;AAC1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EAAE,UAAU,EAAE,KAAK,EAAE,aAAa,EAAE,yBAAe,EAAE,CAAC,CAAC;QAChJ,IAAI,CAAC;YAAC,MAAM,IAAA,mBAAQ,EAAC,MAAM,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAAC,CAAC;gBAC3D,CAAC;YAAC,MAAM,KAAK,CAAC,OAAO,CAAC;QAAC,CAAC;QAChC,IAAI,OAAO,WAAW,KAAK,QAAQ;YAAE,MAAM,IAAA,iBAAM,EAAC,IAAA,gBAAI,EAAC,IAAK,EAAE,aAAa,CAAC,EAAE,IAAA,mBAAO,EAAC,WAAW,CAAC,CAAC,CAAC;QACpG,OAAO,KAAK,CAAC,MAAO,CAAC;IACvB,CAAC;YAAS,CAAC;QAAC,IAAI,IAAI;YAAE,MAAM,IAAA,aAAE,EAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAAC,CAAC;AAC3E,CAAC;AAEY,QAAA,gBAAgB,GAAG,cAAc,CAAC","sourcesContent":["import { Readable, type Writable } from 'node:stream';\nimport { finished, pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { mkdtemp, open, readdir, realpath, rename, rm, stat, type FileHandle } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { ZipFile } from 'yazl';\nimport { BagError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\nimport {\n algorithmsFor, assertSafePath, BAG_DECLARATION, digestBytes, encodeFilename, getHashers,\n compareNames, HASH_BLOCK_SIZE, isDirectory, makeBagInfo, normalizeUnicode, serializeTagFile,\n} from './util.js';\n\nexport interface BagZipOptions {\n bagInfo?: BagInfoInput;\n checksums?: readonly string[];\n /** An optional directory containing the entire bag inside the archive. Default: archive root. */\n bagName?: string;\n /** Deflate level 0–9; default 6. */\n compressionLevel?: number;\n /** Temporary directory for manifests; payloads are never staged. */\n tempDirectory?: string;\n signal?: AbortSignal;\n /** Fixed ZIP modification time for reproducible archives. */\n mtime?: Date;\n /** Called after a payload file has been completely read into the ZIP compressor. */\n onProgress?: (progress: BagZipProgress) => void | Promise<void>;\n}\nexport interface BagZipProgress {\n path: string;\n bytes: bigint;\n hashes: Checksums;\n totalBytes: bigint;\n totalFiles: number;\n}\nexport interface BagZipResult { bytesWritten: bigint; payloadBytes: bigint; payloadFiles: number; bagInfo: BagInfo; }\n\n/** Sources are opened lazily, one at a time. Paths are relative to the payload, without a data/ prefix. */\nexport interface BagZipEntry {\n path: string;\n /** Preserve an empty directory. Its open() function is ignored. */\n directory?: boolean;\n open: () => Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | Promise<Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array>>;\n mtime?: Date;\n mode?: number;\n}\n\nfunction validateOptions(options: BagZipOptions): string[] {\n const level = options.compressionLevel ?? 6;\n if (!Number.isInteger(level) || level < 0 || level > 9) throw new RangeError('compressionLevel must be an integer from 0 to 9');\n if (options.bagName !== undefined) validateEntryPath(options.bagName);\n if (options.mtime && !Number.isFinite(options.mtime.getTime())) throw new BagError('Invalid ZIP modification time');\n return algorithmsFor(options.checksums);\n}\nfunction validateEntryPath(path: string): void {\n if (!path || path.includes('\\\\') || /[\\0\\r\\n]/.test(path) || path.startsWith('~') || path.startsWith('/') || /^[a-z]:/i.test(path) || path.split('/').some(p => !p || p === '.' || p === '..')) {\n throw new BagError(`Unsafe ZIP entry path: ${JSON.stringify(path)}`);\n }\n}\n// CR/LF are legal BagIt payload names: manifests encode them, ZIP headers store their original bytes.\nfunction validatePayloadPath(path: string): void {\n validateEntryPath(path.replace(/[\\r\\n]/g, '_'));\n if (/%0[ad]/i.test(path)) throw new BagError(`Ambiguous BagIt filename contains a literal encoded newline: ${path}`);\n if (/\\s$/.test(encodeFilename(path))) throw new BagError(`BagIt cannot represent trailing whitespace unambiguously: ${JSON.stringify(path)}`);\n}\n\nasync function* folderEntries(directory: string, options: BagZipOptions): AsyncGenerator<BagZipEntry> {\n const root = resolve(directory);\n if (!isDirectory(root)) throw new BagError(`Bag directory ${root} does not exist`);\n const temporaryRoot = await realpath(options.tempDirectory ?? tmpdir());\n const relTemp = relative(await realpath(root), temporaryRoot);\n if (!relTemp || (!isAbsolute(relTemp) && relTemp !== '..' && !relTemp.startsWith(`..${sep}`))) throw new BagError('Manifest temporary directory must be outside the source directory');\n async function* walk(path = ''): AsyncGenerator<BagZipEntry> {\n const entries = (await readdir(join(root, path), { withFileTypes: true })).sort((a, b) => compareNames(a.name, b.name));\n for (const entry of entries) {\n if (entry.isDirectory()) continue;\n const filename = path + entry.name;\n assertSafePath(root, filename, 'source directory');\n if (entry.isSymbolicLink() && isDirectory(join(root, filename))) throw new BagError(`Directory symlinks cannot be exported: ${filename}`);\n yield await fileEntry(filename);\n }\n for (const entry of entries) if (entry.isDirectory()) {\n const filename = path + entry.name;\n const metadata = await stat(join(root, filename));\n yield { path: filename, directory: true, mtime: metadata.mtime, mode: metadata.mode, open: () => [] };\n yield* walk(filename + '/');\n }\n }\n async function fileEntry(path: string): Promise<BagZipEntry> {\n options.signal?.throwIfAborted();\n assertSafePath(root, path, 'source directory');\n const fullPath = join(root, path);\n const before = await stat(fullPath, { bigint: true });\n if (!before.isFile()) throw new BagError(`Payload is not a regular file: ${path}`);\n return {\n path, mtime: new Date(Number(before.mtimeMs)), mode: Number(before.mode),\n async *open() {\n // Check the opened file, rather than just the preceding path stat.\n assertSafePath(root, path, 'source directory');\n const handle = await open(fullPath, 'r');\n try {\n const opened = await handle.stat({ bigint: true });\n if (opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size || opened.mtimeNs !== before.mtimeNs) throw new BagError(`Source file changed before reading: ${path}`);\n const stream = handle.createReadStream({ autoClose: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n try {\n yield* stream;\n const after = await handle.stat({ bigint: true });\n if (after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) throw new BagError(`Source file changed while reading: ${path}`);\n } finally { stream.destroy(); }\n } finally { await handle.close(); }\n },\n };\n }\n yield* walk();\n}\n\ninterface ExportState { result?: BagZipResult; cleanup?: Promise<void>; }\nasync function* archive(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n let complete!: () => void;\n state.cleanup = new Promise<void>(resolve => { complete = resolve; });\n try { yield* archiveContent(entries, options, state); }\n finally { complete(); }\n}\nasync function* archiveContent(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n const algorithms = validateOptions(options);\n options.signal?.throwIfAborted();\n const temp = await mkdtemp(join(options.tempDirectory ?? tmpdir(), 'bagit-zip-'));\n const handles: FileHandle[] = [];\n const zip = new ZipFile();\n const output = zip.outputStream as Readable;\n const controller = new AbortController();\n const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n let active: Readable | undefined;\n let failure: unknown;\n let failed = false;\n const fail = (error: unknown): void => {\n if (failed) return;\n failed = true;\n failure = error;\n controller.abort(error);\n active?.destroy(error instanceof Error ? error : new Error(String(error)));\n output.destroy(error instanceof Error ? error : new Error(String(error)));\n };\n zip.on('error', fail);\n // Install an error listener before producer I/O can fail, even before iteration starts.\n output.on('error', fail);\n const onAbort = (): void => fail(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n\n async function addEntry(name: string, input: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, mtime?: Date, mode?: number): Promise<void> {\n signal.throwIfAborted();\n const source = Readable.from(input, { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal });\n active = source;\n const done = finished(source, { cleanup: true });\n // Register rejection handling immediately; addReadStreamLazy can throw synchronously.\n void done.catch(fail);\n try {\n zip.addReadStreamLazy(name, {\n mtime: options.mtime ?? mtime ?? new Date(), mode: mode ?? 0o100644,\n compressionLevel: options.compressionLevel ?? 6,\n }, cb => cb(null, source));\n await done;\n } finally {\n source.destroy();\n await done.catch(() => {});\n active = undefined;\n }\n }\n function addDirectory(name: string, mtime?: Date, mode = 0o40755): void {\n signal.throwIfAborted();\n zip.addEmptyDirectory(name, { mtime: options.mtime ?? mtime ?? new Date(), mode });\n }\n\n const produce = async (): Promise<Omit<BagZipResult, 'bytesWritten'>> => {\n const manifests = new Map<string, { path: string; handle: FileHandle }>();\n for (const a of algorithms) {\n const path = join(temp, `manifest-${a}.txt`);\n const handle = await open(path, 'w');\n handles.push(handle);\n manifests.set(a, { path, handle });\n }\n const prefix = options.bagName ? `${options.bagName}/` : '';\n const seen = new Map<string, string>();\n const directories = new Set<string>();\n const files = new Set<string>();\n let totalBytes = 0n;\n let totalFiles = 0;\n addDirectory(`${prefix}data/`);\n for await (const entry of entries) {\n signal.throwIfAborted();\n validatePayloadPath(entry.path);\n const normalized = normalizeUnicode(entry.path);\n const previous = seen.get(normalized);\n if (previous !== undefined) throw new FileNormalizationConflict(entry.path, previous);\n if (!entry.directory && directories.has(normalized)) throw new BagError(`Conflicting payload file and directory: ${entry.path}`);\n const parts = normalized.split('/');\n for (let i = 1; i < parts.length; i++) {\n const parent = parts.slice(0, i).join('/');\n if (files.has(parent)) throw new BagError(`Conflicting payload paths: ${parent} and ${entry.path}`);\n directories.add(parent);\n }\n if (entry.directory && files.has(normalized)) throw new BagError(`Conflicting payload file and directory: ${entry.path}`);\n seen.set(normalized, entry.path);\n if (entry.directory) {\n directories.add(normalized);\n addDirectory(`${prefix}data/${entry.path}/`, entry.mtime, entry.mode);\n continue;\n }\n files.add(normalized);\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n async function* hashed(): AsyncGenerator<Uint8Array> {\n const source = await entry.open();\n try {\n for await (const chunk of source) {\n signal.throwIfAborted();\n if (!(chunk instanceof Uint8Array)) throw new TypeError('Payload sources must produce Uint8Array or Buffer chunks');\n bytes += BigInt(chunk.length);\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk;\n }\n } finally { if (source instanceof Readable) source.destroy(); }\n }\n await addEntry(`${prefix}data/${entry.path}`, hashed(), entry.mtime, entry.mode);\n const hashes = Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')]));\n for (const a of algorithms) await manifests.get(a)!.handle.writeFile(`${hashes[a]} ${encodeFilename(`data/${entry.path}`)}\\n`);\n totalBytes += bytes;\n totalFiles++;\n await options.onProgress?.({ path: entry.path, bytes, hashes, totalBytes, totalFiles });\n }\n const tags: { name: string; hashes: Checksums }[] = [];\n for (const a of algorithms) {\n const manifest = manifests.get(a)!;\n await manifest.handle.close();\n const hashers = getHashers(algorithms);\n async function* content(): AsyncGenerator<Buffer> {\n for await (const chunk of createReadStream(manifest.path, { signal })) {\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk as Buffer;\n }\n }\n const name = `manifest-${a}.txt`;\n await addEntry(prefix + name, content());\n tags.push({ name, hashes: Object.fromEntries(Object.entries(hashers).map(([alg, h]) => [alg, h.digest('hex')])) });\n }\n const bagInfo = makeBagInfo(options.bagInfo, totalBytes, totalFiles);\n for (const [name, text] of [['bagit.txt', BAG_DECLARATION], ['bag-info.txt', serializeTagFile(bagInfo)]]) {\n const bytes = Buffer.from(text!, 'utf8');\n await addEntry(prefix + name!, [bytes]);\n tags.push({ name: name!, hashes: digestBytes(bytes, algorithms) });\n }\n for (const a of algorithms) {\n const text = tags.map(t => `${t.hashes[a]} ${encodeFilename(t.name)}\\n`).join('');\n await addEntry(`${prefix}tagmanifest-${a}.txt`, [Buffer.from(text)]);\n }\n zip.end();\n return { payloadBytes: totalBytes, payloadFiles: totalFiles, bagInfo };\n };\n const done = produce().catch(error => { fail(error); return undefined; });\n try {\n if (signal.aborted) fail(signal.reason);\n let bytesWritten = 0n;\n for await (const chunk of output) {\n bytesWritten += BigInt(chunk.length);\n yield chunk as Buffer;\n }\n const result = await done;\n if (failed) throw failure;\n state.result = { ...result!, bytesWritten };\n } finally {\n signal.removeEventListener('abort', onAbort);\n controller.abort();\n active?.destroy();\n output.destroy();\n await done;\n await Promise.allSettled(handles.map(h => h.close()));\n await rm(temp, { recursive: true, force: true });\n }\n}\n\n/** Pipe directly into an S3/Ceph multipart upload Body. Errors are emitted on the stream. */\nexport function createBagZipStream(directory: string, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(folderEntries(directory, options), options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Stream a bag from lazy application-provided sources, without first creating a payload directory. */\nexport function createBagZipStreamFromEntries(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(entries, options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Write an archive to a Writable, or atomically replace a path after successful completion. Ends the destination. */\nexport async function folderToBagZip(directory: string, destination: string | Writable, options: BagZipOptions = {}): Promise<BagZipResult> {\n validateOptions(options);\n options.signal?.throwIfAborted();\n if (!isDirectory(resolve(directory))) throw new BagError(`Bag directory ${resolve(directory)} does not exist`);\n const state: ExportState = {};\n let temp: string | undefined;\n try {\n let output: Writable;\n const outputPath = typeof destination === 'string' ? destination : 'path' in destination && typeof destination.path === 'string' ? destination.path : undefined;\n if (outputPath !== undefined) {\n const target = resolve(outputPath);\n // Resolve existing parent symlinks before checking containment.\n const actual = join(await realpath(dirname(target)), basename(target));\n const rel = relative(await realpath(directory), actual);\n if (!rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))) throw new BagError('ZIP destination must be outside the source directory');\n }\n if (typeof destination === 'string') {\n const target = resolve(destination);\n temp = await mkdtemp(join(dirname(target), '.bagit-output-'));\n output = createWriteStream(join(temp, 'archive.zip'), { flags: 'wx' });\n } else output = destination;\n const source = Readable.from(archive(folderEntries(directory, options), options, state), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE });\n try { await pipeline(source, output, { signal: options.signal }); }\n finally { await state.cleanup; }\n if (typeof destination === 'string') await rename(join(temp!, 'archive.zip'), resolve(destination));\n return state.result!;\n } finally { if (temp) await rm(temp, { recursive: true, force: true }); }\n}\n\nexport const folderToBagitZip = folderToBagZip;\n"]}
|
|
1
|
+
{"version":3,"file":"zip.js","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":";;;AA+TA,gDAGC;AAGD,sEAGC;AAGD,wCA2BC;AAtWD,6CAAsD;AACtD,mDAA0D;AAC1D,qCAA8D;AAC9D,+CAAuG;AACvG,qCAAiC;AACjC,yCAAwF;AACxF,+BAA+B;AAC/B,2CAAkE;AAElE,uCAGmB;AAsCnB,SAAS,eAAe,CAAC,OAAsB;IAC7C,MAAM,KAAK,GAAG,OAAO,CAAC,gBAAgB,IAAI,CAAC,CAAC;IAC5C,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,iDAAiD,CAAC,CAAC;IAChI,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS;QAAE,iBAAiB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IACtE,IAAI,OAAO,CAAC,KAAK,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC;QAAE,MAAM,IAAI,oBAAQ,CAAC,+BAA+B,CAAC,CAAC;IACpH,OAAO,IAAA,uBAAa,EAAC,OAAO,CAAC,SAAS,CAAC,CAAC;AAC1C,CAAC;AACD,SAAS,iBAAiB,CAAC,IAAY;IACrC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,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QAChC,IAAI,OAAO,WAAW,KAAK,QAAQ;YAAE,MAAM,IAAA,iBAAM,EAAC,IAAA,gBAAI,EAAC,IAAK,EAAE,aAAa,CAAC,EAAE,IAAA,mBAAO,EAAC,WAAW,CAAC,CAAC,CAAC;QACpG,OAAO,KAAK,CAAC,MAAO,CAAC;IACvB,CAAC;YAAS,CAAC;QAAC,IAAI,IAAI;YAAE,MAAM,IAAA,aAAE,EAAC,IAAI,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAAC,CAAC;AAC3E,CAAC;AAEY,QAAA,gBAAgB,GAAG,cAAc,CAAC","sourcesContent":["import { Readable, type Writable } from 'node:stream';\nimport { finished, pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { mkdtemp, open, readdir, realpath, rename, rm, stat, type FileHandle } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { ZipFile } from 'yazl';\nimport { BagError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\nimport {\n algorithmsFor, assertSafePath, BAG_DECLARATION, digestBytes, encodeFilename, getHashers,\n compareNames, HASH_BLOCK_SIZE, isDirectory, makeBagInfo, normalizeUnicode, serializeTagFile,\n} from './util.js';\n\nexport interface BagZipOptions {\n bagInfo?: BagInfoInput;\n checksums?: readonly string[];\n /** An optional directory containing the entire bag inside the archive. Default: archive root. */\n bagName?: string;\n /** Lazy custom tag files, with paths relative to the bag root. Use fresh iterables and sources for retries. */\n tagFiles?: Iterable<BagZipEntry> | AsyncIterable<BagZipEntry>;\n /** Deflate level 0–9; default 6. */\n compressionLevel?: number;\n /** Temporary directory for payload manifests; payloads and custom tag files are never staged. */\n tempDirectory?: string;\n signal?: AbortSignal;\n /** Fixed ZIP modification time for reproducible archives. */\n mtime?: Date;\n /** Called after a payload file has been completely read into the ZIP compressor. */\n onProgress?: (progress: BagZipProgress) => void | Promise<void>;\n}\nexport interface BagZipProgress {\n path: string;\n bytes: bigint;\n hashes: Checksums;\n totalBytes: bigint;\n totalFiles: number;\n}\nexport interface BagZipResult { bytesWritten: bigint; payloadBytes: bigint; payloadFiles: number; bagInfo: BagInfo; }\n\n/** Sources are opened lazily, one at a time. Payload paths are relative to data/; tagFiles paths are relative to the bag root. */\nexport interface BagZipEntry {\n path: string;\n /** Preserve an empty directory. Its open() function is ignored. */\n directory?: boolean;\n open: () => Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | Promise<Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array>>;\n mtime?: Date;\n mode?: number;\n}\n\nfunction validateOptions(options: BagZipOptions): string[] {\n const level = options.compressionLevel ?? 6;\n if (!Number.isInteger(level) || level < 0 || level > 9) throw new RangeError('compressionLevel must be an integer from 0 to 9');\n if (options.bagName !== undefined) validateEntryPath(options.bagName);\n if (options.mtime && !Number.isFinite(options.mtime.getTime())) throw new BagError('Invalid ZIP modification time');\n return algorithmsFor(options.checksums);\n}\nfunction validateEntryPath(path: string): void {\n if (!path || path.includes('\\\\') || /[\\0\\r\\n]/.test(path) || path.startsWith('~') || path.startsWith('/') || /^[a-z]:/i.test(path) || path.split('/').some(p => !p || p === '.' || p === '..')) {\n throw new BagError(`Unsafe ZIP entry path: ${JSON.stringify(path)}`);\n }\n}\n// CR/LF are legal BagIt payload names: manifests encode them, ZIP headers store their original bytes.\nfunction validatePayloadPath(path: string): void {\n validateEntryPath(path.replace(/[\\r\\n]/g, '_'));\n if (/%0[ad]/i.test(path)) throw new BagError(`Ambiguous BagIt filename contains a literal encoded newline: ${path}`);\n if (/\\s$/.test(encodeFilename(path))) throw new BagError(`BagIt cannot represent trailing whitespace unambiguously: ${JSON.stringify(path)}`);\n}\n\nfunction entryRegistry(kind: string, reservedFiles: readonly string[] = []): (entry: BagZipEntry) => void {\n const seen = new Map<string, string>();\n const directories = new Set<string>();\n const files = new Set(reservedFiles);\n return entry => {\n validatePayloadPath(entry.path);\n const normalized = normalizeUnicode(entry.path);\n const previous = seen.get(normalized);\n if (previous !== undefined) throw new FileNormalizationConflict(entry.path, previous);\n if (files.has(normalized) || (!entry.directory && directories.has(normalized))) throw new BagError(`Conflicting ${kind} file and directory: ${entry.path}`);\n const parts = normalized.split('/');\n for (let i = 1; i < parts.length; i++) {\n const parent = parts.slice(0, i).join('/');\n if (files.has(parent)) throw new BagError(`Conflicting ${kind} paths: ${parent} and ${entry.path}`);\n directories.add(parent);\n }\n seen.set(normalized, entry.path);\n if (entry.directory) directories.add(normalized);\n else files.add(normalized);\n };\n}\n\nasync function* folderEntries(directory: string, options: BagZipOptions): AsyncGenerator<BagZipEntry> {\n const root = resolve(directory);\n if (!isDirectory(root)) throw new BagError(`Bag directory ${root} does not exist`);\n const temporaryRoot = await realpath(options.tempDirectory ?? tmpdir());\n const relTemp = relative(await realpath(root), temporaryRoot);\n if (!relTemp || (!isAbsolute(relTemp) && relTemp !== '..' && !relTemp.startsWith(`..${sep}`))) throw new BagError('Manifest temporary directory must be outside the source directory');\n async function* walk(path = ''): AsyncGenerator<BagZipEntry> {\n const entries = (await readdir(join(root, path), { withFileTypes: true })).sort((a, b) => compareNames(a.name, b.name));\n for (const entry of entries) {\n if (entry.isDirectory()) continue;\n const filename = path + entry.name;\n assertSafePath(root, filename, 'source directory');\n if (entry.isSymbolicLink() && isDirectory(join(root, filename))) throw new BagError(`Directory symlinks cannot be exported: ${filename}`);\n yield await fileEntry(filename);\n }\n for (const entry of entries) if (entry.isDirectory()) {\n const filename = path + entry.name;\n const metadata = await stat(join(root, filename));\n yield { path: filename, directory: true, mtime: metadata.mtime, mode: metadata.mode, open: () => [] };\n yield* walk(filename + '/');\n }\n }\n async function fileEntry(path: string): Promise<BagZipEntry> {\n options.signal?.throwIfAborted();\n assertSafePath(root, path, 'source directory');\n const fullPath = join(root, path);\n const before = await stat(fullPath, { bigint: true });\n if (!before.isFile()) throw new BagError(`Payload is not a regular file: ${path}`);\n return {\n path, mtime: new Date(Number(before.mtimeMs)), mode: Number(before.mode),\n async *open() {\n // Check the opened file, rather than just the preceding path stat.\n assertSafePath(root, path, 'source directory');\n const handle = await open(fullPath, 'r');\n try {\n const opened = await handle.stat({ bigint: true });\n if (opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size || opened.mtimeNs !== before.mtimeNs) throw new BagError(`Source file changed before reading: ${path}`);\n const stream = handle.createReadStream({ autoClose: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n try {\n yield* stream;\n const after = await handle.stat({ bigint: true });\n if (after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) throw new BagError(`Source file changed while reading: ${path}`);\n } finally { stream.destroy(); }\n } finally { await handle.close(); }\n },\n };\n }\n yield* walk();\n}\n\ninterface ExportState { result?: BagZipResult; cleanup?: Promise<void>; }\nasync function* archive(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n let complete!: () => void;\n state.cleanup = new Promise<void>(resolve => { complete = resolve; });\n try { yield* archiveContent(entries, options, state); }\n finally { complete(); }\n}\nasync function* archiveContent(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n const algorithms = validateOptions(options);\n options.signal?.throwIfAborted();\n const temp = await mkdtemp(join(options.tempDirectory ?? tmpdir(), 'bagit-zip-'));\n const handles: FileHandle[] = [];\n const zip = new ZipFile();\n const output = zip.outputStream as Readable;\n const controller = new AbortController();\n const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n let active: Readable | undefined;\n let failure: unknown;\n let failed = false;\n const fail = (error: unknown): void => {\n if (failed) return;\n failed = true;\n failure = error;\n controller.abort(error);\n active?.destroy(error instanceof Error ? error : new Error(String(error)));\n output.destroy(error instanceof Error ? error : new Error(String(error)));\n };\n zip.on('error', fail);\n // Install an error listener before producer I/O can fail, even before iteration starts.\n output.on('error', fail);\n const onAbort = (): void => fail(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n\n async function addEntry(name: string, input: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, mtime?: Date, mode?: number): Promise<void> {\n signal.throwIfAborted();\n const source = Readable.from(input, { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal });\n active = source;\n const done = finished(source, { cleanup: true });\n // Register rejection handling immediately; addReadStreamLazy can throw synchronously.\n void done.catch(fail);\n try {\n zip.addReadStreamLazy(name, {\n mtime: options.mtime ?? mtime ?? new Date(), mode: mode ?? 0o100644,\n compressionLevel: options.compressionLevel ?? 6,\n }, cb => cb(null, source));\n await done;\n } finally {\n source.destroy();\n await done.catch(() => {});\n active = undefined;\n }\n }\n function addDirectory(name: string, mtime?: Date, mode = 0o40755): void {\n signal.throwIfAborted();\n zip.addEmptyDirectory(name, { mtime: options.mtime ?? mtime ?? new Date(), mode });\n }\n\n async function addSource(entry: BagZipEntry, name: string): Promise<{ bytes: bigint; hashes: Checksums }> {\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n async function* hashed(): AsyncGenerator<Uint8Array> {\n signal.throwIfAborted();\n const source = await entry.open();\n const destroy = (): void => {\n if (source instanceof Readable) source.destroy();\n };\n signal.addEventListener('abort', destroy, { once: true });\n try {\n signal.throwIfAborted();\n for await (const chunk of source) {\n signal.throwIfAborted();\n if (!(chunk instanceof Uint8Array)) throw new TypeError('ZIP sources must produce Uint8Array or Buffer chunks');\n bytes += BigInt(chunk.length);\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk;\n }\n } finally {\n signal.removeEventListener('abort', destroy);\n destroy();\n }\n }\n await addEntry(name, hashed(), entry.mtime, entry.mode);\n return { bytes, hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])) };\n }\n\n const produce = async (): Promise<Omit<BagZipResult, 'bytesWritten'>> => {\n const manifests = new Map<string, { path: string; handle: FileHandle }>();\n for (const a of algorithms) {\n const path = join(temp, `manifest-${a}.txt`);\n const handle = await open(path, 'w');\n handles.push(handle);\n manifests.set(a, { path, handle });\n }\n const prefix = options.bagName ? `${options.bagName}/` : '';\n const registerPayload = entryRegistry('payload');\n let totalBytes = 0n;\n let totalFiles = 0;\n addDirectory(`${prefix}data/`);\n for await (const entry of entries) {\n signal.throwIfAborted();\n registerPayload(entry);\n if (entry.directory) {\n addDirectory(`${prefix}data/${entry.path}/`, entry.mtime, entry.mode);\n continue;\n }\n const { bytes, hashes } = await addSource(entry, `${prefix}data/${entry.path}`);\n for (const a of algorithms) await manifests.get(a)!.handle.writeFile(`${hashes[a]} ${encodeFilename(`data/${entry.path}`)}\\n`);\n totalBytes += bytes;\n totalFiles++;\n await options.onProgress?.({ path: entry.path, bytes, hashes, totalBytes, totalFiles });\n }\n const tags: { name: string; hashes: Checksums }[] = [];\n const registerTag = entryRegistry('tag', ['bagit.txt', 'bag-info.txt', 'data']);\n for await (const entry of options.tagFiles ?? []) {\n signal.throwIfAborted();\n // Unlike payload paths (which start with data/), root tags can begin with\n // whitespace or checksum-tool binary markers that manifest parsers strip.\n if (/^[\\s*]/.test(encodeFilename(entry.path))) throw new BagError(`Ambiguous BagIt tag filename: ${JSON.stringify(entry.path)}`);\n // Reserve manifest namespaces, including algorithms not selected for this export.\n const root = normalizeUnicode(entry.path).split('/')[0]!;\n if (/^(?:tagmanifest|manifest)-.*\\.txt$/.test(root)) throw new BagError(`Reserved tag-file path: ${entry.path}`);\n registerTag(entry);\n if (entry.directory) addDirectory(`${prefix}${entry.path}/`, entry.mtime, entry.mode);\n else {\n const { hashes } = await addSource(entry, prefix + entry.path);\n tags.push({ name: entry.path, hashes });\n }\n }\n for (const a of algorithms) {\n const manifest = manifests.get(a)!;\n await manifest.handle.close();\n const hashers = getHashers(algorithms);\n async function* content(): AsyncGenerator<Buffer> {\n for await (const chunk of createReadStream(manifest.path, { signal })) {\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk as Buffer;\n }\n }\n const name = `manifest-${a}.txt`;\n await addEntry(prefix + name, content());\n tags.push({ name, hashes: Object.fromEntries(Object.entries(hashers).map(([alg, h]) => [alg, h.digest('hex')])) });\n }\n const bagInfo = makeBagInfo(options.bagInfo, totalBytes, totalFiles);\n for (const [name, text] of [['bagit.txt', BAG_DECLARATION], ['bag-info.txt', serializeTagFile(bagInfo)]]) {\n const bytes = Buffer.from(text!, 'utf8');\n await addEntry(prefix + name!, [bytes]);\n tags.push({ name: name!, hashes: digestBytes(bytes, algorithms) });\n }\n for (const a of algorithms) {\n const text = tags.map(t => `${t.hashes[a]} ${encodeFilename(t.name)}\\n`).join('');\n await addEntry(`${prefix}tagmanifest-${a}.txt`, [Buffer.from(text)]);\n }\n zip.end();\n return { payloadBytes: totalBytes, payloadFiles: totalFiles, bagInfo };\n };\n const done = produce().catch(error => { fail(error); return undefined; });\n try {\n if (signal.aborted) fail(signal.reason);\n let bytesWritten = 0n;\n for await (const chunk of output) {\n bytesWritten += BigInt(chunk.length);\n yield chunk as Buffer;\n }\n const result = await done;\n if (failed) throw failure;\n state.result = { ...result!, bytesWritten };\n } finally {\n signal.removeEventListener('abort', onAbort);\n controller.abort();\n active?.destroy();\n output.destroy();\n await done;\n await Promise.allSettled(handles.map(h => h.close()));\n await rm(temp, { recursive: true, force: true });\n }\n}\n\n/** Pipe directly into an S3/Ceph multipart upload Body. Errors are emitted on the stream. */\nexport function createBagZipStream(directory: string, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(folderEntries(directory, options), options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Stream a bag from lazy application-provided sources, without first creating a payload directory. */\nexport function createBagZipStreamFromEntries(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(entries, options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Write an archive to a Writable, or atomically replace a path after successful completion. Ends the destination. */\nexport async function folderToBagZip(directory: string, destination: string | Writable, options: BagZipOptions = {}): Promise<BagZipResult> {\n validateOptions(options);\n options.signal?.throwIfAborted();\n if (!isDirectory(resolve(directory))) throw new BagError(`Bag directory ${resolve(directory)} does not exist`);\n const state: ExportState = {};\n let temp: string | undefined;\n try {\n let output: Writable;\n const outputPath = typeof destination === 'string' ? destination : 'path' in destination && typeof destination.path === 'string' ? destination.path : undefined;\n if (outputPath !== undefined) {\n const target = resolve(outputPath);\n // Resolve existing parent symlinks before checking containment.\n const actual = join(await realpath(dirname(target)), basename(target));\n const rel = relative(await realpath(directory), actual);\n if (!rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))) throw new BagError('ZIP destination must be outside the source directory');\n }\n if (typeof destination === 'string') {\n const target = resolve(destination);\n temp = await mkdtemp(join(dirname(target), '.bagit-output-'));\n output = createWriteStream(join(temp, 'archive.zip'), { flags: 'wx' });\n } else output = destination;\n const source = Readable.from(archive(folderEntries(directory, options), options, state), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE });\n try { await pipeline(source, output, { signal: options.signal }); }\n finally { await state.cleanup; }\n if (typeof destination === 'string') await rename(join(temp!, 'archive.zip'), resolve(destination));\n return state.result!;\n } finally { if (temp) await rm(temp, { recursive: true, force: true }); }\n}\n\nexport const folderToBagitZip = folderToBagZip;\n"]}
|
package/dist/esm/util.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type Hash } from 'node:crypto';
|
|
2
2
|
import type { BagInfo, BagInfoInput, Checksums } from './types.js';
|
|
3
|
-
export declare const VERSION = "1.
|
|
3
|
+
export declare const VERSION = "1.1.0";
|
|
4
4
|
export declare const DEFAULT_CHECKSUMS: readonly string[];
|
|
5
5
|
export declare const HASH_BLOCK_SIZE: number;
|
|
6
6
|
export declare const BAG_DECLARATION = "BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n";
|
package/dist/esm/util.js
CHANGED
|
@@ -3,7 +3,7 @@ import { createReadStream, existsSync, readdirSync, realpathSync, statSync, cons
|
|
|
3
3
|
import { readFile } from 'node:fs/promises';
|
|
4
4
|
import { dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';
|
|
5
5
|
import { BagError, BagValidationError, FileNormalizationConflict } from './errors.js';
|
|
6
|
-
export const VERSION = '1.
|
|
6
|
+
export const VERSION = '1.1.0';
|
|
7
7
|
export const DEFAULT_CHECKSUMS = Object.freeze(['sha256', 'sha512']);
|
|
8
8
|
export const HASH_BLOCK_SIZE = 512 * 1024;
|
|
9
9
|
export const BAG_DECLARATION = 'BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n';
|
package/dist/esm/util.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAa,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACnH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AACrF,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAGtF,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAC/B,MAAM,CAAC,MAAM,iBAAiB,GAAsB,MAAM,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC;AACxF,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,GAAG,IAAI,CAAC;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,UAAU,CAAC,wCAAwC,CAAC,CAAC;IAC1H,OAAO,WAAW,CAAC;AACrB,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,aAAa,CAAO,KAAmB,EAAE,WAAmB,EAAE,EAA4B;IAC9G,MAAM,MAAM,GAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,OAAgB,CAAC;IACrB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,IAAI,EAAE;QACzG,OAAO,CAAC,MAAM,EAAE,CAAC;YACf,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC;YACjB,IAAI,CAAC,IAAI,KAAK,CAAC,MAAM;gBAAE,OAAO;YAC9B,IAAI,CAAC;gBAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC;YAAC,CAAC;YACxC,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,GAAG,IAAI,CAAC;gBAAC,OAAO,GAAG,KAAK,CAAC;YAAC,CAAC;QACnD,CAAC;IACH,CAAC,CAAC,CAAC,CAAC;IACJ,IAAI,MAAM;QAAE,MAAM,OAAO,CAAC;IAC1B,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createHash, type Hash } from 'node:crypto';\nimport { createReadStream, existsSync, readdirSync, realpathSync, statSync, constants, accessSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';\nimport { BagError, BagValidationError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\n\nexport const VERSION = '1.0.0';\nexport const DEFAULT_CHECKSUMS: readonly string[] = Object.freeze(['sha256', 'sha512']);\nexport const HASH_BLOCK_SIZE = 512 * 1024;\nexport const BAG_DECLARATION = 'BagIt-Version: 1.0\\nTag-File-Character-Encoding: UTF-8\\n';\nexport const STANDARD_BAG_INFO_HEADERS: readonly string[] = Object.freeze([\n 'Source-Organization', 'Organization-Address', 'Contact-Name', 'Contact-Phone', 'Contact-Email',\n 'External-Description', 'External-Identifier', 'Bag-Size', 'Bag-Group-Identifier', 'Bag-Count',\n 'Internal-Sender-Identifier', 'Internal-Sender-Description', 'BagIt-Profile-Identifier',\n]);\n// Python's guaranteed fixed-length algorithms, mapped to OpenSSL names where necessary.\nconst HASH_NAMES: Record<string, string> = {\n blake2b: 'blake2b512', blake2s: 'blake2s256',\n sha3_224: 'sha3-224', sha3_256: 'sha3-256', sha3_384: 'sha3-384', sha3_512: 'sha3-512',\n};\nexport const CHECKSUM_ALGOS: readonly string[] = Object.freeze([\n 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',\n 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'blake2b', 'blake2s',\n]);\nexport function getHashers(algorithms: readonly string[]): Record<string, Hash> {\n const result: Record<string, Hash> = Object.create(null);\n for (const alg of algorithms) {\n if (!CHECKSUM_ALGOS.includes(alg)) continue;\n try { result[alg] = createHash(HASH_NAMES[alg] ?? alg); } catch { /* unavailable in this OpenSSL build */ }\n }\n if (!Object.keys(result).length) throw new BagError('Unable to continue: no supported checksum algorithms were requested');\n return result;\n}\nexport function algorithmsFor(algorithms: readonly string[] = DEFAULT_CHECKSUMS): string[] {\n return Object.keys(getHashers(algorithms));\n}\nexport function digestBytes(bytes: Uint8Array, algorithms: readonly string[]): Checksums {\n return Object.fromEntries(Object.entries(getHashers(algorithms)).map(([a, h]) => [a, h.update(bytes).digest('hex')]));\n}\nexport async function hashFile(path: string, algorithms: readonly string[], signal?: AbortSignal): Promise<{ hashes: Checksums; bytes: bigint }> {\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n try {\n for await (const block of createReadStream(path, { highWaterMark: HASH_BLOCK_SIZE, signal })) {\n bytes += BigInt(block.length);\n for (const hash of Object.values(hashers)) hash.update(block);\n }\n } catch (error) {\n signal?.throwIfAborted();\n throw new BagValidationError(`Could not read ${path}: ${String(error)}`, [], { cause: error });\n }\n return { hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])), bytes };\n}\nexport async function generateManifestLines(filename: string, algorithms: readonly string[] = DEFAULT_CHECKSUMS, signal?: AbortSignal): Promise<[algorithm: string, digest: string, filename: string, bytes: bigint][]> {\n const { hashes, bytes } = await hashFile(filename, algorithms, signal);\n return Object.entries(hashes).map(([algorithm, digest]) => [algorithm, digest, filename, bytes]);\n}\nexport const normalizeUnicode = (s: string): string => s.normalize('NFC');\nexport function buildUnicodeNormalizedLookupDict(filenames: Iterable<string>): Record<string, string> {\n const result: Record<string, string> = Object.create(null);\n for (const filename of filenames) {\n const normalized = normalizeUnicode(filename);\n if (Object.hasOwn(result, normalized)) throw new FileNormalizationConflict(filename, result[normalized]!);\n result[normalized] = filename;\n }\n return result;\n}\nexport const encodeFilename = (s: string): string => s.replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\nexport const decodeFilename = (s: string): string => s.replace(/%0d/gi, '\\r').replace(/%0a/gi, '\\n');\nexport const posixPath = (s: string): string => s.split(sep).join('/');\nexport const isFile = (p: string): boolean => { try { return statSync(p).isFile(); } catch { return false; } };\nexport const isDirectory = (p: string): boolean => { try { return statSync(p).isDirectory(); } catch { return false; } };\n\n/** Match os.walk: sorted files at each level, then sorted directories; do not follow directory symlinks. */\nexport function* walkFiles(root: string, prefix = ''): Generator<string> {\n if (!isDirectory(root)) return;\n const entries = readdirSync(root, { withFileTypes: true }).sort((a, b) => compareNames(a.name, b.name));\n for (const e of entries) {\n const p = join(root, e.name);\n if (e.isFile() || (e.isSymbolicLink() && !isDirectory(p))) yield prefix + e.name;\n }\n for (const e of entries) if (e.isDirectory()) yield* walkFiles(join(root, e.name), `${prefix}${e.name}/`);\n}\nexport function compareNames(a: string, b: string): number {\n // Python sorts Unicode code points, whereas JavaScript's default sort uses UTF-16 code units.\n const ac = Array.from(a, c => c.codePointAt(0)!);\n const bc = Array.from(b, c => c.codePointAt(0)!);\n for (let i = 0; i < Math.min(ac.length, bc.length); i++) if (ac[i] !== bc[i]) return ac[i]! - bc[i]!;\n return ac.length - bc.length;\n}\nfunction canonicalMissingPath(path: string): string {\n if (existsSync(path)) return realpathSync(path);\n const parent = dirname(path);\n if (parent === path) return path;\n // realpath still detects symlinks in the existing part of an absent fetch target.\n return join(canonicalMissingPath(parent), relative(parent, path));\n}\nexport function pathIsDangerous(root: string, filename: string): boolean {\n if (!filename || filename.includes('\\0') || isAbsolute(filename) || win32.isAbsolute(filename) || filename.startsWith('~')) return true;\n const actual = canonicalMissingPath(resolve(root, filename));\n const rel = relative(realpathSync(root), actual);\n return rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel);\n}\nexport function assertSafePath(root: string, filename: string, context = 'manifest'): void {\n if (pathIsDangerous(root, filename)) throw new BagError(`Path \"${filename}\" in ${context} is unsafe`);\n}\nexport function decodeText(bytes: Uint8Array, encoding = 'utf-8'): string {\n let label = encodingLabel(encoding);\n if (label === 'utf-16') {\n if (bytes[0] === 0xfe && bytes[1] === 0xff) label = 'utf-16be';\n else if (bytes[0] === 0xff && bytes[1] === 0xfe) label = 'utf-16le';\n else if (bytes.length) throw new BagValidationError('UTF-16 tag file must begin with a byte-order mark');\n }\n if (label === 'utf-8-sig') return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n if (label === 'ascii' || label === 'us-ascii') {\n if (bytes.some(b => b > 127)) throw new BagValidationError('Non-ASCII byte in ASCII tag file');\n return Buffer.from(bytes).toString('ascii');\n }\n // TextDecoder maps ISO-8859-1 to Windows-1252; Python uses the actual ISO mapping.\n if (['latin-1', 'latin1', 'iso-8859-1'].includes(label)) return Buffer.from(bytes).toString('latin1');\n try { return new TextDecoder(label, { fatal: true }).decode(bytes); }\n catch (e) { throw new BagValidationError(`Cannot decode tag file as ${encoding}`, [], { cause: e }); }\n}\nexport function checkEncoding(encoding: string): void {\n const label = encodingLabel(encoding);\n if (['utf-8-sig', 'latin-1'].includes(label)) return;\n try { new TextDecoder(label); }\n catch { throw new BagValidationError(`Unsupported encoding: ${encoding}`); }\n}\nexport function encodeText(text: string, encoding = 'utf-8'): Buffer {\n const label = encodingLabel(encoding);\n if (['utf-8', 'utf8', 'utf-8-sig'].includes(label)) {\n const bytes = Buffer.from(text, 'utf8');\n return label === 'utf-8-sig' ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), bytes]) : bytes;\n }\n if (['utf-16', 'utf-16le', 'utf-16-le', 'utf16le'].includes(label)) {\n const bytes = Buffer.from(text, 'utf16le');\n return label === 'utf-16' ? Buffer.concat([Buffer.from([0xff, 0xfe]), bytes]) : bytes;\n }\n if (['utf-16be', 'utf-16-be'].includes(label)) return Buffer.from(text, 'utf16le').swap16();\n const table = new Map<string, number>();\n for (let b = 0; b < 256; b++) {\n try { const c = decodeText(Uint8Array.of(b), encoding); if (c.length === 1 && !table.has(c)) table.set(c, b); } catch { /* invalid single byte */ }\n }\n const bytes: number[] = [];\n for (const c of text) {\n const b = table.get(c);\n if (b === undefined) throw new BagError(`Cannot encode character ${JSON.stringify(c)} as ${encoding}`);\n bytes.push(b);\n }\n return Buffer.from(bytes);\n}\nfunction encodingLabel(encoding: string): string {\n const label = encoding.toLowerCase().replace(/_/g, '-');\n return ({ utf8: 'utf-8', utf16: 'utf-16', utf16le: 'utf-16le', utf16be: 'utf-16be', 'utf-16-le': 'utf-16le', 'utf-16-be': 'utf-16be' } as Record<string, string>)[label] ?? label;\n}\nexport function parseTagFile(text: string, filename = 'tag file'): BagInfo {\n const result: BagInfo = Object.create(null);\n let key: string | undefined;\n let value = '';\n const emit = (): void => {\n if (!key) return;\n const v = value.trim();\n const prev = result[key];\n result[key] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [prev, v];\n };\n for (const line of text.replace(/\\r\\n?/g, '\\n').match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n if (!line.trim()) continue;\n if (/^\\s/.test(line) && key !== undefined) value += line;\n else {\n emit();\n const colon = line.indexOf(':');\n if (colon < 0) throw new BagValidationError(`${filename} contains invalid tag: ${line.trim()}`);\n key = line.slice(0, colon).trim();\n value = line.slice(colon + 1);\n }\n }\n emit();\n return result;\n}\nexport function serializeTagFile(info: BagInfoInput): string {\n let result = '';\n for (const key of Object.keys(info).sort(compareNames)) {\n if (!key || /[\\r\\n:]/.test(key)) throw new BagError(`Invalid metadata field name: ${key}`);\n const values = Array.isArray(info[key]) ? info[key] : [info[key]];\n for (const value of values!) result += `${key}: ${String(value).replace(/[\\r\\n]/g, '')}\\n`;\n }\n return result;\n}\nexport function makeBagInfo(info: BagInfoInput | undefined, bytes: bigint, files: number): BagInfo {\n const date = new Date();\n const today = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;\n return parseTagFile(serializeTagFile({\n 'Bagging-Date': today,\n 'Bag-Software-Agent': `bagit-node v${VERSION}`,\n ...info,\n 'Payload-Oxum': `${bytes}.${files}`,\n }));\n}\nexport async function loadTagFile(path: string, encoding = 'utf-8'): Promise<BagInfo> {\n return parseTagFile(decodeText(await readFile(path), encoding), path);\n}\nexport function checkPermissions(root: string, saving = false): void {\n try { accessSync(root, constants.R_OK | constants.W_OK | constants.X_OK); }\n catch {\n throw new BagError(saving ? `Cannot save bag to non-existent or inaccessible directory ${root}` : 'Missing permissions to move all files and directories');\n }\n const dirs = [root];\n const files: string[] = [];\n // Finish the write check before reporting unreadable descendants, matching Python.\n for (let i = 0; i < dirs.length; i++) {\n const dir = dirs[i]!;\n try { accessSync(dir, constants.W_OK); }\n catch { throw new BagError('Missing permissions to move all files and directories'); }\n let entries;\n try { entries = readdirSync(dir, { withFileTypes: true }); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n for (const e of entries) {\n if (e.isDirectory()) dirs.push(join(dir, e.name));\n else files.push(join(dir, e.name));\n }\n }\n for (const p of [...dirs, ...files]) {\n try { accessSync(p, constants.R_OK); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n }\n}\nexport function checkConcurrency(concurrency = 1): number {\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer');\n return concurrency;\n}\nexport async function mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (value: T) => Promise<R>): Promise<R[]> {\n const result: R[] = new Array(items.length);\n let next = 0;\n let failure: unknown;\n let failed = false;\n await Promise.all(Array.from({ length: Math.min(checkConcurrency(concurrency), items.length) }, async () => {\n while (!failed) {\n const i = next++;\n if (i >= items.length) return;\n try { result[i] = await fn(items[i]!); }\n catch (error) { failed = true; failure = error; }\n }\n }));\n if (failed) throw failure;\n return result;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"util.js","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAa,MAAM,aAAa,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACnH,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AACrF,OAAO,EAAE,QAAQ,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAGtF,MAAM,CAAC,MAAM,OAAO,GAAG,OAAO,CAAC;AAC/B,MAAM,CAAC,MAAM,iBAAiB,GAAsB,MAAM,CAAC,MAAM,CA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GAAG,CAAC;IAC9C,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,WAAW,CAAC,IAAI,WAAW,GAAG,CAAC;QAAE,MAAM,IAAI,UAAU,CAAC,wCAAwC,CAAC,CAAC;IAC1H,OAAO,WAAW,CAAC;AACrB,CAAC;AACD,MAAM,CAAC,KAAK,UAAU,aAAa,CAAO,KAAmB,EAAE,WAAmB,EAAE,EAA4B;IAC9G,MAAM,MAAM,GAAQ,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5C,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,IAAI,OAAgB,CAAC;IACrB,IAAI,MAAM,GAAG,KAAK,CAAC;IACnB,MAAM,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,GAAG,CAAC,gBAAgB,CAAC,WAAW,CAAC,EAAE,KAAK,CAAC,MAAM,CAAC,EAAE,EAAE,KAAK,IAAI,EAAE;QACzG,OAAO,CAAC,MAAM,EAAE,CAAC;YACf,MAAM,CAAC,GAAG,IAAI,EAAE,CAAC;YACjB,IAAI,CAAC,IAAI,KAAK,CAAC,MAAM;gBAAE,OAAO;YAC9B,IAAI,CAAC;gBAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC;YAAC,CAAC;YACxC,OAAO,KAAK,EAAE,CAAC;gBAAC,MAAM,GAAG,IAAI,CAAC;gBAAC,OAAO,GAAG,KAAK,CAAC;YAAC,CAAC;QACnD,CAAC;IACH,CAAC,CAAC,CAAC,CAAC;IACJ,IAAI,MAAM;QAAE,MAAM,OAAO,CAAC;IAC1B,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createHash, type Hash } from 'node:crypto';\nimport { createReadStream, existsSync, readdirSync, realpathSync, statSync, constants, accessSync } from 'node:fs';\nimport { readFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';\nimport { BagError, BagValidationError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\n\nexport const VERSION = '1.1.0';\nexport const DEFAULT_CHECKSUMS: readonly string[] = Object.freeze(['sha256', 'sha512']);\nexport const HASH_BLOCK_SIZE = 512 * 1024;\nexport const BAG_DECLARATION = 'BagIt-Version: 1.0\\nTag-File-Character-Encoding: UTF-8\\n';\nexport const STANDARD_BAG_INFO_HEADERS: readonly string[] = Object.freeze([\n 'Source-Organization', 'Organization-Address', 'Contact-Name', 'Contact-Phone', 'Contact-Email',\n 'External-Description', 'External-Identifier', 'Bag-Size', 'Bag-Group-Identifier', 'Bag-Count',\n 'Internal-Sender-Identifier', 'Internal-Sender-Description', 'BagIt-Profile-Identifier',\n]);\n// Python's guaranteed fixed-length algorithms, mapped to OpenSSL names where necessary.\nconst HASH_NAMES: Record<string, string> = {\n blake2b: 'blake2b512', blake2s: 'blake2s256',\n sha3_224: 'sha3-224', sha3_256: 'sha3-256', sha3_384: 'sha3-384', sha3_512: 'sha3-512',\n};\nexport const CHECKSUM_ALGOS: readonly string[] = Object.freeze([\n 'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',\n 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'blake2b', 'blake2s',\n]);\nexport function getHashers(algorithms: readonly string[]): Record<string, Hash> {\n const result: Record<string, Hash> = Object.create(null);\n for (const alg of algorithms) {\n if (!CHECKSUM_ALGOS.includes(alg)) continue;\n try { result[alg] = createHash(HASH_NAMES[alg] ?? alg); } catch { /* unavailable in this OpenSSL build */ }\n }\n if (!Object.keys(result).length) throw new BagError('Unable to continue: no supported checksum algorithms were requested');\n return result;\n}\nexport function algorithmsFor(algorithms: readonly string[] = DEFAULT_CHECKSUMS): string[] {\n return Object.keys(getHashers(algorithms));\n}\nexport function digestBytes(bytes: Uint8Array, algorithms: readonly string[]): Checksums {\n return Object.fromEntries(Object.entries(getHashers(algorithms)).map(([a, h]) => [a, h.update(bytes).digest('hex')]));\n}\nexport async function hashFile(path: string, algorithms: readonly string[], signal?: AbortSignal): Promise<{ hashes: Checksums; bytes: bigint }> {\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n try {\n for await (const block of createReadStream(path, { highWaterMark: HASH_BLOCK_SIZE, signal })) {\n bytes += BigInt(block.length);\n for (const hash of Object.values(hashers)) hash.update(block);\n }\n } catch (error) {\n signal?.throwIfAborted();\n throw new BagValidationError(`Could not read ${path}: ${String(error)}`, [], { cause: error });\n }\n return { hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])), bytes };\n}\nexport async function generateManifestLines(filename: string, algorithms: readonly string[] = DEFAULT_CHECKSUMS, signal?: AbortSignal): Promise<[algorithm: string, digest: string, filename: string, bytes: bigint][]> {\n const { hashes, bytes } = await hashFile(filename, algorithms, signal);\n return Object.entries(hashes).map(([algorithm, digest]) => [algorithm, digest, filename, bytes]);\n}\nexport const normalizeUnicode = (s: string): string => s.normalize('NFC');\nexport function buildUnicodeNormalizedLookupDict(filenames: Iterable<string>): Record<string, string> {\n const result: Record<string, string> = Object.create(null);\n for (const filename of filenames) {\n const normalized = normalizeUnicode(filename);\n if (Object.hasOwn(result, normalized)) throw new FileNormalizationConflict(filename, result[normalized]!);\n result[normalized] = filename;\n }\n return result;\n}\nexport const encodeFilename = (s: string): string => s.replace(/\\r/g, '%0D').replace(/\\n/g, '%0A');\nexport const decodeFilename = (s: string): string => s.replace(/%0d/gi, '\\r').replace(/%0a/gi, '\\n');\nexport const posixPath = (s: string): string => s.split(sep).join('/');\nexport const isFile = (p: string): boolean => { try { return statSync(p).isFile(); } catch { return false; } };\nexport const isDirectory = (p: string): boolean => { try { return statSync(p).isDirectory(); } catch { return false; } };\n\n/** Match os.walk: sorted files at each level, then sorted directories; do not follow directory symlinks. */\nexport function* walkFiles(root: string, prefix = ''): Generator<string> {\n if (!isDirectory(root)) return;\n const entries = readdirSync(root, { withFileTypes: true }).sort((a, b) => compareNames(a.name, b.name));\n for (const e of entries) {\n const p = join(root, e.name);\n if (e.isFile() || (e.isSymbolicLink() && !isDirectory(p))) yield prefix + e.name;\n }\n for (const e of entries) if (e.isDirectory()) yield* walkFiles(join(root, e.name), `${prefix}${e.name}/`);\n}\nexport function compareNames(a: string, b: string): number {\n // Python sorts Unicode code points, whereas JavaScript's default sort uses UTF-16 code units.\n const ac = Array.from(a, c => c.codePointAt(0)!);\n const bc = Array.from(b, c => c.codePointAt(0)!);\n for (let i = 0; i < Math.min(ac.length, bc.length); i++) if (ac[i] !== bc[i]) return ac[i]! - bc[i]!;\n return ac.length - bc.length;\n}\nfunction canonicalMissingPath(path: string): string {\n if (existsSync(path)) return realpathSync(path);\n const parent = dirname(path);\n if (parent === path) return path;\n // realpath still detects symlinks in the existing part of an absent fetch target.\n return join(canonicalMissingPath(parent), relative(parent, path));\n}\nexport function pathIsDangerous(root: string, filename: string): boolean {\n if (!filename || filename.includes('\\0') || isAbsolute(filename) || win32.isAbsolute(filename) || filename.startsWith('~')) return true;\n const actual = canonicalMissingPath(resolve(root, filename));\n const rel = relative(realpathSync(root), actual);\n return rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel);\n}\nexport function assertSafePath(root: string, filename: string, context = 'manifest'): void {\n if (pathIsDangerous(root, filename)) throw new BagError(`Path \"${filename}\" in ${context} is unsafe`);\n}\nexport function decodeText(bytes: Uint8Array, encoding = 'utf-8'): string {\n let label = encodingLabel(encoding);\n if (label === 'utf-16') {\n if (bytes[0] === 0xfe && bytes[1] === 0xff) label = 'utf-16be';\n else if (bytes[0] === 0xff && bytes[1] === 0xfe) label = 'utf-16le';\n else if (bytes.length) throw new BagValidationError('UTF-16 tag file must begin with a byte-order mark');\n }\n if (label === 'utf-8-sig') return new TextDecoder('utf-8', { fatal: true }).decode(bytes);\n if (label === 'ascii' || label === 'us-ascii') {\n if (bytes.some(b => b > 127)) throw new BagValidationError('Non-ASCII byte in ASCII tag file');\n return Buffer.from(bytes).toString('ascii');\n }\n // TextDecoder maps ISO-8859-1 to Windows-1252; Python uses the actual ISO mapping.\n if (['latin-1', 'latin1', 'iso-8859-1'].includes(label)) return Buffer.from(bytes).toString('latin1');\n try { return new TextDecoder(label, { fatal: true }).decode(bytes); }\n catch (e) { throw new BagValidationError(`Cannot decode tag file as ${encoding}`, [], { cause: e }); }\n}\nexport function checkEncoding(encoding: string): void {\n const label = encodingLabel(encoding);\n if (['utf-8-sig', 'latin-1'].includes(label)) return;\n try { new TextDecoder(label); }\n catch { throw new BagValidationError(`Unsupported encoding: ${encoding}`); }\n}\nexport function encodeText(text: string, encoding = 'utf-8'): Buffer {\n const label = encodingLabel(encoding);\n if (['utf-8', 'utf8', 'utf-8-sig'].includes(label)) {\n const bytes = Buffer.from(text, 'utf8');\n return label === 'utf-8-sig' ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), bytes]) : bytes;\n }\n if (['utf-16', 'utf-16le', 'utf-16-le', 'utf16le'].includes(label)) {\n const bytes = Buffer.from(text, 'utf16le');\n return label === 'utf-16' ? Buffer.concat([Buffer.from([0xff, 0xfe]), bytes]) : bytes;\n }\n if (['utf-16be', 'utf-16-be'].includes(label)) return Buffer.from(text, 'utf16le').swap16();\n const table = new Map<string, number>();\n for (let b = 0; b < 256; b++) {\n try { const c = decodeText(Uint8Array.of(b), encoding); if (c.length === 1 && !table.has(c)) table.set(c, b); } catch { /* invalid single byte */ }\n }\n const bytes: number[] = [];\n for (const c of text) {\n const b = table.get(c);\n if (b === undefined) throw new BagError(`Cannot encode character ${JSON.stringify(c)} as ${encoding}`);\n bytes.push(b);\n }\n return Buffer.from(bytes);\n}\nfunction encodingLabel(encoding: string): string {\n const label = encoding.toLowerCase().replace(/_/g, '-');\n return ({ utf8: 'utf-8', utf16: 'utf-16', utf16le: 'utf-16le', utf16be: 'utf-16be', 'utf-16-le': 'utf-16le', 'utf-16-be': 'utf-16be' } as Record<string, string>)[label] ?? label;\n}\nexport function parseTagFile(text: string, filename = 'tag file'): BagInfo {\n const result: BagInfo = Object.create(null);\n let key: string | undefined;\n let value = '';\n const emit = (): void => {\n if (!key) return;\n const v = value.trim();\n const prev = result[key];\n result[key] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [prev, v];\n };\n for (const line of text.replace(/\\r\\n?/g, '\\n').match(/[^\\n]*\\n|[^\\n]+$/g) ?? []) {\n if (!line.trim()) continue;\n if (/^\\s/.test(line) && key !== undefined) value += line;\n else {\n emit();\n const colon = line.indexOf(':');\n if (colon < 0) throw new BagValidationError(`${filename} contains invalid tag: ${line.trim()}`);\n key = line.slice(0, colon).trim();\n value = line.slice(colon + 1);\n }\n }\n emit();\n return result;\n}\nexport function serializeTagFile(info: BagInfoInput): string {\n let result = '';\n for (const key of Object.keys(info).sort(compareNames)) {\n if (!key || /[\\r\\n:]/.test(key)) throw new BagError(`Invalid metadata field name: ${key}`);\n const values = Array.isArray(info[key]) ? info[key] : [info[key]];\n for (const value of values!) result += `${key}: ${String(value).replace(/[\\r\\n]/g, '')}\\n`;\n }\n return result;\n}\nexport function makeBagInfo(info: BagInfoInput | undefined, bytes: bigint, files: number): BagInfo {\n const date = new Date();\n const today = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;\n return parseTagFile(serializeTagFile({\n 'Bagging-Date': today,\n 'Bag-Software-Agent': `bagit-node v${VERSION}`,\n ...info,\n 'Payload-Oxum': `${bytes}.${files}`,\n }));\n}\nexport async function loadTagFile(path: string, encoding = 'utf-8'): Promise<BagInfo> {\n return parseTagFile(decodeText(await readFile(path), encoding), path);\n}\nexport function checkPermissions(root: string, saving = false): void {\n try { accessSync(root, constants.R_OK | constants.W_OK | constants.X_OK); }\n catch {\n throw new BagError(saving ? `Cannot save bag to non-existent or inaccessible directory ${root}` : 'Missing permissions to move all files and directories');\n }\n const dirs = [root];\n const files: string[] = [];\n // Finish the write check before reporting unreadable descendants, matching Python.\n for (let i = 0; i < dirs.length; i++) {\n const dir = dirs[i]!;\n try { accessSync(dir, constants.W_OK); }\n catch { throw new BagError('Missing permissions to move all files and directories'); }\n let entries;\n try { entries = readdirSync(dir, { withFileTypes: true }); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n for (const e of entries) {\n if (e.isDirectory()) dirs.push(join(dir, e.name));\n else files.push(join(dir, e.name));\n }\n }\n for (const p of [...dirs, ...files]) {\n try { accessSync(p, constants.R_OK); }\n catch { throw new BagError('Read permissions are required to calculate file fixities'); }\n }\n}\nexport function checkConcurrency(concurrency = 1): number {\n if (!Number.isSafeInteger(concurrency) || concurrency < 1) throw new RangeError('concurrency must be a positive integer');\n return concurrency;\n}\nexport async function mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (value: T) => Promise<R>): Promise<R[]> {\n const result: R[] = new Array(items.length);\n let next = 0;\n let failure: unknown;\n let failed = false;\n await Promise.all(Array.from({ length: Math.min(checkConcurrency(concurrency), items.length) }, async () => {\n while (!failed) {\n const i = next++;\n if (i >= items.length) return;\n try { result[i] = await fn(items[i]!); }\n catch (error) { failed = true; failure = error; }\n }\n }));\n if (failed) throw failure;\n return result;\n}\n"]}
|
package/dist/esm/zip.d.ts
CHANGED
|
@@ -5,9 +5,11 @@ export interface BagZipOptions {
|
|
|
5
5
|
checksums?: readonly string[];
|
|
6
6
|
/** An optional directory containing the entire bag inside the archive. Default: archive root. */
|
|
7
7
|
bagName?: string;
|
|
8
|
+
/** Lazy custom tag files, with paths relative to the bag root. Use fresh iterables and sources for retries. */
|
|
9
|
+
tagFiles?: Iterable<BagZipEntry> | AsyncIterable<BagZipEntry>;
|
|
8
10
|
/** Deflate level 0–9; default 6. */
|
|
9
11
|
compressionLevel?: number;
|
|
10
|
-
/** Temporary directory for manifests; payloads are never staged. */
|
|
12
|
+
/** Temporary directory for payload manifests; payloads and custom tag files are never staged. */
|
|
11
13
|
tempDirectory?: string;
|
|
12
14
|
signal?: AbortSignal;
|
|
13
15
|
/** Fixed ZIP modification time for reproducible archives. */
|
|
@@ -28,7 +30,7 @@ export interface BagZipResult {
|
|
|
28
30
|
payloadFiles: number;
|
|
29
31
|
bagInfo: BagInfo;
|
|
30
32
|
}
|
|
31
|
-
/** Sources are opened lazily, one at a time.
|
|
33
|
+
/** Sources are opened lazily, one at a time. Payload paths are relative to data/; tagFiles paths are relative to the bag root. */
|
|
32
34
|
export interface BagZipEntry {
|
|
33
35
|
path: string;
|
|
34
36
|
/** Preserve an empty directory. Its open() function is ignored. */
|
package/dist/esm/zip.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zip.d.ts","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAQtD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAMnE,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,iGAAiG;IACjG,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oCAAoC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,
|
|
1
|
+
{"version":3,"file":"zip.d.ts","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,QAAQ,EAAE,MAAM,aAAa,CAAC;AAQtD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAMnE,MAAM,WAAW,aAAa;IAC5B,OAAO,CAAC,EAAE,YAAY,CAAC;IACvB,SAAS,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,iGAAiG;IACjG,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,+GAA+G;IAC/G,QAAQ,C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B,6BAA6B,CAAC,OAAO,EAAE,aAAa,CAAC,WAAW,CAAC,GAAG,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,GAAE,aAAkB,GAAG,QAAQ,CAGhJ;AAED,sHAAsH;AACtH,wBAAsB,cAAc,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,QAAQ,EAAE,OAAO,GAAE,aAAkB,GAAG,OAAO,CAAC,YAAY,CAAC,CA2B1I;AAED,eAAO,MAAM,gBAAgB,uBAAiB,CAAC"}
|
package/dist/esm/zip.js
CHANGED
|
@@ -30,6 +30,32 @@ function validatePayloadPath(path) {
|
|
|
30
30
|
if (/\s$/.test(encodeFilename(path)))
|
|
31
31
|
throw new BagError(`BagIt cannot represent trailing whitespace unambiguously: ${JSON.stringify(path)}`);
|
|
32
32
|
}
|
|
33
|
+
function entryRegistry(kind, reservedFiles = []) {
|
|
34
|
+
const seen = new Map();
|
|
35
|
+
const directories = new Set();
|
|
36
|
+
const files = new Set(reservedFiles);
|
|
37
|
+
return entry => {
|
|
38
|
+
validatePayloadPath(entry.path);
|
|
39
|
+
const normalized = normalizeUnicode(entry.path);
|
|
40
|
+
const previous = seen.get(normalized);
|
|
41
|
+
if (previous !== undefined)
|
|
42
|
+
throw new FileNormalizationConflict(entry.path, previous);
|
|
43
|
+
if (files.has(normalized) || (!entry.directory && directories.has(normalized)))
|
|
44
|
+
throw new BagError(`Conflicting ${kind} file and directory: ${entry.path}`);
|
|
45
|
+
const parts = normalized.split('/');
|
|
46
|
+
for (let i = 1; i < parts.length; i++) {
|
|
47
|
+
const parent = parts.slice(0, i).join('/');
|
|
48
|
+
if (files.has(parent))
|
|
49
|
+
throw new BagError(`Conflicting ${kind} paths: ${parent} and ${entry.path}`);
|
|
50
|
+
directories.add(parent);
|
|
51
|
+
}
|
|
52
|
+
seen.set(normalized, entry.path);
|
|
53
|
+
if (entry.directory)
|
|
54
|
+
directories.add(normalized);
|
|
55
|
+
else
|
|
56
|
+
files.add(normalized);
|
|
57
|
+
};
|
|
58
|
+
}
|
|
33
59
|
async function* folderEntries(directory, options) {
|
|
34
60
|
const root = resolve(directory);
|
|
35
61
|
if (!isDirectory(root))
|
|
@@ -153,6 +179,37 @@ async function* archiveContent(entries, options, state) {
|
|
|
153
179
|
signal.throwIfAborted();
|
|
154
180
|
zip.addEmptyDirectory(name, { mtime: options.mtime ?? mtime ?? new Date(), mode });
|
|
155
181
|
}
|
|
182
|
+
async function addSource(entry, name) {
|
|
183
|
+
const hashers = getHashers(algorithms);
|
|
184
|
+
let bytes = 0n;
|
|
185
|
+
async function* hashed() {
|
|
186
|
+
signal.throwIfAborted();
|
|
187
|
+
const source = await entry.open();
|
|
188
|
+
const destroy = () => {
|
|
189
|
+
if (source instanceof Readable)
|
|
190
|
+
source.destroy();
|
|
191
|
+
};
|
|
192
|
+
signal.addEventListener('abort', destroy, { once: true });
|
|
193
|
+
try {
|
|
194
|
+
signal.throwIfAborted();
|
|
195
|
+
for await (const chunk of source) {
|
|
196
|
+
signal.throwIfAborted();
|
|
197
|
+
if (!(chunk instanceof Uint8Array))
|
|
198
|
+
throw new TypeError('ZIP sources must produce Uint8Array or Buffer chunks');
|
|
199
|
+
bytes += BigInt(chunk.length);
|
|
200
|
+
for (const h of Object.values(hashers))
|
|
201
|
+
h.update(chunk);
|
|
202
|
+
yield chunk;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
signal.removeEventListener('abort', destroy);
|
|
207
|
+
destroy();
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
await addEntry(name, hashed(), entry.mtime, entry.mode);
|
|
211
|
+
return { bytes, hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])) };
|
|
212
|
+
}
|
|
156
213
|
const produce = async () => {
|
|
157
214
|
const manifests = new Map();
|
|
158
215
|
for (const a of algorithms) {
|
|
@@ -162,59 +219,18 @@ async function* archiveContent(entries, options, state) {
|
|
|
162
219
|
manifests.set(a, { path, handle });
|
|
163
220
|
}
|
|
164
221
|
const prefix = options.bagName ? `${options.bagName}/` : '';
|
|
165
|
-
const
|
|
166
|
-
const directories = new Set();
|
|
167
|
-
const files = new Set();
|
|
222
|
+
const registerPayload = entryRegistry('payload');
|
|
168
223
|
let totalBytes = 0n;
|
|
169
224
|
let totalFiles = 0;
|
|
170
225
|
addDirectory(`${prefix}data/`);
|
|
171
226
|
for await (const entry of entries) {
|
|
172
227
|
signal.throwIfAborted();
|
|
173
|
-
|
|
174
|
-
const normalized = normalizeUnicode(entry.path);
|
|
175
|
-
const previous = seen.get(normalized);
|
|
176
|
-
if (previous !== undefined)
|
|
177
|
-
throw new FileNormalizationConflict(entry.path, previous);
|
|
178
|
-
if (!entry.directory && directories.has(normalized))
|
|
179
|
-
throw new BagError(`Conflicting payload file and directory: ${entry.path}`);
|
|
180
|
-
const parts = normalized.split('/');
|
|
181
|
-
for (let i = 1; i < parts.length; i++) {
|
|
182
|
-
const parent = parts.slice(0, i).join('/');
|
|
183
|
-
if (files.has(parent))
|
|
184
|
-
throw new BagError(`Conflicting payload paths: ${parent} and ${entry.path}`);
|
|
185
|
-
directories.add(parent);
|
|
186
|
-
}
|
|
187
|
-
if (entry.directory && files.has(normalized))
|
|
188
|
-
throw new BagError(`Conflicting payload file and directory: ${entry.path}`);
|
|
189
|
-
seen.set(normalized, entry.path);
|
|
228
|
+
registerPayload(entry);
|
|
190
229
|
if (entry.directory) {
|
|
191
|
-
directories.add(normalized);
|
|
192
230
|
addDirectory(`${prefix}data/${entry.path}/`, entry.mtime, entry.mode);
|
|
193
231
|
continue;
|
|
194
232
|
}
|
|
195
|
-
|
|
196
|
-
const hashers = getHashers(algorithms);
|
|
197
|
-
let bytes = 0n;
|
|
198
|
-
async function* hashed() {
|
|
199
|
-
const source = await entry.open();
|
|
200
|
-
try {
|
|
201
|
-
for await (const chunk of source) {
|
|
202
|
-
signal.throwIfAborted();
|
|
203
|
-
if (!(chunk instanceof Uint8Array))
|
|
204
|
-
throw new TypeError('Payload sources must produce Uint8Array or Buffer chunks');
|
|
205
|
-
bytes += BigInt(chunk.length);
|
|
206
|
-
for (const h of Object.values(hashers))
|
|
207
|
-
h.update(chunk);
|
|
208
|
-
yield chunk;
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
finally {
|
|
212
|
-
if (source instanceof Readable)
|
|
213
|
-
source.destroy();
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
await addEntry(`${prefix}data/${entry.path}`, hashed(), entry.mtime, entry.mode);
|
|
217
|
-
const hashes = Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')]));
|
|
233
|
+
const { bytes, hashes } = await addSource(entry, `${prefix}data/${entry.path}`);
|
|
218
234
|
for (const a of algorithms)
|
|
219
235
|
await manifests.get(a).handle.writeFile(`${hashes[a]} ${encodeFilename(`data/${entry.path}`)}\n`);
|
|
220
236
|
totalBytes += bytes;
|
|
@@ -222,6 +238,25 @@ async function* archiveContent(entries, options, state) {
|
|
|
222
238
|
await options.onProgress?.({ path: entry.path, bytes, hashes, totalBytes, totalFiles });
|
|
223
239
|
}
|
|
224
240
|
const tags = [];
|
|
241
|
+
const registerTag = entryRegistry('tag', ['bagit.txt', 'bag-info.txt', 'data']);
|
|
242
|
+
for await (const entry of options.tagFiles ?? []) {
|
|
243
|
+
signal.throwIfAborted();
|
|
244
|
+
// Unlike payload paths (which start with data/), root tags can begin with
|
|
245
|
+
// whitespace or checksum-tool binary markers that manifest parsers strip.
|
|
246
|
+
if (/^[\s*]/.test(encodeFilename(entry.path)))
|
|
247
|
+
throw new BagError(`Ambiguous BagIt tag filename: ${JSON.stringify(entry.path)}`);
|
|
248
|
+
// Reserve manifest namespaces, including algorithms not selected for this export.
|
|
249
|
+
const root = normalizeUnicode(entry.path).split('/')[0];
|
|
250
|
+
if (/^(?:tagmanifest|manifest)-.*\.txt$/.test(root))
|
|
251
|
+
throw new BagError(`Reserved tag-file path: ${entry.path}`);
|
|
252
|
+
registerTag(entry);
|
|
253
|
+
if (entry.directory)
|
|
254
|
+
addDirectory(`${prefix}${entry.path}/`, entry.mtime, entry.mode);
|
|
255
|
+
else {
|
|
256
|
+
const { hashes } = await addSource(entry, prefix + entry.path);
|
|
257
|
+
tags.push({ name: entry.path, hashes });
|
|
258
|
+
}
|
|
259
|
+
}
|
|
225
260
|
for (const a of algorithms) {
|
|
226
261
|
const manifest = manifests.get(a);
|
|
227
262
|
await manifest.handle.close();
|
package/dist/esm/zip.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"zip.js","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAiB,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAmB,MAAM,kBAAkB,CAAC;AACvG,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AACxF,OAAO,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAC/B,OAAO,EAAE,QAAQ,EAAE,yBAAyB,EAAE,MAAM,aAAa,CAAC;AAElE,OAAO,EACL,aAAa,EAAE,cAAc,EAAE,eAAe,EAAE,WAAW,EAAE,cAAc,EAAE,UAAU,EACvF,YAAY,EAAE,eAAe,EAAE,WAAW,EAAE,WAAW,EAAE,gBAAgB,EAAE,gBAAgB,GAC5F,MAAM,WAAW,CAAC;AAoCnB,SAAS,eAAe,CAAC,OAAsB;I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AAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAAC,CAAC;AAC3E,CAAC;AAED,MAAM,CAAC,MAAM,gBAAgB,GAAG,cAAc,CAAC","sourcesContent":["import { Readable, type Writable } from 'node:stream';\nimport { finished, pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { mkdtemp, open, readdir, realpath, rename, rm, stat, type FileHandle } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { ZipFile } from 'yazl';\nimport { BagError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\nimport {\n algorithmsFor, assertSafePath, BAG_DECLARATION, digestBytes, encodeFilename, getHashers,\n compareNames, HASH_BLOCK_SIZE, isDirectory, makeBagInfo, normalizeUnicode, serializeTagFile,\n} from './util.js';\n\nexport interface BagZipOptions {\n bagInfo?: BagInfoInput;\n checksums?: readonly string[];\n /** An optional directory containing the entire bag inside the archive. Default: archive root. */\n bagName?: string;\n /** Deflate level 0–9; default 6. */\n compressionLevel?: number;\n /** Temporary directory for manifests; payloads are never staged. */\n tempDirectory?: string;\n signal?: AbortSignal;\n /** Fixed ZIP modification time for reproducible archives. */\n mtime?: Date;\n /** Called after a payload file has been completely read into the ZIP compressor. */\n onProgress?: (progress: BagZipProgress) => void | Promise<void>;\n}\nexport interface BagZipProgress {\n path: string;\n bytes: bigint;\n hashes: Checksums;\n totalBytes: bigint;\n totalFiles: number;\n}\nexport interface BagZipResult { bytesWritten: bigint; payloadBytes: bigint; payloadFiles: number; bagInfo: BagInfo; }\n\n/** Sources are opened lazily, one at a time. Paths are relative to the payload, without a data/ prefix. */\nexport interface BagZipEntry {\n path: string;\n /** Preserve an empty directory. Its open() function is ignored. */\n directory?: boolean;\n open: () => Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | Promise<Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array>>;\n mtime?: Date;\n mode?: number;\n}\n\nfunction validateOptions(options: BagZipOptions): string[] {\n const level = options.compressionLevel ?? 6;\n if (!Number.isInteger(level) || level < 0 || level > 9) throw new RangeError('compressionLevel must be an integer from 0 to 9');\n if (options.bagName !== undefined) validateEntryPath(options.bagName);\n if (options.mtime && !Number.isFinite(options.mtime.getTime())) throw new BagError('Invalid ZIP modification time');\n return algorithmsFor(options.checksums);\n}\nfunction validateEntryPath(path: string): void {\n if (!path || path.includes('\\\\') || /[\\0\\r\\n]/.test(path) || path.startsWith('~') || path.startsWith('/') || /^[a-z]:/i.test(path) || path.split('/').some(p => !p || p === '.' || p === '..')) {\n throw new BagError(`Unsafe ZIP entry path: ${JSON.stringify(path)}`);\n }\n}\n// CR/LF are legal BagIt payload names: manifests encode them, ZIP headers store their original bytes.\nfunction validatePayloadPath(path: string): void {\n validateEntryPath(path.replace(/[\\r\\n]/g, '_'));\n if (/%0[ad]/i.test(path)) throw new BagError(`Ambiguous BagIt filename contains a literal encoded newline: ${path}`);\n if (/\\s$/.test(encodeFilename(path))) throw new BagError(`BagIt cannot represent trailing whitespace unambiguously: ${JSON.stringify(path)}`);\n}\n\nasync function* folderEntries(directory: string, options: BagZipOptions): AsyncGenerator<BagZipEntry> {\n const root = resolve(directory);\n if (!isDirectory(root)) throw new BagError(`Bag directory ${root} does not exist`);\n const temporaryRoot = await realpath(options.tempDirectory ?? tmpdir());\n const relTemp = relative(await realpath(root), temporaryRoot);\n if (!relTemp || (!isAbsolute(relTemp) && relTemp !== '..' && !relTemp.startsWith(`..${sep}`))) throw new BagError('Manifest temporary directory must be outside the source directory');\n async function* walk(path = ''): AsyncGenerator<BagZipEntry> {\n const entries = (await readdir(join(root, path), { withFileTypes: true })).sort((a, b) => compareNames(a.name, b.name));\n for (const entry of entries) {\n if (entry.isDirectory()) continue;\n const filename = path + entry.name;\n assertSafePath(root, filename, 'source directory');\n if (entry.isSymbolicLink() && isDirectory(join(root, filename))) throw new BagError(`Directory symlinks cannot be exported: ${filename}`);\n yield await fileEntry(filename);\n }\n for (const entry of entries) if (entry.isDirectory()) {\n const filename = path + entry.name;\n const metadata = await stat(join(root, filename));\n yield { path: filename, directory: true, mtime: metadata.mtime, mode: metadata.mode, open: () => [] };\n yield* walk(filename + '/');\n }\n }\n async function fileEntry(path: string): Promise<BagZipEntry> {\n options.signal?.throwIfAborted();\n assertSafePath(root, path, 'source directory');\n const fullPath = join(root, path);\n const before = await stat(fullPath, { bigint: true });\n if (!before.isFile()) throw new BagError(`Payload is not a regular file: ${path}`);\n return {\n path, mtime: new Date(Number(before.mtimeMs)), mode: Number(before.mode),\n async *open() {\n // Check the opened file, rather than just the preceding path stat.\n assertSafePath(root, path, 'source directory');\n const handle = await open(fullPath, 'r');\n try {\n const opened = await handle.stat({ bigint: true });\n if (opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size || opened.mtimeNs !== before.mtimeNs) throw new BagError(`Source file changed before reading: ${path}`);\n const stream = handle.createReadStream({ autoClose: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n try {\n yield* stream;\n const after = await handle.stat({ bigint: true });\n if (after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) throw new BagError(`Source file changed while reading: ${path}`);\n } finally { stream.destroy(); }\n } finally { await handle.close(); }\n },\n };\n }\n yield* walk();\n}\n\ninterface ExportState { result?: BagZipResult; cleanup?: Promise<void>; }\nasync function* archive(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n let complete!: () => void;\n state.cleanup = new Promise<void>(resolve => { complete = resolve; });\n try { yield* archiveContent(entries, options, state); }\n finally { complete(); }\n}\nasync function* archiveContent(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n const algorithms = validateOptions(options);\n options.signal?.throwIfAborted();\n const temp = await mkdtemp(join(options.tempDirectory ?? tmpdir(), 'bagit-zip-'));\n const handles: FileHandle[] = [];\n const zip = new ZipFile();\n const output = zip.outputStream as Readable;\n const controller = new AbortController();\n const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n let active: Readable | undefined;\n let failure: unknown;\n let failed = false;\n const fail = (error: unknown): void => {\n if (failed) return;\n failed = true;\n failure = error;\n controller.abort(error);\n active?.destroy(error instanceof Error ? error : new Error(String(error)));\n output.destroy(error instanceof Error ? error : new Error(String(error)));\n };\n zip.on('error', fail);\n // Install an error listener before producer I/O can fail, even before iteration starts.\n output.on('error', fail);\n const onAbort = (): void => fail(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n\n async function addEntry(name: string, input: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, mtime?: Date, mode?: number): Promise<void> {\n signal.throwIfAborted();\n const source = Readable.from(input, { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal });\n active = source;\n const done = finished(source, { cleanup: true });\n // Register rejection handling immediately; addReadStreamLazy can throw synchronously.\n void done.catch(fail);\n try {\n zip.addReadStreamLazy(name, {\n mtime: options.mtime ?? mtime ?? new Date(), mode: mode ?? 0o100644,\n compressionLevel: options.compressionLevel ?? 6,\n }, cb => cb(null, source));\n await done;\n } finally {\n source.destroy();\n await done.catch(() => {});\n active = undefined;\n }\n }\n function addDirectory(name: string, mtime?: Date, mode = 0o40755): void {\n signal.throwIfAborted();\n zip.addEmptyDirectory(name, { mtime: options.mtime ?? mtime ?? new Date(), mode });\n }\n\n const produce = async (): Promise<Omit<BagZipResult, 'bytesWritten'>> => {\n const manifests = new Map<string, { path: string; handle: FileHandle }>();\n for (const a of algorithms) {\n const path = join(temp, `manifest-${a}.txt`);\n const handle = await open(path, 'w');\n handles.push(handle);\n manifests.set(a, { path, handle });\n }\n const prefix = options.bagName ? `${options.bagName}/` : '';\n const seen = new Map<string, string>();\n const directories = new Set<string>();\n const files = new Set<string>();\n let totalBytes = 0n;\n let totalFiles = 0;\n addDirectory(`${prefix}data/`);\n for await (const entry of entries) {\n signal.throwIfAborted();\n validatePayloadPath(entry.path);\n const normalized = normalizeUnicode(entry.path);\n const previous = seen.get(normalized);\n if (previous !== undefined) throw new FileNormalizationConflict(entry.path, previous);\n if (!entry.directory && directories.has(normalized)) throw new BagError(`Conflicting payload file and directory: ${entry.path}`);\n const parts = normalized.split('/');\n for (let i = 1; i < parts.length; i++) {\n const parent = parts.slice(0, i).join('/');\n if (files.has(parent)) throw new BagError(`Conflicting payload paths: ${parent} and ${entry.path}`);\n directories.add(parent);\n }\n if (entry.directory && files.has(normalized)) throw new BagError(`Conflicting payload file and directory: ${entry.path}`);\n seen.set(normalized, entry.path);\n if (entry.directory) {\n directories.add(normalized);\n addDirectory(`${prefix}data/${entry.path}/`, entry.mtime, entry.mode);\n continue;\n }\n files.add(normalized);\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n async function* hashed(): AsyncGenerator<Uint8Array> {\n const source = await entry.open();\n try {\n for await (const chunk of source) {\n signal.throwIfAborted();\n if (!(chunk instanceof Uint8Array)) throw new TypeError('Payload sources must produce Uint8Array or Buffer chunks');\n bytes += BigInt(chunk.length);\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk;\n }\n } finally { if (source instanceof Readable) source.destroy(); }\n }\n await addEntry(`${prefix}data/${entry.path}`, hashed(), entry.mtime, entry.mode);\n const hashes = Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')]));\n for (const a of algorithms) await manifests.get(a)!.handle.writeFile(`${hashes[a]} ${encodeFilename(`data/${entry.path}`)}\\n`);\n totalBytes += bytes;\n totalFiles++;\n await options.onProgress?.({ path: entry.path, bytes, hashes, totalBytes, totalFiles });\n }\n const tags: { name: string; hashes: Checksums }[] = [];\n for (const a of algorithms) {\n const manifest = manifests.get(a)!;\n await manifest.handle.close();\n const hashers = getHashers(algorithms);\n async function* content(): AsyncGenerator<Buffer> {\n for await (const chunk of createReadStream(manifest.path, { signal })) {\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk as Buffer;\n }\n }\n const name = `manifest-${a}.txt`;\n await addEntry(prefix + name, content());\n tags.push({ name, hashes: Object.fromEntries(Object.entries(hashers).map(([alg, h]) => [alg, h.digest('hex')])) });\n }\n const bagInfo = makeBagInfo(options.bagInfo, totalBytes, totalFiles);\n for (const [name, text] of [['bagit.txt', BAG_DECLARATION], ['bag-info.txt', serializeTagFile(bagInfo)]]) {\n const bytes = Buffer.from(text!, 'utf8');\n await addEntry(prefix + name!, [bytes]);\n tags.push({ name: name!, hashes: digestBytes(bytes, algorithms) });\n }\n for (const a of algorithms) {\n const text = tags.map(t => `${t.hashes[a]} ${encodeFilename(t.name)}\\n`).join('');\n await addEntry(`${prefix}tagmanifest-${a}.txt`, [Buffer.from(text)]);\n }\n zip.end();\n return { payloadBytes: totalBytes, payloadFiles: totalFiles, bagInfo };\n };\n const done = produce().catch(error => { fail(error); return undefined; });\n try {\n if (signal.aborted) fail(signal.reason);\n let bytesWritten = 0n;\n for await (const chunk of output) {\n bytesWritten += BigInt(chunk.length);\n yield chunk as Buffer;\n }\n const result = await done;\n if (failed) throw failure;\n state.result = { ...result!, bytesWritten };\n } finally {\n signal.removeEventListener('abort', onAbort);\n controller.abort();\n active?.destroy();\n output.destroy();\n await done;\n await Promise.allSettled(handles.map(h => h.close()));\n await rm(temp, { recursive: true, force: true });\n }\n}\n\n/** Pipe directly into an S3/Ceph multipart upload Body. Errors are emitted on the stream. */\nexport function createBagZipStream(directory: string, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(folderEntries(directory, options), options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Stream a bag from lazy application-provided sources, without first creating a payload directory. */\nexport function createBagZipStreamFromEntries(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(entries, options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Write an archive to a Writable, or atomically replace a path after successful completion. Ends the destination. */\nexport async function folderToBagZip(directory: string, destination: string | Writable, options: BagZipOptions = {}): Promise<BagZipResult> {\n validateOptions(options);\n options.signal?.throwIfAborted();\n if (!isDirectory(resolve(directory))) throw new BagError(`Bag directory ${resolve(directory)} does not exist`);\n const state: ExportState = {};\n let temp: string | undefined;\n try {\n let output: Writable;\n const outputPath = typeof destination === 'string' ? destination : 'path' in destination && typeof destination.path === 'string' ? destination.path : undefined;\n if (outputPath !== undefined) {\n const target = resolve(outputPath);\n // Resolve existing parent symlinks before checking containment.\n const actual = join(await realpath(dirname(target)), basename(target));\n const rel = relative(await realpath(directory), actual);\n if (!rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))) throw new BagError('ZIP destination must be outside the source directory');\n }\n if (typeof destination === 'string') {\n const target = resolve(destination);\n temp = await mkdtemp(join(dirname(target), '.bagit-output-'));\n output = createWriteStream(join(temp, 'archive.zip'), { flags: 'wx' });\n } else output = destination;\n const source = Readable.from(archive(folderEntries(directory, options), options, state), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE });\n try { await pipeline(source, output, { signal: options.signal }); }\n finally { await state.cleanup; }\n if (typeof destination === 'string') await rename(join(temp!, 'archive.zip'), resolve(destination));\n return state.result!;\n } finally { if (temp) await rm(temp, { recursive: true, force: true }); }\n}\n\nexport const folderToBagitZip = folderToBagZip;\n"]}
|
|
1
|
+
{"version":3,"file":"zip.js","sourceRoot":"","sources":["../../src/zip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAiB,MAAM,aAAa,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AAC9D,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ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GAAG,cAAc,CAAC","sourcesContent":["import { Readable, type Writable } from 'node:stream';\nimport { finished, pipeline } from 'node:stream/promises';\nimport { createReadStream, createWriteStream } from 'node:fs';\nimport { mkdtemp, open, readdir, realpath, rename, rm, stat, type FileHandle } from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';\nimport { ZipFile } from 'yazl';\nimport { BagError, FileNormalizationConflict } from './errors.js';\nimport type { BagInfo, BagInfoInput, Checksums } from './types.js';\nimport {\n algorithmsFor, assertSafePath, BAG_DECLARATION, digestBytes, encodeFilename, getHashers,\n compareNames, HASH_BLOCK_SIZE, isDirectory, makeBagInfo, normalizeUnicode, serializeTagFile,\n} from './util.js';\n\nexport interface BagZipOptions {\n bagInfo?: BagInfoInput;\n checksums?: readonly string[];\n /** An optional directory containing the entire bag inside the archive. Default: archive root. */\n bagName?: string;\n /** Lazy custom tag files, with paths relative to the bag root. Use fresh iterables and sources for retries. */\n tagFiles?: Iterable<BagZipEntry> | AsyncIterable<BagZipEntry>;\n /** Deflate level 0–9; default 6. */\n compressionLevel?: number;\n /** Temporary directory for payload manifests; payloads and custom tag files are never staged. */\n tempDirectory?: string;\n signal?: AbortSignal;\n /** Fixed ZIP modification time for reproducible archives. */\n mtime?: Date;\n /** Called after a payload file has been completely read into the ZIP compressor. */\n onProgress?: (progress: BagZipProgress) => void | Promise<void>;\n}\nexport interface BagZipProgress {\n path: string;\n bytes: bigint;\n hashes: Checksums;\n totalBytes: bigint;\n totalFiles: number;\n}\nexport interface BagZipResult { bytesWritten: bigint; payloadBytes: bigint; payloadFiles: number; bagInfo: BagInfo; }\n\n/** Sources are opened lazily, one at a time. Payload paths are relative to data/; tagFiles paths are relative to the bag root. */\nexport interface BagZipEntry {\n path: string;\n /** Preserve an empty directory. Its open() function is ignored. */\n directory?: boolean;\n open: () => Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | Promise<Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array>>;\n mtime?: Date;\n mode?: number;\n}\n\nfunction validateOptions(options: BagZipOptions): string[] {\n const level = options.compressionLevel ?? 6;\n if (!Number.isInteger(level) || level < 0 || level > 9) throw new RangeError('compressionLevel must be an integer from 0 to 9');\n if (options.bagName !== undefined) validateEntryPath(options.bagName);\n if (options.mtime && !Number.isFinite(options.mtime.getTime())) throw new BagError('Invalid ZIP modification time');\n return algorithmsFor(options.checksums);\n}\nfunction validateEntryPath(path: string): void {\n if (!path || path.includes('\\\\') || /[\\0\\r\\n]/.test(path) || path.startsWith('~') || path.startsWith('/') || /^[a-z]:/i.test(path) || path.split('/').some(p => !p || p === '.' || p === '..')) {\n throw new BagError(`Unsafe ZIP entry path: ${JSON.stringify(path)}`);\n }\n}\n// CR/LF are legal BagIt payload names: manifests encode them, ZIP headers store their original bytes.\nfunction validatePayloadPath(path: string): void {\n validateEntryPath(path.replace(/[\\r\\n]/g, '_'));\n if (/%0[ad]/i.test(path)) throw new BagError(`Ambiguous BagIt filename contains a literal encoded newline: ${path}`);\n if (/\\s$/.test(encodeFilename(path))) throw new BagError(`BagIt cannot represent trailing whitespace unambiguously: ${JSON.stringify(path)}`);\n}\n\nfunction entryRegistry(kind: string, reservedFiles: readonly string[] = []): (entry: BagZipEntry) => void {\n const seen = new Map<string, string>();\n const directories = new Set<string>();\n const files = new Set(reservedFiles);\n return entry => {\n validatePayloadPath(entry.path);\n const normalized = normalizeUnicode(entry.path);\n const previous = seen.get(normalized);\n if (previous !== undefined) throw new FileNormalizationConflict(entry.path, previous);\n if (files.has(normalized) || (!entry.directory && directories.has(normalized))) throw new BagError(`Conflicting ${kind} file and directory: ${entry.path}`);\n const parts = normalized.split('/');\n for (let i = 1; i < parts.length; i++) {\n const parent = parts.slice(0, i).join('/');\n if (files.has(parent)) throw new BagError(`Conflicting ${kind} paths: ${parent} and ${entry.path}`);\n directories.add(parent);\n }\n seen.set(normalized, entry.path);\n if (entry.directory) directories.add(normalized);\n else files.add(normalized);\n };\n}\n\nasync function* folderEntries(directory: string, options: BagZipOptions): AsyncGenerator<BagZipEntry> {\n const root = resolve(directory);\n if (!isDirectory(root)) throw new BagError(`Bag directory ${root} does not exist`);\n const temporaryRoot = await realpath(options.tempDirectory ?? tmpdir());\n const relTemp = relative(await realpath(root), temporaryRoot);\n if (!relTemp || (!isAbsolute(relTemp) && relTemp !== '..' && !relTemp.startsWith(`..${sep}`))) throw new BagError('Manifest temporary directory must be outside the source directory');\n async function* walk(path = ''): AsyncGenerator<BagZipEntry> {\n const entries = (await readdir(join(root, path), { withFileTypes: true })).sort((a, b) => compareNames(a.name, b.name));\n for (const entry of entries) {\n if (entry.isDirectory()) continue;\n const filename = path + entry.name;\n assertSafePath(root, filename, 'source directory');\n if (entry.isSymbolicLink() && isDirectory(join(root, filename))) throw new BagError(`Directory symlinks cannot be exported: ${filename}`);\n yield await fileEntry(filename);\n }\n for (const entry of entries) if (entry.isDirectory()) {\n const filename = path + entry.name;\n const metadata = await stat(join(root, filename));\n yield { path: filename, directory: true, mtime: metadata.mtime, mode: metadata.mode, open: () => [] };\n yield* walk(filename + '/');\n }\n }\n async function fileEntry(path: string): Promise<BagZipEntry> {\n options.signal?.throwIfAborted();\n assertSafePath(root, path, 'source directory');\n const fullPath = join(root, path);\n const before = await stat(fullPath, { bigint: true });\n if (!before.isFile()) throw new BagError(`Payload is not a regular file: ${path}`);\n return {\n path, mtime: new Date(Number(before.mtimeMs)), mode: Number(before.mode),\n async *open() {\n // Check the opened file, rather than just the preceding path stat.\n assertSafePath(root, path, 'source directory');\n const handle = await open(fullPath, 'r');\n try {\n const opened = await handle.stat({ bigint: true });\n if (opened.dev !== before.dev || opened.ino !== before.ino || opened.size !== before.size || opened.mtimeNs !== before.mtimeNs) throw new BagError(`Source file changed before reading: ${path}`);\n const stream = handle.createReadStream({ autoClose: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n try {\n yield* stream;\n const after = await handle.stat({ bigint: true });\n if (after.size !== opened.size || after.mtimeNs !== opened.mtimeNs || after.ctimeNs !== opened.ctimeNs) throw new BagError(`Source file changed while reading: ${path}`);\n } finally { stream.destroy(); }\n } finally { await handle.close(); }\n },\n };\n }\n yield* walk();\n}\n\ninterface ExportState { result?: BagZipResult; cleanup?: Promise<void>; }\nasync function* archive(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n let complete!: () => void;\n state.cleanup = new Promise<void>(resolve => { complete = resolve; });\n try { yield* archiveContent(entries, options, state); }\n finally { complete(); }\n}\nasync function* archiveContent(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions, state: ExportState): AsyncGenerator<Buffer> {\n const algorithms = validateOptions(options);\n options.signal?.throwIfAborted();\n const temp = await mkdtemp(join(options.tempDirectory ?? tmpdir(), 'bagit-zip-'));\n const handles: FileHandle[] = [];\n const zip = new ZipFile();\n const output = zip.outputStream as Readable;\n const controller = new AbortController();\n const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n let active: Readable | undefined;\n let failure: unknown;\n let failed = false;\n const fail = (error: unknown): void => {\n if (failed) return;\n failed = true;\n failure = error;\n controller.abort(error);\n active?.destroy(error instanceof Error ? error : new Error(String(error)));\n output.destroy(error instanceof Error ? error : new Error(String(error)));\n };\n zip.on('error', fail);\n // Install an error listener before producer I/O can fail, even before iteration starts.\n output.on('error', fail);\n const onAbort = (): void => fail(signal.reason);\n signal.addEventListener('abort', onAbort, { once: true });\n\n async function addEntry(name: string, input: AsyncIterable<Uint8Array> | Iterable<Uint8Array>, mtime?: Date, mode?: number): Promise<void> {\n signal.throwIfAborted();\n const source = Readable.from(input, { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal });\n active = source;\n const done = finished(source, { cleanup: true });\n // Register rejection handling immediately; addReadStreamLazy can throw synchronously.\n void done.catch(fail);\n try {\n zip.addReadStreamLazy(name, {\n mtime: options.mtime ?? mtime ?? new Date(), mode: mode ?? 0o100644,\n compressionLevel: options.compressionLevel ?? 6,\n }, cb => cb(null, source));\n await done;\n } finally {\n source.destroy();\n await done.catch(() => {});\n active = undefined;\n }\n }\n function addDirectory(name: string, mtime?: Date, mode = 0o40755): void {\n signal.throwIfAborted();\n zip.addEmptyDirectory(name, { mtime: options.mtime ?? mtime ?? new Date(), mode });\n }\n\n async function addSource(entry: BagZipEntry, name: string): Promise<{ bytes: bigint; hashes: Checksums }> {\n const hashers = getHashers(algorithms);\n let bytes = 0n;\n async function* hashed(): AsyncGenerator<Uint8Array> {\n signal.throwIfAborted();\n const source = await entry.open();\n const destroy = (): void => {\n if (source instanceof Readable) source.destroy();\n };\n signal.addEventListener('abort', destroy, { once: true });\n try {\n signal.throwIfAborted();\n for await (const chunk of source) {\n signal.throwIfAborted();\n if (!(chunk instanceof Uint8Array)) throw new TypeError('ZIP sources must produce Uint8Array or Buffer chunks');\n bytes += BigInt(chunk.length);\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk;\n }\n } finally {\n signal.removeEventListener('abort', destroy);\n destroy();\n }\n }\n await addEntry(name, hashed(), entry.mtime, entry.mode);\n return { bytes, hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])) };\n }\n\n const produce = async (): Promise<Omit<BagZipResult, 'bytesWritten'>> => {\n const manifests = new Map<string, { path: string; handle: FileHandle }>();\n for (const a of algorithms) {\n const path = join(temp, `manifest-${a}.txt`);\n const handle = await open(path, 'w');\n handles.push(handle);\n manifests.set(a, { path, handle });\n }\n const prefix = options.bagName ? `${options.bagName}/` : '';\n const registerPayload = entryRegistry('payload');\n let totalBytes = 0n;\n let totalFiles = 0;\n addDirectory(`${prefix}data/`);\n for await (const entry of entries) {\n signal.throwIfAborted();\n registerPayload(entry);\n if (entry.directory) {\n addDirectory(`${prefix}data/${entry.path}/`, entry.mtime, entry.mode);\n continue;\n }\n const { bytes, hashes } = await addSource(entry, `${prefix}data/${entry.path}`);\n for (const a of algorithms) await manifests.get(a)!.handle.writeFile(`${hashes[a]} ${encodeFilename(`data/${entry.path}`)}\\n`);\n totalBytes += bytes;\n totalFiles++;\n await options.onProgress?.({ path: entry.path, bytes, hashes, totalBytes, totalFiles });\n }\n const tags: { name: string; hashes: Checksums }[] = [];\n const registerTag = entryRegistry('tag', ['bagit.txt', 'bag-info.txt', 'data']);\n for await (const entry of options.tagFiles ?? []) {\n signal.throwIfAborted();\n // Unlike payload paths (which start with data/), root tags can begin with\n // whitespace or checksum-tool binary markers that manifest parsers strip.\n if (/^[\\s*]/.test(encodeFilename(entry.path))) throw new BagError(`Ambiguous BagIt tag filename: ${JSON.stringify(entry.path)}`);\n // Reserve manifest namespaces, including algorithms not selected for this export.\n const root = normalizeUnicode(entry.path).split('/')[0]!;\n if (/^(?:tagmanifest|manifest)-.*\\.txt$/.test(root)) throw new BagError(`Reserved tag-file path: ${entry.path}`);\n registerTag(entry);\n if (entry.directory) addDirectory(`${prefix}${entry.path}/`, entry.mtime, entry.mode);\n else {\n const { hashes } = await addSource(entry, prefix + entry.path);\n tags.push({ name: entry.path, hashes });\n }\n }\n for (const a of algorithms) {\n const manifest = manifests.get(a)!;\n await manifest.handle.close();\n const hashers = getHashers(algorithms);\n async function* content(): AsyncGenerator<Buffer> {\n for await (const chunk of createReadStream(manifest.path, { signal })) {\n for (const h of Object.values(hashers)) h.update(chunk);\n yield chunk as Buffer;\n }\n }\n const name = `manifest-${a}.txt`;\n await addEntry(prefix + name, content());\n tags.push({ name, hashes: Object.fromEntries(Object.entries(hashers).map(([alg, h]) => [alg, h.digest('hex')])) });\n }\n const bagInfo = makeBagInfo(options.bagInfo, totalBytes, totalFiles);\n for (const [name, text] of [['bagit.txt', BAG_DECLARATION], ['bag-info.txt', serializeTagFile(bagInfo)]]) {\n const bytes = Buffer.from(text!, 'utf8');\n await addEntry(prefix + name!, [bytes]);\n tags.push({ name: name!, hashes: digestBytes(bytes, algorithms) });\n }\n for (const a of algorithms) {\n const text = tags.map(t => `${t.hashes[a]} ${encodeFilename(t.name)}\\n`).join('');\n await addEntry(`${prefix}tagmanifest-${a}.txt`, [Buffer.from(text)]);\n }\n zip.end();\n return { payloadBytes: totalBytes, payloadFiles: totalFiles, bagInfo };\n };\n const done = produce().catch(error => { fail(error); return undefined; });\n try {\n if (signal.aborted) fail(signal.reason);\n let bytesWritten = 0n;\n for await (const chunk of output) {\n bytesWritten += BigInt(chunk.length);\n yield chunk as Buffer;\n }\n const result = await done;\n if (failed) throw failure;\n state.result = { ...result!, bytesWritten };\n } finally {\n signal.removeEventListener('abort', onAbort);\n controller.abort();\n active?.destroy();\n output.destroy();\n await done;\n await Promise.allSettled(handles.map(h => h.close()));\n await rm(temp, { recursive: true, force: true });\n }\n}\n\n/** Pipe directly into an S3/Ceph multipart upload Body. Errors are emitted on the stream. */\nexport function createBagZipStream(directory: string, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(folderEntries(directory, options), options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Stream a bag from lazy application-provided sources, without first creating a payload directory. */\nexport function createBagZipStreamFromEntries(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options: BagZipOptions = {}): Readable {\n validateOptions(options);\n return Readable.from(archive(entries, options, {}), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE, signal: options.signal });\n}\n\n/** Write an archive to a Writable, or atomically replace a path after successful completion. Ends the destination. */\nexport async function folderToBagZip(directory: string, destination: string | Writable, options: BagZipOptions = {}): Promise<BagZipResult> {\n validateOptions(options);\n options.signal?.throwIfAborted();\n if (!isDirectory(resolve(directory))) throw new BagError(`Bag directory ${resolve(directory)} does not exist`);\n const state: ExportState = {};\n let temp: string | undefined;\n try {\n let output: Writable;\n const outputPath = typeof destination === 'string' ? destination : 'path' in destination && typeof destination.path === 'string' ? destination.path : undefined;\n if (outputPath !== undefined) {\n const target = resolve(outputPath);\n // Resolve existing parent symlinks before checking containment.\n const actual = join(await realpath(dirname(target)), basename(target));\n const rel = relative(await realpath(directory), actual);\n if (!rel || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`))) throw new BagError('ZIP destination must be outside the source directory');\n }\n if (typeof destination === 'string') {\n const target = resolve(destination);\n temp = await mkdtemp(join(dirname(target), '.bagit-output-'));\n output = createWriteStream(join(temp, 'archive.zip'), { flags: 'wx' });\n } else output = destination;\n const source = Readable.from(archive(folderEntries(directory, options), options, state), { objectMode: false, highWaterMark: HASH_BLOCK_SIZE });\n try { await pipeline(source, output, { signal: options.signal }); }\n finally { await state.cleanup; }\n if (typeof destination === 'string') await rename(join(temp!, 'archive.zip'), resolve(destination));\n return state.result!;\n } finally { if (temp) await rm(temp, { recursive: true, force: true }); }\n}\n\nexport const folderToBagitZip = folderToBagZip;\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "bagit-node",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "TypeScript BagIt library with ESM, CommonJS and streaming ZIP64 export",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/cjs/index.js",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"files": [
|
|
22
22
|
"dist",
|
|
23
23
|
"README.md",
|
|
24
|
+
"CHANGELOG.md",
|
|
24
25
|
"LICENSE",
|
|
25
26
|
"NOTICE"
|
|
26
27
|
],
|