bagit-node 0.0.0-stage → 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/LICENSE +21 -0
- package/NOTICE +6 -0
- package/README.md +246 -2
- package/dist/cjs/bag.d.ts +59 -0
- package/dist/cjs/bag.d.ts.map +1 -0
- package/dist/cjs/bag.js +329 -0
- package/dist/cjs/bag.js.map +1 -0
- package/dist/cjs/errors.d.ts +32 -0
- package/dist/cjs/errors.d.ts.map +1 -0
- package/dist/cjs/errors.js +60 -0
- package/dist/cjs/errors.js.map +1 -0
- package/dist/cjs/index.d.ts +6 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +39 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/types.d.ts +29 -0
- package/dist/cjs/types.d.ts.map +1 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/types.js.map +1 -0
- package/dist/cjs/util.d.ts +39 -0
- package/dist/cjs/util.d.ts.map +1 -0
- package/dist/cjs/util.js +355 -0
- package/dist/cjs/util.js.map +1 -0
- package/dist/cjs/zip.d.ts +49 -0
- package/dist/cjs/zip.d.ts.map +1 -0
- package/dist/cjs/zip.js +371 -0
- package/dist/cjs/zip.js.map +1 -0
- package/dist/esm/bag.d.ts +59 -0
- package/dist/esm/bag.d.ts.map +1 -0
- package/dist/esm/bag.js +322 -0
- package/dist/esm/bag.js.map +1 -0
- package/dist/esm/errors.d.ts +32 -0
- package/dist/esm/errors.d.ts.map +1 -0
- package/dist/esm/errors.js +50 -0
- package/dist/esm/errors.js.map +1 -0
- package/dist/esm/index.d.ts +6 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/types.d.ts +29 -0
- package/dist/esm/types.d.ts.map +1 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/types.js.map +1 -0
- package/dist/esm/util.d.ts +39 -0
- package/dist/esm/util.d.ts.map +1 -0
- package/dist/esm/util.js +326 -0
- package/dist/esm/util.js.map +1 -0
- package/dist/esm/zip.d.ts +49 -0
- package/dist/esm/zip.d.ts.map +1 -0
- package/dist/esm/zip.js +365 -0
- package/dist/esm/zip.js.map +1 -0
- package/package.json +47 -4
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type Hash } from 'node:crypto';
|
|
2
|
+
import type { BagInfo, BagInfoInput, Checksums } from './types.js';
|
|
3
|
+
export declare const VERSION = "1.1.0";
|
|
4
|
+
export declare const DEFAULT_CHECKSUMS: readonly string[];
|
|
5
|
+
export declare const HASH_BLOCK_SIZE: number;
|
|
6
|
+
export declare const BAG_DECLARATION = "BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n";
|
|
7
|
+
export declare const STANDARD_BAG_INFO_HEADERS: readonly string[];
|
|
8
|
+
export declare const CHECKSUM_ALGOS: readonly string[];
|
|
9
|
+
export declare function getHashers(algorithms: readonly string[]): Record<string, Hash>;
|
|
10
|
+
export declare function algorithmsFor(algorithms?: readonly string[]): string[];
|
|
11
|
+
export declare function digestBytes(bytes: Uint8Array, algorithms: readonly string[]): Checksums;
|
|
12
|
+
export declare function hashFile(path: string, algorithms: readonly string[], signal?: AbortSignal): Promise<{
|
|
13
|
+
hashes: Checksums;
|
|
14
|
+
bytes: bigint;
|
|
15
|
+
}>;
|
|
16
|
+
export declare function generateManifestLines(filename: string, algorithms?: readonly string[], signal?: AbortSignal): Promise<[algorithm: string, digest: string, filename: string, bytes: bigint][]>;
|
|
17
|
+
export declare const normalizeUnicode: (s: string) => string;
|
|
18
|
+
export declare function buildUnicodeNormalizedLookupDict(filenames: Iterable<string>): Record<string, string>;
|
|
19
|
+
export declare const encodeFilename: (s: string) => string;
|
|
20
|
+
export declare const decodeFilename: (s: string) => string;
|
|
21
|
+
export declare const posixPath: (s: string) => string;
|
|
22
|
+
export declare const isFile: (p: string) => boolean;
|
|
23
|
+
export declare const isDirectory: (p: string) => boolean;
|
|
24
|
+
/** Match os.walk: sorted files at each level, then sorted directories; do not follow directory symlinks. */
|
|
25
|
+
export declare function walkFiles(root: string, prefix?: string): Generator<string>;
|
|
26
|
+
export declare function compareNames(a: string, b: string): number;
|
|
27
|
+
export declare function pathIsDangerous(root: string, filename: string): boolean;
|
|
28
|
+
export declare function assertSafePath(root: string, filename: string, context?: string): void;
|
|
29
|
+
export declare function decodeText(bytes: Uint8Array, encoding?: string): string;
|
|
30
|
+
export declare function checkEncoding(encoding: string): void;
|
|
31
|
+
export declare function encodeText(text: string, encoding?: string): Buffer;
|
|
32
|
+
export declare function parseTagFile(text: string, filename?: string): BagInfo;
|
|
33
|
+
export declare function serializeTagFile(info: BagInfoInput): string;
|
|
34
|
+
export declare function makeBagInfo(info: BagInfoInput | undefined, bytes: bigint, files: number): BagInfo;
|
|
35
|
+
export declare function loadTagFile(path: string, encoding?: string): Promise<BagInfo>;
|
|
36
|
+
export declare function checkPermissions(root: string, saving?: boolean): void;
|
|
37
|
+
export declare function checkConcurrency(concurrency?: number): number;
|
|
38
|
+
export declare function mapConcurrent<T, R>(items: readonly T[], concurrency: number, fn: (value: T) => Promise<R>): Promise<R[]>;
|
|
39
|
+
//# sourceMappingURL=util.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"util.d.ts","sourceRoot":"","sources":["../../src/util.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,KAAK,IAAI,EAAE,MAAM,aAAa,CAAC;AAKpD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAEnE,eAAO,MAAM,OAAO,UAAU,CAAC;AAC/B,eAAO,MAAM,iBAAiB,EAAE,SAAS,MAAM,EAAwC,CAAC;AACxF,eAAO,MAAM,eAAe,QAAa,CAAC;AAC1C,eAAO,MAAM,eAAe,6DAA6D,CAAC;AAC1F,eAAO,MAAM,yB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,CAGxD;AACD,wBAAsB,aAAa,CAAC,CAAC,EAAE,CAAC,EAAE,KAAK,EAAE,SAAS,CAAC,EAAE,EAAE,WAAW,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAe9H"}
|
package/dist/cjs/util.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.isDirectory = exports.isFile = exports.posixPath = exports.decodeFilename = exports.encodeFilename = exports.normalizeUnicode = exports.CHECKSUM_ALGOS = exports.STANDARD_BAG_INFO_HEADERS = exports.BAG_DECLARATION = exports.HASH_BLOCK_SIZE = exports.DEFAULT_CHECKSUMS = exports.VERSION = void 0;
|
|
4
|
+
exports.getHashers = getHashers;
|
|
5
|
+
exports.algorithmsFor = algorithmsFor;
|
|
6
|
+
exports.digestBytes = digestBytes;
|
|
7
|
+
exports.hashFile = hashFile;
|
|
8
|
+
exports.generateManifestLines = generateManifestLines;
|
|
9
|
+
exports.buildUnicodeNormalizedLookupDict = buildUnicodeNormalizedLookupDict;
|
|
10
|
+
exports.walkFiles = walkFiles;
|
|
11
|
+
exports.compareNames = compareNames;
|
|
12
|
+
exports.pathIsDangerous = pathIsDangerous;
|
|
13
|
+
exports.assertSafePath = assertSafePath;
|
|
14
|
+
exports.decodeText = decodeText;
|
|
15
|
+
exports.checkEncoding = checkEncoding;
|
|
16
|
+
exports.encodeText = encodeText;
|
|
17
|
+
exports.parseTagFile = parseTagFile;
|
|
18
|
+
exports.serializeTagFile = serializeTagFile;
|
|
19
|
+
exports.makeBagInfo = makeBagInfo;
|
|
20
|
+
exports.loadTagFile = loadTagFile;
|
|
21
|
+
exports.checkPermissions = checkPermissions;
|
|
22
|
+
exports.checkConcurrency = checkConcurrency;
|
|
23
|
+
exports.mapConcurrent = mapConcurrent;
|
|
24
|
+
const node_crypto_1 = require("node:crypto");
|
|
25
|
+
const node_fs_1 = require("node:fs");
|
|
26
|
+
const promises_1 = require("node:fs/promises");
|
|
27
|
+
const node_path_1 = require("node:path");
|
|
28
|
+
const errors_js_1 = require("./errors.js");
|
|
29
|
+
exports.VERSION = '1.1.0';
|
|
30
|
+
exports.DEFAULT_CHECKSUMS = Object.freeze(['sha256', 'sha512']);
|
|
31
|
+
exports.HASH_BLOCK_SIZE = 512 * 1024;
|
|
32
|
+
exports.BAG_DECLARATION = 'BagIt-Version: 1.0\nTag-File-Character-Encoding: UTF-8\n';
|
|
33
|
+
exports.STANDARD_BAG_INFO_HEADERS = Object.freeze([
|
|
34
|
+
'Source-Organization', 'Organization-Address', 'Contact-Name', 'Contact-Phone', 'Contact-Email',
|
|
35
|
+
'External-Description', 'External-Identifier', 'Bag-Size', 'Bag-Group-Identifier', 'Bag-Count',
|
|
36
|
+
'Internal-Sender-Identifier', 'Internal-Sender-Description', 'BagIt-Profile-Identifier',
|
|
37
|
+
]);
|
|
38
|
+
// Python's guaranteed fixed-length algorithms, mapped to OpenSSL names where necessary.
|
|
39
|
+
const HASH_NAMES = {
|
|
40
|
+
blake2b: 'blake2b512', blake2s: 'blake2s256',
|
|
41
|
+
sha3_224: 'sha3-224', sha3_256: 'sha3-256', sha3_384: 'sha3-384', sha3_512: 'sha3-512',
|
|
42
|
+
};
|
|
43
|
+
exports.CHECKSUM_ALGOS = Object.freeze([
|
|
44
|
+
'md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512',
|
|
45
|
+
'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', 'blake2b', 'blake2s',
|
|
46
|
+
]);
|
|
47
|
+
function getHashers(algorithms) {
|
|
48
|
+
const result = Object.create(null);
|
|
49
|
+
for (const alg of algorithms) {
|
|
50
|
+
if (!exports.CHECKSUM_ALGOS.includes(alg))
|
|
51
|
+
continue;
|
|
52
|
+
try {
|
|
53
|
+
result[alg] = (0, node_crypto_1.createHash)(HASH_NAMES[alg] ?? alg);
|
|
54
|
+
}
|
|
55
|
+
catch { /* unavailable in this OpenSSL build */ }
|
|
56
|
+
}
|
|
57
|
+
if (!Object.keys(result).length)
|
|
58
|
+
throw new errors_js_1.BagError('Unable to continue: no supported checksum algorithms were requested');
|
|
59
|
+
return result;
|
|
60
|
+
}
|
|
61
|
+
function algorithmsFor(algorithms = exports.DEFAULT_CHECKSUMS) {
|
|
62
|
+
return Object.keys(getHashers(algorithms));
|
|
63
|
+
}
|
|
64
|
+
function digestBytes(bytes, algorithms) {
|
|
65
|
+
return Object.fromEntries(Object.entries(getHashers(algorithms)).map(([a, h]) => [a, h.update(bytes).digest('hex')]));
|
|
66
|
+
}
|
|
67
|
+
async function hashFile(path, algorithms, signal) {
|
|
68
|
+
const hashers = getHashers(algorithms);
|
|
69
|
+
let bytes = 0n;
|
|
70
|
+
try {
|
|
71
|
+
for await (const block of (0, node_fs_1.createReadStream)(path, { highWaterMark: exports.HASH_BLOCK_SIZE, signal })) {
|
|
72
|
+
bytes += BigInt(block.length);
|
|
73
|
+
for (const hash of Object.values(hashers))
|
|
74
|
+
hash.update(block);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
signal?.throwIfAborted();
|
|
79
|
+
throw new errors_js_1.BagValidationError(`Could not read ${path}: ${String(error)}`, [], { cause: error });
|
|
80
|
+
}
|
|
81
|
+
return { hashes: Object.fromEntries(Object.entries(hashers).map(([a, h]) => [a, h.digest('hex')])), bytes };
|
|
82
|
+
}
|
|
83
|
+
async function generateManifestLines(filename, algorithms = exports.DEFAULT_CHECKSUMS, signal) {
|
|
84
|
+
const { hashes, bytes } = await hashFile(filename, algorithms, signal);
|
|
85
|
+
return Object.entries(hashes).map(([algorithm, digest]) => [algorithm, digest, filename, bytes]);
|
|
86
|
+
}
|
|
87
|
+
const normalizeUnicode = (s) => s.normalize('NFC');
|
|
88
|
+
exports.normalizeUnicode = normalizeUnicode;
|
|
89
|
+
function buildUnicodeNormalizedLookupDict(filenames) {
|
|
90
|
+
const result = Object.create(null);
|
|
91
|
+
for (const filename of filenames) {
|
|
92
|
+
const normalized = (0, exports.normalizeUnicode)(filename);
|
|
93
|
+
if (Object.hasOwn(result, normalized))
|
|
94
|
+
throw new errors_js_1.FileNormalizationConflict(filename, result[normalized]);
|
|
95
|
+
result[normalized] = filename;
|
|
96
|
+
}
|
|
97
|
+
return result;
|
|
98
|
+
}
|
|
99
|
+
const encodeFilename = (s) => s.replace(/\r/g, '%0D').replace(/\n/g, '%0A');
|
|
100
|
+
exports.encodeFilename = encodeFilename;
|
|
101
|
+
const decodeFilename = (s) => s.replace(/%0d/gi, '\r').replace(/%0a/gi, '\n');
|
|
102
|
+
exports.decodeFilename = decodeFilename;
|
|
103
|
+
const posixPath = (s) => s.split(node_path_1.sep).join('/');
|
|
104
|
+
exports.posixPath = posixPath;
|
|
105
|
+
const isFile = (p) => { try {
|
|
106
|
+
return (0, node_fs_1.statSync)(p).isFile();
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return false;
|
|
110
|
+
} };
|
|
111
|
+
exports.isFile = isFile;
|
|
112
|
+
const isDirectory = (p) => { try {
|
|
113
|
+
return (0, node_fs_1.statSync)(p).isDirectory();
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return false;
|
|
117
|
+
} };
|
|
118
|
+
exports.isDirectory = isDirectory;
|
|
119
|
+
/** Match os.walk: sorted files at each level, then sorted directories; do not follow directory symlinks. */
|
|
120
|
+
function* walkFiles(root, prefix = '') {
|
|
121
|
+
if (!(0, exports.isDirectory)(root))
|
|
122
|
+
return;
|
|
123
|
+
const entries = (0, node_fs_1.readdirSync)(root, { withFileTypes: true }).sort((a, b) => compareNames(a.name, b.name));
|
|
124
|
+
for (const e of entries) {
|
|
125
|
+
const p = (0, node_path_1.join)(root, e.name);
|
|
126
|
+
if (e.isFile() || (e.isSymbolicLink() && !(0, exports.isDirectory)(p)))
|
|
127
|
+
yield prefix + e.name;
|
|
128
|
+
}
|
|
129
|
+
for (const e of entries)
|
|
130
|
+
if (e.isDirectory())
|
|
131
|
+
yield* walkFiles((0, node_path_1.join)(root, e.name), `${prefix}${e.name}/`);
|
|
132
|
+
}
|
|
133
|
+
function compareNames(a, b) {
|
|
134
|
+
// Python sorts Unicode code points, whereas JavaScript's default sort uses UTF-16 code units.
|
|
135
|
+
const ac = Array.from(a, c => c.codePointAt(0));
|
|
136
|
+
const bc = Array.from(b, c => c.codePointAt(0));
|
|
137
|
+
for (let i = 0; i < Math.min(ac.length, bc.length); i++)
|
|
138
|
+
if (ac[i] !== bc[i])
|
|
139
|
+
return ac[i] - bc[i];
|
|
140
|
+
return ac.length - bc.length;
|
|
141
|
+
}
|
|
142
|
+
function canonicalMissingPath(path) {
|
|
143
|
+
if ((0, node_fs_1.existsSync)(path))
|
|
144
|
+
return (0, node_fs_1.realpathSync)(path);
|
|
145
|
+
const parent = (0, node_path_1.dirname)(path);
|
|
146
|
+
if (parent === path)
|
|
147
|
+
return path;
|
|
148
|
+
// realpath still detects symlinks in the existing part of an absent fetch target.
|
|
149
|
+
return (0, node_path_1.join)(canonicalMissingPath(parent), (0, node_path_1.relative)(parent, path));
|
|
150
|
+
}
|
|
151
|
+
function pathIsDangerous(root, filename) {
|
|
152
|
+
if (!filename || filename.includes('\0') || (0, node_path_1.isAbsolute)(filename) || node_path_1.win32.isAbsolute(filename) || filename.startsWith('~'))
|
|
153
|
+
return true;
|
|
154
|
+
const actual = canonicalMissingPath((0, node_path_1.resolve)(root, filename));
|
|
155
|
+
const rel = (0, node_path_1.relative)((0, node_fs_1.realpathSync)(root), actual);
|
|
156
|
+
return rel === '..' || rel.startsWith(`..${node_path_1.sep}`) || (0, node_path_1.isAbsolute)(rel);
|
|
157
|
+
}
|
|
158
|
+
function assertSafePath(root, filename, context = 'manifest') {
|
|
159
|
+
if (pathIsDangerous(root, filename))
|
|
160
|
+
throw new errors_js_1.BagError(`Path "${filename}" in ${context} is unsafe`);
|
|
161
|
+
}
|
|
162
|
+
function decodeText(bytes, encoding = 'utf-8') {
|
|
163
|
+
let label = encodingLabel(encoding);
|
|
164
|
+
if (label === 'utf-16') {
|
|
165
|
+
if (bytes[0] === 0xfe && bytes[1] === 0xff)
|
|
166
|
+
label = 'utf-16be';
|
|
167
|
+
else if (bytes[0] === 0xff && bytes[1] === 0xfe)
|
|
168
|
+
label = 'utf-16le';
|
|
169
|
+
else if (bytes.length)
|
|
170
|
+
throw new errors_js_1.BagValidationError('UTF-16 tag file must begin with a byte-order mark');
|
|
171
|
+
}
|
|
172
|
+
if (label === 'utf-8-sig')
|
|
173
|
+
return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
174
|
+
if (label === 'ascii' || label === 'us-ascii') {
|
|
175
|
+
if (bytes.some(b => b > 127))
|
|
176
|
+
throw new errors_js_1.BagValidationError('Non-ASCII byte in ASCII tag file');
|
|
177
|
+
return Buffer.from(bytes).toString('ascii');
|
|
178
|
+
}
|
|
179
|
+
// TextDecoder maps ISO-8859-1 to Windows-1252; Python uses the actual ISO mapping.
|
|
180
|
+
if (['latin-1', 'latin1', 'iso-8859-1'].includes(label))
|
|
181
|
+
return Buffer.from(bytes).toString('latin1');
|
|
182
|
+
try {
|
|
183
|
+
return new TextDecoder(label, { fatal: true }).decode(bytes);
|
|
184
|
+
}
|
|
185
|
+
catch (e) {
|
|
186
|
+
throw new errors_js_1.BagValidationError(`Cannot decode tag file as ${encoding}`, [], { cause: e });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
function checkEncoding(encoding) {
|
|
190
|
+
const label = encodingLabel(encoding);
|
|
191
|
+
if (['utf-8-sig', 'latin-1'].includes(label))
|
|
192
|
+
return;
|
|
193
|
+
try {
|
|
194
|
+
new TextDecoder(label);
|
|
195
|
+
}
|
|
196
|
+
catch {
|
|
197
|
+
throw new errors_js_1.BagValidationError(`Unsupported encoding: ${encoding}`);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function encodeText(text, encoding = 'utf-8') {
|
|
201
|
+
const label = encodingLabel(encoding);
|
|
202
|
+
if (['utf-8', 'utf8', 'utf-8-sig'].includes(label)) {
|
|
203
|
+
const bytes = Buffer.from(text, 'utf8');
|
|
204
|
+
return label === 'utf-8-sig' ? Buffer.concat([Buffer.from([0xef, 0xbb, 0xbf]), bytes]) : bytes;
|
|
205
|
+
}
|
|
206
|
+
if (['utf-16', 'utf-16le', 'utf-16-le', 'utf16le'].includes(label)) {
|
|
207
|
+
const bytes = Buffer.from(text, 'utf16le');
|
|
208
|
+
return label === 'utf-16' ? Buffer.concat([Buffer.from([0xff, 0xfe]), bytes]) : bytes;
|
|
209
|
+
}
|
|
210
|
+
if (['utf-16be', 'utf-16-be'].includes(label))
|
|
211
|
+
return Buffer.from(text, 'utf16le').swap16();
|
|
212
|
+
const table = new Map();
|
|
213
|
+
for (let b = 0; b < 256; b++) {
|
|
214
|
+
try {
|
|
215
|
+
const c = decodeText(Uint8Array.of(b), encoding);
|
|
216
|
+
if (c.length === 1 && !table.has(c))
|
|
217
|
+
table.set(c, b);
|
|
218
|
+
}
|
|
219
|
+
catch { /* invalid single byte */ }
|
|
220
|
+
}
|
|
221
|
+
const bytes = [];
|
|
222
|
+
for (const c of text) {
|
|
223
|
+
const b = table.get(c);
|
|
224
|
+
if (b === undefined)
|
|
225
|
+
throw new errors_js_1.BagError(`Cannot encode character ${JSON.stringify(c)} as ${encoding}`);
|
|
226
|
+
bytes.push(b);
|
|
227
|
+
}
|
|
228
|
+
return Buffer.from(bytes);
|
|
229
|
+
}
|
|
230
|
+
function encodingLabel(encoding) {
|
|
231
|
+
const label = encoding.toLowerCase().replace(/_/g, '-');
|
|
232
|
+
return { utf8: 'utf-8', utf16: 'utf-16', utf16le: 'utf-16le', utf16be: 'utf-16be', 'utf-16-le': 'utf-16le', 'utf-16-be': 'utf-16be' }[label] ?? label;
|
|
233
|
+
}
|
|
234
|
+
function parseTagFile(text, filename = 'tag file') {
|
|
235
|
+
const result = Object.create(null);
|
|
236
|
+
let key;
|
|
237
|
+
let value = '';
|
|
238
|
+
const emit = () => {
|
|
239
|
+
if (!key)
|
|
240
|
+
return;
|
|
241
|
+
const v = value.trim();
|
|
242
|
+
const prev = result[key];
|
|
243
|
+
result[key] = prev === undefined ? v : Array.isArray(prev) ? [...prev, v] : [prev, v];
|
|
244
|
+
};
|
|
245
|
+
for (const line of text.replace(/\r\n?/g, '\n').match(/[^\n]*\n|[^\n]+$/g) ?? []) {
|
|
246
|
+
if (!line.trim())
|
|
247
|
+
continue;
|
|
248
|
+
if (/^\s/.test(line) && key !== undefined)
|
|
249
|
+
value += line;
|
|
250
|
+
else {
|
|
251
|
+
emit();
|
|
252
|
+
const colon = line.indexOf(':');
|
|
253
|
+
if (colon < 0)
|
|
254
|
+
throw new errors_js_1.BagValidationError(`${filename} contains invalid tag: ${line.trim()}`);
|
|
255
|
+
key = line.slice(0, colon).trim();
|
|
256
|
+
value = line.slice(colon + 1);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
emit();
|
|
260
|
+
return result;
|
|
261
|
+
}
|
|
262
|
+
function serializeTagFile(info) {
|
|
263
|
+
let result = '';
|
|
264
|
+
for (const key of Object.keys(info).sort(compareNames)) {
|
|
265
|
+
if (!key || /[\r\n:]/.test(key))
|
|
266
|
+
throw new errors_js_1.BagError(`Invalid metadata field name: ${key}`);
|
|
267
|
+
const values = Array.isArray(info[key]) ? info[key] : [info[key]];
|
|
268
|
+
for (const value of values)
|
|
269
|
+
result += `${key}: ${String(value).replace(/[\r\n]/g, '')}\n`;
|
|
270
|
+
}
|
|
271
|
+
return result;
|
|
272
|
+
}
|
|
273
|
+
function makeBagInfo(info, bytes, files) {
|
|
274
|
+
const date = new Date();
|
|
275
|
+
const today = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
276
|
+
return parseTagFile(serializeTagFile({
|
|
277
|
+
'Bagging-Date': today,
|
|
278
|
+
'Bag-Software-Agent': `bagit-node v${exports.VERSION}`,
|
|
279
|
+
...info,
|
|
280
|
+
'Payload-Oxum': `${bytes}.${files}`,
|
|
281
|
+
}));
|
|
282
|
+
}
|
|
283
|
+
async function loadTagFile(path, encoding = 'utf-8') {
|
|
284
|
+
return parseTagFile(decodeText(await (0, promises_1.readFile)(path), encoding), path);
|
|
285
|
+
}
|
|
286
|
+
function checkPermissions(root, saving = false) {
|
|
287
|
+
try {
|
|
288
|
+
(0, node_fs_1.accessSync)(root, node_fs_1.constants.R_OK | node_fs_1.constants.W_OK | node_fs_1.constants.X_OK);
|
|
289
|
+
}
|
|
290
|
+
catch {
|
|
291
|
+
throw new errors_js_1.BagError(saving ? `Cannot save bag to non-existent or inaccessible directory ${root}` : 'Missing permissions to move all files and directories');
|
|
292
|
+
}
|
|
293
|
+
const dirs = [root];
|
|
294
|
+
const files = [];
|
|
295
|
+
// Finish the write check before reporting unreadable descendants, matching Python.
|
|
296
|
+
for (let i = 0; i < dirs.length; i++) {
|
|
297
|
+
const dir = dirs[i];
|
|
298
|
+
try {
|
|
299
|
+
(0, node_fs_1.accessSync)(dir, node_fs_1.constants.W_OK);
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
throw new errors_js_1.BagError('Missing permissions to move all files and directories');
|
|
303
|
+
}
|
|
304
|
+
let entries;
|
|
305
|
+
try {
|
|
306
|
+
entries = (0, node_fs_1.readdirSync)(dir, { withFileTypes: true });
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
throw new errors_js_1.BagError('Read permissions are required to calculate file fixities');
|
|
310
|
+
}
|
|
311
|
+
for (const e of entries) {
|
|
312
|
+
if (e.isDirectory())
|
|
313
|
+
dirs.push((0, node_path_1.join)(dir, e.name));
|
|
314
|
+
else
|
|
315
|
+
files.push((0, node_path_1.join)(dir, e.name));
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
for (const p of [...dirs, ...files]) {
|
|
319
|
+
try {
|
|
320
|
+
(0, node_fs_1.accessSync)(p, node_fs_1.constants.R_OK);
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
throw new errors_js_1.BagError('Read permissions are required to calculate file fixities');
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
function checkConcurrency(concurrency = 1) {
|
|
328
|
+
if (!Number.isSafeInteger(concurrency) || concurrency < 1)
|
|
329
|
+
throw new RangeError('concurrency must be a positive integer');
|
|
330
|
+
return concurrency;
|
|
331
|
+
}
|
|
332
|
+
async function mapConcurrent(items, concurrency, fn) {
|
|
333
|
+
const result = new Array(items.length);
|
|
334
|
+
let next = 0;
|
|
335
|
+
let failure;
|
|
336
|
+
let failed = false;
|
|
337
|
+
await Promise.all(Array.from({ length: Math.min(checkConcurrency(concurrency), items.length) }, async () => {
|
|
338
|
+
while (!failed) {
|
|
339
|
+
const i = next++;
|
|
340
|
+
if (i >= items.length)
|
|
341
|
+
return;
|
|
342
|
+
try {
|
|
343
|
+
result[i] = await fn(items[i]);
|
|
344
|
+
}
|
|
345
|
+
catch (error) {
|
|
346
|
+
failed = true;
|
|
347
|
+
failure = error;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
}));
|
|
351
|
+
if (failed)
|
|
352
|
+
throw failure;
|
|
353
|
+
return result;
|
|
354
|
+
}
|
|
355
|
+
//# sourceMappingURL=util.js.map
|
|
@@ -0,0 +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;AACD,gCAsBC;AAKD,oCAuBC;AACD,4CAQC;AACD,kCASC;AACD,kCAEC;AACD,4CAwBC;AACD,4CAGC;AACD,sCAeC;AAvPD,6CAAoD;AAC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AAC;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"]}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { Readable, type Writable } from 'node:stream';
|
|
2
|
+
import type { BagInfo, BagInfoInput, Checksums } from './types.js';
|
|
3
|
+
export interface BagZipOptions {
|
|
4
|
+
bagInfo?: BagInfoInput;
|
|
5
|
+
checksums?: readonly string[];
|
|
6
|
+
/** An optional directory containing the entire bag inside the archive. Default: archive root. */
|
|
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>;
|
|
10
|
+
/** Deflate level 0–9; default 6. */
|
|
11
|
+
compressionLevel?: number;
|
|
12
|
+
/** Temporary directory for payload manifests; payloads and custom tag files are never staged. */
|
|
13
|
+
tempDirectory?: string;
|
|
14
|
+
signal?: AbortSignal;
|
|
15
|
+
/** Fixed ZIP modification time for reproducible archives. */
|
|
16
|
+
mtime?: Date;
|
|
17
|
+
/** Called after a payload file has been completely read into the ZIP compressor. */
|
|
18
|
+
onProgress?: (progress: BagZipProgress) => void | Promise<void>;
|
|
19
|
+
}
|
|
20
|
+
export interface BagZipProgress {
|
|
21
|
+
path: string;
|
|
22
|
+
bytes: bigint;
|
|
23
|
+
hashes: Checksums;
|
|
24
|
+
totalBytes: bigint;
|
|
25
|
+
totalFiles: number;
|
|
26
|
+
}
|
|
27
|
+
export interface BagZipResult {
|
|
28
|
+
bytesWritten: bigint;
|
|
29
|
+
payloadBytes: bigint;
|
|
30
|
+
payloadFiles: number;
|
|
31
|
+
bagInfo: BagInfo;
|
|
32
|
+
}
|
|
33
|
+
/** Sources are opened lazily, one at a time. Payload paths are relative to data/; tagFiles paths are relative to the bag root. */
|
|
34
|
+
export interface BagZipEntry {
|
|
35
|
+
path: string;
|
|
36
|
+
/** Preserve an empty directory. Its open() function is ignored. */
|
|
37
|
+
directory?: boolean;
|
|
38
|
+
open: () => Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array> | Promise<Readable | AsyncIterable<Uint8Array> | Iterable<Uint8Array>>;
|
|
39
|
+
mtime?: Date;
|
|
40
|
+
mode?: number;
|
|
41
|
+
}
|
|
42
|
+
/** Pipe directly into an S3/Ceph multipart upload Body. Errors are emitted on the stream. */
|
|
43
|
+
export declare function createBagZipStream(directory: string, options?: BagZipOptions): Readable;
|
|
44
|
+
/** Stream a bag from lazy application-provided sources, without first creating a payload directory. */
|
|
45
|
+
export declare function createBagZipStreamFromEntries(entries: AsyncIterable<BagZipEntry> | Iterable<BagZipEntry>, options?: BagZipOptions): Readable;
|
|
46
|
+
/** Write an archive to a Writable, or atomically replace a path after successful completion. Ends the destination. */
|
|
47
|
+
export declare function folderToBagZip(directory: string, destination: string | Writable, options?: BagZipOptions): Promise<BagZipResult>;
|
|
48
|
+
export declare const folderToBagitZip: typeof folderToBagZip;
|
|
49
|
+
//# sourceMappingURL=zip.d.ts.map
|
|
@@ -0,0 +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,+GAA+G;IAC/G,QAAQ,CAAC,EAAE,QAAQ,CAAC,WAAW,CAAC,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;IAC9D,oCAAoC;IACpC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,iGAAiG;IACjG,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,6DAA6D;IAC7D,KAAK,CAAC,EAAE,IAAI,CAAC;IACb,oFAAoF;IACpF,UAAU,CAAC,EAAE,CAAC,QAAQ,EAAE,cAAc,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACjE;AACD,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb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