@ipab/bundle 0.0.0 → 0.1.0-rc.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/src/parsing.ts ADDED
@@ -0,0 +1,349 @@
1
+ import { isMap, isSeq, parseAllDocuments } from "yaml";
2
+ import { ContentBundleError } from "./errors.js";
3
+ import type { BundleManifest, ContentType } from "./types.js";
4
+
5
+ export function record(value: unknown): value is Record<string, unknown> {
6
+ return value !== null && typeof value === "object" && !Array.isArray(value);
7
+ }
8
+
9
+ export function safePath(path: string): string {
10
+ if (
11
+ !path ||
12
+ path.length > 1024 ||
13
+ path.split("/").some((part) => !part || part === "." || part === "..") ||
14
+ /[\\:%?#]/u.test(path) ||
15
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(
16
+ path,
17
+ ) ||
18
+ [...path].some(
19
+ (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127,
20
+ )
21
+ )
22
+ throw new ContentBundleError(
23
+ "PATH_INVALID",
24
+ "Unsafe bundle-relative path.",
25
+ path,
26
+ );
27
+ return path;
28
+ }
29
+
30
+ export function assertJson(
31
+ value: unknown,
32
+ maximumNodes = 100_000,
33
+ maximumDepth = 64,
34
+ charge: () => void = () => {},
35
+ ): void {
36
+ jsonLimits(maximumNodes, maximumDepth);
37
+ const ancestors = new Set<object>();
38
+ let nodes = 0;
39
+ const visit = (item: unknown, depth: number): void => {
40
+ charge();
41
+ if (++nodes > maximumNodes || depth > maximumDepth)
42
+ throw new ContentBundleError(
43
+ "LIMIT_EXCEEDED",
44
+ "JSON value exceeds node/depth limits.",
45
+ );
46
+ if (typeof item === "string") {
47
+ if (
48
+ /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(
49
+ item,
50
+ )
51
+ )
52
+ throw new ContentBundleError(
53
+ "CONTENT_INVALID",
54
+ "Invalid Unicode surrogate.",
55
+ );
56
+ return;
57
+ }
58
+ if (item === null || typeof item === "boolean") return;
59
+ if (
60
+ typeof item === "number" &&
61
+ Number.isFinite(item) &&
62
+ (!Number.isInteger(item) || Number.isSafeInteger(item))
63
+ )
64
+ return;
65
+ if (
66
+ typeof item !== "object" ||
67
+ ancestors.has(item) ||
68
+ (!Array.isArray(item) &&
69
+ Object.getPrototypeOf(item) !== Object.prototype &&
70
+ Object.getPrototypeOf(item) !== null)
71
+ )
72
+ throw new ContentBundleError(
73
+ "CONTENT_INVALID",
74
+ "Expected finite, acyclic JSON-compatible data with safe integers.",
75
+ );
76
+ ancestors.add(item);
77
+ if (
78
+ Array.isArray(item) &&
79
+ (Object.keys(item).length !== item.length ||
80
+ Object.keys(item).some((key, index) => key !== String(index)))
81
+ )
82
+ throw new ContentBundleError(
83
+ "CONTENT_INVALID",
84
+ "Expected a dense JSON array without extra properties.",
85
+ );
86
+ for (const [key, child] of Object.entries(item)) {
87
+ if (!Array.isArray(item)) visit(key, depth + 1);
88
+ visit(child, depth + 1);
89
+ }
90
+ ancestors.delete(item);
91
+ };
92
+ visit(value, 0);
93
+ }
94
+
95
+ function jsonLimits(nodes: number, depth: number): void {
96
+ if (
97
+ ![nodes, depth].every((value) => Number.isSafeInteger(value) && value > 0)
98
+ )
99
+ throw new ContentBundleError(
100
+ "OPTIONS_INVALID",
101
+ "JSON limits must be positive safe integers.",
102
+ );
103
+ }
104
+
105
+ function json(source: string, maximumDepth: number): unknown {
106
+ let offset = 0;
107
+ const space = () => {
108
+ while (/[ \t\r\n]/u.test(source[offset] ?? "") && offset < source.length)
109
+ offset++;
110
+ };
111
+ const string = (): string => {
112
+ const start = offset++;
113
+ while (offset < source.length) {
114
+ const char = source[offset++];
115
+ if (char === "\\") offset++;
116
+ else if (char === '"')
117
+ return JSON.parse(source.slice(start, offset)) as string;
118
+ }
119
+ throw new Error("Unterminated JSON string.");
120
+ };
121
+ const value = (depth: number): unknown => {
122
+ if (depth > maximumDepth)
123
+ throw new ContentBundleError("LIMIT_EXCEEDED", "JSON depth exceeded.");
124
+ space();
125
+ const char = source[offset];
126
+ if (char === '"') return string();
127
+ if (char === "{" || char === "[") {
128
+ offset++;
129
+ const object: Record<string, unknown> = Object.create(null) as Record<
130
+ string,
131
+ unknown
132
+ >;
133
+ const array: unknown[] = [];
134
+ const close = char === "{" ? "}" : "]";
135
+ space();
136
+ if (source[offset] === close) {
137
+ offset++;
138
+ return char === "{" ? object : array;
139
+ }
140
+ for (;;) {
141
+ if (char === "{") {
142
+ space();
143
+ if (source[offset] !== '"') throw new Error("Expected JSON key.");
144
+ const key = string();
145
+ if (Object.hasOwn(object, key))
146
+ throw new Error("Duplicate JSON key.");
147
+ space();
148
+ if (source[offset++] !== ":") throw new Error("Expected colon.");
149
+ object[key] = value(depth + 1);
150
+ } else array.push(value(depth + 1));
151
+ space();
152
+ const next = source[offset++];
153
+ if (next === close) return char === "{" ? object : array;
154
+ if (next !== ",") throw new Error("Expected comma.");
155
+ }
156
+ }
157
+ const token =
158
+ /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/u.exec(
159
+ source.slice(offset),
160
+ );
161
+ if (!token) throw new Error("Invalid JSON token.");
162
+ offset += token[0].length;
163
+ return JSON.parse(token[0]) as unknown;
164
+ };
165
+ const result = value(0);
166
+ space();
167
+ if (offset !== source.length) throw new Error("Trailing JSON input.");
168
+ return result;
169
+ }
170
+
171
+ export function canonicalJson(
172
+ value: unknown,
173
+ nodes = 100_000,
174
+ depth = 64,
175
+ charge: () => void = () => {},
176
+ ): Uint8Array {
177
+ assertJson(value, nodes, depth, charge);
178
+ const serialize = (item: unknown): string => {
179
+ if (Array.isArray(item)) return `[${item.map(serialize).join(",")}]`;
180
+ if (record(item))
181
+ return `{${Object.keys(item)
182
+ .sort()
183
+ .map((key) => `${JSON.stringify(key)}:${serialize(item[key])}`)
184
+ .join(",")}}`;
185
+ return JSON.stringify(item);
186
+ };
187
+ return new TextEncoder().encode(serialize(value));
188
+ }
189
+
190
+ export function parseData(
191
+ bytes: Uint8Array,
192
+ type: ContentType,
193
+ nodes = 100_000,
194
+ depth = 64,
195
+ charge: () => void = () => {},
196
+ ): unknown {
197
+ jsonLimits(nodes, depth);
198
+ try {
199
+ const source = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
200
+ let value: unknown;
201
+ if (type === "application/json") value = json(source, depth);
202
+ else if (type === "application/jsonl") {
203
+ const lines = source.split("\n");
204
+ if (lines.at(-1) === "") lines.pop();
205
+ value = lines.map((line, index): unknown => {
206
+ try {
207
+ return json(line, depth);
208
+ } catch (cause) {
209
+ const failure =
210
+ cause instanceof ContentBundleError ? cause : undefined;
211
+ throw new ContentBundleError(
212
+ failure?.code ?? "CONTENT_INVALID",
213
+ failure
214
+ ? `${failure.message} (JSONL line ${String(index + 1)}).`
215
+ : `Invalid JSONL at line ${String(index + 1)}.`,
216
+ failure?.path ?? "",
217
+ `/${String(index)}${failure?.pointer ?? ""}`,
218
+ failure?.referenceChain ?? [],
219
+ { cause },
220
+ );
221
+ }
222
+ });
223
+ } else {
224
+ const documents = parseAllDocuments(source, {
225
+ schema: "core",
226
+ uniqueKeys: true,
227
+ });
228
+ if (documents.length !== 1)
229
+ throw new ContentBundleError(
230
+ "CONTENT_INVALID",
231
+ "Expected one YAML document.",
232
+ );
233
+ const document = documents[0]!;
234
+ const issue = document.errors[0] ?? document.warnings[0];
235
+ if (issue) throw new ContentBundleError("CONTENT_INVALID", issue.message);
236
+ let visited = 0;
237
+ const inspect = (node: unknown, level: number): void => {
238
+ charge();
239
+ if (++visited > nodes || level > depth)
240
+ throw new ContentBundleError(
241
+ "LIMIT_EXCEEDED",
242
+ "YAML value exceeds node/depth limits.",
243
+ );
244
+ if (isMap(node))
245
+ for (const pair of node.items) {
246
+ inspect(pair.key, level + 1);
247
+ inspect(pair.value, level + 1);
248
+ }
249
+ else if (isSeq(node))
250
+ for (const child of node.items) inspect(child, level + 1);
251
+ };
252
+ inspect(document.contents, 0);
253
+ value = document.toJS({ maxAliasCount: 100 });
254
+ }
255
+ assertJson(value, nodes, depth, charge);
256
+ return value;
257
+ } catch (cause) {
258
+ if (cause instanceof ContentBundleError) throw cause;
259
+ throw new ContentBundleError(
260
+ "CONTENT_INVALID",
261
+ "Invalid UTF-8 or document syntax.",
262
+ "",
263
+ "",
264
+ [],
265
+ { cause },
266
+ );
267
+ }
268
+ }
269
+
270
+ export function normalizeBundleManifest(value: unknown): BundleManifest {
271
+ if (
272
+ !record(value) ||
273
+ Object.keys(value).some(
274
+ (key) => !["name", "description", "entry"].includes(key),
275
+ ) ||
276
+ typeof value.name !== "string" ||
277
+ !value.name.trim() ||
278
+ (value.description !== undefined &&
279
+ typeof value.description !== "string") ||
280
+ !record(value.entry) ||
281
+ Object.keys(value.entry).some(
282
+ (key) => !["path", "schema", "contentType", "defaultValue"].includes(key),
283
+ )
284
+ )
285
+ throw new Error(
286
+ "Expected name, optional description and a complete entry definition.",
287
+ );
288
+ const { path, schema, contentType, defaultValue } = value.entry;
289
+ if (
290
+ typeof path !== "string" ||
291
+ (typeof schema !== "boolean" && !record(schema)) ||
292
+ !Object.hasOwn(value.entry, "defaultValue")
293
+ )
294
+ throw new Error(
295
+ "Entry requires path, schema, contentType and defaultValue.",
296
+ );
297
+ safePath(path);
298
+ if (
299
+ [".bundle.yaml", ".bundle-ignore"].some(
300
+ (control) => path === control || path.startsWith(`${control}/`),
301
+ )
302
+ )
303
+ throw new Error("Entry path conflicts with a bundle control file.");
304
+ if (
305
+ contentType !== "application/json" &&
306
+ contentType !== "application/yaml" &&
307
+ contentType !== "application/jsonl"
308
+ )
309
+ throw new Error("Unsupported content type.");
310
+ if (contentType === "application/jsonl" && !Array.isArray(defaultValue))
311
+ throw new Error("JSONL defaultValue must be an array.");
312
+ return Object.freeze({
313
+ name: value.name,
314
+ description: value.description ?? "",
315
+ entry: Object.freeze({
316
+ path,
317
+ schema,
318
+ contentType,
319
+ defaultValue,
320
+ } satisfies BundleManifest["entry"]),
321
+ });
322
+ }
323
+
324
+ export function parseBundleManifest(
325
+ bytes: Uint8Array,
326
+ maximum = 64 * 1024 * 1024,
327
+ charge: () => void = () => {},
328
+ ): BundleManifest {
329
+ if (bytes.byteLength > maximum)
330
+ throw new ContentBundleError(
331
+ "LIMIT_EXCEEDED",
332
+ "Bundle manifest exceeds its parsing byte limit.",
333
+ );
334
+ try {
335
+ const value = parseData(bytes, "application/yaml", 100_000, 64, charge);
336
+ return normalizeBundleManifest(value);
337
+ } catch (cause) {
338
+ if (cause instanceof ContentBundleError && cause.code === "LIMIT_EXCEEDED")
339
+ throw cause;
340
+ throw new ContentBundleError(
341
+ "MANIFEST_INVALID",
342
+ `Invalid .bundle.yaml: ${cause instanceof Error ? cause.message : "invalid data"}`,
343
+ ".bundle.yaml",
344
+ "",
345
+ [],
346
+ { cause },
347
+ );
348
+ }
349
+ }