@ipab/bundle 0.0.0 → 0.1.0-rc.1

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/src/bundle.ts ADDED
@@ -0,0 +1,444 @@
1
+ import { ContentError, IpfsStore, openContent } from "@ipab/ipfs-store";
2
+ import type { UnixfsNode } from "@ipab/ipfs-store";
3
+ import { CID } from "multiformats/cid";
4
+ import { ContentBundleError } from "./errors.js";
5
+ import {
6
+ entryValidation,
7
+ parseBundleManifest,
8
+ parseData,
9
+ safePath,
10
+ } from "./parsing.js";
11
+ import {
12
+ decodeSchema,
13
+ encodeSchema,
14
+ schemaBlockBytes,
15
+ validateValue,
16
+ } from "./schema.js";
17
+ import type {
18
+ BundleLimits,
19
+ ContentBundle,
20
+ OpenBundleOptions,
21
+ SchemaBlock,
22
+ } from "./types.js";
23
+
24
+ export const bundleLimits: Readonly<BundleLimits> = Object.freeze({
25
+ bytes: 64 * 1024 * 1024,
26
+ blocks: 16_384,
27
+ blockBytes: 2 * 1024 * 1024,
28
+ parsingBytes: 64 * 1024 * 1024,
29
+ files: 2048,
30
+ depth: 64,
31
+ jsonDepth: 64,
32
+ validationDepth: 64,
33
+ manifestBytes: 64 * 1024 * 1024,
34
+ schemaBytes: schemaBlockBytes,
35
+ documentBytes: 8 * 1024 * 1024,
36
+ nodes: 100_000,
37
+ });
38
+ export function resolveBundleLimits(
39
+ overrides: Partial<BundleLimits> = {},
40
+ ): BundleLimits {
41
+ const limits = { ...bundleLimits, ...overrides };
42
+ for (const [key, value] of Object.entries(limits))
43
+ if (
44
+ !Object.hasOwn(bundleLimits, key) ||
45
+ !Number.isSafeInteger(value) ||
46
+ value <= 0
47
+ )
48
+ throw new ContentBundleError(
49
+ "OPTIONS_INVALID",
50
+ "Limits must be known positive safe integers.",
51
+ );
52
+ return limits;
53
+ }
54
+ function contextual(
55
+ cause: unknown,
56
+ path: string,
57
+ pointer = "",
58
+ chain: readonly string[] = [],
59
+ signal?: AbortSignal,
60
+ ): ContentBundleError {
61
+ if (cause instanceof ContentBundleError)
62
+ return new ContentBundleError(
63
+ cause.code,
64
+ cause.message,
65
+ cause.path || path,
66
+ cause.pointer || pointer,
67
+ [...chain, ...cause.referenceChain],
68
+ { cause },
69
+ );
70
+ const capacity =
71
+ (cause instanceof ContentError && cause.code === "capacity_exceeded") ||
72
+ (cause instanceof Error && /capacity exceeded/u.test(cause.message));
73
+ return new ContentBundleError(
74
+ signal?.aborted
75
+ ? "ABORTED"
76
+ : capacity
77
+ ? "LIMIT_EXCEEDED"
78
+ : "CONTENT_UNAVAILABLE",
79
+ "Cannot read or verify bundle content.",
80
+ path,
81
+ pointer,
82
+ chain,
83
+ { cause },
84
+ );
85
+ }
86
+ async function collect(node: UnixfsNode, maximum: number): Promise<Uint8Array> {
87
+ if (node.type === "directory")
88
+ throw new ContentBundleError("CONTENT_INVALID", "Expected a regular file.");
89
+ if (node.size > BigInt(maximum))
90
+ throw new ContentBundleError(
91
+ "LIMIT_EXCEEDED",
92
+ "File exceeds its parsing byte limit.",
93
+ );
94
+ const parts: Uint8Array[] = [];
95
+ let length = 0;
96
+ for await (const part of node.content()) {
97
+ length += part.byteLength;
98
+ if (length > maximum)
99
+ throw new ContentBundleError(
100
+ "LIMIT_EXCEEDED",
101
+ "File exceeds its parsing byte limit.",
102
+ );
103
+ parts.push(part);
104
+ }
105
+ const bytes = new Uint8Array(length);
106
+ let offset = 0;
107
+ for (const part of parts) {
108
+ bytes.set(part, offset);
109
+ offset += part.byteLength;
110
+ }
111
+ return bytes;
112
+ }
113
+ function reader(
114
+ root: CID,
115
+ files: ReadonlySet<string>,
116
+ source: OpenBundleOptions,
117
+ limits: BundleLimits,
118
+ ): ContentBundle["readFile"] {
119
+ return async (path, request = {}) => {
120
+ safePath(path);
121
+ if (!files.has(path))
122
+ throw new ContentBundleError(
123
+ "CONTENT_UNAVAILABLE",
124
+ "Bundle file does not exist.",
125
+ path,
126
+ );
127
+ const lifetime = new AbortController();
128
+ const signal = request.signal
129
+ ? AbortSignal.any([request.signal, lifetime.signal])
130
+ : lifetime.signal;
131
+ let node: Awaited<ReturnType<typeof openContent>>;
132
+ const seen = new Set<string>();
133
+ let bytesRead = 0;
134
+ try {
135
+ node = await openContent(
136
+ {
137
+ block: {
138
+ get: async (value, options) => {
139
+ const cid = CID.parse(value);
140
+ const bytes = await source.resolveCid(cid, options ?? {});
141
+ const key = cid.toV1().toString();
142
+ if (!seen.has(key)) {
143
+ seen.add(key);
144
+ bytesRead += bytes.byteLength;
145
+ if (bytesRead > limits.bytes || seen.size > limits.blocks)
146
+ throw new ContentBundleError(
147
+ "LIMIT_EXCEEDED",
148
+ "File stream block/byte budget exceeded.",
149
+ path,
150
+ );
151
+ }
152
+ return bytes;
153
+ },
154
+ },
155
+ },
156
+ `${root.toString()}/${path}`,
157
+ {
158
+ cacheBlocks: false,
159
+ signal,
160
+ retainedBlocks: new Map(),
161
+ retentionBudget: { bytes: 0, limit: limits.bytes },
162
+ maxBlockBytes: limits.blockBytes,
163
+ maxDagBlocks: limits.blocks,
164
+ depth: limits.depth,
165
+ },
166
+ );
167
+ if (node.type !== "raw" && node.type !== "file")
168
+ throw new ContentBundleError(
169
+ "CONTENT_INVALID",
170
+ "Expected a file.",
171
+ path,
172
+ );
173
+ } catch (cause) {
174
+ throw contextual(cause, path, "", [], signal);
175
+ }
176
+ const iterator = node.content()[Symbol.asyncIterator]();
177
+ let finished = false;
178
+ const release = async () => {
179
+ if (!finished) {
180
+ finished = true;
181
+ lifetime.abort();
182
+ await iterator.return();
183
+ }
184
+ };
185
+ return new ReadableStream<Uint8Array>(
186
+ {
187
+ async pull(controller) {
188
+ try {
189
+ signal.throwIfAborted();
190
+ const part = await iterator.next();
191
+ if (part.done) {
192
+ await release();
193
+ controller.close();
194
+ } else controller.enqueue(Uint8Array.from(part.value));
195
+ } catch (cause) {
196
+ const error = contextual(cause, path, "", [], signal);
197
+ try {
198
+ await release();
199
+ } finally {
200
+ controller.error(error);
201
+ }
202
+ }
203
+ },
204
+ cancel: release,
205
+ },
206
+ { highWaterMark: 0 },
207
+ );
208
+ };
209
+ }
210
+
211
+ async function operation(
212
+ rootCid: CID,
213
+ options: OpenBundleOptions,
214
+ expected?: SchemaBlock,
215
+ ): Promise<ContentBundle> {
216
+ const limits = resolveBundleLimits(options.limits);
217
+ if (typeof options.resolveCid !== "function")
218
+ throw new ContentBundleError(
219
+ "OPTIONS_INVALID",
220
+ "A CID block resolver is required.",
221
+ );
222
+ const cid = CID.decode(Uint8Array.from(rootCid.bytes));
223
+ if (cid.code !== 0x70)
224
+ throw new ContentBundleError(
225
+ "CONTENT_INVALID",
226
+ "Bundle root must be a UnixFS directory CID.",
227
+ );
228
+ const store = IpfsStore.fromClient(
229
+ {
230
+ block: {
231
+ get: async (value, request) =>
232
+ options.resolveCid(CID.parse(value), request ?? {}),
233
+ },
234
+ },
235
+ {
236
+ bytes: limits.bytes,
237
+ blocks: limits.blocks,
238
+ blockBytes: limits.blockBytes,
239
+ depth: limits.depth,
240
+ },
241
+ );
242
+ const request = options.signal ? { signal: options.signal } : {};
243
+ const files = new Set<string>();
244
+ const directories = new Set<string>();
245
+ let parsed = 0,
246
+ work = 0;
247
+ const charge = () => {
248
+ if (options.signal?.aborted)
249
+ throw new ContentBundleError(
250
+ "ABORTED",
251
+ "Bundle validation cancelled.",
252
+ "",
253
+ "",
254
+ [],
255
+ { cause: options.signal.reason },
256
+ );
257
+ if (++work > limits.nodes)
258
+ throw new ContentBundleError(
259
+ "LIMIT_EXCEEDED",
260
+ "Schema/data work budget exceeded.",
261
+ );
262
+ };
263
+ const join = (base: string, path: string) =>
264
+ base ? `${base}/${safePath(path)}` : safePath(path);
265
+ const read = (path: string) =>
266
+ store.read(path ? `${cid.toString()}/${path}` : cid, request);
267
+ const bytesAt = async (path: string, maximum: number) => {
268
+ if (!files.has(path))
269
+ throw new ContentBundleError(
270
+ "CONTENT_UNAVAILABLE",
271
+ "Bundle file does not exist.",
272
+ path,
273
+ );
274
+ const bytes = await collect(await read(path), maximum);
275
+ parsed += bytes.byteLength;
276
+ if (parsed > limits.parsingBytes)
277
+ throw new ContentBundleError(
278
+ "LIMIT_EXCEEDED",
279
+ "Parsing byte budget exceeded.",
280
+ path,
281
+ );
282
+ return bytes;
283
+ };
284
+ const index = async (path: string, depth: number): Promise<void> => {
285
+ charge();
286
+ if (depth > limits.depth)
287
+ throw new ContentBundleError(
288
+ "LIMIT_EXCEEDED",
289
+ "Tree depth exceeded.",
290
+ path,
291
+ );
292
+ const node = await read(path);
293
+ if (node.type === "directory") {
294
+ if (directories.has(path))
295
+ throw new ContentBundleError(
296
+ "PATH_INVALID",
297
+ "Duplicate directory.",
298
+ path,
299
+ );
300
+ directories.add(path);
301
+ for await (const child of node.entries()) {
302
+ if (child.name.includes("/"))
303
+ throw new ContentBundleError(
304
+ "PATH_INVALID",
305
+ "Unsafe directory name.",
306
+ path,
307
+ );
308
+ await index(join(path, child.name), depth + 1);
309
+ }
310
+ } else {
311
+ if (!path || files.has(path))
312
+ throw new ContentBundleError(
313
+ "PATH_INVALID",
314
+ "Invalid or duplicate file.",
315
+ path,
316
+ );
317
+ if (files.size >= limits.files)
318
+ throw new ContentBundleError(
319
+ "LIMIT_EXCEEDED",
320
+ "File count exceeded.",
321
+ path,
322
+ );
323
+ files.add(path);
324
+ }
325
+ };
326
+ try {
327
+ await store.prepare(cid, request);
328
+ await index("", 0);
329
+ const manifest = parseBundleManifest(
330
+ await bytesAt(".bundle.yaml", limits.manifestBytes),
331
+ limits.manifestBytes,
332
+ charge,
333
+ );
334
+ const schema = await encodeSchema(manifest, {
335
+ nodes: limits.nodes,
336
+ depth: limits.validationDepth,
337
+ jsonDepth: limits.jsonDepth,
338
+ schemaBytes: limits.schemaBytes,
339
+ charge,
340
+ });
341
+ if (expected && !schema.cid.equals(expected.cid))
342
+ throw new ContentBundleError(
343
+ "SCHEMA_INVALID",
344
+ "Schema CID differs from the explicit validator.",
345
+ );
346
+ const path = manifest.entry.path;
347
+ const validation = entryValidation(manifest.entry);
348
+ try {
349
+ const bytes = await bytesAt(path, limits.documentBytes);
350
+ if (validation.status !== "unsupported") {
351
+ const value = parseData(
352
+ bytes,
353
+ manifest.entry.contentType.toLowerCase(),
354
+ limits.nodes,
355
+ limits.jsonDepth,
356
+ charge,
357
+ );
358
+ if (manifest.entry.schema !== undefined)
359
+ validateValue(schema, value, {
360
+ charge,
361
+ depth: limits.validationDepth,
362
+ });
363
+ }
364
+ } catch (cause) {
365
+ throw contextual(cause, path, "", [], options.signal);
366
+ }
367
+ return Object.freeze({
368
+ kind: "content",
369
+ get cid() {
370
+ return CID.decode(Uint8Array.from(cid.bytes));
371
+ },
372
+ manifest,
373
+ schemaKey: schema.cid.toString(),
374
+ schema,
375
+ validation,
376
+ readFile: reader(cid, files, options, limits),
377
+ });
378
+ } catch (cause) {
379
+ throw contextual(cause, cid.toString(), "", [], options.signal);
380
+ } finally {
381
+ await store.close();
382
+ }
383
+ }
384
+ export async function openBundle(
385
+ root: CID,
386
+ options: OpenBundleOptions,
387
+ ): Promise<ContentBundle> {
388
+ return operation(root, options);
389
+ }
390
+ export async function openSchema(
391
+ root: CID,
392
+ options: OpenBundleOptions,
393
+ ): Promise<SchemaBlock> {
394
+ const limits = resolveBundleLimits(options.limits);
395
+ if (typeof options.resolveCid !== "function")
396
+ throw new ContentBundleError(
397
+ "OPTIONS_INVALID",
398
+ "A CID block resolver is required.",
399
+ );
400
+ if (root.version !== 1 || root.code !== 0x71 || root.multihash.code !== 0x12)
401
+ throw new ContentBundleError(
402
+ "SCHEMA_INVALID",
403
+ "Schema must be a CIDv1 DAG-CBOR SHA-256 block.",
404
+ );
405
+ let work = 0;
406
+ try {
407
+ options.signal?.throwIfAborted();
408
+ const bytes = await options.resolveCid(
409
+ root,
410
+ options.signal ? { signal: options.signal } : {},
411
+ );
412
+ if (
413
+ bytes.length >
414
+ Math.min(limits.blockBytes, limits.bytes, limits.parsingBytes)
415
+ )
416
+ throw new ContentBundleError(
417
+ "LIMIT_EXCEEDED",
418
+ "Schema read byte budget exceeded.",
419
+ );
420
+ return await decodeSchema(root, bytes, {
421
+ nodes: limits.nodes,
422
+ depth: limits.validationDepth,
423
+ jsonDepth: limits.jsonDepth,
424
+ schemaBytes: limits.schemaBytes,
425
+ charge() {
426
+ options.signal?.throwIfAborted();
427
+ if (++work > limits.nodes)
428
+ throw new ContentBundleError(
429
+ "LIMIT_EXCEEDED",
430
+ "Schema work budget exceeded.",
431
+ );
432
+ },
433
+ });
434
+ } catch (cause) {
435
+ throw contextual(cause, root.toString(), "", [], options.signal);
436
+ }
437
+ }
438
+ export async function validateContentBundle(
439
+ root: CID,
440
+ schema: SchemaBlock,
441
+ options: OpenBundleOptions,
442
+ ): Promise<ContentBundle> {
443
+ return operation(root, options, schema);
444
+ }
package/src/data.ts ADDED
@@ -0,0 +1,18 @@
1
+ export {
2
+ parseBundleManifest,
3
+ parseData,
4
+ canonicalJson,
5
+ safePath,
6
+ } from "./parsing.js";
7
+ export {
8
+ encodeSchema,
9
+ inspectSchema,
10
+ schemaDialect,
11
+ validateValue as validateSchemaValue,
12
+ } from "./schema.js";
13
+ export type { SchemaOptions, ValidationContext } from "./schema.js";
14
+ export type {
15
+ BundleManifest,
16
+ SchemaDefinitions,
17
+ SchemaBlock,
18
+ } from "./types.js";
package/src/errors.ts ADDED
@@ -0,0 +1,16 @@
1
+ import type { ContentBundleErrorCode } from "./types.js";
2
+
3
+ export class ContentBundleError extends Error {
4
+ override readonly name = "ContentBundleError";
5
+
6
+ constructor(
7
+ readonly code: ContentBundleErrorCode,
8
+ message: string,
9
+ readonly path = "",
10
+ readonly pointer = "",
11
+ readonly referenceChain: readonly string[] = [],
12
+ options?: ErrorOptions,
13
+ ) {
14
+ super(message, options);
15
+ }
16
+ }
package/src/index.ts ADDED
@@ -0,0 +1,37 @@
1
+ export {
2
+ openBundle,
3
+ openSchema,
4
+ validateContentBundle,
5
+ bundleLimits,
6
+ resolveBundleLimits,
7
+ } from "./bundle.js";
8
+ export {
9
+ parseBundleManifest,
10
+ parseData,
11
+ canonicalJson,
12
+ safePath,
13
+ } from "./parsing.js";
14
+ export {
15
+ inspectSchema,
16
+ inspectBundleSchema,
17
+ encodeSchema,
18
+ decodeSchema,
19
+ schemaBlockBytes,
20
+ schemaDialect,
21
+ declaresBundleSchema,
22
+ validateValue as validateSchemaValue,
23
+ } from "./schema.js";
24
+ export type { SchemaOptions, ValidationContext } from "./schema.js";
25
+ export { ContentBundleError } from "./errors.js";
26
+ export type {
27
+ ContentBundle,
28
+ EntryValidation,
29
+ OpenBundleOptions,
30
+ BundleLimits,
31
+ BundleManifest,
32
+ ContentType,
33
+ JsonSchema,
34
+ SchemaBlock,
35
+ SchemaDefinitions,
36
+ ContentBundleErrorCode,
37
+ } from "./types.js";