@3leaps/yamlprims 0.0.0-stage → 0.1.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/LICENSE-APACHE +190 -0
- package/LICENSE-MIT +21 -0
- package/NOTICE +12 -0
- package/README.md +20 -2
- package/dist/index.d.ts +230 -0
- package/dist/index.js +2275 -0
- package/dist/wasm.d.ts +1 -0
- package/dist/wasm.js +2 -0
- package/package.json +41 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,2275 @@
|
|
|
1
|
+
// SPDX-License-Identifier: MIT OR Apache-2.0
|
|
2
|
+
import { WASM_BASE64 } from "./wasm.js";
|
|
3
|
+
function wasmBytes() {
|
|
4
|
+
const g = globalThis;
|
|
5
|
+
if (typeof g.atob !== "function") {
|
|
6
|
+
throw new Error("yamlprims: atob is unavailable");
|
|
7
|
+
}
|
|
8
|
+
const raw = g.atob(WASM_BASE64);
|
|
9
|
+
const out = new Uint8Array(raw.length);
|
|
10
|
+
for (let i = 0; i < raw.length; i++) {
|
|
11
|
+
out[i] = raw.charCodeAt(i);
|
|
12
|
+
}
|
|
13
|
+
return out;
|
|
14
|
+
}
|
|
15
|
+
export const ABI_VERSION = 1;
|
|
16
|
+
export const MAX_OPTIONS_BYTES = 64 * 1024;
|
|
17
|
+
export const MAX_WASM_INPUT_CEILING = 64 * 1024 * 1024;
|
|
18
|
+
export const MAX_WASM_MEMORY_BYTES = 128 * 1024 * 1024;
|
|
19
|
+
export const MAX_WASM_MEMORY_PAGES = 2048;
|
|
20
|
+
export const WASM_HIGH_WATER_RECYCLE_BYTES = 16 * 1024 * 1024;
|
|
21
|
+
export const MAX_SAFE_METADATA_INT = 9_007_199_254_740_991; // 2^53 - 1
|
|
22
|
+
export const I128_MIN = -170141183460469231731687303715884105728n;
|
|
23
|
+
export const I128_MAX = 170141183460469231731687303715884105727n;
|
|
24
|
+
export const U128_MAX = 340282366920938463463374607431768211455n;
|
|
25
|
+
const CANONICAL_NAN_BITS = "7ff8000000000000";
|
|
26
|
+
const CANONICAL_NAN_BIGINT = 0x7ff8000000000000n;
|
|
27
|
+
const NODE_OVERHEAD = 64n;
|
|
28
|
+
const ENTRY_OVERHEAD = 24n;
|
|
29
|
+
const MAX_MESSAGE_BYTES = 4096;
|
|
30
|
+
const MAX_FIELD_BYTES = 1024;
|
|
31
|
+
export const SYNTAX_KINDS = new Set([
|
|
32
|
+
"unexpected_eof_flow_sequence",
|
|
33
|
+
"unexpected_eof_flow_mapping",
|
|
34
|
+
"unexpected_eof_implicit_flow_mapping",
|
|
35
|
+
"unexpected_eof_block_sequence",
|
|
36
|
+
"unexpected_eof_block_mapping",
|
|
37
|
+
"unexpected_eof",
|
|
38
|
+
"expected_stream_start",
|
|
39
|
+
"duplicate_version_directive",
|
|
40
|
+
"duplicate_tag_directive",
|
|
41
|
+
"expected_document_start",
|
|
42
|
+
"missing_document_end_before_directive",
|
|
43
|
+
"anchor_count_overflow",
|
|
44
|
+
"expected_node_content",
|
|
45
|
+
"expected_block_mapping_key",
|
|
46
|
+
"expected_flow_mapping_separator",
|
|
47
|
+
"expected_flow_sequence_separator",
|
|
48
|
+
"expected_block_sequence_entry",
|
|
49
|
+
"undeclared_tag_handle",
|
|
50
|
+
"expected_tag_bang",
|
|
51
|
+
"expected_tag_directive_bang",
|
|
52
|
+
"invalid_global_tag_character",
|
|
53
|
+
"simple_key_expected",
|
|
54
|
+
"invalid_simple_key",
|
|
55
|
+
"invalid_document_end",
|
|
56
|
+
"invalid_indentation",
|
|
57
|
+
"bom_inside_document",
|
|
58
|
+
"unexpected_character",
|
|
59
|
+
"tab_not_allowed",
|
|
60
|
+
"tab_in_block_indentation",
|
|
61
|
+
"comment_intercepted_scalar",
|
|
62
|
+
"expected_whitespace",
|
|
63
|
+
"comment_not_separated",
|
|
64
|
+
"invalid_directive_terminator",
|
|
65
|
+
"missing_yaml_version_separator",
|
|
66
|
+
"missing_directive_name",
|
|
67
|
+
"invalid_directive_name",
|
|
68
|
+
"directive_byte_limit_exceeded",
|
|
69
|
+
"too_many_reserved_directive_params",
|
|
70
|
+
"yaml_version_too_long",
|
|
71
|
+
"missing_yaml_version",
|
|
72
|
+
"invalid_tag_directive_terminator",
|
|
73
|
+
"invalid_tag_terminator",
|
|
74
|
+
"missing_tag_uri",
|
|
75
|
+
"unclosed_verbatim_tag",
|
|
76
|
+
"invalid_tag_escape",
|
|
77
|
+
"invalid_tag_utf8_leading_byte",
|
|
78
|
+
"invalid_tag_utf8_trailing_byte",
|
|
79
|
+
"invalid_tag_utf8",
|
|
80
|
+
"missing_anchor_or_alias_name",
|
|
81
|
+
"misplaced_flow_collection_end",
|
|
82
|
+
"mismatched_flow_collection_end",
|
|
83
|
+
"unclosed_flow_collection",
|
|
84
|
+
"block_entry_in_flow_collection",
|
|
85
|
+
"block_sequence_entry_not_allowed",
|
|
86
|
+
"invalid_block_entry_whitespace",
|
|
87
|
+
"zero_block_scalar_indent",
|
|
88
|
+
"invalid_block_scalar_header",
|
|
89
|
+
"tab_at_block_scalar_start",
|
|
90
|
+
"invalid_block_scalar_indent",
|
|
91
|
+
"document_indicator_in_quoted_scalar",
|
|
92
|
+
"unclosed_quoted_scalar",
|
|
93
|
+
"tab_in_indentation",
|
|
94
|
+
"invalid_quoted_scalar_indent",
|
|
95
|
+
"invalid_trailing_single_quoted_scalar",
|
|
96
|
+
"invalid_trailing_double_quoted_scalar",
|
|
97
|
+
"unknown_quoted_scalar_escape",
|
|
98
|
+
"invalid_quoted_scalar_hex_escape",
|
|
99
|
+
"invalid_low_surrogate_hex_escape",
|
|
100
|
+
"invalid_low_surrogate",
|
|
101
|
+
"missing_low_surrogate",
|
|
102
|
+
"unpaired_low_surrogate",
|
|
103
|
+
"invalid_unicode_escape",
|
|
104
|
+
"invalid_flow_scalar_indent",
|
|
105
|
+
"plain_scalar_starts_with_dash_flow_indicator",
|
|
106
|
+
"tab_in_plain_scalar",
|
|
107
|
+
"unexpected_end_of_plain_scalar",
|
|
108
|
+
"mapping_key_not_allowed",
|
|
109
|
+
"flow_mapping_value_adjacent_collection",
|
|
110
|
+
"invalid_mapping_value_whitespace",
|
|
111
|
+
"invalid_colon_placement",
|
|
112
|
+
"mapping_value_not_allowed",
|
|
113
|
+
]);
|
|
114
|
+
const LIMIT_KINDS = new Set([
|
|
115
|
+
"max_input_bytes",
|
|
116
|
+
"max_depth",
|
|
117
|
+
"max_nodes",
|
|
118
|
+
"max_expanded_nodes",
|
|
119
|
+
"max_alias_events",
|
|
120
|
+
"max_owned_bytes",
|
|
121
|
+
"max_scalar_bytes",
|
|
122
|
+
"max_key_bytes",
|
|
123
|
+
"max_mapping_entries",
|
|
124
|
+
"max_documents",
|
|
125
|
+
]);
|
|
126
|
+
const EMPTY_DETAIL_ERROR_KINDS = new Set([
|
|
127
|
+
"unsupported_yaml_version",
|
|
128
|
+
"invalid_options",
|
|
129
|
+
"duplicate_key",
|
|
130
|
+
"invalid_key",
|
|
131
|
+
"unknown_anchor",
|
|
132
|
+
"recursive_alias",
|
|
133
|
+
"merge_rejected",
|
|
134
|
+
"merge_source",
|
|
135
|
+
"unknown_tag",
|
|
136
|
+
"tag_kind_mismatch",
|
|
137
|
+
"tag_value_mismatch",
|
|
138
|
+
"integer_out_of_range",
|
|
139
|
+
"float_out_of_range",
|
|
140
|
+
"multiple_documents",
|
|
141
|
+
"custom",
|
|
142
|
+
"internal",
|
|
143
|
+
]);
|
|
144
|
+
export class YamlprimsError extends Error {
|
|
145
|
+
kind;
|
|
146
|
+
detail;
|
|
147
|
+
site;
|
|
148
|
+
byteOffset;
|
|
149
|
+
utf16Offset;
|
|
150
|
+
line;
|
|
151
|
+
column;
|
|
152
|
+
related;
|
|
153
|
+
path;
|
|
154
|
+
rawMessage;
|
|
155
|
+
constructor(init) {
|
|
156
|
+
const src = init.site.source ?? null;
|
|
157
|
+
super(init.message);
|
|
158
|
+
this.name = "YamlprimsError";
|
|
159
|
+
this.kind = init.kind;
|
|
160
|
+
const rawDetail = init.detail;
|
|
161
|
+
if (init.kind === "syntax" && typeof rawDetail["syntaxKind"] === "string" && !("syntax_kind" in rawDetail)) {
|
|
162
|
+
this.detail = { syntax_kind: rawDetail["syntaxKind"] };
|
|
163
|
+
}
|
|
164
|
+
else if (init.kind === "invalid_utf8" && "invalidLen" in rawDetail && !("invalid_len" in rawDetail)) {
|
|
165
|
+
this.detail = { invalid_len: rawDetail["invalidLen"] ?? null };
|
|
166
|
+
}
|
|
167
|
+
else {
|
|
168
|
+
this.detail = init.detail;
|
|
169
|
+
}
|
|
170
|
+
this.site = init.site;
|
|
171
|
+
this.byteOffset = src !== null ? src.byteOffset : null;
|
|
172
|
+
this.utf16Offset = src !== null ? src.utf16Offset : null;
|
|
173
|
+
this.line = src !== null ? src.line : null;
|
|
174
|
+
this.column = src !== null ? src.column : null;
|
|
175
|
+
this.related = init.related ?? [];
|
|
176
|
+
this.path = init.path ?? [];
|
|
177
|
+
this.rawMessage = init.message;
|
|
178
|
+
}
|
|
179
|
+
location() {
|
|
180
|
+
return this.site.source ?? null;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
export function defaultLimits() {
|
|
184
|
+
return {
|
|
185
|
+
maxInputBytes: 8 * 1024 * 1024,
|
|
186
|
+
maxDepth: 128,
|
|
187
|
+
maxNodes: 250_000,
|
|
188
|
+
maxExpandedNodes: 100_000,
|
|
189
|
+
maxAliasEvents: 10_000,
|
|
190
|
+
maxOwnedBytes: 64 * 1024 * 1024,
|
|
191
|
+
maxScalarBytes: 1 * 1024 * 1024,
|
|
192
|
+
maxKeyBytes: 64 * 1024,
|
|
193
|
+
maxMappingEntries: 100_000,
|
|
194
|
+
maxDocuments: 1_024,
|
|
195
|
+
maxOutputBytes: 64 * 1024 * 1024,
|
|
196
|
+
maxWarnings: 1_000,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
export function defaultOptions() {
|
|
200
|
+
return {
|
|
201
|
+
mergeKeys: "reject",
|
|
202
|
+
unknownTags: "preserve",
|
|
203
|
+
limits: defaultLimits(),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function notSourceError(kind, detail, message, lastKnown = null) {
|
|
207
|
+
return new YamlprimsError({
|
|
208
|
+
kind,
|
|
209
|
+
detail,
|
|
210
|
+
site: { notSource: { lastKnown } },
|
|
211
|
+
message,
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
function invalidOptionsError(message) {
|
|
215
|
+
return notSourceError("invalid_options", {}, message);
|
|
216
|
+
}
|
|
217
|
+
function pickLimit(input, camel, snake, fallback) {
|
|
218
|
+
if (!input)
|
|
219
|
+
return fallback;
|
|
220
|
+
const c = input[camel];
|
|
221
|
+
const s = input[snake];
|
|
222
|
+
if (c !== undefined && s !== undefined && c !== s) {
|
|
223
|
+
throw invalidOptionsError(`conflicting limit values for ${String(camel)}`);
|
|
224
|
+
}
|
|
225
|
+
const chosen = c !== undefined ? c : s !== undefined ? s : fallback;
|
|
226
|
+
if (typeof chosen !== "number" || !Number.isInteger(chosen) || !Number.isSafeInteger(chosen)) {
|
|
227
|
+
throw invalidOptionsError(`limit ${String(camel)} must be a safe integer`);
|
|
228
|
+
}
|
|
229
|
+
return chosen;
|
|
230
|
+
}
|
|
231
|
+
const KNOWN_OPTION_KEYS = new Set([
|
|
232
|
+
"mergeKeys",
|
|
233
|
+
"unknownTags",
|
|
234
|
+
"limits",
|
|
235
|
+
"merge_keys",
|
|
236
|
+
"unknown_tags",
|
|
237
|
+
]);
|
|
238
|
+
const KNOWN_LIMIT_KEYS = new Set([
|
|
239
|
+
"maxInputBytes",
|
|
240
|
+
"maxDepth",
|
|
241
|
+
"maxNodes",
|
|
242
|
+
"maxExpandedNodes",
|
|
243
|
+
"maxAliasEvents",
|
|
244
|
+
"maxOwnedBytes",
|
|
245
|
+
"maxScalarBytes",
|
|
246
|
+
"maxKeyBytes",
|
|
247
|
+
"maxMappingEntries",
|
|
248
|
+
"maxDocuments",
|
|
249
|
+
"maxOutputBytes",
|
|
250
|
+
"maxWarnings",
|
|
251
|
+
"max_input_bytes",
|
|
252
|
+
"max_depth",
|
|
253
|
+
"max_nodes",
|
|
254
|
+
"max_expanded_nodes",
|
|
255
|
+
"max_alias_events",
|
|
256
|
+
"max_owned_bytes",
|
|
257
|
+
"max_scalar_bytes",
|
|
258
|
+
"max_key_bytes",
|
|
259
|
+
"max_mapping_entries",
|
|
260
|
+
"max_documents",
|
|
261
|
+
"max_output_bytes",
|
|
262
|
+
"max_warnings",
|
|
263
|
+
]);
|
|
264
|
+
export function validateOptions(options) {
|
|
265
|
+
if (options === undefined) {
|
|
266
|
+
return defaultOptions();
|
|
267
|
+
}
|
|
268
|
+
if (typeof options !== "object" || options === null || Array.isArray(options)) {
|
|
269
|
+
throw invalidOptionsError("options must be an object");
|
|
270
|
+
}
|
|
271
|
+
for (const k of Object.keys(options)) {
|
|
272
|
+
if (!KNOWN_OPTION_KEYS.has(k)) {
|
|
273
|
+
throw invalidOptionsError(`unknown option key: ${k}`);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
if (options.mergeKeys !== undefined &&
|
|
277
|
+
options.merge_keys !== undefined &&
|
|
278
|
+
options.mergeKeys !== options.merge_keys) {
|
|
279
|
+
throw invalidOptionsError("conflicting mergeKeys options");
|
|
280
|
+
}
|
|
281
|
+
if (options.unknownTags !== undefined &&
|
|
282
|
+
options.unknown_tags !== undefined &&
|
|
283
|
+
options.unknownTags !== options.unknown_tags) {
|
|
284
|
+
throw invalidOptionsError("conflicting unknownTags options");
|
|
285
|
+
}
|
|
286
|
+
const rawMergeKeys = options.mergeKeys ?? options.merge_keys ?? "reject";
|
|
287
|
+
const mergeKeys = rawMergeKeys === "as-key" ? "as_key" : rawMergeKeys;
|
|
288
|
+
if (mergeKeys !== "reject" && mergeKeys !== "apply" && mergeKeys !== "as_key") {
|
|
289
|
+
throw invalidOptionsError("invalid mergeKeys option");
|
|
290
|
+
}
|
|
291
|
+
const unknownTags = options.unknownTags ?? options.unknown_tags ?? "preserve";
|
|
292
|
+
if (unknownTags !== "preserve" && unknownTags !== "reject") {
|
|
293
|
+
throw invalidOptionsError("invalid unknownTags option");
|
|
294
|
+
}
|
|
295
|
+
const limIn = options.limits;
|
|
296
|
+
if (limIn !== undefined) {
|
|
297
|
+
if (typeof limIn !== "object" || limIn === null || Array.isArray(limIn)) {
|
|
298
|
+
throw invalidOptionsError("limits must be an object");
|
|
299
|
+
}
|
|
300
|
+
for (const k of Object.keys(limIn)) {
|
|
301
|
+
if (!KNOWN_LIMIT_KEYS.has(k)) {
|
|
302
|
+
throw invalidOptionsError(`unknown limit key: ${k}`);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const def = defaultLimits();
|
|
307
|
+
const limits = {
|
|
308
|
+
maxInputBytes: pickLimit(limIn, "maxInputBytes", "max_input_bytes", def.maxInputBytes),
|
|
309
|
+
maxDepth: pickLimit(limIn, "maxDepth", "max_depth", def.maxDepth),
|
|
310
|
+
maxNodes: pickLimit(limIn, "maxNodes", "max_nodes", def.maxNodes),
|
|
311
|
+
maxExpandedNodes: pickLimit(limIn, "maxExpandedNodes", "max_expanded_nodes", def.maxExpandedNodes),
|
|
312
|
+
maxAliasEvents: pickLimit(limIn, "maxAliasEvents", "max_alias_events", def.maxAliasEvents),
|
|
313
|
+
maxOwnedBytes: pickLimit(limIn, "maxOwnedBytes", "max_owned_bytes", def.maxOwnedBytes),
|
|
314
|
+
maxScalarBytes: pickLimit(limIn, "maxScalarBytes", "max_scalar_bytes", def.maxScalarBytes),
|
|
315
|
+
maxKeyBytes: pickLimit(limIn, "maxKeyBytes", "max_key_bytes", def.maxKeyBytes),
|
|
316
|
+
maxMappingEntries: pickLimit(limIn, "maxMappingEntries", "max_mapping_entries", def.maxMappingEntries),
|
|
317
|
+
maxDocuments: pickLimit(limIn, "maxDocuments", "max_documents", def.maxDocuments),
|
|
318
|
+
maxOutputBytes: pickLimit(limIn, "maxOutputBytes", "max_output_bytes", def.maxOutputBytes),
|
|
319
|
+
maxWarnings: pickLimit(limIn, "maxWarnings", "max_warnings", def.maxWarnings),
|
|
320
|
+
};
|
|
321
|
+
const all = [
|
|
322
|
+
limits.maxInputBytes,
|
|
323
|
+
limits.maxDepth,
|
|
324
|
+
limits.maxNodes,
|
|
325
|
+
limits.maxExpandedNodes,
|
|
326
|
+
limits.maxAliasEvents,
|
|
327
|
+
limits.maxOwnedBytes,
|
|
328
|
+
limits.maxScalarBytes,
|
|
329
|
+
limits.maxKeyBytes,
|
|
330
|
+
limits.maxMappingEntries,
|
|
331
|
+
limits.maxDocuments,
|
|
332
|
+
limits.maxOutputBytes,
|
|
333
|
+
limits.maxWarnings,
|
|
334
|
+
];
|
|
335
|
+
if (all.some((v) => v < 1)) {
|
|
336
|
+
throw invalidOptionsError("every limit must be at least 1");
|
|
337
|
+
}
|
|
338
|
+
if (limits.maxDepth > 255) {
|
|
339
|
+
throw invalidOptionsError("max_depth must be at most 255");
|
|
340
|
+
}
|
|
341
|
+
if (limits.maxScalarBytes > limits.maxOwnedBytes || limits.maxKeyBytes > limits.maxOwnedBytes) {
|
|
342
|
+
throw invalidOptionsError("max_scalar_bytes and max_key_bytes must not exceed max_owned_bytes");
|
|
343
|
+
}
|
|
344
|
+
return { mergeKeys, unknownTags, limits };
|
|
345
|
+
}
|
|
346
|
+
function isDefaultOptions(opts) {
|
|
347
|
+
const def = defaultOptions();
|
|
348
|
+
return (opts.mergeKeys === def.mergeKeys &&
|
|
349
|
+
opts.unknownTags === def.unknownTags &&
|
|
350
|
+
opts.limits.maxInputBytes === def.limits.maxInputBytes &&
|
|
351
|
+
opts.limits.maxDepth === def.limits.maxDepth &&
|
|
352
|
+
opts.limits.maxNodes === def.limits.maxNodes &&
|
|
353
|
+
opts.limits.maxExpandedNodes === def.limits.maxExpandedNodes &&
|
|
354
|
+
opts.limits.maxAliasEvents === def.limits.maxAliasEvents &&
|
|
355
|
+
opts.limits.maxOwnedBytes === def.limits.maxOwnedBytes &&
|
|
356
|
+
opts.limits.maxScalarBytes === def.limits.maxScalarBytes &&
|
|
357
|
+
opts.limits.maxKeyBytes === def.limits.maxKeyBytes &&
|
|
358
|
+
opts.limits.maxMappingEntries === def.limits.maxMappingEntries &&
|
|
359
|
+
opts.limits.maxDocuments === def.limits.maxDocuments &&
|
|
360
|
+
opts.limits.maxOutputBytes === def.limits.maxOutputBytes &&
|
|
361
|
+
opts.limits.maxWarnings === def.limits.maxWarnings);
|
|
362
|
+
}
|
|
363
|
+
const encoder = new TextEncoder();
|
|
364
|
+
const decoder = new TextDecoder("utf-8", { fatal: true });
|
|
365
|
+
function clampU32(n) {
|
|
366
|
+
return n > 0xffffffff ? 0xffffffff : n;
|
|
367
|
+
}
|
|
368
|
+
function serializeWasmOptions(opts) {
|
|
369
|
+
if (isDefaultOptions(opts)) {
|
|
370
|
+
return new Uint8Array(0);
|
|
371
|
+
}
|
|
372
|
+
const l = opts.limits;
|
|
373
|
+
const json = `{"merge_keys":"${opts.mergeKeys}","unknown_tags":"${opts.unknownTags}","limits":{"max_input_bytes":${clampU32(l.maxInputBytes)},"max_depth":${clampU32(l.maxDepth)},"max_nodes":${clampU32(l.maxNodes)},"max_expanded_nodes":${clampU32(l.maxExpandedNodes)},"max_alias_events":${clampU32(l.maxAliasEvents)},"max_owned_bytes":${clampU32(l.maxOwnedBytes)},"max_scalar_bytes":${clampU32(l.maxScalarBytes)},"max_key_bytes":${clampU32(l.maxKeyBytes)},"max_mapping_entries":${clampU32(l.maxMappingEntries)},"max_documents":${clampU32(l.maxDocuments)},"max_output_bytes":${clampU32(l.maxOutputBytes)},"max_warnings":${clampU32(l.maxWarnings)}}}`;
|
|
374
|
+
return encoder.encode(json);
|
|
375
|
+
}
|
|
376
|
+
const wasmModule = new WebAssembly.Module(wasmBytes());
|
|
377
|
+
let activeInstance = null;
|
|
378
|
+
let instanceBusy = false;
|
|
379
|
+
let instanceTrapped = false;
|
|
380
|
+
let releaseCallCount = 0;
|
|
381
|
+
let recreateCount = 0;
|
|
382
|
+
function getWasmExports() {
|
|
383
|
+
if (activeInstance === null || instanceTrapped) {
|
|
384
|
+
const inst = new WebAssembly.Instance(wasmModule, {});
|
|
385
|
+
const exports = inst.exports;
|
|
386
|
+
const ver = exports.abi_version() >>> 0;
|
|
387
|
+
if (ver !== ABI_VERSION) {
|
|
388
|
+
throw notSourceError("internal", {}, `unexpected WASM abi_version: ${ver}`);
|
|
389
|
+
}
|
|
390
|
+
activeInstance = { inst, exports };
|
|
391
|
+
instanceTrapped = false;
|
|
392
|
+
recreateCount += 1;
|
|
393
|
+
}
|
|
394
|
+
return activeInstance.exports;
|
|
395
|
+
}
|
|
396
|
+
function assertWellFormedUnicode(s, label) {
|
|
397
|
+
if (typeof s !== "string") {
|
|
398
|
+
throw notSourceError("internal", {}, `${label} must be a string`);
|
|
399
|
+
}
|
|
400
|
+
for (let i = 0; i < s.length; i++) {
|
|
401
|
+
const code = s.charCodeAt(i);
|
|
402
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
403
|
+
const next = i + 1 < s.length ? s.charCodeAt(i + 1) : 0;
|
|
404
|
+
if (next < 0xdc00 || next > 0xdfff) {
|
|
405
|
+
throw notSourceError("internal", {}, `${label} contains an unpaired high surrogate`);
|
|
406
|
+
}
|
|
407
|
+
i++;
|
|
408
|
+
}
|
|
409
|
+
else if (code >= 0xdc00 && code <= 0xdfff) {
|
|
410
|
+
throw notSourceError("internal", {}, `${label} contains an unpaired low surrogate`);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
function toInputBytes(input) {
|
|
415
|
+
if (typeof input === "string") {
|
|
416
|
+
for (let i = 0; i < input.length; i++) {
|
|
417
|
+
const code = input.charCodeAt(i);
|
|
418
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
419
|
+
const next = i + 1 < input.length ? input.charCodeAt(i + 1) : 0;
|
|
420
|
+
if (next < 0xdc00 || next > 0xdfff) {
|
|
421
|
+
throw new TypeError("input string contains an unpaired high surrogate");
|
|
422
|
+
}
|
|
423
|
+
i++;
|
|
424
|
+
}
|
|
425
|
+
else if (code >= 0xdc00 && code <= 0xdfff) {
|
|
426
|
+
throw new TypeError("input string contains an unpaired low surrogate");
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return encoder.encode(input);
|
|
430
|
+
}
|
|
431
|
+
if (input instanceof Uint8Array) {
|
|
432
|
+
return input;
|
|
433
|
+
}
|
|
434
|
+
throw new TypeError("input must be a string or Uint8Array");
|
|
435
|
+
}
|
|
436
|
+
function decodeFallbackStatus2(bytes, defaultMaxOutput) {
|
|
437
|
+
try {
|
|
438
|
+
const text = decoder.decode(bytes);
|
|
439
|
+
const parsed = JSON.parse(text);
|
|
440
|
+
if (parsed.kind === "output_limit_exceeded") {
|
|
441
|
+
const configured = typeof parsed.configured === "number" && Number.isSafeInteger(parsed.configured)
|
|
442
|
+
? parsed.configured
|
|
443
|
+
: defaultMaxOutput;
|
|
444
|
+
return notSourceError("output_limit_exceeded", { configured }, parsed.message ?? `encoded output exceeds max_output_bytes (${configured})`);
|
|
445
|
+
}
|
|
446
|
+
return notSourceError("internal", {}, parsed.message ?? "WASM internal error");
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
return notSourceError("internal", {}, "WASM status 2 fallback error");
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
function runWasmLoad(inputBytes, opts, mode, simulateTrap = false) {
|
|
453
|
+
if (instanceBusy) {
|
|
454
|
+
throw notSourceError("internal", {}, "reentrant WASM execution is forbidden");
|
|
455
|
+
}
|
|
456
|
+
const optsBytes = serializeWasmOptions(opts);
|
|
457
|
+
const exports = getWasmExports();
|
|
458
|
+
instanceBusy = true;
|
|
459
|
+
let localTrapped = false;
|
|
460
|
+
try {
|
|
461
|
+
const optPtr = exports.options_reserve(optsBytes.byteLength) >>> 0;
|
|
462
|
+
if (optPtr === 0) {
|
|
463
|
+
if (optsBytes.byteLength > MAX_OPTIONS_BYTES) {
|
|
464
|
+
throw invalidOptionsError("options payload exceeds WASM options limit");
|
|
465
|
+
}
|
|
466
|
+
activeInstance = null;
|
|
467
|
+
throw notSourceError("internal", {}, "WASM options reservation failed (linear memory ceiling exceeded)");
|
|
468
|
+
}
|
|
469
|
+
if (optsBytes.byteLength > 0) {
|
|
470
|
+
new Uint8Array(exports.memory.buffer, optPtr, optsBytes.byteLength).set(optsBytes);
|
|
471
|
+
}
|
|
472
|
+
const wasmMaxInput = clampU32(opts.limits.maxInputBytes);
|
|
473
|
+
const inPtr = exports.input_reserve(inputBytes.byteLength, wasmMaxInput) >>> 0;
|
|
474
|
+
if (inPtr === 0) {
|
|
475
|
+
if (inputBytes.byteLength > opts.limits.maxInputBytes) {
|
|
476
|
+
throw new YamlprimsError({
|
|
477
|
+
kind: "limit_exceeded",
|
|
478
|
+
detail: { limit: "max_input_bytes", configured: opts.limits.maxInputBytes },
|
|
479
|
+
site: { source: { byteOffset: 0, utf16Offset: 0, line: 1, column: 1 } },
|
|
480
|
+
message: `max_input_bytes (${opts.limits.maxInputBytes}) exceeded`,
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
if (inputBytes.byteLength > MAX_WASM_INPUT_CEILING) {
|
|
484
|
+
throw new YamlprimsError({
|
|
485
|
+
kind: "limit_exceeded",
|
|
486
|
+
detail: { limit: "max_input_bytes", configured: MAX_WASM_INPUT_CEILING },
|
|
487
|
+
site: { source: { byteOffset: 0, utf16Offset: 0, line: 1, column: 1 } },
|
|
488
|
+
message: `max_input_bytes (${MAX_WASM_INPUT_CEILING}) exceeded`,
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
activeInstance = null;
|
|
492
|
+
throw notSourceError("internal", {}, "WASM input reservation failed (linear memory ceiling exceeded)");
|
|
493
|
+
}
|
|
494
|
+
if (inputBytes.byteLength > 0) {
|
|
495
|
+
new Uint8Array(exports.memory.buffer, inPtr, inputBytes.byteLength).set(inputBytes);
|
|
496
|
+
}
|
|
497
|
+
if (simulateTrap) {
|
|
498
|
+
throw new WebAssembly.RuntimeError("simulated unreachable trap");
|
|
499
|
+
}
|
|
500
|
+
const status = mode === "plain"
|
|
501
|
+
? exports.load_plain(inputBytes.byteLength, optsBytes.byteLength) >>> 0
|
|
502
|
+
: exports.load_wire(inputBytes.byteLength, optsBytes.byteLength, mode === "wire-single" ? 1 : 0) >>> 0;
|
|
503
|
+
const outPtr = exports.output_ptr() >>> 0;
|
|
504
|
+
const outLen = exports.output_len() >>> 0;
|
|
505
|
+
const output = new Uint8Array(exports.memory.buffer, outPtr, outLen).slice();
|
|
506
|
+
return { status, output };
|
|
507
|
+
}
|
|
508
|
+
catch (err) {
|
|
509
|
+
if (err instanceof WebAssembly.RuntimeError) {
|
|
510
|
+
localTrapped = true;
|
|
511
|
+
instanceTrapped = true;
|
|
512
|
+
activeInstance = null;
|
|
513
|
+
throw notSourceError("internal", {}, `WASM runtime trap: ${err.message}`);
|
|
514
|
+
}
|
|
515
|
+
throw err;
|
|
516
|
+
}
|
|
517
|
+
finally {
|
|
518
|
+
instanceBusy = false;
|
|
519
|
+
// Never call release() when the instance trapped: discard and recreate directly.
|
|
520
|
+
if (!localTrapped && !instanceTrapped && activeInstance !== null) {
|
|
521
|
+
exports.release();
|
|
522
|
+
releaseCallCount += 1;
|
|
523
|
+
if (exports.memory.buffer.byteLength > WASM_HIGH_WATER_RECYCLE_BYTES) {
|
|
524
|
+
activeInstance = null;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
function createWasmTestHarness() {
|
|
530
|
+
return {
|
|
531
|
+
module: wasmModule,
|
|
532
|
+
createRawInstance: () => {
|
|
533
|
+
const inst = new WebAssembly.Instance(wasmModule, {});
|
|
534
|
+
return inst.exports;
|
|
535
|
+
},
|
|
536
|
+
getActiveMemory: () => getWasmExports().memory,
|
|
537
|
+
simulateTrapOnLoad: (input) => {
|
|
538
|
+
const opts = defaultOptions();
|
|
539
|
+
runWasmLoad(toInputBytes(input), opts, "wire-single", true);
|
|
540
|
+
},
|
|
541
|
+
runWithBusyInstance: (fn) => {
|
|
542
|
+
const prev = instanceBusy;
|
|
543
|
+
instanceBusy = true;
|
|
544
|
+
try {
|
|
545
|
+
fn();
|
|
546
|
+
}
|
|
547
|
+
finally {
|
|
548
|
+
instanceBusy = prev;
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
stats: () => ({
|
|
552
|
+
releaseCallCount,
|
|
553
|
+
recreateCount,
|
|
554
|
+
instanceTrapped,
|
|
555
|
+
}),
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
// ---- Single-pass O(N) UTF-16 offset index --------------------------------
|
|
559
|
+
class Utf16Index {
|
|
560
|
+
bytes;
|
|
561
|
+
limit;
|
|
562
|
+
pureAscii;
|
|
563
|
+
cpByte;
|
|
564
|
+
cpUtf16;
|
|
565
|
+
constructor(bytes, limitByteOffset) {
|
|
566
|
+
this.bytes = bytes;
|
|
567
|
+
const lim = limitByteOffset !== undefined
|
|
568
|
+
? Math.min(Math.max(0, limitByteOffset), bytes.byteLength)
|
|
569
|
+
: bytes.byteLength;
|
|
570
|
+
this.limit = lim;
|
|
571
|
+
let i = 0;
|
|
572
|
+
while (i < lim && (bytes[i] ?? 0) < 0x80) {
|
|
573
|
+
i++;
|
|
574
|
+
}
|
|
575
|
+
if (i === lim) {
|
|
576
|
+
this.pureAscii = true;
|
|
577
|
+
this.cpByte = null;
|
|
578
|
+
this.cpUtf16 = null;
|
|
579
|
+
return;
|
|
580
|
+
}
|
|
581
|
+
this.pureAscii = false;
|
|
582
|
+
const numBuckets = (lim >>> 6) + 2;
|
|
583
|
+
const cpByte = new Uint32Array(numBuckets);
|
|
584
|
+
const cpUtf16 = new Uint32Array(numBuckets);
|
|
585
|
+
const firstNonAsciiBucket = i >>> 6;
|
|
586
|
+
for (let k = 0; k <= firstNonAsciiBucket; k++) {
|
|
587
|
+
const b = k << 6;
|
|
588
|
+
cpByte[k] = b;
|
|
589
|
+
cpUtf16[k] = b;
|
|
590
|
+
}
|
|
591
|
+
let pos = firstNonAsciiBucket << 6;
|
|
592
|
+
let u16 = pos;
|
|
593
|
+
let nextBucket = firstNonAsciiBucket + 1;
|
|
594
|
+
while (pos < lim) {
|
|
595
|
+
while (nextBucket < numBuckets && pos >= nextBucket << 6) {
|
|
596
|
+
cpByte[nextBucket] = pos;
|
|
597
|
+
cpUtf16[nextBucket] = u16;
|
|
598
|
+
nextBucket++;
|
|
599
|
+
}
|
|
600
|
+
const b0 = bytes[pos] ?? 0;
|
|
601
|
+
if (b0 < 0x80) {
|
|
602
|
+
pos += 1;
|
|
603
|
+
u16 += 1;
|
|
604
|
+
}
|
|
605
|
+
else if ((b0 & 0xe0) === 0xc0) {
|
|
606
|
+
if (pos + 2 > lim)
|
|
607
|
+
break;
|
|
608
|
+
pos += 2;
|
|
609
|
+
u16 += 1;
|
|
610
|
+
}
|
|
611
|
+
else if ((b0 & 0xf0) === 0xe0) {
|
|
612
|
+
if (pos + 3 > lim)
|
|
613
|
+
break;
|
|
614
|
+
pos += 3;
|
|
615
|
+
u16 += 1;
|
|
616
|
+
}
|
|
617
|
+
else if ((b0 & 0xf8) === 0xf0) {
|
|
618
|
+
if (pos + 4 > lim)
|
|
619
|
+
break;
|
|
620
|
+
pos += 4;
|
|
621
|
+
u16 += 2;
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
break;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
while (nextBucket < numBuckets) {
|
|
628
|
+
cpByte[nextBucket] = pos;
|
|
629
|
+
cpUtf16[nextBucket] = u16;
|
|
630
|
+
nextBucket++;
|
|
631
|
+
}
|
|
632
|
+
this.cpByte = cpByte;
|
|
633
|
+
this.cpUtf16 = cpUtf16;
|
|
634
|
+
}
|
|
635
|
+
utf16At(byteOffset) {
|
|
636
|
+
if (byteOffset < 0 || byteOffset > this.limit) {
|
|
637
|
+
throw notSourceError("internal", {}, `location byte_offset ${byteOffset} exceeds valid prefix (${this.limit})`);
|
|
638
|
+
}
|
|
639
|
+
if (this.pureAscii) {
|
|
640
|
+
return byteOffset;
|
|
641
|
+
}
|
|
642
|
+
const cpByte = this.cpByte;
|
|
643
|
+
const cpUtf16 = this.cpUtf16;
|
|
644
|
+
let k = byteOffset >>> 6;
|
|
645
|
+
while (k > 0 && (cpByte[k] ?? 0) > byteOffset) {
|
|
646
|
+
k--;
|
|
647
|
+
}
|
|
648
|
+
let pos = cpByte[k] ?? 0;
|
|
649
|
+
let u16 = cpUtf16[k] ?? 0;
|
|
650
|
+
const bytes = this.bytes;
|
|
651
|
+
while (pos < byteOffset) {
|
|
652
|
+
const b0 = bytes[pos] ?? 0;
|
|
653
|
+
if (b0 < 0x80) {
|
|
654
|
+
pos += 1;
|
|
655
|
+
u16 += 1;
|
|
656
|
+
}
|
|
657
|
+
else if ((b0 & 0xe0) === 0xc0) {
|
|
658
|
+
pos += 2;
|
|
659
|
+
u16 += 1;
|
|
660
|
+
}
|
|
661
|
+
else if ((b0 & 0xf0) === 0xe0) {
|
|
662
|
+
pos += 3;
|
|
663
|
+
u16 += 1;
|
|
664
|
+
}
|
|
665
|
+
else if ((b0 & 0xf8) === 0xf0) {
|
|
666
|
+
pos += 4;
|
|
667
|
+
u16 += 2;
|
|
668
|
+
}
|
|
669
|
+
else {
|
|
670
|
+
throw notSourceError("internal", {}, "invalid UTF-8 inside valid prefix");
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
if (pos !== byteOffset) {
|
|
674
|
+
throw notSourceError("internal", {}, `location byte_offset ${byteOffset} is not on a UTF-8 character boundary`);
|
|
675
|
+
}
|
|
676
|
+
return u16;
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
// ---- Float bits & Key equality (§5.1, §11.1) -----------------------------
|
|
680
|
+
const floatBuf = new ArrayBuffer(8);
|
|
681
|
+
const floatView = new DataView(floatBuf);
|
|
682
|
+
function bitsToFloat(bitsHex) {
|
|
683
|
+
const raw = BigInt("0x" + bitsHex);
|
|
684
|
+
// IEEE 754 binary64 NaN: exponent all 1s (0x7ff0_0000_0000_0000) and mantissa != 0.
|
|
685
|
+
const isNan = (raw & 0x7ff0000000000000n) === 0x7ff0000000000000n && (raw & 0x000fffffffffffffn) !== 0n;
|
|
686
|
+
const canonicalBig = isNan ? CANONICAL_NAN_BIGINT : raw;
|
|
687
|
+
floatView.setBigUint64(0, canonicalBig, false);
|
|
688
|
+
const value = floatView.getFloat64(0, false);
|
|
689
|
+
const canonicalBits = isNan ? CANONICAL_NAN_BITS : bitsHex;
|
|
690
|
+
return { value, canonicalBits };
|
|
691
|
+
}
|
|
692
|
+
export function floatToBits(f) {
|
|
693
|
+
if (Number.isNaN(f)) {
|
|
694
|
+
return CANONICAL_NAN_BITS;
|
|
695
|
+
}
|
|
696
|
+
floatView.setFloat64(0, f, false);
|
|
697
|
+
const u = floatView.getBigUint64(0, false);
|
|
698
|
+
return u.toString(16).padStart(16, "0");
|
|
699
|
+
}
|
|
700
|
+
function normFloatBits(f) {
|
|
701
|
+
if (f === 0) {
|
|
702
|
+
return 0n;
|
|
703
|
+
}
|
|
704
|
+
if (Number.isNaN(f)) {
|
|
705
|
+
return CANONICAL_NAN_BIGINT;
|
|
706
|
+
}
|
|
707
|
+
floatView.setFloat64(0, f, false);
|
|
708
|
+
return floatView.getBigUint64(0, false);
|
|
709
|
+
}
|
|
710
|
+
export function containsNan(node) {
|
|
711
|
+
const stack = [node];
|
|
712
|
+
const visited = new Set();
|
|
713
|
+
while (stack.length > 0) {
|
|
714
|
+
const cur = stack.pop();
|
|
715
|
+
if (visited.has(cur))
|
|
716
|
+
continue;
|
|
717
|
+
visited.add(cur);
|
|
718
|
+
switch (cur.kind) {
|
|
719
|
+
case "float":
|
|
720
|
+
if (Number.isNaN(cur.value))
|
|
721
|
+
return true;
|
|
722
|
+
break;
|
|
723
|
+
case "sequence":
|
|
724
|
+
for (const item of cur.items)
|
|
725
|
+
stack.push(item);
|
|
726
|
+
break;
|
|
727
|
+
case "mapping":
|
|
728
|
+
for (const [k, v] of cur.entries) {
|
|
729
|
+
stack.push(k, v);
|
|
730
|
+
}
|
|
731
|
+
break;
|
|
732
|
+
case "tagged":
|
|
733
|
+
stack.push(cur.value);
|
|
734
|
+
break;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return false;
|
|
738
|
+
}
|
|
739
|
+
export function keyEq(a, b) {
|
|
740
|
+
if (a.kind !== b.kind)
|
|
741
|
+
return false;
|
|
742
|
+
switch (a.kind) {
|
|
743
|
+
case "null":
|
|
744
|
+
return true;
|
|
745
|
+
case "bool":
|
|
746
|
+
return a.value === b.value;
|
|
747
|
+
case "int":
|
|
748
|
+
return a.value === b.value;
|
|
749
|
+
case "float": {
|
|
750
|
+
const bf = b;
|
|
751
|
+
if (Number.isNaN(a.value) || Number.isNaN(bf.value))
|
|
752
|
+
return false;
|
|
753
|
+
return normFloatBits(a.value) === normFloatBits(bf.value);
|
|
754
|
+
}
|
|
755
|
+
case "string":
|
|
756
|
+
return a.value === b.value;
|
|
757
|
+
case "sequence": {
|
|
758
|
+
const bs = b;
|
|
759
|
+
if (a.items.length !== bs.items.length)
|
|
760
|
+
return false;
|
|
761
|
+
for (let i = 0; i < a.items.length; i++) {
|
|
762
|
+
if (!keyEq(a.items[i], bs.items[i]))
|
|
763
|
+
return false;
|
|
764
|
+
}
|
|
765
|
+
return true;
|
|
766
|
+
}
|
|
767
|
+
case "mapping": {
|
|
768
|
+
const bm = b;
|
|
769
|
+
if (a.entries.length !== bm.entries.length)
|
|
770
|
+
return false;
|
|
771
|
+
const used = new Uint8Array(bm.entries.length);
|
|
772
|
+
for (const [ak, av] of a.entries) {
|
|
773
|
+
let found = false;
|
|
774
|
+
for (let j = 0; j < bm.entries.length; j++) {
|
|
775
|
+
if (used[j])
|
|
776
|
+
continue;
|
|
777
|
+
const [bk, bv] = bm.entries[j];
|
|
778
|
+
if (keyEq(ak, bk)) {
|
|
779
|
+
if (!keyEq(av, bv))
|
|
780
|
+
return false;
|
|
781
|
+
used[j] = 1;
|
|
782
|
+
found = true;
|
|
783
|
+
break;
|
|
784
|
+
}
|
|
785
|
+
}
|
|
786
|
+
if (!found)
|
|
787
|
+
return false;
|
|
788
|
+
}
|
|
789
|
+
return true;
|
|
790
|
+
}
|
|
791
|
+
case "tagged": {
|
|
792
|
+
const bt = b;
|
|
793
|
+
return a.tag.uri === bt.tag.uri && keyEq(a.value, bt.value);
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
export function mappingGet(mapping, key) {
|
|
798
|
+
const entries = Array.isArray(mapping) ? mapping : mapping.entries;
|
|
799
|
+
if (typeof key === "string") {
|
|
800
|
+
for (const [k, v] of entries) {
|
|
801
|
+
if (k.kind === "string" && k.value === key) {
|
|
802
|
+
return v;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
return undefined;
|
|
806
|
+
}
|
|
807
|
+
for (const [k, v] of entries) {
|
|
808
|
+
if (keyEq(k, key)) {
|
|
809
|
+
return v;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
return undefined;
|
|
813
|
+
}
|
|
814
|
+
class WireJsonParser {
|
|
815
|
+
s;
|
|
816
|
+
pos = 0;
|
|
817
|
+
maxDepth;
|
|
818
|
+
constructor(s, maxDepth) {
|
|
819
|
+
this.s = s;
|
|
820
|
+
this.maxDepth = maxDepth;
|
|
821
|
+
}
|
|
822
|
+
parseRoot() {
|
|
823
|
+
const val = this.parseValue(0);
|
|
824
|
+
this.skipWs();
|
|
825
|
+
if (this.pos !== this.s.length) {
|
|
826
|
+
throw notSourceError("internal", {}, "trailing characters after wire JSON");
|
|
827
|
+
}
|
|
828
|
+
return val;
|
|
829
|
+
}
|
|
830
|
+
skipWs() {
|
|
831
|
+
while (this.pos < this.s.length) {
|
|
832
|
+
const c = this.s.charCodeAt(this.pos);
|
|
833
|
+
if (c === 0x20 || c === 0x09 || c === 0x0a || c === 0x0d) {
|
|
834
|
+
this.pos++;
|
|
835
|
+
}
|
|
836
|
+
else {
|
|
837
|
+
break;
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
expectChar(code) {
|
|
842
|
+
this.skipWs();
|
|
843
|
+
if (this.pos >= this.s.length || this.s.charCodeAt(this.pos) !== code) {
|
|
844
|
+
throw notSourceError("internal", {}, "malformed wire JSON");
|
|
845
|
+
}
|
|
846
|
+
this.pos++;
|
|
847
|
+
}
|
|
848
|
+
parseValue(depth) {
|
|
849
|
+
if (depth > this.maxDepth) {
|
|
850
|
+
throw notSourceError("internal", {}, "wire JSON nesting exceeds maximum depth");
|
|
851
|
+
}
|
|
852
|
+
this.skipWs();
|
|
853
|
+
if (this.pos >= this.s.length) {
|
|
854
|
+
throw notSourceError("internal", {}, "unexpected end of wire JSON");
|
|
855
|
+
}
|
|
856
|
+
const c = this.s.charCodeAt(this.pos);
|
|
857
|
+
if (c === 0x7b /* { */)
|
|
858
|
+
return this.parseObject(depth + 1);
|
|
859
|
+
if (c === 0x5b /* [ */)
|
|
860
|
+
return this.parseArray(depth + 1);
|
|
861
|
+
if (c === 0x22 /* " */)
|
|
862
|
+
return { t: "str", v: this.parseString() };
|
|
863
|
+
if (c === 0x74 /* t */) {
|
|
864
|
+
if (this.s.startsWith("true", this.pos)) {
|
|
865
|
+
this.pos += 4;
|
|
866
|
+
return { t: "bool", v: true };
|
|
867
|
+
}
|
|
868
|
+
throw notSourceError("internal", {}, "invalid literal in wire JSON");
|
|
869
|
+
}
|
|
870
|
+
if (c === 0x66 /* f */) {
|
|
871
|
+
if (this.s.startsWith("false", this.pos)) {
|
|
872
|
+
this.pos += 5;
|
|
873
|
+
return { t: "bool", v: false };
|
|
874
|
+
}
|
|
875
|
+
throw notSourceError("internal", {}, "invalid literal in wire JSON");
|
|
876
|
+
}
|
|
877
|
+
if (c === 0x6e /* n */) {
|
|
878
|
+
if (this.s.startsWith("null", this.pos)) {
|
|
879
|
+
this.pos += 4;
|
|
880
|
+
return { t: "null" };
|
|
881
|
+
}
|
|
882
|
+
throw notSourceError("internal", {}, "invalid literal in wire JSON");
|
|
883
|
+
}
|
|
884
|
+
if (c >= 0x30 && c <= 0x39) {
|
|
885
|
+
return this.parseUnsignedInt();
|
|
886
|
+
}
|
|
887
|
+
throw notSourceError("internal", {}, "unexpected token in wire JSON");
|
|
888
|
+
}
|
|
889
|
+
parseUnsignedInt() {
|
|
890
|
+
const start = this.pos;
|
|
891
|
+
while (this.pos < this.s.length) {
|
|
892
|
+
const c = this.s.charCodeAt(this.pos);
|
|
893
|
+
if (c >= 0x30 && c <= 0x39) {
|
|
894
|
+
this.pos++;
|
|
895
|
+
}
|
|
896
|
+
else if (c === 0x2e || c === 0x65 || c === 0x45 || c === 0x2b || c === 0x2d) {
|
|
897
|
+
throw notSourceError("internal", {}, "non-canonical number in wire JSON");
|
|
898
|
+
}
|
|
899
|
+
else {
|
|
900
|
+
break;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
const raw = this.s.slice(start, this.pos);
|
|
904
|
+
if (raw.length > 1 && raw.charCodeAt(0) === 0x30) {
|
|
905
|
+
throw notSourceError("internal", {}, "leading zero in wire metadata integer");
|
|
906
|
+
}
|
|
907
|
+
const big = BigInt(raw);
|
|
908
|
+
if (big > BigInt(MAX_SAFE_METADATA_INT)) {
|
|
909
|
+
throw notSourceError("internal", {}, "wire metadata integer exceeds 2^53-1");
|
|
910
|
+
}
|
|
911
|
+
return { t: "int", raw, v: Number(big) };
|
|
912
|
+
}
|
|
913
|
+
parseString() {
|
|
914
|
+
this.expectChar(0x22);
|
|
915
|
+
const start = this.pos;
|
|
916
|
+
let out = "";
|
|
917
|
+
let chunkStart = start;
|
|
918
|
+
while (this.pos < this.s.length) {
|
|
919
|
+
const c = this.s.charCodeAt(this.pos);
|
|
920
|
+
if (c === 0x22) {
|
|
921
|
+
out += this.s.slice(chunkStart, this.pos);
|
|
922
|
+
this.pos++;
|
|
923
|
+
return out;
|
|
924
|
+
}
|
|
925
|
+
if (c < 0x20) {
|
|
926
|
+
throw notSourceError("internal", {}, "unescaped control character in wire JSON string");
|
|
927
|
+
}
|
|
928
|
+
if (c >= 0xd800 && c <= 0xdbff) {
|
|
929
|
+
const next = this.pos + 1 < this.s.length ? this.s.charCodeAt(this.pos + 1) : 0;
|
|
930
|
+
if (next < 0xdc00 || next > 0xdfff) {
|
|
931
|
+
throw notSourceError("internal", {}, "unpaired high surrogate in wire JSON string");
|
|
932
|
+
}
|
|
933
|
+
this.pos += 2;
|
|
934
|
+
continue;
|
|
935
|
+
}
|
|
936
|
+
if (c >= 0xdc00 && c <= 0xdfff) {
|
|
937
|
+
throw notSourceError("internal", {}, "unpaired low surrogate in wire JSON string");
|
|
938
|
+
}
|
|
939
|
+
if (c === 0x5c /* \ */) {
|
|
940
|
+
out += this.s.slice(chunkStart, this.pos);
|
|
941
|
+
this.pos++;
|
|
942
|
+
if (this.pos >= this.s.length) {
|
|
943
|
+
throw notSourceError("internal", {}, "unterminated escape in wire JSON string");
|
|
944
|
+
}
|
|
945
|
+
const esc = this.s.charCodeAt(this.pos++);
|
|
946
|
+
switch (esc) {
|
|
947
|
+
case 0x22:
|
|
948
|
+
out += '"';
|
|
949
|
+
break;
|
|
950
|
+
case 0x5c:
|
|
951
|
+
out += "\\";
|
|
952
|
+
break;
|
|
953
|
+
case 0x2f:
|
|
954
|
+
out += "/";
|
|
955
|
+
break;
|
|
956
|
+
case 0x62:
|
|
957
|
+
out += "\b";
|
|
958
|
+
break;
|
|
959
|
+
case 0x66:
|
|
960
|
+
out += "\f";
|
|
961
|
+
break;
|
|
962
|
+
case 0x6e:
|
|
963
|
+
out += "\n";
|
|
964
|
+
break;
|
|
965
|
+
case 0x72:
|
|
966
|
+
out += "\r";
|
|
967
|
+
break;
|
|
968
|
+
case 0x74:
|
|
969
|
+
out += "\t";
|
|
970
|
+
break;
|
|
971
|
+
case 0x75: {
|
|
972
|
+
const hex = this.s.slice(this.pos, this.pos + 4);
|
|
973
|
+
if (!/^[0-9a-fA-F]{4}$/.test(hex)) {
|
|
974
|
+
throw notSourceError("internal", {}, "invalid \\uXXXX escape in wire JSON");
|
|
975
|
+
}
|
|
976
|
+
this.pos += 4;
|
|
977
|
+
const code = parseInt(hex, 16);
|
|
978
|
+
if (code >= 0xd800 && code <= 0xdbff) {
|
|
979
|
+
if (this.s.charCodeAt(this.pos) !== 0x5c ||
|
|
980
|
+
this.s.charCodeAt(this.pos + 1) !== 0x75) {
|
|
981
|
+
throw notSourceError("internal", {}, "unpaired high surrogate in wire JSON");
|
|
982
|
+
}
|
|
983
|
+
const lowHex = this.s.slice(this.pos + 2, this.pos + 6);
|
|
984
|
+
if (!/^[0-9a-fA-F]{4}$/.test(lowHex)) {
|
|
985
|
+
throw notSourceError("internal", {}, "invalid low surrogate escape in wire JSON");
|
|
986
|
+
}
|
|
987
|
+
const low = parseInt(lowHex, 16);
|
|
988
|
+
if (low < 0xdc00 || low > 0xdfff) {
|
|
989
|
+
throw notSourceError("internal", {}, "invalid surrogate pair in wire JSON");
|
|
990
|
+
}
|
|
991
|
+
this.pos += 6;
|
|
992
|
+
out += String.fromCharCode(code, low);
|
|
993
|
+
}
|
|
994
|
+
else if (code >= 0xdc00 && code <= 0xdfff) {
|
|
995
|
+
throw notSourceError("internal", {}, "unpaired low surrogate in wire JSON");
|
|
996
|
+
}
|
|
997
|
+
else {
|
|
998
|
+
out += String.fromCharCode(code);
|
|
999
|
+
}
|
|
1000
|
+
break;
|
|
1001
|
+
}
|
|
1002
|
+
default:
|
|
1003
|
+
throw notSourceError("internal", {}, "unknown escape in wire JSON string");
|
|
1004
|
+
}
|
|
1005
|
+
chunkStart = this.pos;
|
|
1006
|
+
continue;
|
|
1007
|
+
}
|
|
1008
|
+
this.pos++;
|
|
1009
|
+
}
|
|
1010
|
+
throw notSourceError("internal", {}, "unterminated string in wire JSON");
|
|
1011
|
+
}
|
|
1012
|
+
parseArray(depth) {
|
|
1013
|
+
this.expectChar(0x5b);
|
|
1014
|
+
this.skipWs();
|
|
1015
|
+
const items = [];
|
|
1016
|
+
if (this.pos < this.s.length && this.s.charCodeAt(this.pos) === 0x5d) {
|
|
1017
|
+
this.pos++;
|
|
1018
|
+
return { t: "arr", items };
|
|
1019
|
+
}
|
|
1020
|
+
while (true) {
|
|
1021
|
+
items.push(this.parseValue(depth));
|
|
1022
|
+
this.skipWs();
|
|
1023
|
+
if (this.pos < this.s.length && this.s.charCodeAt(this.pos) === 0x2c) {
|
|
1024
|
+
this.pos++;
|
|
1025
|
+
continue;
|
|
1026
|
+
}
|
|
1027
|
+
this.expectChar(0x5d);
|
|
1028
|
+
return { t: "arr", items };
|
|
1029
|
+
}
|
|
1030
|
+
}
|
|
1031
|
+
parseObject(depth) {
|
|
1032
|
+
this.expectChar(0x7b);
|
|
1033
|
+
this.skipWs();
|
|
1034
|
+
const map = new Map();
|
|
1035
|
+
if (this.pos < this.s.length && this.s.charCodeAt(this.pos) === 0x7d) {
|
|
1036
|
+
this.pos++;
|
|
1037
|
+
return { t: "obj", map };
|
|
1038
|
+
}
|
|
1039
|
+
while (true) {
|
|
1040
|
+
const key = this.parseString();
|
|
1041
|
+
if (map.has(key)) {
|
|
1042
|
+
throw notSourceError("internal", {}, `duplicate JSON object key: ${key}`);
|
|
1043
|
+
}
|
|
1044
|
+
this.expectChar(0x3a);
|
|
1045
|
+
const val = this.parseValue(depth);
|
|
1046
|
+
map.set(key, val);
|
|
1047
|
+
this.skipWs();
|
|
1048
|
+
if (this.pos < this.s.length && this.s.charCodeAt(this.pos) === 0x2c) {
|
|
1049
|
+
this.pos++;
|
|
1050
|
+
continue;
|
|
1051
|
+
}
|
|
1052
|
+
this.expectChar(0x7d);
|
|
1053
|
+
return { t: "obj", map };
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
function expectExactKeys(obj, required) {
|
|
1058
|
+
if (obj.size !== required.length) {
|
|
1059
|
+
throw notSourceError("internal", {}, "unexpected or missing fields in wire object");
|
|
1060
|
+
}
|
|
1061
|
+
for (const k of required) {
|
|
1062
|
+
if (!obj.has(k)) {
|
|
1063
|
+
throw notSourceError("internal", {}, `missing required wire field: ${k}`);
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
function expectStr(val, field) {
|
|
1068
|
+
if (!val || val.t !== "str") {
|
|
1069
|
+
throw notSourceError("internal", {}, `expected string for ${field}`);
|
|
1070
|
+
}
|
|
1071
|
+
return val.v;
|
|
1072
|
+
}
|
|
1073
|
+
function expectBool(val, field) {
|
|
1074
|
+
if (!val || val.t !== "bool") {
|
|
1075
|
+
throw notSourceError("internal", {}, `expected boolean for ${field}`);
|
|
1076
|
+
}
|
|
1077
|
+
return val.v;
|
|
1078
|
+
}
|
|
1079
|
+
function expectInt(val, field) {
|
|
1080
|
+
if (!val || val.t !== "int") {
|
|
1081
|
+
throw notSourceError("internal", {}, `expected unsigned integer for ${field}`);
|
|
1082
|
+
}
|
|
1083
|
+
return val.v;
|
|
1084
|
+
}
|
|
1085
|
+
function decodeLoc(val, idx) {
|
|
1086
|
+
if (val.t !== "arr" || val.items.length !== 3) {
|
|
1087
|
+
throw notSourceError("internal", {}, "Loc must be [byte, line, col]");
|
|
1088
|
+
}
|
|
1089
|
+
const byteOffset = expectInt(val.items[0], "Loc.byte");
|
|
1090
|
+
const line = expectInt(val.items[1], "Loc.line");
|
|
1091
|
+
const column = expectInt(val.items[2], "Loc.col");
|
|
1092
|
+
if (line < 1 || column < 1) {
|
|
1093
|
+
throw notSourceError("internal", {}, "Loc line and column must be >= 1");
|
|
1094
|
+
}
|
|
1095
|
+
const utf16Offset = idx !== null ? idx.utf16At(byteOffset) : byteOffset;
|
|
1096
|
+
return { byteOffset, utf16Offset, line, column };
|
|
1097
|
+
}
|
|
1098
|
+
function decodeSpan(val, idx) {
|
|
1099
|
+
if (val.t !== "arr" || val.items.length !== 6) {
|
|
1100
|
+
throw notSourceError("internal", {}, "Span must be 6-element array");
|
|
1101
|
+
}
|
|
1102
|
+
const sb = expectInt(val.items[0], "Span.start_byte");
|
|
1103
|
+
const sl = expectInt(val.items[1], "Span.start_line");
|
|
1104
|
+
const sc = expectInt(val.items[2], "Span.start_col");
|
|
1105
|
+
const eb = expectInt(val.items[3], "Span.end_byte");
|
|
1106
|
+
const el = expectInt(val.items[4], "Span.end_line");
|
|
1107
|
+
const ec = expectInt(val.items[5], "Span.end_col");
|
|
1108
|
+
if (sl < 1 || sc < 1 || el < 1 || ec < 1 || eb < sb) {
|
|
1109
|
+
throw notSourceError("internal", {}, "invalid Span coordinates");
|
|
1110
|
+
}
|
|
1111
|
+
return {
|
|
1112
|
+
start: {
|
|
1113
|
+
byteOffset: sb,
|
|
1114
|
+
utf16Offset: idx !== null ? idx.utf16At(sb) : sb,
|
|
1115
|
+
line: sl,
|
|
1116
|
+
column: sc,
|
|
1117
|
+
},
|
|
1118
|
+
end: {
|
|
1119
|
+
byteOffset: eb,
|
|
1120
|
+
utf16Offset: idx !== null ? idx.utf16At(eb) : eb,
|
|
1121
|
+
line: el,
|
|
1122
|
+
column: ec,
|
|
1123
|
+
},
|
|
1124
|
+
};
|
|
1125
|
+
}
|
|
1126
|
+
function decodeNode(val, ctx, depth) {
|
|
1127
|
+
if (val.t !== "obj") {
|
|
1128
|
+
throw notSourceError("internal", {}, "Node must be a JSON object");
|
|
1129
|
+
}
|
|
1130
|
+
if (ctx.nodesRemaining <= 0) {
|
|
1131
|
+
throw notSourceError("internal", {}, "wire Node count exceeds max_nodes");
|
|
1132
|
+
}
|
|
1133
|
+
ctx.nodesRemaining -= 1;
|
|
1134
|
+
const map = val.map;
|
|
1135
|
+
const kind = expectStr(map.get("kind"), "Node.kind");
|
|
1136
|
+
const spanVal = map.get("span");
|
|
1137
|
+
const viaVal = map.get("via");
|
|
1138
|
+
const tagStartVal = map.get("tag_start");
|
|
1139
|
+
if (!spanVal || !viaVal || !tagStartVal) {
|
|
1140
|
+
throw notSourceError("internal", {}, "Node missing location fields");
|
|
1141
|
+
}
|
|
1142
|
+
if (ctx.forbidLocations) {
|
|
1143
|
+
if (spanVal.t !== "null" || viaVal.t !== "null" || tagStartVal.t !== "null") {
|
|
1144
|
+
throw notSourceError("internal", {}, "PathKey must have null span, via and tag_start");
|
|
1145
|
+
}
|
|
1146
|
+
}
|
|
1147
|
+
const span = spanVal.t === "null" ? null : decodeSpan(spanVal, ctx.idx);
|
|
1148
|
+
let via = null;
|
|
1149
|
+
if (viaVal.t !== "null") {
|
|
1150
|
+
if (viaVal.t !== "obj" || viaVal.map.size !== 1) {
|
|
1151
|
+
throw notSourceError("internal", {}, "invalid Node.via");
|
|
1152
|
+
}
|
|
1153
|
+
const aliasSpan = viaVal.map.get("alias");
|
|
1154
|
+
const mergeSpan = viaVal.map.get("merge");
|
|
1155
|
+
if (aliasSpan) {
|
|
1156
|
+
const s = decodeSpan(aliasSpan, ctx.idx);
|
|
1157
|
+
via = { kind: "alias", alias: s, useSite: s };
|
|
1158
|
+
}
|
|
1159
|
+
else if (mergeSpan) {
|
|
1160
|
+
const s = decodeSpan(mergeSpan, ctx.idx);
|
|
1161
|
+
via = { kind: "merge", merge: s, directive: s };
|
|
1162
|
+
}
|
|
1163
|
+
else {
|
|
1164
|
+
throw notSourceError("internal", {}, "unknown Via variant");
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
const tagStart = tagStartVal.t === "null" ? null : decodeLoc(tagStartVal, ctx.idx);
|
|
1168
|
+
switch (kind) {
|
|
1169
|
+
case "null": {
|
|
1170
|
+
expectExactKeys(map, ["kind", "span", "via", "tag_start"]);
|
|
1171
|
+
return { kind: "null", span, via, tagStart };
|
|
1172
|
+
}
|
|
1173
|
+
case "bool": {
|
|
1174
|
+
expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
|
|
1175
|
+
return {
|
|
1176
|
+
kind: "bool",
|
|
1177
|
+
value: expectBool(map.get("value"), "bool.value"),
|
|
1178
|
+
span,
|
|
1179
|
+
via,
|
|
1180
|
+
tagStart,
|
|
1181
|
+
};
|
|
1182
|
+
}
|
|
1183
|
+
case "int": {
|
|
1184
|
+
expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
|
|
1185
|
+
const raw = expectStr(map.get("value"), "int.value");
|
|
1186
|
+
if (!/^(0|-?[1-9][0-9]*)$/.test(raw)) {
|
|
1187
|
+
throw notSourceError("internal", {}, `non-canonical wire int: ${raw}`);
|
|
1188
|
+
}
|
|
1189
|
+
const big = BigInt(raw);
|
|
1190
|
+
if (big < I128_MIN || big > U128_MAX) {
|
|
1191
|
+
throw notSourceError("internal", {}, `wire int out of 128-bit range: ${raw}`);
|
|
1192
|
+
}
|
|
1193
|
+
return { kind: "int", value: big, span, via, tagStart };
|
|
1194
|
+
}
|
|
1195
|
+
case "float": {
|
|
1196
|
+
expectExactKeys(map, ["kind", "bits", "span", "via", "tag_start"]);
|
|
1197
|
+
const rawBits = expectStr(map.get("bits"), "float.bits");
|
|
1198
|
+
if (!/^[0-9a-f]{16}$/.test(rawBits)) {
|
|
1199
|
+
throw notSourceError("internal", {}, `invalid wire float bits: ${rawBits}`);
|
|
1200
|
+
}
|
|
1201
|
+
const { value, canonicalBits } = bitsToFloat(rawBits);
|
|
1202
|
+
return { kind: "float", value, bits: canonicalBits, span, via, tagStart };
|
|
1203
|
+
}
|
|
1204
|
+
case "string": {
|
|
1205
|
+
expectExactKeys(map, ["kind", "value", "span", "via", "tag_start"]);
|
|
1206
|
+
const strVal = expectStr(map.get("value"), "string.value");
|
|
1207
|
+
return { kind: "string", value: strVal, span, via, tagStart };
|
|
1208
|
+
}
|
|
1209
|
+
case "sequence": {
|
|
1210
|
+
expectExactKeys(map, ["kind", "items", "span", "via", "tag_start"]);
|
|
1211
|
+
if (depth + 1 > ctx.opts.limits.maxDepth) {
|
|
1212
|
+
throw notSourceError("internal", {}, "wire sequence depth exceeds max_depth");
|
|
1213
|
+
}
|
|
1214
|
+
const itemsVal = map.get("items");
|
|
1215
|
+
if (itemsVal.t !== "arr") {
|
|
1216
|
+
throw notSourceError("internal", {}, "sequence.items must be an array");
|
|
1217
|
+
}
|
|
1218
|
+
const items = itemsVal.items.map((it) => decodeNode(it, ctx, depth + 1));
|
|
1219
|
+
return { kind: "sequence", items, span, via, tagStart };
|
|
1220
|
+
}
|
|
1221
|
+
case "mapping": {
|
|
1222
|
+
expectExactKeys(map, ["kind", "entries", "span", "via", "tag_start"]);
|
|
1223
|
+
if (depth + 1 > ctx.opts.limits.maxDepth) {
|
|
1224
|
+
throw notSourceError("internal", {}, "wire mapping depth exceeds max_depth");
|
|
1225
|
+
}
|
|
1226
|
+
const entriesVal = map.get("entries");
|
|
1227
|
+
if (entriesVal.t !== "arr") {
|
|
1228
|
+
throw notSourceError("internal", {}, "mapping.entries must be an array");
|
|
1229
|
+
}
|
|
1230
|
+
if (entriesVal.items.length > ctx.opts.limits.maxMappingEntries) {
|
|
1231
|
+
throw notSourceError("internal", {}, "wire mapping entries exceed max_mapping_entries");
|
|
1232
|
+
}
|
|
1233
|
+
const entries = [];
|
|
1234
|
+
for (const item of entriesVal.items) {
|
|
1235
|
+
if (item.t !== "obj") {
|
|
1236
|
+
throw notSourceError("internal", {}, "mapping entry must be an object");
|
|
1237
|
+
}
|
|
1238
|
+
expectExactKeys(item.map, ["key", "value"]);
|
|
1239
|
+
const k = decodeNode(item.map.get("key"), ctx, depth + 1);
|
|
1240
|
+
const v = decodeNode(item.map.get("value"), ctx, depth + 1);
|
|
1241
|
+
if (containsNan(k)) {
|
|
1242
|
+
throw notSourceError("internal", {}, "wire mapping key contains NaN");
|
|
1243
|
+
}
|
|
1244
|
+
for (const [ek] of entries) {
|
|
1245
|
+
if (keyEq(ek, k)) {
|
|
1246
|
+
throw notSourceError("internal", {}, "wire mapping contains duplicate key");
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
1249
|
+
entries.push([k, v]);
|
|
1250
|
+
}
|
|
1251
|
+
return { kind: "mapping", entries, span, via, tagStart };
|
|
1252
|
+
}
|
|
1253
|
+
case "tagged": {
|
|
1254
|
+
expectExactKeys(map, ["kind", "tag", "value", "span", "via", "tag_start"]);
|
|
1255
|
+
const tagVal = map.get("tag");
|
|
1256
|
+
if (tagVal.t !== "obj") {
|
|
1257
|
+
throw notSourceError("internal", {}, "tagged.tag must be an object");
|
|
1258
|
+
}
|
|
1259
|
+
expectExactKeys(tagVal.map, ["uri", "handle", "suffix"]);
|
|
1260
|
+
const uri = expectStr(tagVal.map.get("uri"), "tag.uri");
|
|
1261
|
+
const handle = expectStr(tagVal.map.get("handle"), "tag.handle");
|
|
1262
|
+
const suffix = expectStr(tagVal.map.get("suffix"), "tag.suffix");
|
|
1263
|
+
if (uri.length === 0) {
|
|
1264
|
+
throw notSourceError("internal", {}, "tag.uri must not be empty");
|
|
1265
|
+
}
|
|
1266
|
+
// Tagged wrapper does not add collection depth; nested Tagged-in-Tagged is forbidden.
|
|
1267
|
+
const inner = decodeNode(map.get("value"), ctx, depth);
|
|
1268
|
+
if (inner.kind === "tagged") {
|
|
1269
|
+
throw notSourceError("internal", {}, "nested Tagged-in-Tagged is invalid in yamlprims-value/1");
|
|
1270
|
+
}
|
|
1271
|
+
return {
|
|
1272
|
+
kind: "tagged",
|
|
1273
|
+
tag: { uri, handle, suffix },
|
|
1274
|
+
value: inner,
|
|
1275
|
+
span,
|
|
1276
|
+
via,
|
|
1277
|
+
tagStart,
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
default:
|
|
1281
|
+
throw notSourceError("internal", {}, `unknown wire Node kind: ${kind}`);
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
function decodeErrorEnvelope(errObj, opts, sourceBytes) {
|
|
1285
|
+
expectExactKeys(errObj, ["kind", "detail", "site", "related", "path", "message"]);
|
|
1286
|
+
const kindStr = expectStr(errObj.get("kind"), "error.kind");
|
|
1287
|
+
const detailVal = errObj.get("detail");
|
|
1288
|
+
if (detailVal.t !== "obj") {
|
|
1289
|
+
throw notSourceError("internal", {}, "error.detail must be an object");
|
|
1290
|
+
}
|
|
1291
|
+
let detail;
|
|
1292
|
+
if (kindStr === "invalid_utf8") {
|
|
1293
|
+
expectExactKeys(detailVal.map, ["invalid_len"]);
|
|
1294
|
+
const il = detailVal.map.get("invalid_len");
|
|
1295
|
+
if (il.t === "null") {
|
|
1296
|
+
detail = { invalid_len: null };
|
|
1297
|
+
}
|
|
1298
|
+
else if (il.t === "int") {
|
|
1299
|
+
detail = { invalid_len: il.v };
|
|
1300
|
+
}
|
|
1301
|
+
else {
|
|
1302
|
+
throw notSourceError("internal", {}, "invalid invalid_utf8.invalid_len");
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
else if (kindStr === "syntax") {
|
|
1306
|
+
expectExactKeys(detailVal.map, ["syntax_kind"]);
|
|
1307
|
+
const sk = expectStr(detailVal.map.get("syntax_kind"), "detail.syntax_kind");
|
|
1308
|
+
if (!SYNTAX_KINDS.has(sk)) {
|
|
1309
|
+
throw notSourceError("internal", {}, `unknown syntax_kind: ${sk}`);
|
|
1310
|
+
}
|
|
1311
|
+
detail = { syntax_kind: sk };
|
|
1312
|
+
}
|
|
1313
|
+
else if (kindStr === "limit_exceeded") {
|
|
1314
|
+
expectExactKeys(detailVal.map, ["limit", "configured"]);
|
|
1315
|
+
const lim = expectStr(detailVal.map.get("limit"), "detail.limit");
|
|
1316
|
+
if (!LIMIT_KINDS.has(lim)) {
|
|
1317
|
+
throw notSourceError("internal", {}, `unknown limit kind: ${lim}`);
|
|
1318
|
+
}
|
|
1319
|
+
const configured = expectInt(detailVal.map.get("configured"), "detail.configured");
|
|
1320
|
+
detail = { limit: lim, configured };
|
|
1321
|
+
}
|
|
1322
|
+
else if (kindStr === "type") {
|
|
1323
|
+
expectExactKeys(detailVal.map, ["expected", "found"]);
|
|
1324
|
+
const expected = expectStr(detailVal.map.get("expected"), "detail.expected");
|
|
1325
|
+
const found = expectStr(detailVal.map.get("found"), "detail.found");
|
|
1326
|
+
detail = { expected, found };
|
|
1327
|
+
}
|
|
1328
|
+
else if (kindStr === "missing_field" || kindStr === "unknown_field") {
|
|
1329
|
+
expectExactKeys(detailVal.map, ["field"]);
|
|
1330
|
+
const field = expectStr(detailVal.map.get("field"), "detail.field");
|
|
1331
|
+
detail = { field };
|
|
1332
|
+
}
|
|
1333
|
+
else if (kindStr === "output_limit_exceeded") {
|
|
1334
|
+
expectExactKeys(detailVal.map, ["configured"]);
|
|
1335
|
+
const configured = expectInt(detailVal.map.get("configured"), "detail.configured");
|
|
1336
|
+
detail = { configured };
|
|
1337
|
+
}
|
|
1338
|
+
else if (EMPTY_DETAIL_ERROR_KINDS.has(kindStr)) {
|
|
1339
|
+
expectExactKeys(detailVal.map, []);
|
|
1340
|
+
detail = {};
|
|
1341
|
+
}
|
|
1342
|
+
else {
|
|
1343
|
+
throw notSourceError("internal", {}, `unknown error kind: ${kindStr}`);
|
|
1344
|
+
}
|
|
1345
|
+
const siteVal = errObj.get("site");
|
|
1346
|
+
if (siteVal.t !== "obj" || siteVal.map.size !== 1) {
|
|
1347
|
+
throw notSourceError("internal", {}, "invalid error.site");
|
|
1348
|
+
}
|
|
1349
|
+
// For invalid_utf8, only the prefix up to the site's byte_offset is guaranteed valid UTF-8.
|
|
1350
|
+
let validPrefixLimit;
|
|
1351
|
+
const srcLocRaw = siteVal.map.get("source");
|
|
1352
|
+
if (srcLocRaw && srcLocRaw.t === "arr" && srcLocRaw.items.length === 3) {
|
|
1353
|
+
validPrefixLimit = expectInt(srcLocRaw.items[0], "site.source.byte");
|
|
1354
|
+
}
|
|
1355
|
+
const idx = sourceBytes !== undefined
|
|
1356
|
+
? new Utf16Index(sourceBytes, kindStr === "invalid_utf8" ? validPrefixLimit : sourceBytes.byteLength)
|
|
1357
|
+
: null;
|
|
1358
|
+
let site;
|
|
1359
|
+
if (srcLocRaw) {
|
|
1360
|
+
site = { source: decodeLoc(srcLocRaw, idx) };
|
|
1361
|
+
}
|
|
1362
|
+
else {
|
|
1363
|
+
const ns = siteVal.map.get("not_source");
|
|
1364
|
+
if (!ns || ns.t !== "obj") {
|
|
1365
|
+
throw notSourceError("internal", {}, "invalid error.site.not_source");
|
|
1366
|
+
}
|
|
1367
|
+
expectExactKeys(ns.map, ["last_known"]);
|
|
1368
|
+
const lk = ns.map.get("last_known");
|
|
1369
|
+
site = {
|
|
1370
|
+
notSource: {
|
|
1371
|
+
lastKnown: lk.t === "null" ? null : decodeLoc(lk, idx),
|
|
1372
|
+
},
|
|
1373
|
+
};
|
|
1374
|
+
}
|
|
1375
|
+
const relVal = errObj.get("related");
|
|
1376
|
+
if (relVal.t !== "arr") {
|
|
1377
|
+
throw notSourceError("internal", {}, "error.related must be an array");
|
|
1378
|
+
}
|
|
1379
|
+
const related = [];
|
|
1380
|
+
for (const r of relVal.items) {
|
|
1381
|
+
if (r.t !== "obj") {
|
|
1382
|
+
throw notSourceError("internal", {}, "related entry must be an object");
|
|
1383
|
+
}
|
|
1384
|
+
expectExactKeys(r.map, ["role", "span"]);
|
|
1385
|
+
const role = expectStr(r.map.get("role"), "related.role");
|
|
1386
|
+
if (role !== "first_definition" &&
|
|
1387
|
+
role !== "alias_use" &&
|
|
1388
|
+
role !== "merge_directive" &&
|
|
1389
|
+
role !== "anchor_definition") {
|
|
1390
|
+
throw notSourceError("internal", {}, `unknown related.role: ${role}`);
|
|
1391
|
+
}
|
|
1392
|
+
const span = decodeSpan(r.map.get("span"), idx);
|
|
1393
|
+
related.push({ role, span });
|
|
1394
|
+
}
|
|
1395
|
+
const pathVal = errObj.get("path");
|
|
1396
|
+
if (pathVal.t !== "arr") {
|
|
1397
|
+
throw notSourceError("internal", {}, "error.path must be an array");
|
|
1398
|
+
}
|
|
1399
|
+
if (pathVal.items.length > opts.limits.maxDepth) {
|
|
1400
|
+
throw notSourceError("internal", {}, "error.path length exceeds max_depth");
|
|
1401
|
+
}
|
|
1402
|
+
const path = [];
|
|
1403
|
+
for (const seg of pathVal.items) {
|
|
1404
|
+
if (seg.t !== "obj" || seg.map.size !== 1) {
|
|
1405
|
+
throw notSourceError("internal", {}, "invalid path segment");
|
|
1406
|
+
}
|
|
1407
|
+
const idxSeg = seg.map.get("index");
|
|
1408
|
+
const keySeg = seg.map.get("key");
|
|
1409
|
+
if (idxSeg) {
|
|
1410
|
+
path.push({ index: expectInt(idxSeg, "path.index") });
|
|
1411
|
+
}
|
|
1412
|
+
else if (keySeg) {
|
|
1413
|
+
const ctx = {
|
|
1414
|
+
opts,
|
|
1415
|
+
idx: null,
|
|
1416
|
+
nodesRemaining: opts.limits.maxNodes,
|
|
1417
|
+
forbidLocations: true,
|
|
1418
|
+
};
|
|
1419
|
+
const keyNode = decodeNode(keySeg, ctx, 0);
|
|
1420
|
+
preflightKeyNode(keyNode, opts.limits);
|
|
1421
|
+
path.push({ key: keyNode });
|
|
1422
|
+
}
|
|
1423
|
+
else {
|
|
1424
|
+
throw notSourceError("internal", {}, "unknown path segment variant");
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
const message = expectStr(errObj.get("message"), "error.message");
|
|
1428
|
+
return new YamlprimsError({
|
|
1429
|
+
kind: kindStr,
|
|
1430
|
+
detail,
|
|
1431
|
+
site,
|
|
1432
|
+
related,
|
|
1433
|
+
path,
|
|
1434
|
+
message,
|
|
1435
|
+
});
|
|
1436
|
+
}
|
|
1437
|
+
export function decodeWire(wireJson, options, sourceInput) {
|
|
1438
|
+
const opts = validateOptions(options);
|
|
1439
|
+
assertWellFormedUnicode(wireJson, "wireJson");
|
|
1440
|
+
const wireByteLen = encoder.encode(wireJson).byteLength;
|
|
1441
|
+
if (wireByteLen > opts.limits.maxOutputBytes) {
|
|
1442
|
+
throw notSourceError("output_limit_exceeded", { configured: opts.limits.maxOutputBytes }, `wire input exceeds max_output_bytes (${opts.limits.maxOutputBytes})`);
|
|
1443
|
+
}
|
|
1444
|
+
const sourceBytes = sourceInput !== undefined ? toInputBytes(sourceInput) : undefined;
|
|
1445
|
+
const maxJsonDepth = opts.limits.maxDepth * 4 + 32;
|
|
1446
|
+
const root = new WireJsonParser(wireJson, maxJsonDepth).parseRoot();
|
|
1447
|
+
if (root.t !== "obj") {
|
|
1448
|
+
throw notSourceError("internal", {}, "wire root must be a JSON object");
|
|
1449
|
+
}
|
|
1450
|
+
const fmt = expectStr(root.map.get("format"), "format");
|
|
1451
|
+
if (fmt !== "yamlprims-value") {
|
|
1452
|
+
throw notSourceError("internal", {}, `unsupported wire format: ${fmt}`);
|
|
1453
|
+
}
|
|
1454
|
+
const ver = expectInt(root.map.get("version"), "version");
|
|
1455
|
+
if (ver !== 1) {
|
|
1456
|
+
throw notSourceError("internal", {}, `unsupported wire version: ${ver}`);
|
|
1457
|
+
}
|
|
1458
|
+
if (root.map.has("documents")) {
|
|
1459
|
+
expectExactKeys(root.map, ["format", "version", "documents"]);
|
|
1460
|
+
const docsVal = root.map.get("documents");
|
|
1461
|
+
if (docsVal.t !== "arr") {
|
|
1462
|
+
throw notSourceError("internal", {}, "documents must be an array");
|
|
1463
|
+
}
|
|
1464
|
+
if (docsVal.items.length > opts.limits.maxDocuments) {
|
|
1465
|
+
throw notSourceError("internal", {}, "wire document count exceeds max_documents");
|
|
1466
|
+
}
|
|
1467
|
+
const idx = sourceBytes !== undefined ? new Utf16Index(sourceBytes) : null;
|
|
1468
|
+
const ctx = {
|
|
1469
|
+
opts,
|
|
1470
|
+
idx,
|
|
1471
|
+
nodesRemaining: opts.limits.maxNodes,
|
|
1472
|
+
forbidLocations: false,
|
|
1473
|
+
};
|
|
1474
|
+
const documents = [];
|
|
1475
|
+
for (const d of docsVal.items) {
|
|
1476
|
+
if (d.t !== "obj") {
|
|
1477
|
+
throw notSourceError("internal", {}, "Document must be an object");
|
|
1478
|
+
}
|
|
1479
|
+
expectExactKeys(d.map, ["yaml_version", "explicit_start", "root"]);
|
|
1480
|
+
const yvVal = d.map.get("yaml_version");
|
|
1481
|
+
let yamlVersion = null;
|
|
1482
|
+
if (yvVal.t !== "null") {
|
|
1483
|
+
if (yvVal.t !== "arr" || yvVal.items.length !== 2) {
|
|
1484
|
+
throw notSourceError("internal", {}, "yaml_version must be null or [major, minor]");
|
|
1485
|
+
}
|
|
1486
|
+
const major = expectInt(yvVal.items[0], "yaml_version.major");
|
|
1487
|
+
const minor = expectInt(yvVal.items[1], "yaml_version.minor");
|
|
1488
|
+
if (major > 0xffffffff || minor > 0xffffffff) {
|
|
1489
|
+
throw notSourceError("internal", {}, "yaml_version exceeds u32 range");
|
|
1490
|
+
}
|
|
1491
|
+
yamlVersion = [major, minor];
|
|
1492
|
+
}
|
|
1493
|
+
const explicitStart = expectBool(d.map.get("explicit_start"), "explicit_start");
|
|
1494
|
+
const rootNode = decodeNode(d.map.get("root"), ctx, 0);
|
|
1495
|
+
documents.push({ yamlVersion, explicitStart, root: rootNode });
|
|
1496
|
+
}
|
|
1497
|
+
return { kind: "documents", documents };
|
|
1498
|
+
}
|
|
1499
|
+
if (root.map.has("error")) {
|
|
1500
|
+
expectExactKeys(root.map, ["format", "version", "error"]);
|
|
1501
|
+
const errVal = root.map.get("error");
|
|
1502
|
+
if (errVal.t !== "obj") {
|
|
1503
|
+
throw notSourceError("internal", {}, "error must be an object");
|
|
1504
|
+
}
|
|
1505
|
+
return {
|
|
1506
|
+
kind: "error",
|
|
1507
|
+
error: decodeErrorEnvelope(errVal.map, opts, sourceBytes),
|
|
1508
|
+
};
|
|
1509
|
+
}
|
|
1510
|
+
throw notSourceError("internal", {}, "wire envelope must contain documents or error");
|
|
1511
|
+
}
|
|
1512
|
+
// ---- Canonical wire encoder & plain projection ---------------------------
|
|
1513
|
+
class BoundedWriter {
|
|
1514
|
+
chunks = [];
|
|
1515
|
+
byteLen = 0;
|
|
1516
|
+
maxBytes;
|
|
1517
|
+
constructor(maxBytes) {
|
|
1518
|
+
this.maxBytes = maxBytes;
|
|
1519
|
+
}
|
|
1520
|
+
pushRaw(ascii) {
|
|
1521
|
+
const len = ascii.length;
|
|
1522
|
+
if (this.byteLen + len > this.maxBytes) {
|
|
1523
|
+
this.throwOver();
|
|
1524
|
+
}
|
|
1525
|
+
this.byteLen += len;
|
|
1526
|
+
this.chunks.push(ascii);
|
|
1527
|
+
}
|
|
1528
|
+
pushMetaInt(n, label) {
|
|
1529
|
+
if (typeof n !== "number" ||
|
|
1530
|
+
!Number.isInteger(n) ||
|
|
1531
|
+
n < 0 ||
|
|
1532
|
+
n > MAX_SAFE_METADATA_INT) {
|
|
1533
|
+
throw notSourceError("internal", {}, `metadata integer out of range for ${label}`);
|
|
1534
|
+
}
|
|
1535
|
+
this.pushRaw(String(n));
|
|
1536
|
+
}
|
|
1537
|
+
pushString(s) {
|
|
1538
|
+
assertWellFormedUnicode(s, "string");
|
|
1539
|
+
this.pushStringParts(s, "");
|
|
1540
|
+
}
|
|
1541
|
+
pushBoundedString(s, maxUtf8Bytes) {
|
|
1542
|
+
assertWellFormedUnicode(s, "string");
|
|
1543
|
+
const utf8 = encoder.encode(s);
|
|
1544
|
+
if (utf8.byteLength <= maxUtf8Bytes) {
|
|
1545
|
+
this.pushStringParts(s, "");
|
|
1546
|
+
return;
|
|
1547
|
+
}
|
|
1548
|
+
// Ellipsis '…' is 3 UTF-8 bytes.
|
|
1549
|
+
let cut = Math.max(0, maxUtf8Bytes - 3);
|
|
1550
|
+
while (cut > 0 && ((utf8[cut] ?? 0) & 0xc0) === 0x80) {
|
|
1551
|
+
cut--;
|
|
1552
|
+
}
|
|
1553
|
+
const prefix = decoder.decode(utf8.subarray(0, cut));
|
|
1554
|
+
this.pushStringParts(prefix, "…");
|
|
1555
|
+
}
|
|
1556
|
+
pushStringParts(a, b) {
|
|
1557
|
+
assertWellFormedUnicode(a, "string");
|
|
1558
|
+
assertWellFormedUnicode(b, "string");
|
|
1559
|
+
const aBytes = encoder.encode(a).byteLength;
|
|
1560
|
+
const bBytes = encoder.encode(b).byteLength;
|
|
1561
|
+
if (this.byteLen + aBytes + bBytes + 2 > this.maxBytes) {
|
|
1562
|
+
this.throwOver();
|
|
1563
|
+
}
|
|
1564
|
+
this.pushRaw('"');
|
|
1565
|
+
for (const part of [a, b]) {
|
|
1566
|
+
let run = 0;
|
|
1567
|
+
for (let i = 0; i < part.length; i++) {
|
|
1568
|
+
const c = part.charCodeAt(i);
|
|
1569
|
+
let esc = null;
|
|
1570
|
+
if (c === 0x22)
|
|
1571
|
+
esc = '\\"';
|
|
1572
|
+
else if (c === 0x5c)
|
|
1573
|
+
esc = "\\\\";
|
|
1574
|
+
else if (c === 0x08)
|
|
1575
|
+
esc = "\\b";
|
|
1576
|
+
else if (c === 0x0c)
|
|
1577
|
+
esc = "\\f";
|
|
1578
|
+
else if (c === 0x0a)
|
|
1579
|
+
esc = "\\n";
|
|
1580
|
+
else if (c === 0x0d)
|
|
1581
|
+
esc = "\\r";
|
|
1582
|
+
else if (c === 0x09)
|
|
1583
|
+
esc = "\\t";
|
|
1584
|
+
else if (c < 0x20)
|
|
1585
|
+
esc = `\\u${c.toString(16).padStart(4, "0")}`;
|
|
1586
|
+
if (esc !== null) {
|
|
1587
|
+
if (i > run) {
|
|
1588
|
+
this.pushUtf8Slice(part.slice(run, i));
|
|
1589
|
+
}
|
|
1590
|
+
this.pushRaw(esc);
|
|
1591
|
+
run = i + 1;
|
|
1592
|
+
}
|
|
1593
|
+
}
|
|
1594
|
+
if (run < part.length) {
|
|
1595
|
+
this.pushUtf8Slice(part.slice(run));
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
this.pushRaw('"');
|
|
1599
|
+
}
|
|
1600
|
+
pushUtf8Slice(sub) {
|
|
1601
|
+
const len = encoder.encode(sub).byteLength;
|
|
1602
|
+
if (this.byteLen + len > this.maxBytes) {
|
|
1603
|
+
this.throwOver();
|
|
1604
|
+
}
|
|
1605
|
+
this.byteLen += len;
|
|
1606
|
+
this.chunks.push(sub);
|
|
1607
|
+
}
|
|
1608
|
+
pushLoc(loc) {
|
|
1609
|
+
if (loc.line < 1 || loc.column < 1) {
|
|
1610
|
+
throw notSourceError("internal", {}, "Location line and column must be >= 1");
|
|
1611
|
+
}
|
|
1612
|
+
this.pushRaw("[");
|
|
1613
|
+
this.pushMetaInt(loc.byteOffset, "Location.byteOffset");
|
|
1614
|
+
this.pushRaw(",");
|
|
1615
|
+
this.pushMetaInt(loc.line, "Location.line");
|
|
1616
|
+
this.pushRaw(",");
|
|
1617
|
+
this.pushMetaInt(loc.column, "Location.column");
|
|
1618
|
+
this.pushRaw("]");
|
|
1619
|
+
}
|
|
1620
|
+
pushSpan(span) {
|
|
1621
|
+
if (span.start.line < 1 ||
|
|
1622
|
+
span.start.column < 1 ||
|
|
1623
|
+
span.end.line < 1 ||
|
|
1624
|
+
span.end.column < 1 ||
|
|
1625
|
+
span.end.byteOffset < span.start.byteOffset) {
|
|
1626
|
+
throw notSourceError("internal", {}, "invalid Span coordinates");
|
|
1627
|
+
}
|
|
1628
|
+
this.pushRaw("[");
|
|
1629
|
+
this.pushMetaInt(span.start.byteOffset, "Span.start.byteOffset");
|
|
1630
|
+
this.pushRaw(",");
|
|
1631
|
+
this.pushMetaInt(span.start.line, "Span.start.line");
|
|
1632
|
+
this.pushRaw(",");
|
|
1633
|
+
this.pushMetaInt(span.start.column, "Span.start.column");
|
|
1634
|
+
this.pushRaw(",");
|
|
1635
|
+
this.pushMetaInt(span.end.byteOffset, "Span.end.byteOffset");
|
|
1636
|
+
this.pushRaw(",");
|
|
1637
|
+
this.pushMetaInt(span.end.line, "Span.end.line");
|
|
1638
|
+
this.pushRaw(",");
|
|
1639
|
+
this.pushMetaInt(span.end.column, "Span.end.column");
|
|
1640
|
+
this.pushRaw("]");
|
|
1641
|
+
}
|
|
1642
|
+
finish() {
|
|
1643
|
+
return this.chunks.join("");
|
|
1644
|
+
}
|
|
1645
|
+
throwOver() {
|
|
1646
|
+
throw notSourceError("output_limit_exceeded", { configured: this.maxBytes }, `encoded output exceeds max_output_bytes (${this.maxBytes})`);
|
|
1647
|
+
}
|
|
1648
|
+
}
|
|
1649
|
+
function writeNodeValue(w, n, withSpans, st, depth) {
|
|
1650
|
+
if (st.nodesRemaining <= 0) {
|
|
1651
|
+
throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: st.opts.limits.maxNodes }, "tree exceeds max_nodes");
|
|
1652
|
+
}
|
|
1653
|
+
st.nodesRemaining -= 1;
|
|
1654
|
+
if (st.activeAncestors.has(n)) {
|
|
1655
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "cyclic node graph exceeds max_depth");
|
|
1656
|
+
}
|
|
1657
|
+
w.pushRaw('{"kind":');
|
|
1658
|
+
w.pushString(n.kind);
|
|
1659
|
+
switch (n.kind) {
|
|
1660
|
+
case "null":
|
|
1661
|
+
break;
|
|
1662
|
+
case "bool":
|
|
1663
|
+
w.pushRaw(n.value ? ',"value":true' : ',"value":false');
|
|
1664
|
+
break;
|
|
1665
|
+
case "int": {
|
|
1666
|
+
if (typeof n.value !== "bigint" || n.value < I128_MIN || n.value > U128_MAX) {
|
|
1667
|
+
throw notSourceError("integer_out_of_range", {}, "integer node out of 128-bit range");
|
|
1668
|
+
}
|
|
1669
|
+
w.pushRaw(',"value":');
|
|
1670
|
+
w.pushString(n.value.toString(10));
|
|
1671
|
+
break;
|
|
1672
|
+
}
|
|
1673
|
+
case "float": {
|
|
1674
|
+
w.pushRaw(',"bits":');
|
|
1675
|
+
w.pushString(floatToBits(n.value));
|
|
1676
|
+
break;
|
|
1677
|
+
}
|
|
1678
|
+
case "string": {
|
|
1679
|
+
w.pushRaw(',"value":');
|
|
1680
|
+
w.pushString(n.value);
|
|
1681
|
+
break;
|
|
1682
|
+
}
|
|
1683
|
+
case "sequence": {
|
|
1684
|
+
if (depth + 1 > st.opts.limits.maxDepth) {
|
|
1685
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "sequence nesting exceeds max_depth");
|
|
1686
|
+
}
|
|
1687
|
+
st.activeAncestors.add(n);
|
|
1688
|
+
w.pushRaw(',"items":[');
|
|
1689
|
+
for (let i = 0; i < n.items.length; i++) {
|
|
1690
|
+
if (i > 0)
|
|
1691
|
+
w.pushRaw(",");
|
|
1692
|
+
writeNode(w, n.items[i], withSpans, st, depth + 1);
|
|
1693
|
+
}
|
|
1694
|
+
w.pushRaw("]");
|
|
1695
|
+
st.activeAncestors.delete(n);
|
|
1696
|
+
break;
|
|
1697
|
+
}
|
|
1698
|
+
case "mapping": {
|
|
1699
|
+
if (depth + 1 > st.opts.limits.maxDepth) {
|
|
1700
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: st.opts.limits.maxDepth }, "mapping nesting exceeds max_depth");
|
|
1701
|
+
}
|
|
1702
|
+
if (n.entries.length > st.opts.limits.maxMappingEntries) {
|
|
1703
|
+
throw notSourceError("limit_exceeded", { limit: "max_mapping_entries", configured: st.opts.limits.maxMappingEntries }, "mapping entries exceed max_mapping_entries");
|
|
1704
|
+
}
|
|
1705
|
+
st.activeAncestors.add(n);
|
|
1706
|
+
w.pushRaw(',"entries":[');
|
|
1707
|
+
for (let i = 0; i < n.entries.length; i++) {
|
|
1708
|
+
const [k, v] = n.entries[i];
|
|
1709
|
+
if (containsNan(k)) {
|
|
1710
|
+
throw notSourceError("invalid_key", {}, "mapping key contains NaN");
|
|
1711
|
+
}
|
|
1712
|
+
for (let j = 0; j < i; j++) {
|
|
1713
|
+
if (keyEq(n.entries[j][0], k)) {
|
|
1714
|
+
throw notSourceError("duplicate_key", {}, "duplicate mapping key");
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
if (i > 0)
|
|
1718
|
+
w.pushRaw(",");
|
|
1719
|
+
w.pushRaw('{"key":');
|
|
1720
|
+
writeNode(w, k, withSpans, st, depth + 1);
|
|
1721
|
+
w.pushRaw(',"value":');
|
|
1722
|
+
writeNode(w, v, withSpans, st, depth + 1);
|
|
1723
|
+
w.pushRaw("}");
|
|
1724
|
+
}
|
|
1725
|
+
w.pushRaw("]");
|
|
1726
|
+
st.activeAncestors.delete(n);
|
|
1727
|
+
break;
|
|
1728
|
+
}
|
|
1729
|
+
case "tagged": {
|
|
1730
|
+
if (!n.tag || typeof n.tag.uri !== "string" || n.tag.uri.length === 0) {
|
|
1731
|
+
throw notSourceError("internal", {}, "tagged node must have a non-empty tag.uri");
|
|
1732
|
+
}
|
|
1733
|
+
if (n.value.kind === "tagged") {
|
|
1734
|
+
throw notSourceError("internal", {}, "nested Tagged-in-Tagged is invalid in yamlprims-value/1");
|
|
1735
|
+
}
|
|
1736
|
+
st.activeAncestors.add(n);
|
|
1737
|
+
w.pushRaw(',"tag":{"uri":');
|
|
1738
|
+
w.pushString(n.tag.uri);
|
|
1739
|
+
w.pushRaw(',"handle":');
|
|
1740
|
+
w.pushString(n.tag.handle ?? "");
|
|
1741
|
+
w.pushRaw(',"suffix":');
|
|
1742
|
+
w.pushString(n.tag.suffix ?? "");
|
|
1743
|
+
w.pushRaw('},"value":');
|
|
1744
|
+
writeNode(w, n.value, withSpans, st, depth);
|
|
1745
|
+
st.activeAncestors.delete(n);
|
|
1746
|
+
break;
|
|
1747
|
+
}
|
|
1748
|
+
}
|
|
1749
|
+
}
|
|
1750
|
+
function writeNode(w, n, withSpans, st, depth) {
|
|
1751
|
+
writeNodeValue(w, n, withSpans, st, depth);
|
|
1752
|
+
w.pushRaw(',"span":');
|
|
1753
|
+
if (withSpans && n.span !== null && n.span !== undefined) {
|
|
1754
|
+
w.pushSpan(n.span);
|
|
1755
|
+
}
|
|
1756
|
+
else {
|
|
1757
|
+
w.pushRaw("null");
|
|
1758
|
+
}
|
|
1759
|
+
w.pushRaw(',"via":');
|
|
1760
|
+
if (withSpans && n.via !== null && n.via !== undefined) {
|
|
1761
|
+
if (n.via.kind === "alias") {
|
|
1762
|
+
w.pushRaw('{"alias":');
|
|
1763
|
+
w.pushSpan(n.via.alias ?? n.via.useSite);
|
|
1764
|
+
w.pushRaw("}");
|
|
1765
|
+
}
|
|
1766
|
+
else {
|
|
1767
|
+
w.pushRaw('{"merge":');
|
|
1768
|
+
w.pushSpan(n.via.merge ?? n.via.directive);
|
|
1769
|
+
w.pushRaw("}");
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
else {
|
|
1773
|
+
w.pushRaw("null");
|
|
1774
|
+
}
|
|
1775
|
+
w.pushRaw(',"tag_start":');
|
|
1776
|
+
if (withSpans && n.tagStart !== null && n.tagStart !== undefined) {
|
|
1777
|
+
w.pushLoc(n.tagStart);
|
|
1778
|
+
}
|
|
1779
|
+
else {
|
|
1780
|
+
w.pushRaw("null");
|
|
1781
|
+
}
|
|
1782
|
+
w.pushRaw("}");
|
|
1783
|
+
}
|
|
1784
|
+
export function encode(docs, options) {
|
|
1785
|
+
const opts = validateOptions(options);
|
|
1786
|
+
if (docs.length > opts.limits.maxDocuments) {
|
|
1787
|
+
throw notSourceError("limit_exceeded", { limit: "max_documents", configured: opts.limits.maxDocuments }, `document count exceeds max_documents (${opts.limits.maxDocuments})`);
|
|
1788
|
+
}
|
|
1789
|
+
const w = new BoundedWriter(opts.limits.maxOutputBytes);
|
|
1790
|
+
const st = {
|
|
1791
|
+
opts,
|
|
1792
|
+
nodesRemaining: opts.limits.maxNodes,
|
|
1793
|
+
activeAncestors: new Set(),
|
|
1794
|
+
};
|
|
1795
|
+
w.pushRaw('{"format":"yamlprims-value","version":1,"documents":[');
|
|
1796
|
+
for (let i = 0; i < docs.length; i++) {
|
|
1797
|
+
if (i > 0)
|
|
1798
|
+
w.pushRaw(",");
|
|
1799
|
+
const d = docs[i];
|
|
1800
|
+
w.pushRaw('{"yaml_version":');
|
|
1801
|
+
if (d.yamlVersion !== null && d.yamlVersion !== undefined) {
|
|
1802
|
+
const [maj, min] = d.yamlVersion;
|
|
1803
|
+
if (!Number.isInteger(maj) ||
|
|
1804
|
+
!Number.isInteger(min) ||
|
|
1805
|
+
maj < 0 ||
|
|
1806
|
+
min < 0 ||
|
|
1807
|
+
maj > 0xffffffff ||
|
|
1808
|
+
min > 0xffffffff) {
|
|
1809
|
+
throw notSourceError("internal", {}, "invalid Document.yamlVersion");
|
|
1810
|
+
}
|
|
1811
|
+
w.pushRaw(`[${maj},${min}]`);
|
|
1812
|
+
}
|
|
1813
|
+
else {
|
|
1814
|
+
w.pushRaw("null");
|
|
1815
|
+
}
|
|
1816
|
+
w.pushRaw(d.explicitStart ? ',"explicit_start":true,"root":' : ',"explicit_start":false,"root":');
|
|
1817
|
+
writeNode(w, d.root, true, st, 0);
|
|
1818
|
+
w.pushRaw("}");
|
|
1819
|
+
}
|
|
1820
|
+
w.pushRaw("]}");
|
|
1821
|
+
return w.finish();
|
|
1822
|
+
}
|
|
1823
|
+
function tagWeightBytes(tag) {
|
|
1824
|
+
assertWellFormedUnicode(tag.uri, "tag.uri");
|
|
1825
|
+
assertWellFormedUnicode(tag.handle ?? "", "tag.handle");
|
|
1826
|
+
assertWellFormedUnicode(tag.suffix ?? "", "tag.suffix");
|
|
1827
|
+
return BigInt(encoder.encode(tag.uri).byteLength +
|
|
1828
|
+
encoder.encode(tag.handle ?? "").byteLength +
|
|
1829
|
+
encoder.encode(tag.suffix ?? "").byteLength);
|
|
1830
|
+
}
|
|
1831
|
+
function preflightKeyNode(rootKey, limits) {
|
|
1832
|
+
const maxKey = BigInt(limits.maxKeyBytes);
|
|
1833
|
+
let weight = NODE_OVERHEAD;
|
|
1834
|
+
if (weight > maxKey) {
|
|
1835
|
+
throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, "error path key exceeds max_key_bytes");
|
|
1836
|
+
}
|
|
1837
|
+
const stack = [{ node: rootKey, depth: 0 }];
|
|
1838
|
+
while (stack.length > 0) {
|
|
1839
|
+
const { node, depth } = stack.pop();
|
|
1840
|
+
let more = 0n;
|
|
1841
|
+
let children = 0;
|
|
1842
|
+
if (node.kind === "string") {
|
|
1843
|
+
assertWellFormedUnicode(node.value, "string node");
|
|
1844
|
+
more = BigInt(encoder.encode(node.value).byteLength);
|
|
1845
|
+
}
|
|
1846
|
+
else if (node.kind === "tagged") {
|
|
1847
|
+
more = tagWeightBytes(node.tag) + NODE_OVERHEAD;
|
|
1848
|
+
children = 1;
|
|
1849
|
+
}
|
|
1850
|
+
else if (node.kind === "sequence") {
|
|
1851
|
+
more = NODE_OVERHEAD * BigInt(node.items.length);
|
|
1852
|
+
children = node.items.length;
|
|
1853
|
+
}
|
|
1854
|
+
else if (node.kind === "mapping") {
|
|
1855
|
+
more = (2n * NODE_OVERHEAD + ENTRY_OVERHEAD) * BigInt(node.entries.length);
|
|
1856
|
+
children = 2 * node.entries.length;
|
|
1857
|
+
}
|
|
1858
|
+
weight += more;
|
|
1859
|
+
if (weight > maxKey) {
|
|
1860
|
+
throw notSourceError("limit_exceeded", { limit: "max_key_bytes", configured: limits.maxKeyBytes }, "error path key exceeds max_key_bytes");
|
|
1861
|
+
}
|
|
1862
|
+
if (children > 0 && node.kind !== "tagged" && depth + 1 > limits.maxDepth) {
|
|
1863
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: limits.maxDepth }, "error path key nests deeper than max_depth");
|
|
1864
|
+
}
|
|
1865
|
+
if (node.kind === "tagged") {
|
|
1866
|
+
stack.push({ node: node.value, depth });
|
|
1867
|
+
}
|
|
1868
|
+
else if (node.kind === "sequence") {
|
|
1869
|
+
for (const it of node.items) {
|
|
1870
|
+
stack.push({ node: it, depth: depth + 1 });
|
|
1871
|
+
}
|
|
1872
|
+
}
|
|
1873
|
+
else if (node.kind === "mapping") {
|
|
1874
|
+
for (const [k, v] of node.entries) {
|
|
1875
|
+
stack.push({ node: k, depth: depth + 1 });
|
|
1876
|
+
stack.push({ node: v, depth: depth + 1 });
|
|
1877
|
+
}
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
export function encodeError(err, options) {
|
|
1882
|
+
const opts = validateOptions(options);
|
|
1883
|
+
if (err.path.length > opts.limits.maxDepth) {
|
|
1884
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, `error path has ${err.path.length} segments, more than max_depth`);
|
|
1885
|
+
}
|
|
1886
|
+
for (const seg of err.path) {
|
|
1887
|
+
if ("key" in seg) {
|
|
1888
|
+
preflightKeyNode(seg.key, opts.limits);
|
|
1889
|
+
}
|
|
1890
|
+
}
|
|
1891
|
+
const w = new BoundedWriter(opts.limits.maxOutputBytes);
|
|
1892
|
+
w.pushRaw('{"format":"yamlprims-value","version":1,"error":{"kind":');
|
|
1893
|
+
w.pushString(err.kind);
|
|
1894
|
+
w.pushRaw(',"detail":');
|
|
1895
|
+
const d = err.detail;
|
|
1896
|
+
if (err.kind === "invalid_utf8") {
|
|
1897
|
+
if (Object.keys(d).length !== 1 || !("invalid_len" in d)) {
|
|
1898
|
+
throw notSourceError("internal", {}, "invalid invalid_utf8 detail");
|
|
1899
|
+
}
|
|
1900
|
+
const il = d["invalid_len"];
|
|
1901
|
+
if (il === null) {
|
|
1902
|
+
w.pushRaw('{"invalid_len":null}');
|
|
1903
|
+
}
|
|
1904
|
+
else if (typeof il === "number") {
|
|
1905
|
+
w.pushRaw('{"invalid_len":');
|
|
1906
|
+
w.pushMetaInt(il, "detail.invalid_len");
|
|
1907
|
+
w.pushRaw("}");
|
|
1908
|
+
}
|
|
1909
|
+
else {
|
|
1910
|
+
throw notSourceError("internal", {}, "invalid invalid_utf8.invalid_len");
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
else if (err.kind === "syntax") {
|
|
1914
|
+
if (Object.keys(d).length !== 1 || typeof d["syntax_kind"] !== "string") {
|
|
1915
|
+
throw notSourceError("internal", {}, "invalid syntax detail");
|
|
1916
|
+
}
|
|
1917
|
+
const sk = d["syntax_kind"];
|
|
1918
|
+
if (!SYNTAX_KINDS.has(sk)) {
|
|
1919
|
+
throw notSourceError("internal", {}, `unknown syntax_kind: ${sk}`);
|
|
1920
|
+
}
|
|
1921
|
+
w.pushRaw('{"syntax_kind":');
|
|
1922
|
+
w.pushString(sk);
|
|
1923
|
+
w.pushRaw("}");
|
|
1924
|
+
}
|
|
1925
|
+
else if (err.kind === "limit_exceeded") {
|
|
1926
|
+
if (Object.keys(d).length !== 2 ||
|
|
1927
|
+
typeof d["limit"] !== "string" ||
|
|
1928
|
+
typeof d["configured"] !== "number" ||
|
|
1929
|
+
!LIMIT_KINDS.has(d["limit"])) {
|
|
1930
|
+
throw notSourceError("internal", {}, "invalid limit_exceeded detail");
|
|
1931
|
+
}
|
|
1932
|
+
w.pushRaw('{"limit":');
|
|
1933
|
+
w.pushString(d["limit"]);
|
|
1934
|
+
w.pushRaw(',"configured":');
|
|
1935
|
+
w.pushMetaInt(d["configured"], "detail.configured");
|
|
1936
|
+
w.pushRaw("}");
|
|
1937
|
+
}
|
|
1938
|
+
else if (err.kind === "type") {
|
|
1939
|
+
if (Object.keys(d).length !== 2 ||
|
|
1940
|
+
typeof d["expected"] !== "string" ||
|
|
1941
|
+
typeof d["found"] !== "string") {
|
|
1942
|
+
throw notSourceError("internal", {}, "invalid type detail");
|
|
1943
|
+
}
|
|
1944
|
+
w.pushRaw('{"expected":');
|
|
1945
|
+
w.pushBoundedString(d["expected"], MAX_FIELD_BYTES);
|
|
1946
|
+
w.pushRaw(',"found":');
|
|
1947
|
+
w.pushBoundedString(d["found"], MAX_FIELD_BYTES);
|
|
1948
|
+
w.pushRaw("}");
|
|
1949
|
+
}
|
|
1950
|
+
else if (err.kind === "missing_field" || err.kind === "unknown_field") {
|
|
1951
|
+
if (Object.keys(d).length !== 1 || typeof d["field"] !== "string") {
|
|
1952
|
+
throw notSourceError("internal", {}, `invalid ${err.kind} detail`);
|
|
1953
|
+
}
|
|
1954
|
+
w.pushRaw('{"field":');
|
|
1955
|
+
w.pushBoundedString(d["field"], MAX_FIELD_BYTES);
|
|
1956
|
+
w.pushRaw("}");
|
|
1957
|
+
}
|
|
1958
|
+
else if (err.kind === "output_limit_exceeded") {
|
|
1959
|
+
if (Object.keys(d).length !== 1 || typeof d["configured"] !== "number") {
|
|
1960
|
+
throw notSourceError("internal", {}, "invalid output_limit_exceeded detail");
|
|
1961
|
+
}
|
|
1962
|
+
w.pushRaw('{"configured":');
|
|
1963
|
+
w.pushMetaInt(d["configured"], "detail.configured");
|
|
1964
|
+
w.pushRaw("}");
|
|
1965
|
+
}
|
|
1966
|
+
else if (EMPTY_DETAIL_ERROR_KINDS.has(err.kind)) {
|
|
1967
|
+
if (Object.keys(d).length !== 0) {
|
|
1968
|
+
throw notSourceError("internal", {}, `non-empty detail for ${err.kind}`);
|
|
1969
|
+
}
|
|
1970
|
+
w.pushRaw("{}");
|
|
1971
|
+
}
|
|
1972
|
+
else {
|
|
1973
|
+
throw notSourceError("internal", {}, `unknown error kind: ${String(err.kind)}`);
|
|
1974
|
+
}
|
|
1975
|
+
w.pushRaw(',"site":');
|
|
1976
|
+
if (err.site.source !== undefined) {
|
|
1977
|
+
w.pushRaw('{"source":');
|
|
1978
|
+
w.pushLoc(err.site.source);
|
|
1979
|
+
w.pushRaw("}");
|
|
1980
|
+
}
|
|
1981
|
+
else {
|
|
1982
|
+
w.pushRaw('{"not_source":{"last_known":');
|
|
1983
|
+
if (err.site.notSource.lastKnown !== null) {
|
|
1984
|
+
w.pushLoc(err.site.notSource.lastKnown);
|
|
1985
|
+
}
|
|
1986
|
+
else {
|
|
1987
|
+
w.pushRaw("null");
|
|
1988
|
+
}
|
|
1989
|
+
w.pushRaw("}}");
|
|
1990
|
+
}
|
|
1991
|
+
w.pushRaw(',"related":[');
|
|
1992
|
+
for (let i = 0; i < err.related.length; i++) {
|
|
1993
|
+
if (i > 0)
|
|
1994
|
+
w.pushRaw(",");
|
|
1995
|
+
const r = err.related[i];
|
|
1996
|
+
w.pushRaw('{"role":');
|
|
1997
|
+
w.pushString(r.role);
|
|
1998
|
+
w.pushRaw(',"span":');
|
|
1999
|
+
w.pushSpan(r.span);
|
|
2000
|
+
w.pushRaw("}");
|
|
2001
|
+
}
|
|
2002
|
+
const st = {
|
|
2003
|
+
opts,
|
|
2004
|
+
nodesRemaining: opts.limits.maxNodes,
|
|
2005
|
+
activeAncestors: new Set(),
|
|
2006
|
+
};
|
|
2007
|
+
w.pushRaw('],"path":[');
|
|
2008
|
+
for (let i = 0; i < err.path.length; i++) {
|
|
2009
|
+
if (i > 0)
|
|
2010
|
+
w.pushRaw(",");
|
|
2011
|
+
const p = err.path[i];
|
|
2012
|
+
if ("index" in p) {
|
|
2013
|
+
w.pushRaw('{"index":');
|
|
2014
|
+
w.pushMetaInt(p.index, "path.index");
|
|
2015
|
+
w.pushRaw("}");
|
|
2016
|
+
}
|
|
2017
|
+
else {
|
|
2018
|
+
w.pushRaw('{"key":');
|
|
2019
|
+
writeNodeValue(w, p.key, false, st, 0);
|
|
2020
|
+
w.pushRaw(',"span":null,"via":null,"tag_start":null}}');
|
|
2021
|
+
}
|
|
2022
|
+
}
|
|
2023
|
+
w.pushRaw('],"message":');
|
|
2024
|
+
w.pushBoundedString(err.rawMessage, MAX_MESSAGE_BYTES);
|
|
2025
|
+
w.pushRaw("}}");
|
|
2026
|
+
return w.finish();
|
|
2027
|
+
}
|
|
2028
|
+
function isDocument(val) {
|
|
2029
|
+
return "root" in val && !("kind" in val);
|
|
2030
|
+
}
|
|
2031
|
+
function lossError(node, what, expected = "plain JSON value") {
|
|
2032
|
+
const site = node.span !== null && node.span !== undefined
|
|
2033
|
+
? { source: node.span.start }
|
|
2034
|
+
: { notSource: { lastKnown: null } };
|
|
2035
|
+
return new YamlprimsError({
|
|
2036
|
+
kind: "type",
|
|
2037
|
+
detail: { expected, found: what },
|
|
2038
|
+
site,
|
|
2039
|
+
message: `cannot write ${what} as plain JSON without loss`,
|
|
2040
|
+
});
|
|
2041
|
+
}
|
|
2042
|
+
/**
|
|
2043
|
+
* Lossy projection to plain JavaScript values (`spec-v1.4 §11.3`):
|
|
2044
|
+
* - `Int` within `±(2^53-1)` -> `number`; outside -> throws `YamlprimsError` (`kind: "type"`).
|
|
2045
|
+
* - `Float` (including `-0.0`, `NaN`, `±Infinity`) -> `number` in memory.
|
|
2046
|
+
* - `Mapping` with `String` keys -> null-prototype object (`Object.create(null)`);
|
|
2047
|
+
* non-`String` keys -> throws `YamlprimsError` (`kind: "type"`).
|
|
2048
|
+
* - `Tagged` -> throws `YamlprimsError` (`kind: "type"`).
|
|
2049
|
+
*/
|
|
2050
|
+
export function toPlain(nodeOrDoc, options) {
|
|
2051
|
+
const opts = validateOptions(options);
|
|
2052
|
+
const root = isDocument(nodeOrDoc) ? nodeOrDoc.root : nodeOrDoc;
|
|
2053
|
+
let nodesRemaining = opts.limits.maxNodes;
|
|
2054
|
+
const active = new Set();
|
|
2055
|
+
function walk(n, depth) {
|
|
2056
|
+
if (nodesRemaining <= 0) {
|
|
2057
|
+
throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: opts.limits.maxNodes }, "tree exceeds max_nodes");
|
|
2058
|
+
}
|
|
2059
|
+
nodesRemaining -= 1;
|
|
2060
|
+
if (active.has(n)) {
|
|
2061
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "cyclic node graph exceeds max_depth");
|
|
2062
|
+
}
|
|
2063
|
+
switch (n.kind) {
|
|
2064
|
+
case "null":
|
|
2065
|
+
return null;
|
|
2066
|
+
case "bool":
|
|
2067
|
+
return n.value;
|
|
2068
|
+
case "int": {
|
|
2069
|
+
const maxSafe = BigInt(MAX_SAFE_METADATA_INT);
|
|
2070
|
+
if (n.value < -maxSafe || n.value > maxSafe) {
|
|
2071
|
+
throw lossError(n, "integer outside safe integer range");
|
|
2072
|
+
}
|
|
2073
|
+
return n.value === 0n ? 0 : Number(n.value);
|
|
2074
|
+
}
|
|
2075
|
+
case "float":
|
|
2076
|
+
return n.value;
|
|
2077
|
+
case "string":
|
|
2078
|
+
assertWellFormedUnicode(n.value, "string node");
|
|
2079
|
+
return n.value;
|
|
2080
|
+
case "sequence": {
|
|
2081
|
+
if (depth + 1 > opts.limits.maxDepth) {
|
|
2082
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "sequence nesting exceeds max_depth");
|
|
2083
|
+
}
|
|
2084
|
+
active.add(n);
|
|
2085
|
+
const out = n.items.map((it) => walk(it, depth + 1));
|
|
2086
|
+
active.delete(n);
|
|
2087
|
+
return out;
|
|
2088
|
+
}
|
|
2089
|
+
case "mapping": {
|
|
2090
|
+
if (depth + 1 > opts.limits.maxDepth) {
|
|
2091
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "mapping nesting exceeds max_depth");
|
|
2092
|
+
}
|
|
2093
|
+
active.add(n);
|
|
2094
|
+
const obj = Object.create(null);
|
|
2095
|
+
for (const [k, v] of n.entries) {
|
|
2096
|
+
if (k.kind !== "string") {
|
|
2097
|
+
active.delete(n);
|
|
2098
|
+
throw lossError(k, "non-string key");
|
|
2099
|
+
}
|
|
2100
|
+
try {
|
|
2101
|
+
assertWellFormedUnicode(k.value, "mapping key");
|
|
2102
|
+
}
|
|
2103
|
+
catch (err) {
|
|
2104
|
+
active.delete(n);
|
|
2105
|
+
throw err;
|
|
2106
|
+
}
|
|
2107
|
+
if (Object.prototype.hasOwnProperty.call(obj, k.value)) {
|
|
2108
|
+
active.delete(n);
|
|
2109
|
+
throw notSourceError("duplicate_key", {}, "duplicate mapping key");
|
|
2110
|
+
}
|
|
2111
|
+
obj[k.value] = walk(v, depth + 1);
|
|
2112
|
+
}
|
|
2113
|
+
active.delete(n);
|
|
2114
|
+
return obj;
|
|
2115
|
+
}
|
|
2116
|
+
case "tagged":
|
|
2117
|
+
throw lossError(n, "tagged value");
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
return walk(root, 0);
|
|
2121
|
+
}
|
|
2122
|
+
function formatPlainFloat(f) {
|
|
2123
|
+
if (Object.is(f, -0)) {
|
|
2124
|
+
return "-0.0";
|
|
2125
|
+
}
|
|
2126
|
+
const s = String(f);
|
|
2127
|
+
if (!s.includes(".") && !s.includes("e") && !s.includes("E")) {
|
|
2128
|
+
return s + ".0";
|
|
2129
|
+
}
|
|
2130
|
+
return s.replace("e+", "e");
|
|
2131
|
+
}
|
|
2132
|
+
export function encodePlain(nodeOrDoc, options) {
|
|
2133
|
+
const opts = validateOptions(options);
|
|
2134
|
+
const root = isDocument(nodeOrDoc) ? nodeOrDoc.root : nodeOrDoc;
|
|
2135
|
+
const w = new BoundedWriter(opts.limits.maxOutputBytes);
|
|
2136
|
+
let nodesRemaining = opts.limits.maxNodes;
|
|
2137
|
+
const active = new Set();
|
|
2138
|
+
function walk(n, depth) {
|
|
2139
|
+
if (nodesRemaining <= 0) {
|
|
2140
|
+
throw notSourceError("limit_exceeded", { limit: "max_nodes", configured: opts.limits.maxNodes }, "tree exceeds max_nodes");
|
|
2141
|
+
}
|
|
2142
|
+
nodesRemaining -= 1;
|
|
2143
|
+
if (active.has(n)) {
|
|
2144
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "cyclic node graph exceeds max_depth");
|
|
2145
|
+
}
|
|
2146
|
+
switch (n.kind) {
|
|
2147
|
+
case "null":
|
|
2148
|
+
w.pushRaw("null");
|
|
2149
|
+
break;
|
|
2150
|
+
case "bool":
|
|
2151
|
+
w.pushRaw(n.value ? "true" : "false");
|
|
2152
|
+
break;
|
|
2153
|
+
case "int":
|
|
2154
|
+
w.pushRaw(n.value.toString(10));
|
|
2155
|
+
break;
|
|
2156
|
+
case "float":
|
|
2157
|
+
if (!Number.isFinite(n.value)) {
|
|
2158
|
+
throw lossError(n, "non-finite float");
|
|
2159
|
+
}
|
|
2160
|
+
w.pushRaw(formatPlainFloat(n.value));
|
|
2161
|
+
break;
|
|
2162
|
+
case "string":
|
|
2163
|
+
w.pushString(n.value);
|
|
2164
|
+
break;
|
|
2165
|
+
case "sequence":
|
|
2166
|
+
if (depth + 1 > opts.limits.maxDepth) {
|
|
2167
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "sequence nesting exceeds max_depth");
|
|
2168
|
+
}
|
|
2169
|
+
active.add(n);
|
|
2170
|
+
w.pushRaw("[");
|
|
2171
|
+
for (let i = 0; i < n.items.length; i++) {
|
|
2172
|
+
if (i > 0)
|
|
2173
|
+
w.pushRaw(",");
|
|
2174
|
+
walk(n.items[i], depth + 1);
|
|
2175
|
+
}
|
|
2176
|
+
w.pushRaw("]");
|
|
2177
|
+
active.delete(n);
|
|
2178
|
+
break;
|
|
2179
|
+
case "mapping":
|
|
2180
|
+
if (depth + 1 > opts.limits.maxDepth) {
|
|
2181
|
+
throw notSourceError("limit_exceeded", { limit: "max_depth", configured: opts.limits.maxDepth }, "mapping nesting exceeds max_depth");
|
|
2182
|
+
}
|
|
2183
|
+
active.add(n);
|
|
2184
|
+
w.pushRaw("{");
|
|
2185
|
+
for (let i = 0; i < n.entries.length; i++) {
|
|
2186
|
+
const [k, v] = n.entries[i];
|
|
2187
|
+
if (k.kind !== "string") {
|
|
2188
|
+
active.delete(n);
|
|
2189
|
+
throw lossError(k, "non-string key");
|
|
2190
|
+
}
|
|
2191
|
+
if (i > 0)
|
|
2192
|
+
w.pushRaw(",");
|
|
2193
|
+
w.pushString(k.value);
|
|
2194
|
+
w.pushRaw(":");
|
|
2195
|
+
walk(v, depth + 1);
|
|
2196
|
+
}
|
|
2197
|
+
w.pushRaw("}");
|
|
2198
|
+
active.delete(n);
|
|
2199
|
+
break;
|
|
2200
|
+
case "tagged":
|
|
2201
|
+
throw lossError(n, "tagged value");
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
walk(root, 0);
|
|
2205
|
+
return w.finish();
|
|
2206
|
+
}
|
|
2207
|
+
// ---- Primary entrypoints -------------------------------------------------
|
|
2208
|
+
export function loadAll(input, options) {
|
|
2209
|
+
const opts = validateOptions(options);
|
|
2210
|
+
const inputBytes = toInputBytes(input);
|
|
2211
|
+
const { status, output } = runWasmLoad(inputBytes, opts, "wire-all");
|
|
2212
|
+
if (status === 2) {
|
|
2213
|
+
throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
|
|
2214
|
+
}
|
|
2215
|
+
const wireText = decoder.decode(output);
|
|
2216
|
+
const decoded = decodeWire(wireText, opts, inputBytes);
|
|
2217
|
+
if (decoded.kind === "error") {
|
|
2218
|
+
throw decoded.error;
|
|
2219
|
+
}
|
|
2220
|
+
return decoded.documents;
|
|
2221
|
+
}
|
|
2222
|
+
export function load(input, options) {
|
|
2223
|
+
const opts = validateOptions(options);
|
|
2224
|
+
const inputBytes = toInputBytes(input);
|
|
2225
|
+
const { status, output } = runWasmLoad(inputBytes, opts, "wire-single");
|
|
2226
|
+
if (status === 2) {
|
|
2227
|
+
throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
|
|
2228
|
+
}
|
|
2229
|
+
const wireText = decoder.decode(output);
|
|
2230
|
+
const decoded = decodeWire(wireText, opts, inputBytes);
|
|
2231
|
+
if (decoded.kind === "error") {
|
|
2232
|
+
throw decoded.error;
|
|
2233
|
+
}
|
|
2234
|
+
if (decoded.documents.length !== 1) {
|
|
2235
|
+
throw notSourceError("internal", {}, "expected single document from load_wire");
|
|
2236
|
+
}
|
|
2237
|
+
return decoded.documents[0];
|
|
2238
|
+
}
|
|
2239
|
+
export function loadBytes(input, options) {
|
|
2240
|
+
if (!(input instanceof Uint8Array)) {
|
|
2241
|
+
throw new TypeError("loadBytes requires a Uint8Array");
|
|
2242
|
+
}
|
|
2243
|
+
return load(input, options);
|
|
2244
|
+
}
|
|
2245
|
+
export function loadAllBytes(input, options) {
|
|
2246
|
+
if (!(input instanceof Uint8Array)) {
|
|
2247
|
+
throw new TypeError("loadAllBytes requires a Uint8Array");
|
|
2248
|
+
}
|
|
2249
|
+
return loadAll(input, options);
|
|
2250
|
+
}
|
|
2251
|
+
export function loadPlain(input, options) {
|
|
2252
|
+
const opts = validateOptions(options);
|
|
2253
|
+
const inputBytes = toInputBytes(input);
|
|
2254
|
+
const { status, output } = runWasmLoad(inputBytes, opts, "plain");
|
|
2255
|
+
if (status === 2) {
|
|
2256
|
+
throw decodeFallbackStatus2(output, opts.limits.maxOutputBytes);
|
|
2257
|
+
}
|
|
2258
|
+
const text = decoder.decode(output);
|
|
2259
|
+
if (status === 1) {
|
|
2260
|
+
const decoded = decodeWire(text, opts, inputBytes);
|
|
2261
|
+
if (decoded.kind === "error") {
|
|
2262
|
+
throw decoded.error;
|
|
2263
|
+
}
|
|
2264
|
+
throw notSourceError("internal", {}, "expected error envelope from load_plain status 1");
|
|
2265
|
+
}
|
|
2266
|
+
return text;
|
|
2267
|
+
}
|
|
2268
|
+
// Internal-only hook for in-repo linear-memory and trap tests (not part of the
|
|
2269
|
+
// public TypeScript declarations or supported package surface).
|
|
2270
|
+
Object.defineProperty(load, Symbol.for("yamlprims.internal.wasmTestHarness"), {
|
|
2271
|
+
value: createWasmTestHarness,
|
|
2272
|
+
enumerable: false,
|
|
2273
|
+
configurable: false,
|
|
2274
|
+
writable: false,
|
|
2275
|
+
});
|