@openedges/pkl-napi 0.0.0-stage → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,2919 @@
1
+ "use strict";
2
+
3
+ const { existsSync } = require("node:fs");
4
+ const { resolve } = require("node:path");
5
+
6
+ function detectLinuxLibc() {
7
+ if (process.platform !== "linux") return null;
8
+ try {
9
+ const report =
10
+ process.report && typeof process.report.getReport === "function"
11
+ ? process.report.getReport()
12
+ : null;
13
+ if (report && report.header && report.header.glibcVersionRuntime) {
14
+ return "gnu";
15
+ }
16
+ const shared = report && Array.isArray(report.sharedObjects) ? report.sharedObjects : [];
17
+ if (shared.some((s) => typeof s === "string" && (s.includes("musl") || s.includes("ld-musl")))) {
18
+ return "musl";
19
+ }
20
+ } catch {
21
+ // Fall through to filesystem probe
22
+ }
23
+ if (
24
+ existsSync("/lib/ld-musl-x86_64.so.1") ||
25
+ existsSync("/lib/ld-musl-aarch64.so.1")
26
+ ) {
27
+ return "musl";
28
+ }
29
+ return "gnu";
30
+ }
31
+
32
+ function loadNativeAddon() {
33
+ const linuxLibc = detectLinuxLibc();
34
+ const candidates = [
35
+ process.env.PKL_NAPI_ADDON_PATH,
36
+ linuxLibc
37
+ ? resolve(__dirname, "..", "native", `pkl_napi.linux-${process.arch}-${linuxLibc}.node`)
38
+ : null,
39
+ resolve(__dirname, "..", "native", `pkl_napi.${process.platform}-${process.arch}.node`),
40
+ resolve(__dirname, "..", "native", "pkl_napi.node"),
41
+ ].filter(Boolean);
42
+
43
+ for (const candidate of candidates) {
44
+ if (existsSync(candidate)) {
45
+ return require(candidate);
46
+ }
47
+ }
48
+ throw new Error(
49
+ `Unable to load native @openedges/pkl-napi addon for ${process.platform}-${process.arch}${linuxLibc ? `-${linuxLibc}` : ""}. Checked: ${candidates.join(", ")}`,
50
+ );
51
+ }
52
+
53
+ const native = loadNativeAddon();
54
+
55
+ const PKL_VERSION = native.productPklVersion ? native.productPklVersion() : "0.32.0";
56
+ const MAX_U64 = (1n << 64n) - 1n;
57
+ const MIN_I64 = -(1n << 63n);
58
+ const MAX_I64 = (1n << 63n) - 1n;
59
+ const FAST_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
60
+ const FAST_MODULE_URI_RE =
61
+ /^[A-Za-z][A-Za-z0-9+.-]*:(?:\/\/\/[A-Za-z0-9\-._~/:$&'()*+,;=]*|\/(?!\/)[A-Za-z0-9\-._~/$&'()*+,;=]*|[A-Za-z0-9\-._~$&'()*+,;=][A-Za-z0-9\-._~/$&'()*+,;=]*)$/;
62
+ const VALID_DURATION_UNITS = new Set(["ns", "us", "ms", "s", "min", "h", "d"]);
63
+ const VALID_DATA_SIZE_UNITS = new Set([
64
+ "b", "kb", "mb", "gb", "tb", "pb", "kib", "mib", "gib", "tib", "pib",
65
+ ]);
66
+ const BLANK_OR_CTRL_RE = /^[\s\x00-\x20]*$/;
67
+ const DECODE_FALLBACK = Symbol("pkl.decode.fallback");
68
+
69
+ class PklError extends Error {
70
+ constructor(message, kind = "evaluation", capability = undefined) {
71
+ super(message);
72
+ this.name = "PklError";
73
+ this.kind = kind;
74
+ this.code = kind;
75
+ if (capability !== undefined) {
76
+ this.capability = capability;
77
+ }
78
+ }
79
+ }
80
+
81
+ function unwrapOutcome(outcome) {
82
+ if (!outcome || typeof outcome !== "object") {
83
+ throw new PklError("Malformed native outcome from pkl-napi.", "evaluation");
84
+ }
85
+ if (!outcome.ok) {
86
+ throw new PklError(
87
+ outcome.message ?? "Unknown Pkl error",
88
+ outcome.kind ?? "evaluation",
89
+ outcome.capability,
90
+ );
91
+ }
92
+ return outcome.value;
93
+ }
94
+
95
+ function capabilities() {
96
+ return {
97
+ vfs: false,
98
+ asyncModuleLoader: true,
99
+ asyncResourceLoader: true,
100
+ nativeFs: true,
101
+ nativeHttp: true,
102
+ externalReaders: true,
103
+ modulePathJar: true,
104
+ projectResolution: true,
105
+ packageCache: true,
106
+ formatter: true,
107
+ repl: true,
108
+ schema: true,
109
+ analyzeImports: true,
110
+ bigint64: true,
111
+ uint8ArrayBytes: true,
112
+ clock64Bit: true,
113
+ platform: process.platform,
114
+ runtime: "napi-node",
115
+ arch: process.arch,
116
+ };
117
+ }
118
+
119
+ class ModuleSource {
120
+ constructor(uri, contents = undefined) {
121
+ if (typeof uri !== "string" || uri.length === 0) {
122
+ throw new PklError("ModuleSource uri must be a non-empty string.", "invalid-argument");
123
+ }
124
+ if (contents !== undefined && typeof contents !== "string") {
125
+ throw new PklError("ModuleSource contents must be a string or undefined.", "invalid-argument");
126
+ }
127
+ this.uri = uri;
128
+ if (contents !== undefined) {
129
+ this.contents = contents;
130
+ }
131
+ Object.freeze(this);
132
+ }
133
+
134
+ static text(text, uri = "repl:text") {
135
+ if (typeof text !== "string") {
136
+ throw new PklError("ModuleSource.text requires a string source.", "invalid-argument");
137
+ }
138
+ if (typeof uri !== "string" || uri.length === 0) {
139
+ throw new PklError("ModuleSource.text uri must be a non-empty string.", "invalid-argument");
140
+ }
141
+ return new ModuleSource(uri, text);
142
+ }
143
+
144
+ static uri(uri) {
145
+ if (typeof uri !== "string" || uri.length === 0) {
146
+ throw new PklError("ModuleSource.uri requires a non-empty string.", "invalid-argument");
147
+ }
148
+ return new ModuleSource(uri, undefined);
149
+ }
150
+
151
+ static path(fsPath) {
152
+ if (typeof fsPath !== "string" || fsPath.length === 0) {
153
+ throw new PklError("ModuleSource.path requires a non-empty string path.", "invalid-argument");
154
+ }
155
+ const uri = unwrapOutcome(native.productPathToFileUri(fsPath));
156
+ return new ModuleSource(uri, undefined);
157
+ }
158
+
159
+ static modulePath(modulePath) {
160
+ if (typeof modulePath !== "string" || modulePath.length === 0) {
161
+ throw new PklError(
162
+ "ModuleSource.modulePath requires a non-empty string path.",
163
+ "invalid-argument",
164
+ );
165
+ }
166
+ const normalized = modulePath.startsWith("modulepath:")
167
+ ? modulePath.slice("modulepath:".length)
168
+ : modulePath;
169
+ const uri = normalized.startsWith("/")
170
+ ? `modulepath:${normalized}`
171
+ : `modulepath:/${normalized}`;
172
+ return new ModuleSource(uri, undefined);
173
+ }
174
+ }
175
+
176
+ function normalizeSource(source) {
177
+ if (source instanceof ModuleSource) {
178
+ return { uri: source.uri, contents: source.contents };
179
+ }
180
+ if (source && typeof source === "object" && typeof source.uri === "string" && source.uri.length > 0) {
181
+ if (source.contents !== undefined && typeof source.contents !== "string") {
182
+ throw new PklError("ModuleSource.contents must be a string.", "invalid-argument");
183
+ }
184
+ return { uri: source.uri, contents: source.contents };
185
+ }
186
+ throw new PklError("Expected a ModuleSource instance.", "invalid-argument");
187
+ }
188
+
189
+ class PklDuration {
190
+ constructor(value, unit) {
191
+ this.value = value;
192
+ this.unit = unit;
193
+ }
194
+ }
195
+
196
+ class PklDataSize {
197
+ constructor(value, unit) {
198
+ this.value = value;
199
+ this.unit = unit;
200
+ }
201
+ }
202
+
203
+ class PklPair {
204
+ constructor(first, second) {
205
+ this.first = first;
206
+ this.second = second;
207
+ }
208
+ }
209
+
210
+ class PklRegex {
211
+ constructor(pattern) {
212
+ this.pattern = pattern;
213
+ }
214
+ }
215
+
216
+ const SYM_ENTRIES = Symbol("pklEntries");
217
+ const SYM_ELEMENTS = Symbol("pklElements");
218
+
219
+ class PklObject {
220
+ constructor(className, moduleUri, properties = {}, entries = undefined, elements = undefined) {
221
+ this.className = className;
222
+ this.moduleUri = moduleUri;
223
+ this.properties = properties;
224
+ if (entries !== undefined) {
225
+ if (entries instanceof Map) {
226
+ this[SYM_ENTRIES] = entries;
227
+ } else if (entries !== null && typeof entries[Symbol.iterator] === "function") {
228
+ this[SYM_ENTRIES] = new Map(entries);
229
+ } else {
230
+ throw new PklError(
231
+ "PklObject entries must be a Map or iterable of [key, value] pairs",
232
+ "invalid-argument",
233
+ );
234
+ }
235
+ }
236
+ if (elements !== undefined) {
237
+ if (Array.isArray(elements)) {
238
+ this[SYM_ELEMENTS] = elements;
239
+ } else if (elements !== null && typeof elements[Symbol.iterator] === "function") {
240
+ this[SYM_ELEMENTS] = Array.from(elements);
241
+ } else {
242
+ throw new PklError("PklObject elements must be an Array or iterable", "invalid-argument");
243
+ }
244
+ }
245
+ }
246
+
247
+ get entries() {
248
+ let m = this[SYM_ENTRIES];
249
+ if (m === undefined) {
250
+ m = new Map();
251
+ if (Object.isExtensible(this)) {
252
+ this[SYM_ENTRIES] = m;
253
+ }
254
+ }
255
+ return m;
256
+ }
257
+
258
+ set entries(val) {
259
+ if (!(val instanceof Map)) {
260
+ throw new PklError("PklObject.entries must be a Map", "invalid-argument");
261
+ }
262
+ this[SYM_ENTRIES] = val;
263
+ }
264
+
265
+ get elements() {
266
+ let a = this[SYM_ELEMENTS];
267
+ if (a === undefined) {
268
+ a = [];
269
+ if (Object.isExtensible(this)) {
270
+ this[SYM_ELEMENTS] = a;
271
+ }
272
+ }
273
+ return a;
274
+ }
275
+
276
+ set elements(val) {
277
+ if (!Array.isArray(val)) {
278
+ throw new PklError("PklObject.elements must be an Array", "invalid-argument");
279
+ }
280
+ this[SYM_ELEMENTS] = val;
281
+ }
282
+
283
+ toJSON() {
284
+ const rawEntries = this[SYM_ENTRIES];
285
+ const rawElements = this[SYM_ELEMENTS];
286
+ return {
287
+ className: this.className,
288
+ moduleUri: this.moduleUri,
289
+ properties: this.properties,
290
+ entries: rawEntries !== undefined ? Array.from(rawEntries.entries()) : [],
291
+ elements: rawElements !== undefined ? rawElements : [],
292
+ };
293
+ }
294
+
295
+ static _peekEntries(obj) {
296
+ const m = obj[SYM_ENTRIES];
297
+ return m === undefined ? null : m;
298
+ }
299
+
300
+ static _peekElements(obj) {
301
+ const a = obj[SYM_ELEMENTS];
302
+ return a === undefined ? null : a;
303
+ }
304
+ }
305
+
306
+ class PklClass {
307
+ constructor(name, moduleUri) {
308
+ this.name = name;
309
+ this.moduleUri = moduleUri;
310
+ }
311
+ }
312
+
313
+ class PklTypeAlias {
314
+ constructor(name, moduleUri) {
315
+ this.name = name;
316
+ this.moduleUri = moduleUri;
317
+ }
318
+ }
319
+
320
+ class PklIntSeq {
321
+ constructor(start, end, step) {
322
+ if (typeof start !== "bigint" || typeof end !== "bigint" || typeof step !== "bigint") {
323
+ throw new PklError(
324
+ "PklIntSeq start, end, and step must be BigInt values",
325
+ "invalid-argument",
326
+ );
327
+ }
328
+ this.start = start;
329
+ this.end = end;
330
+ this.step = step;
331
+ }
332
+ }
333
+
334
+ class PklFunction {}
335
+
336
+ class PklReference {
337
+ constructor(domain, data, path = []) {
338
+ this.domain = domain;
339
+ this.data = data;
340
+ if (Array.isArray(path)) {
341
+ this.path = path;
342
+ } else if (path !== null && path !== undefined && typeof path[Symbol.iterator] === "function") {
343
+ this.path = Array.from(path);
344
+ } else {
345
+ throw new PklError("PklReference path must be an Array or iterable", "invalid-argument");
346
+ }
347
+ }
348
+ }
349
+
350
+ function definePropSafe(obj, key, value) {
351
+ Object.defineProperty(obj, key, {
352
+ value,
353
+ enumerable: true,
354
+ writable: true,
355
+ configurable: true,
356
+ });
357
+ }
358
+
359
+ const MAX_HYDRATE_DEPTH = 256;
360
+ const MAX_DEHYDRATE_DEPTH = 128;
361
+
362
+ function hydrateValue(raw, depth = 0) {
363
+ if (depth > MAX_HYDRATE_DEPTH) {
364
+ throw new PklError("Maximum value nesting depth exceeded.", "decode");
365
+ }
366
+ if (
367
+ raw === null ||
368
+ raw === undefined ||
369
+ typeof raw === "boolean" ||
370
+ typeof raw === "number" ||
371
+ typeof raw === "bigint" ||
372
+ typeof raw === "string"
373
+ ) {
374
+ return raw;
375
+ }
376
+ if (raw instanceof Uint8Array) {
377
+ return raw;
378
+ }
379
+ const nextDepth = depth + 1;
380
+ if (Array.isArray(raw)) {
381
+ const out = new Array(raw.length);
382
+ for (let i = 0; i < raw.length; i += 1) {
383
+ out[i] = hydrateValue(raw[i], nextDepth);
384
+ }
385
+ return out;
386
+ }
387
+ if (typeof raw === "object" && typeof raw.__pklTag === "string") {
388
+ switch (raw.__pklTag) {
389
+ case "set": {
390
+ const set = new Set();
391
+ for (const item of raw.items) {
392
+ set.add(hydrateValue(item, nextDepth));
393
+ }
394
+ return set;
395
+ }
396
+ case "map": {
397
+ const map = new Map();
398
+ for (const [k, v] of raw.entries) {
399
+ map.set(hydrateValue(k, nextDepth), hydrateValue(v, nextDepth));
400
+ }
401
+ return map;
402
+ }
403
+ case "duration":
404
+ return new PklDuration(raw.value, raw.unit);
405
+ case "dataSize":
406
+ return new PklDataSize(raw.value, raw.unit);
407
+ case "regex":
408
+ return new PklRegex(raw.pattern);
409
+ case "pair":
410
+ return new PklPair(hydrateValue(raw.first, nextDepth), hydrateValue(raw.second, nextDepth));
411
+ case "object": {
412
+ const properties = {};
413
+ for (const [k, v] of raw.properties) {
414
+ definePropSafe(properties, k, hydrateValue(v, nextDepth));
415
+ }
416
+ const entries = new Map();
417
+ for (const [k, v] of raw.entries) {
418
+ entries.set(hydrateValue(k, nextDepth), hydrateValue(v, nextDepth));
419
+ }
420
+ const elements = raw.elements.map((item) => hydrateValue(item, nextDepth));
421
+ return new PklObject(raw.className, raw.moduleUri, properties, entries, elements);
422
+ }
423
+ case "class":
424
+ return new PklClass(raw.name, raw.moduleUri);
425
+ case "typeAlias":
426
+ return new PklTypeAlias(raw.name, raw.moduleUri);
427
+ case "intSeq":
428
+ return new PklIntSeq(raw.start, raw.end, raw.step);
429
+ case "function":
430
+ return new PklFunction();
431
+ case "reference":
432
+ return new PklReference(
433
+ hydrateValue(raw.domain, nextDepth),
434
+ hydrateValue(raw.data, nextDepth),
435
+ raw.path.map((item) => hydrateValue(item, nextDepth)),
436
+ );
437
+ default:
438
+ throw new PklError(`Unknown Pkl tag: ${raw.__pklTag}`, "decode");
439
+ }
440
+ }
441
+ return raw;
442
+ }
443
+
444
+ function hydrateSchema(schema) {
445
+ if (!schema || typeof schema !== "object") return schema;
446
+ const hydrateAnnList = (list) => list.map((item) => hydrateValue(item, 0));
447
+ if (Array.isArray(schema.annotations)) {
448
+ schema.annotations = hydrateAnnList(schema.annotations);
449
+ }
450
+ if (schema.supermodule) {
451
+ hydrateSchema(schema.supermodule);
452
+ }
453
+ const hydrateClass = (cls) => {
454
+ if (!cls) return;
455
+ if (Array.isArray(cls.annotations)) {
456
+ cls.annotations = hydrateAnnList(cls.annotations);
457
+ }
458
+ for (const mapName of ["properties", "allProperties", "methods", "allMethods"]) {
459
+ const m = cls[mapName];
460
+ if (m && typeof m === "object") {
461
+ for (const member of Object.values(m)) {
462
+ if (member && Array.isArray(member.annotations)) {
463
+ member.annotations = hydrateAnnList(member.annotations);
464
+ }
465
+ }
466
+ }
467
+ }
468
+ };
469
+ hydrateClass(schema.moduleClass);
470
+ for (const mapName of ["classes", "allClasses"]) {
471
+ const m = schema[mapName];
472
+ if (m && typeof m === "object") {
473
+ for (const cls of Object.values(m)) {
474
+ hydrateClass(cls);
475
+ }
476
+ }
477
+ }
478
+ for (const mapName of ["typeAliases", "allTypeAliases"]) {
479
+ const m = schema[mapName];
480
+ if (m && typeof m === "object") {
481
+ for (const alias of Object.values(m)) {
482
+ if (alias && Array.isArray(alias.annotations)) {
483
+ alias.annotations = hydrateAnnList(alias.annotations);
484
+ }
485
+ }
486
+ }
487
+ }
488
+ return schema;
489
+ }
490
+
491
+ function dehydrateValue(val, depth = 0, seen = null) {
492
+ if (depth > MAX_DEHYDRATE_DEPTH) {
493
+ throw new PklError("Maximum value nesting depth exceeded.", "invalid-argument");
494
+ }
495
+ if (val === null) return null;
496
+ if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") {
497
+ return val;
498
+ }
499
+ if (typeof val === "bigint") {
500
+ if (val < MIN_I64 || val > MAX_I64) {
501
+ throw new PklError(
502
+ `BigInt ${val} is outside signed 64-bit integer range (${MIN_I64}..=${MAX_I64}).`,
503
+ "invalid-argument",
504
+ );
505
+ }
506
+ return val;
507
+ }
508
+ if (val instanceof Uint8Array) {
509
+ return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
510
+ }
511
+ if (val instanceof PklDuration) {
512
+ return { __pklTag: "duration", value: val.value, unit: val.unit };
513
+ }
514
+ if (val instanceof PklDataSize) {
515
+ return { __pklTag: "dataSize", value: val.value, unit: val.unit };
516
+ }
517
+ if (val instanceof PklRegex) {
518
+ return { __pklTag: "regex", pattern: val.pattern };
519
+ }
520
+ if (val instanceof PklClass) {
521
+ return { __pklTag: "class", name: val.name, moduleUri: val.moduleUri };
522
+ }
523
+ if (val instanceof PklTypeAlias) {
524
+ return { __pklTag: "typeAlias", name: val.name, moduleUri: val.moduleUri };
525
+ }
526
+ if (val instanceof PklIntSeq) {
527
+ return {
528
+ __pklTag: "intSeq",
529
+ start: dehydrateValue(val.start, depth + 1, seen),
530
+ end: dehydrateValue(val.end, depth + 1, seen),
531
+ step: dehydrateValue(val.step, depth + 1, seen),
532
+ };
533
+ }
534
+ if (val instanceof PklFunction) {
535
+ return { __pklTag: "function" };
536
+ }
537
+ if (typeof val === "object") {
538
+ const active = seen || new Set();
539
+ if (active.has(val)) {
540
+ throw new PklError(
541
+ "Circular reference detected during Pkl value conversion.",
542
+ "invalid-argument",
543
+ );
544
+ }
545
+ active.add(val);
546
+ const nextDepth = depth + 1;
547
+ try {
548
+ if (Array.isArray(val)) {
549
+ const out = new Array(val.length);
550
+ for (let i = 0; i < val.length; i += 1) {
551
+ out[i] = dehydrateValue(val[i], nextDepth, active);
552
+ }
553
+ return out;
554
+ }
555
+ if (val instanceof Set) {
556
+ const items = [];
557
+ for (const item of val) {
558
+ items.push(dehydrateValue(item, nextDepth, active));
559
+ }
560
+ return { __pklTag: "set", items };
561
+ }
562
+ if (val instanceof Map) {
563
+ const entries = [];
564
+ for (const [k, v] of val.entries()) {
565
+ entries.push([
566
+ dehydrateValue(k, nextDepth, active),
567
+ dehydrateValue(v, nextDepth, active),
568
+ ]);
569
+ }
570
+ return { __pklTag: "map", entries };
571
+ }
572
+ if (val instanceof PklPair) {
573
+ return {
574
+ __pklTag: "pair",
575
+ first: dehydrateValue(val.first, nextDepth, active),
576
+ second: dehydrateValue(val.second, nextDepth, active),
577
+ };
578
+ }
579
+ if (val instanceof PklObject) {
580
+ const properties = Object.entries(val.properties).map(([k, v]) => [
581
+ k,
582
+ dehydrateValue(v, nextDepth, active),
583
+ ]);
584
+ const rawEntries = PklObject._peekEntries(val);
585
+ const entries = rawEntries
586
+ ? Array.from(rawEntries.entries(), ([k, v]) => [
587
+ dehydrateValue(k, nextDepth, active),
588
+ dehydrateValue(v, nextDepth, active),
589
+ ])
590
+ : [];
591
+ const rawElements = PklObject._peekElements(val);
592
+ const elements = rawElements
593
+ ? rawElements.map((item) => dehydrateValue(item, nextDepth, active))
594
+ : [];
595
+ return {
596
+ __pklTag: "object",
597
+ className: val.className,
598
+ moduleUri: val.moduleUri,
599
+ properties,
600
+ entries,
601
+ elements,
602
+ };
603
+ }
604
+ if (val instanceof PklReference) {
605
+ return {
606
+ __pklTag: "reference",
607
+ domain: dehydrateValue(val.domain, nextDepth, active),
608
+ data: dehydrateValue(val.data, nextDepth, active),
609
+ path: val.path.map((item) => dehydrateValue(item, nextDepth, active)),
610
+ };
611
+ }
612
+ const properties = Object.entries(val).map(([k, v]) => [
613
+ k,
614
+ dehydrateValue(v, nextDepth, active),
615
+ ]);
616
+ return {
617
+ __pklTag: "object",
618
+ className: "Dynamic",
619
+ moduleUri: "pkl:base",
620
+ properties,
621
+ entries: [],
622
+ elements: [],
623
+ };
624
+ } finally {
625
+ active.delete(val);
626
+ }
627
+ }
628
+ throw new PklError(`Unsupported JS value type for Pkl conversion: ${typeof val}`, "invalid-argument");
629
+ }
630
+
631
+ function parseTimeoutMs(value) {
632
+ if (value === undefined || value === null) return undefined;
633
+ if (typeof value === "bigint") {
634
+ if (value < 0n || value > MAX_U64) {
635
+ throw new PklError(
636
+ `timeoutMs must be an unsigned 64-bit integer (0..=${MAX_U64}), got ${value}.`,
637
+ "invalid-argument",
638
+ );
639
+ }
640
+ return value;
641
+ }
642
+ if (typeof value === "number") {
643
+ if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value) || value < 0) {
644
+ throw new PklError(
645
+ `timeoutMs must be a non-negative safe integer or unsigned 64-bit BigInt, got ${value}.`,
646
+ "invalid-argument",
647
+ );
648
+ }
649
+ return BigInt(value);
650
+ }
651
+ throw new PklError(
652
+ `timeoutMs must be a number or bigint, got ${typeof value}.`,
653
+ "invalid-argument",
654
+ );
655
+ }
656
+
657
+ function toKeyValueList(input, fieldName) {
658
+ if (input === undefined || input === null) return undefined;
659
+ const out = [];
660
+ if (input instanceof Map) {
661
+ for (const [k, v] of input.entries()) {
662
+ if (v === undefined) continue;
663
+ out.push({ key: String(k), value: String(v) });
664
+ }
665
+ return out;
666
+ }
667
+ if (typeof input === "object" && !Array.isArray(input)) {
668
+ for (const [k, v] of Object.entries(input)) {
669
+ if (v === undefined) continue;
670
+ out.push({ key: k, value: String(v) });
671
+ }
672
+ return out;
673
+ }
674
+ throw new PklError(`${fieldName} must be an object or Map.`, "invalid-argument");
675
+ }
676
+
677
+ function decodeU16(arr) {
678
+ if (!arr || arr.length === 0) return "";
679
+ const CHUNK = 8192;
680
+ if (arr.length <= CHUNK) {
681
+ return String.fromCharCode(...arr);
682
+ }
683
+ let out = "";
684
+ for (let i = 0; i < arr.length; i += CHUNK) {
685
+ out += String.fromCharCode(...arr.subarray(i, Math.min(i + CHUNK, arr.length)));
686
+ }
687
+ return out;
688
+ }
689
+
690
+ function decodeBridgeFrame(frame) {
691
+ if (!frame) return undefined;
692
+ return {
693
+ moduleUri: decodeU16(frame.moduleUriU16),
694
+ memberName: frame.memberNameU16 ? decodeU16(frame.memberNameU16) : null,
695
+ sourceLines: (frame.sourceLinesU16 || []).map(decodeU16),
696
+ startLine: frame.startLine,
697
+ startColumn: frame.startColumn,
698
+ endLine: frame.endLine,
699
+ endColumn: frame.endColumn,
700
+ };
701
+ }
702
+
703
+ function normalizeColorOption(color) {
704
+ if (color === undefined || color === null) return undefined;
705
+ if (typeof color === "boolean") return color ? "always" : "never";
706
+ if (typeof color === "string") {
707
+ const lower = color.toLowerCase();
708
+ if (lower === "never" || lower === "auto" || lower === "always") {
709
+ return lower;
710
+ }
711
+ }
712
+ throw new PklError(
713
+ `Invalid color option "${color}". Expected boolean or "never" | "auto" | "always".`,
714
+ "invalid-argument",
715
+ );
716
+ }
717
+
718
+ function buildNativeOptions(options = {}) {
719
+ if (options !== undefined && options !== null && typeof options !== "object") {
720
+ throw new PklError("EvaluatorOptions must be an object.", "invalid-argument");
721
+ }
722
+ const opts = options || {};
723
+ const nativeOpts = {};
724
+
725
+ if (opts.allowedModules !== undefined) {
726
+ if (!Array.isArray(opts.allowedModules)) {
727
+ throw new PklError("allowedModules must be an array of strings.", "invalid-argument");
728
+ }
729
+ nativeOpts.allowedModules = opts.allowedModules.map(String);
730
+ }
731
+ if (opts.allowedResources !== undefined) {
732
+ if (!Array.isArray(opts.allowedResources)) {
733
+ throw new PklError("allowedResources must be an array of strings.", "invalid-argument");
734
+ }
735
+ nativeOpts.allowedResources = opts.allowedResources.map(String);
736
+ }
737
+ if (opts.rootDir !== undefined && opts.rootDir !== null) {
738
+ nativeOpts.rootDir = String(opts.rootDir);
739
+ }
740
+ if (opts.workingDir !== undefined && opts.workingDir !== null) {
741
+ nativeOpts.workingDir = String(opts.workingDir);
742
+ }
743
+ if (opts.modulePaths !== undefined) {
744
+ if (!Array.isArray(opts.modulePaths)) {
745
+ throw new PklError("modulePaths must be an array of paths.", "invalid-argument");
746
+ }
747
+ nativeOpts.modulePaths = opts.modulePaths.map(String);
748
+ }
749
+ if (opts.properties !== undefined) {
750
+ nativeOpts.properties = toKeyValueList(opts.properties, "properties");
751
+ }
752
+ if (opts.env !== undefined) {
753
+ nativeOpts.env = toKeyValueList(opts.env, "env");
754
+ } else if (opts.project === undefined && opts.projectDir === undefined) {
755
+ // Default to current Node process.env when neither explicit env nor project overrides it.
756
+ nativeOpts.env = toKeyValueList(process.env, "env");
757
+ }
758
+ if (opts.outputFormat !== undefined && opts.outputFormat !== null) {
759
+ nativeOpts.outputFormat = String(opts.outputFormat);
760
+ }
761
+ if (opts.traceMode !== undefined && opts.traceMode !== null) {
762
+ if (opts.traceMode !== "compact" && opts.traceMode !== "pretty") {
763
+ throw new PklError(
764
+ `Invalid traceMode "${opts.traceMode}". Expected "compact" or "pretty".`,
765
+ "invalid-argument",
766
+ );
767
+ }
768
+ nativeOpts.traceMode = opts.traceMode;
769
+ }
770
+ if (opts.powerAssertions !== undefined) {
771
+ nativeOpts.powerAssertions = Boolean(opts.powerAssertions);
772
+ }
773
+ const color = normalizeColorOption(opts.color);
774
+ if (color !== undefined) {
775
+ nativeOpts.color = color;
776
+ }
777
+ const timeoutMs = parseTimeoutMs(opts.timeoutMs);
778
+ if (timeoutMs !== undefined) {
779
+ nativeOpts.timeoutMs = timeoutMs;
780
+ }
781
+ if (opts.noCache === true || opts.cacheDir === null) {
782
+ nativeOpts.noCache = true;
783
+ } else if (opts.cacheDir !== undefined) {
784
+ const cacheDirStr = String(opts.cacheDir);
785
+ if (cacheDirStr.length === 0) {
786
+ throw new PklError("cacheDir must not be an empty string.", "configuration");
787
+ }
788
+ nativeOpts.cacheDir = cacheDirStr;
789
+ }
790
+ if (opts.projectDir !== undefined && opts.projectDir !== null) {
791
+ nativeOpts.projectDir = String(opts.projectDir);
792
+ }
793
+ if (opts.testMode !== undefined) {
794
+ nativeOpts.testMode = Boolean(opts.testMode);
795
+ }
796
+
797
+ if (opts.http !== undefined && opts.http !== null) {
798
+ const http = opts.http;
799
+ const nativeHttp = {};
800
+ const certFiles = [];
801
+ const certPems = [];
802
+ if (Array.isArray(http.caCertificates)) {
803
+ for (const cert of http.caCertificates) {
804
+ if (cert instanceof Uint8Array) {
805
+ certPems.push(new Uint8Array(cert.buffer, cert.byteOffset, cert.byteLength));
806
+ } else if (typeof cert === "string") {
807
+ if (cert.includes("-----BEGIN")) {
808
+ certPems.push(Buffer.from(cert, "utf8"));
809
+ } else {
810
+ certFiles.push(cert);
811
+ }
812
+ } else {
813
+ throw new PklError(
814
+ "http.caCertificates entries must be file paths, PEM strings, or Uint8Array.",
815
+ "invalid-argument",
816
+ );
817
+ }
818
+ }
819
+ }
820
+ if (Array.isArray(http.caCertificateFiles)) {
821
+ for (const filePath of http.caCertificateFiles) {
822
+ if (typeof filePath !== "string") {
823
+ throw new PklError(
824
+ "http.caCertificateFiles entries must be file path strings.",
825
+ "invalid-argument",
826
+ );
827
+ }
828
+ certFiles.push(filePath);
829
+ }
830
+ }
831
+ if (Array.isArray(http.caCertificatePems)) {
832
+ for (const pem of http.caCertificatePems) {
833
+ if (pem instanceof Uint8Array) {
834
+ certPems.push(new Uint8Array(pem.buffer, pem.byteOffset, pem.byteLength));
835
+ } else if (typeof pem === "string") {
836
+ certPems.push(Buffer.from(pem, "utf8"));
837
+ } else {
838
+ throw new PklError(
839
+ "http.caCertificatePems entries must be PEM strings or Uint8Array.",
840
+ "invalid-argument",
841
+ );
842
+ }
843
+ }
844
+ }
845
+ if (certFiles.length > 0) nativeHttp.caCertificateFiles = certFiles;
846
+ if (certPems.length > 0) nativeHttp.caCertificatePems = certPems;
847
+ if (http.proxy !== undefined && http.proxy !== null) {
848
+ if (http.proxy.address !== undefined && http.proxy.address !== null) {
849
+ nativeHttp.proxyAddress = String(http.proxy.address);
850
+ }
851
+ if (Array.isArray(http.proxy.noProxy)) {
852
+ nativeHttp.noProxy = http.proxy.noProxy.map(String);
853
+ }
854
+ }
855
+ if (http.rewrites !== undefined && http.rewrites !== null) {
856
+ nativeHttp.rewrites = toKeyValueList(http.rewrites, "http.rewrites");
857
+ }
858
+ if (http.headers !== undefined && http.headers !== null) {
859
+ const entries = [];
860
+ for (const [urlPattern, hdrMap] of Object.entries(http.headers)) {
861
+ if (!hdrMap || typeof hdrMap !== "object") continue;
862
+ for (const [name, value] of Object.entries(hdrMap)) {
863
+ entries.push({ urlPattern, name, value: String(value) });
864
+ }
865
+ }
866
+ nativeHttp.headers = entries;
867
+ }
868
+ if (http.testPort !== undefined && http.testPort !== null) {
869
+ const port = Number(http.testPort);
870
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
871
+ throw new PklError(`Invalid http.testPort \`${http.testPort}\`.`, "invalid-argument");
872
+ }
873
+ nativeHttp.testPort = port;
874
+ }
875
+ nativeOpts.http = nativeHttp;
876
+ }
877
+
878
+ if (opts.externalModuleReaders && typeof opts.externalModuleReaders === "object") {
879
+ nativeOpts.externalModuleReaders = Object.entries(opts.externalModuleReaders).map(
880
+ ([scheme, cfg]) => {
881
+ if (!cfg || typeof cfg !== "object" || typeof cfg.executable !== "string" || !cfg.executable) {
882
+ throw new PklError(
883
+ `externalModuleReaders[\`${scheme}\`] must be an object with a non-empty string executable.`,
884
+ "invalid-argument",
885
+ );
886
+ }
887
+ return {
888
+ scheme: scheme.replace(/:$/, ""),
889
+ executable: cfg.executable,
890
+ arguments: Array.isArray(cfg.arguments) ? cfg.arguments.map(String) : [],
891
+ };
892
+ },
893
+ );
894
+ }
895
+ if (opts.externalResourceReaders && typeof opts.externalResourceReaders === "object") {
896
+ nativeOpts.externalResourceReaders = Object.entries(opts.externalResourceReaders).map(
897
+ ([scheme, cfg]) => {
898
+ if (!cfg || typeof cfg !== "object" || typeof cfg.executable !== "string" || !cfg.executable) {
899
+ throw new PklError(
900
+ `externalResourceReaders[\`${scheme}\`] must be an object with a non-empty string executable.`,
901
+ "invalid-argument",
902
+ );
903
+ }
904
+ return {
905
+ scheme: scheme.replace(/:$/, ""),
906
+ executable: cfg.executable,
907
+ arguments: Array.isArray(cfg.arguments) ? cfg.arguments.map(String) : [],
908
+ };
909
+ },
910
+ );
911
+ }
912
+
913
+ const moduleReaders = Array.isArray(opts.moduleReaders) ? opts.moduleReaders : [];
914
+ if (moduleReaders.length > 0) {
915
+ nativeOpts.moduleReaders = moduleReaders.map((r, index) => {
916
+ if (!r || typeof r.scheme !== "string" || typeof r.read !== "function") {
917
+ throw new PklError(
918
+ `moduleReaders[${index}] must have string scheme and read() function.`,
919
+ "invalid-argument",
920
+ );
921
+ }
922
+ return {
923
+ index,
924
+ scheme: r.scheme.replace(/:$/, ""),
925
+ isLocal: Boolean(r.isLocal),
926
+ isGlobbable: Boolean(r.isGlobbable),
927
+ hasHierarchicalUris: Boolean(r.hasHierarchicalUris),
928
+ hasFragmentPaths: Boolean(r.hasFragmentPaths),
929
+ isCached: r.isCached === undefined ? true : Boolean(r.isCached),
930
+ hasHasElement: typeof r.hasElement === "function",
931
+ hasListElements: typeof r.listElements === "function",
932
+ };
933
+ });
934
+ }
935
+
936
+ const resourceReaders = Array.isArray(opts.resourceReaders) ? opts.resourceReaders : [];
937
+ if (resourceReaders.length > 0) {
938
+ nativeOpts.resourceReaders = resourceReaders.map((r, index) => {
939
+ if (!r || typeof r.scheme !== "string" || typeof r.read !== "function") {
940
+ throw new PklError(
941
+ `resourceReaders[${index}] must have string scheme and read() function.`,
942
+ "invalid-argument",
943
+ );
944
+ }
945
+ return {
946
+ index,
947
+ scheme: r.scheme.replace(/:$/, ""),
948
+ isGlobbable: Boolean(r.isGlobbable),
949
+ hasHierarchicalUris: Boolean(r.hasHierarchicalUris),
950
+ hasHasElement: typeof r.hasElement === "function",
951
+ hasListElements: typeof r.listElements === "function",
952
+ };
953
+ });
954
+ }
955
+
956
+ const logger = opts.logger || null;
957
+ if (logger !== null) {
958
+ nativeOpts.hasCustomLogger = true;
959
+ nativeOpts.hasLoggerTrace = typeof logger.trace === "function";
960
+ nativeOpts.hasLoggerWarn = typeof logger.warn === "function";
961
+ }
962
+
963
+ const frameTransformer = typeof opts.frameTransformer === "function" ? opts.frameTransformer : null;
964
+ if (frameTransformer) {
965
+ nativeOpts.hasFrameTransformer = true;
966
+ }
967
+
968
+ const securityManager = opts.securityManager || null;
969
+ if (securityManager) {
970
+ nativeOpts.hasSecurityResolveModule = typeof securityManager.checkResolveModule === "function";
971
+ nativeOpts.hasSecurityImportModule = typeof securityManager.checkImportModule === "function";
972
+ nativeOpts.hasSecurityReadResource = typeof securityManager.checkReadResource === "function";
973
+ nativeOpts.hasSecurityResolveResource =
974
+ typeof securityManager.checkResolveResource === "function";
975
+ }
976
+
977
+ const hasCallbacks = Boolean(
978
+ logger ||
979
+ frameTransformer ||
980
+ (securityManager &&
981
+ (nativeOpts.hasSecurityResolveModule ||
982
+ nativeOpts.hasSecurityImportModule ||
983
+ nativeOpts.hasSecurityReadResource ||
984
+ nativeOpts.hasSecurityResolveResource)) ||
985
+ moduleReaders.length > 0 ||
986
+ resourceReaders.length > 0,
987
+ );
988
+
989
+ let nativeProject = undefined;
990
+ if (opts.project !== undefined && opts.project !== null) {
991
+ if (opts.project instanceof Project && opts.project._native) {
992
+ nativeProject = opts.project._native;
993
+ } else {
994
+ throw new PklError("options.project must be a Project instance.", "invalid-argument");
995
+ }
996
+ }
997
+
998
+ let bridgeTarget = null;
999
+ const setBridgeTarget = (target) => {
1000
+ bridgeTarget = target;
1001
+ };
1002
+
1003
+ const safeErrMsg = (err) => {
1004
+ try {
1005
+ if (err instanceof Error && typeof err.message === "string") return err.message;
1006
+ return String(err);
1007
+ } catch {
1008
+ return "Unknown callback error";
1009
+ }
1010
+ };
1011
+
1012
+ const bridgeCallback = hasCallbacks
1013
+ ? (req) => {
1014
+ void (async () => {
1015
+ const target = bridgeTarget;
1016
+ if (!target) return;
1017
+ try {
1018
+ const payload = await dispatchBridgeRequest(req, {
1019
+ logger,
1020
+ frameTransformer,
1021
+ securityManager,
1022
+ moduleReaders,
1023
+ resourceReaders,
1024
+ });
1025
+ try {
1026
+ target.completeBridgeCallback(req.id, { ok: true, ...payload });
1027
+ } catch (marshalErr) {
1028
+ try {
1029
+ target.completeBridgeCallback(req.id, {
1030
+ ok: false,
1031
+ errorKind: "evaluation",
1032
+ errorMessage: safeErrMsg(marshalErr),
1033
+ });
1034
+ } catch {
1035
+ // Target may have been closed concurrently
1036
+ }
1037
+ }
1038
+ } catch (err) {
1039
+ const isSecurity = err instanceof PklError && err.kind === "security";
1040
+ const isIo = err instanceof PklError && err.kind === "io";
1041
+ const msg = safeErrMsg(err);
1042
+ try {
1043
+ target.completeBridgeCallback(req.id, {
1044
+ ok: false,
1045
+ errorKind: isSecurity ? "security" : isIo ? "io" : "evaluation",
1046
+ errorMessage: msg,
1047
+ });
1048
+ } catch {
1049
+ // Target may have been closed concurrently
1050
+ }
1051
+ }
1052
+ })();
1053
+ }
1054
+ : undefined;
1055
+
1056
+ return {
1057
+ nativeOpts,
1058
+ nativeProject,
1059
+ bridgeCallback,
1060
+ setBridgeTarget,
1061
+ signal: opts.signal,
1062
+ };
1063
+ }
1064
+
1065
+ async function dispatchBridgeRequest(req, hooks) {
1066
+ switch (req.op) {
1067
+ case "log": {
1068
+ const msg = decodeU16(req.messageU16);
1069
+ const frame = decodeBridgeFrame(req.frame);
1070
+ if (req.level === "trace" && hooks.logger && typeof hooks.logger.trace === "function") {
1071
+ await hooks.logger.trace(msg, frame);
1072
+ } else if (req.level === "warn" && hooks.logger && typeof hooks.logger.warn === "function") {
1073
+ await hooks.logger.warn(msg, frame);
1074
+ }
1075
+ return {};
1076
+ }
1077
+ case "transformFrame": {
1078
+ const frame = decodeBridgeFrame(req.frame);
1079
+ const transformed = await hooks.frameTransformer(frame);
1080
+ if (!transformed || typeof transformed !== "object") {
1081
+ return {};
1082
+ }
1083
+ const resolvedMemberName =
1084
+ transformed.memberName !== undefined ? transformed.memberName : frame.memberName;
1085
+ return {
1086
+ frame: {
1087
+ moduleUri: String(transformed.moduleUri ?? frame.moduleUri),
1088
+ memberName:
1089
+ resolvedMemberName === null || resolvedMemberName === undefined
1090
+ ? undefined
1091
+ : String(resolvedMemberName),
1092
+ sourceLines: Array.isArray(transformed.sourceLines)
1093
+ ? transformed.sourceLines.map(String)
1094
+ : frame.sourceLines,
1095
+ startLine: Number(transformed.startLine ?? frame.startLine),
1096
+ startColumn: Number(transformed.startColumn ?? frame.startColumn),
1097
+ endLine: Number(transformed.endLine ?? frame.endLine),
1098
+ endColumn: Number(transformed.endColumn ?? frame.endColumn),
1099
+ },
1100
+ };
1101
+ }
1102
+ case "checkResolveModule": {
1103
+ await hooks.securityManager.checkResolveModule(decodeU16(req.uriU16));
1104
+ return {};
1105
+ }
1106
+ case "checkImportModule": {
1107
+ await hooks.securityManager.checkImportModule(
1108
+ decodeU16(req.uriU16),
1109
+ decodeU16(req.uri2U16),
1110
+ );
1111
+ return {};
1112
+ }
1113
+ case "checkReadResource": {
1114
+ await hooks.securityManager.checkReadResource(decodeU16(req.uriU16));
1115
+ return {};
1116
+ }
1117
+ case "checkResolveResource": {
1118
+ await hooks.securityManager.checkResolveResource(decodeU16(req.uriU16));
1119
+ return {};
1120
+ }
1121
+ case "moduleRead": {
1122
+ const reader = hooks.moduleReaders[req.readerIndex];
1123
+ const text = await reader.read(decodeU16(req.uriU16));
1124
+ if (text === null || text === undefined) {
1125
+ return { text: undefined };
1126
+ }
1127
+ if (text instanceof Uint8Array) {
1128
+ return { text: FAST_UTF8_DECODER.decode(text) };
1129
+ }
1130
+ return { text: String(text) };
1131
+ }
1132
+ case "moduleHasElement": {
1133
+ const reader = hooks.moduleReaders[req.readerIndex];
1134
+ const exists = await reader.hasElement(decodeU16(req.uriU16));
1135
+ return { boolValue: Boolean(exists) };
1136
+ }
1137
+ case "moduleListElements": {
1138
+ const reader = hooks.moduleReaders[req.readerIndex];
1139
+ const elements = await reader.listElements(decodeU16(req.uriU16));
1140
+ return {
1141
+ elements: Array.isArray(elements)
1142
+ ? elements.map((el) => ({
1143
+ name: String(el.name),
1144
+ isDirectory: Boolean(el.isDirectory),
1145
+ }))
1146
+ : [],
1147
+ };
1148
+ }
1149
+ case "resourceRead": {
1150
+ const reader = hooks.resourceReaders[req.readerIndex];
1151
+ const value = await reader.read(decodeU16(req.uriU16));
1152
+ if (value === null || value === undefined) {
1153
+ return { missing: true };
1154
+ }
1155
+ if (value instanceof Uint8Array) {
1156
+ return { bytes: new Uint8Array(value.buffer, value.byteOffset, value.byteLength) };
1157
+ }
1158
+ if (typeof value === "string") {
1159
+ return { text: value };
1160
+ }
1161
+ if (typeof value === "object" && value.bytes instanceof Uint8Array) {
1162
+ return {
1163
+ bytes: new Uint8Array(value.bytes.buffer, value.bytes.byteOffset, value.bytes.byteLength),
1164
+ };
1165
+ }
1166
+ if (typeof value === "object" && typeof value.text === "string") {
1167
+ return { text: value.text };
1168
+ }
1169
+ throw new PklError(
1170
+ `ResourceReader.read must return Uint8Array, string, null, or undefined.`,
1171
+ "invalid-argument",
1172
+ );
1173
+ }
1174
+ case "resourceHasElement": {
1175
+ const reader = hooks.resourceReaders[req.readerIndex];
1176
+ const exists = await reader.hasElement(decodeU16(req.uriU16));
1177
+ return { boolValue: Boolean(exists) };
1178
+ }
1179
+ case "resourceListElements": {
1180
+ const reader = hooks.resourceReaders[req.readerIndex];
1181
+ const elements = await reader.listElements(decodeU16(req.uriU16));
1182
+ return {
1183
+ elements: Array.isArray(elements)
1184
+ ? elements.map((el) => ({
1185
+ name: String(el.name),
1186
+ isDirectory: Boolean(el.isDirectory),
1187
+ }))
1188
+ : [],
1189
+ };
1190
+ }
1191
+ default:
1192
+ throw new PklError(`Unknown bridge callback op: ${req.op}`, "evaluation");
1193
+ }
1194
+ }
1195
+
1196
+ class Project {
1197
+ constructor(nativeProject) {
1198
+ this._native = nativeProject;
1199
+ const info = nativeProject.info();
1200
+ this.projectDir = info.projectDir;
1201
+ this.projectFileUri = info.projectFileUri;
1202
+ this.projectBaseUri = info.projectBaseUri;
1203
+ this.package = info.package;
1204
+ this.evaluatorSettings = info.evaluatorSettings;
1205
+ this.tests = info.tests;
1206
+ Object.freeze(this);
1207
+ }
1208
+
1209
+ static async load(dirOrFile, options = undefined) {
1210
+ if (typeof dirOrFile !== "string" || dirOrFile.length === 0) {
1211
+ throw new PklError("Project.load requires a directory or file path.", "invalid-argument");
1212
+ }
1213
+ const env = options?.env !== undefined ? toKeyValueList(options.env, "env") : undefined;
1214
+ const props =
1215
+ options?.properties !== undefined
1216
+ ? toKeyValueList(options.properties, "properties")
1217
+ : undefined;
1218
+ const outcome = await native.NativeProject.load(dirOrFile, env, props);
1219
+ return new Project(unwrapOutcome(outcome));
1220
+ }
1221
+
1222
+ static loadSync(dirOrFile, options = undefined) {
1223
+ if (typeof dirOrFile !== "string" || dirOrFile.length === 0) {
1224
+ throw new PklError("Project.loadSync requires a directory or file path.", "invalid-argument");
1225
+ }
1226
+ const env = options?.env !== undefined ? toKeyValueList(options.env, "env") : undefined;
1227
+ const props =
1228
+ options?.properties !== undefined
1229
+ ? toKeyValueList(options.properties, "properties")
1230
+ : undefined;
1231
+ const outcome = native.NativeProject.loadSync(dirOrFile, env, props);
1232
+ return new Project(unwrapOutcome(outcome));
1233
+ }
1234
+ }
1235
+
1236
+ class Evaluator {
1237
+ constructor(nativeEval, signal = undefined, clearBridge = null) {
1238
+ this._native = nativeEval;
1239
+ this._closed = false;
1240
+ this._closePromise = null;
1241
+ this._nextCallId = 1n;
1242
+ this._pendingFastContinue = 0;
1243
+ this._clearBridge = clearBridge;
1244
+ this._signal = signal || null;
1245
+ this._onAbort = null;
1246
+ if (this._signal && !this._signal.aborted) {
1247
+ this._onAbort = () => {
1248
+ this.cancel();
1249
+ };
1250
+ this._signal.addEventListener("abort", this._onAbort, { once: true });
1251
+ }
1252
+ }
1253
+
1254
+ get isClosed() {
1255
+ return this._closed || this._native.isClosed;
1256
+ }
1257
+
1258
+ cancel() {
1259
+ if (!this._closed) {
1260
+ this._native.cancel();
1261
+ }
1262
+ }
1263
+
1264
+ close() {
1265
+ if (this._closed) {
1266
+ return this._closePromise || Promise.resolve();
1267
+ }
1268
+ this._closed = true;
1269
+ if (this._clearBridge) {
1270
+ this._clearBridge();
1271
+ this._clearBridge = null;
1272
+ }
1273
+ if (this._signal && this._onAbort) {
1274
+ this._signal.removeEventListener("abort", this._onAbort);
1275
+ this._onAbort = null;
1276
+ }
1277
+ const closedImmediately = this._native.closeNow();
1278
+ if (closedImmediately) {
1279
+ this._closePromise = Promise.resolve();
1280
+ return this._closePromise;
1281
+ }
1282
+ this._closePromise = this._native.closeAsync();
1283
+ return this._closePromise;
1284
+ }
1285
+
1286
+ async _continueFastAsync(binary, callOptions) {
1287
+ this._pendingFastContinue += 1;
1288
+ let invoked = false;
1289
+ try {
1290
+ return await this._runAsync(callOptions, (t, id) => {
1291
+ invoked = true;
1292
+ return this._native.continuePendingFast(binary, t, id);
1293
+ });
1294
+ } finally {
1295
+ if (!invoked && typeof this._native?.abortPendingFast === "function") {
1296
+ try {
1297
+ this._native.abortPendingFast();
1298
+ } catch {
1299
+ // Ignore if already closed
1300
+ }
1301
+ }
1302
+ this._pendingFastContinue -= 1;
1303
+ }
1304
+ }
1305
+
1306
+ async _runAsync(callOptions, invoke) {
1307
+ if (this.isClosed) {
1308
+ throw new PklError("Evaluator has been closed.", "closed");
1309
+ }
1310
+ const callSignal = callOptions?.signal;
1311
+ if (this._signal?.aborted || callSignal?.aborted) {
1312
+ throw new PklError("Evaluation was cancelled.", "cancelled");
1313
+ }
1314
+ const timeoutMs = parseTimeoutMs(callOptions?.timeoutMs);
1315
+ const callId = this._nextCallId++;
1316
+ let onCallAbort = null;
1317
+ if (callSignal) {
1318
+ onCallAbort = () => {
1319
+ this._native.cancelCall(callId);
1320
+ };
1321
+ callSignal.addEventListener("abort", onCallAbort, { once: true });
1322
+ }
1323
+ try {
1324
+ const outcome = await invoke(timeoutMs, callId);
1325
+ return unwrapOutcome(outcome);
1326
+ } finally {
1327
+ if (callSignal && onCallAbort) {
1328
+ callSignal.removeEventListener("abort", onCallAbort);
1329
+ }
1330
+ }
1331
+ }
1332
+
1333
+ _runSync(callOptions, invoke) {
1334
+ if (this.isClosed) {
1335
+ throw new PklError("Evaluator has been closed.", "closed");
1336
+ }
1337
+ if (this._signal?.aborted || callOptions?.signal?.aborted) {
1338
+ throw new PklError("Evaluation was cancelled.", "cancelled");
1339
+ }
1340
+ const timeoutMs = parseTimeoutMs(callOptions?.timeoutMs);
1341
+ return unwrapOutcome(invoke(timeoutMs));
1342
+ }
1343
+
1344
+ async evaluateOutputText(source, callOptions = undefined) {
1345
+ const { uri, contents } = normalizeSource(source);
1346
+ if (
1347
+ !(contents !== undefined && uri === "repl:text") &&
1348
+ !this.isClosed &&
1349
+ this._pendingFastContinue === 0 &&
1350
+ !this._signal?.aborted &&
1351
+ !callOptions?.signal &&
1352
+ callOptions?.timeoutMs === undefined
1353
+ ) {
1354
+ const fast = this._native.tryEvaluateOutputTextFast(uri, contents);
1355
+ if (fast !== null && fast !== undefined) {
1356
+ if (fast.__continueAsync) {
1357
+ return this._continueFastAsync(false, callOptions);
1358
+ }
1359
+ return unwrapOutcome(fast);
1360
+ }
1361
+ }
1362
+ return this._runAsync(callOptions, (t, id) =>
1363
+ this._native.evaluateOutputText(uri, contents, t, id),
1364
+ );
1365
+ }
1366
+
1367
+ evaluateOutputTextSync(source, callOptions = undefined) {
1368
+ const { uri, contents } = normalizeSource(source);
1369
+ return this._runSync(callOptions, (t) =>
1370
+ this._native.evaluateOutputTextSync(uri, contents, t),
1371
+ );
1372
+ }
1373
+
1374
+ async evaluateOutputBytes(source, callOptions = undefined) {
1375
+ const { uri, contents } = normalizeSource(source);
1376
+ return this._runAsync(callOptions, (t, id) =>
1377
+ this._native.evaluateOutputBytes(uri, contents, t, id),
1378
+ );
1379
+ }
1380
+
1381
+ evaluateOutputBytesSync(source, callOptions = undefined) {
1382
+ const { uri, contents } = normalizeSource(source);
1383
+ return this._runSync(callOptions, (t) =>
1384
+ this._native.evaluateOutputBytesSync(uri, contents, t),
1385
+ );
1386
+ }
1387
+
1388
+ async evaluateOutputFiles(source, callOptions = undefined) {
1389
+ const { uri, contents } = normalizeSource(source);
1390
+ const entries = await this._runAsync(callOptions, (t, id) =>
1391
+ this._native.evaluateOutputFiles(uri, contents, t, id),
1392
+ );
1393
+ const out = new Map();
1394
+ for (const entry of entries) {
1395
+ out.set(entry.path, entry.bytes);
1396
+ }
1397
+ return out;
1398
+ }
1399
+
1400
+ evaluateOutputFilesSync(source, callOptions = undefined) {
1401
+ const { uri, contents } = normalizeSource(source);
1402
+ const entries = this._runSync(callOptions, (t) =>
1403
+ this._native.evaluateOutputFilesSync(uri, contents, t),
1404
+ );
1405
+ const out = new Map();
1406
+ for (const entry of entries) {
1407
+ out.set(entry.path, entry.bytes);
1408
+ }
1409
+ return out;
1410
+ }
1411
+
1412
+ async evaluateOutputValue(source, callOptions = undefined) {
1413
+ return this.evaluateExpressionValue(source, "output.value", callOptions);
1414
+ }
1415
+
1416
+ evaluateOutputValueSync(source, callOptions = undefined) {
1417
+ const bytes = this.evaluateExpressionPklBinarySync(source, "output.value", callOptions);
1418
+ return decodePklBinary(bytes);
1419
+ }
1420
+
1421
+ async evaluateExpression(source, expr, callOptions = undefined) {
1422
+ const { uri, contents } = normalizeSource(source);
1423
+ if (typeof expr !== "string") {
1424
+ throw new PklError("Expression must be a string.", "invalid-argument");
1425
+ }
1426
+ if (
1427
+ !(contents !== undefined && uri === "repl:text") &&
1428
+ !this.isClosed &&
1429
+ this._pendingFastContinue === 0 &&
1430
+ !this._signal?.aborted &&
1431
+ !callOptions?.signal &&
1432
+ callOptions?.timeoutMs === undefined
1433
+ ) {
1434
+ const fast = this._native.tryEvaluateExpressionFast(uri, contents, expr);
1435
+ if (fast !== null && fast !== undefined) {
1436
+ if (fast.__continueAsync) {
1437
+ return this._continueFastAsync(false, callOptions);
1438
+ }
1439
+ return unwrapOutcome(fast);
1440
+ }
1441
+ }
1442
+ return this._runAsync(callOptions, (t, id) =>
1443
+ this._native.evaluateExpression(uri, contents, expr, t, id),
1444
+ );
1445
+ }
1446
+
1447
+ evaluateExpressionSync(source, expr, callOptions = undefined) {
1448
+ const { uri, contents } = normalizeSource(source);
1449
+ if (typeof expr !== "string") {
1450
+ throw new PklError("Expression must be a string.", "invalid-argument");
1451
+ }
1452
+ return this._runSync(callOptions, (t) =>
1453
+ this._native.evaluateExpressionSync(uri, contents, expr, t),
1454
+ );
1455
+ }
1456
+
1457
+ async evaluateExpressionValue(source, expr, callOptions = undefined) {
1458
+ const { uri, contents } = normalizeSource(source);
1459
+ if (typeof expr !== "string") {
1460
+ throw new PklError("Expression must be a string.", "invalid-argument");
1461
+ }
1462
+ if (
1463
+ !(contents !== undefined && uri === "repl:text") &&
1464
+ !this.isClosed &&
1465
+ this._pendingFastContinue === 0 &&
1466
+ !this._signal?.aborted &&
1467
+ !callOptions?.signal &&
1468
+ callOptions?.timeoutMs === undefined
1469
+ ) {
1470
+ if (expr === "module" || expr === "output.value") {
1471
+ const colBuf = this._native.tryEvaluateExpressionColumnarFast(uri, contents, expr);
1472
+ if (colBuf !== null && colBuf !== undefined) {
1473
+ const unpacked = unpackColumnarBuffer(colBuf);
1474
+ if (unpacked !== DECODE_FALLBACK) {
1475
+ return unpacked;
1476
+ }
1477
+ }
1478
+ }
1479
+ const fast = this._native.tryEvaluateExpressionPklBinaryFast(uri, contents, expr);
1480
+ if (fast !== null && fast !== undefined) {
1481
+ if (fast.__continueAsync) {
1482
+ const bytes = await this._continueFastAsync(true, callOptions);
1483
+ return decodePklBinary(bytes);
1484
+ }
1485
+ return decodePklBinary(unwrapOutcome(fast));
1486
+ }
1487
+ }
1488
+ const bytes = await this._runAsync(callOptions, (t, id) =>
1489
+ this._native.evaluateExpressionPklBinary(uri, contents, expr, t, id),
1490
+ );
1491
+ return decodePklBinary(bytes);
1492
+ }
1493
+
1494
+ evaluateExpressionValueSync(source, expr, callOptions = undefined) {
1495
+ const bytes = this.evaluateExpressionPklBinarySync(source, expr, callOptions);
1496
+ return decodePklBinary(bytes);
1497
+ }
1498
+
1499
+ async evaluateExpressionPklBinary(source, expr, callOptions = undefined) {
1500
+ const { uri, contents } = normalizeSource(source);
1501
+ if (typeof expr !== "string") {
1502
+ throw new PklError("Expression must be a string.", "invalid-argument");
1503
+ }
1504
+ if (
1505
+ !(contents !== undefined && uri === "repl:text") &&
1506
+ !this.isClosed &&
1507
+ this._pendingFastContinue === 0 &&
1508
+ !this._signal?.aborted &&
1509
+ !callOptions?.signal &&
1510
+ callOptions?.timeoutMs === undefined
1511
+ ) {
1512
+ const fast = this._native.tryEvaluateExpressionPklBinaryFast(uri, contents, expr);
1513
+ if (fast !== null && fast !== undefined) {
1514
+ if (fast.__continueAsync) {
1515
+ return this._continueFastAsync(true, callOptions);
1516
+ }
1517
+ const buf = unwrapOutcome(fast);
1518
+ return new Uint8Array(buf);
1519
+ }
1520
+ }
1521
+ return this._runAsync(callOptions, (t, id) =>
1522
+ this._native.evaluateExpressionPklBinary(uri, contents, expr, t, id),
1523
+ );
1524
+ }
1525
+
1526
+ evaluateExpressionPklBinarySync(source, expr, callOptions = undefined) {
1527
+ const { uri, contents } = normalizeSource(source);
1528
+ if (typeof expr !== "string") {
1529
+ throw new PklError("Expression must be a string.", "invalid-argument");
1530
+ }
1531
+ return this._runSync(callOptions, (t) =>
1532
+ this._native.evaluateExpressionPklBinarySync(uri, contents, expr, t),
1533
+ );
1534
+ }
1535
+
1536
+ async evaluateSchema(source, callOptions = undefined) {
1537
+ const { uri, contents } = normalizeSource(source);
1538
+ const schema = await this._runAsync(callOptions, (t, id) =>
1539
+ this._native.evaluateSchema(uri, contents, t, id),
1540
+ );
1541
+ return hydrateSchema(schema);
1542
+ }
1543
+
1544
+ evaluateSchemaSync(source, callOptions = undefined) {
1545
+ const { uri, contents } = normalizeSource(source);
1546
+ const schema = this._runSync(callOptions, (t) =>
1547
+ this._native.evaluateSchemaSync(uri, contents, t),
1548
+ );
1549
+ return hydrateSchema(schema);
1550
+ }
1551
+
1552
+ async evaluateTest(source, testOptions = undefined) {
1553
+ const { uri, contents } = normalizeSource(source);
1554
+ const overwrite = Boolean(testOptions?.overwrite);
1555
+ const reporter = testOptions?.reporter ?? "spec";
1556
+ return this._runAsync(testOptions, (t, id) =>
1557
+ this._native.evaluateTest(uri, contents, overwrite, reporter, t, id),
1558
+ );
1559
+ }
1560
+
1561
+ evaluateTestSync(source, testOptions = undefined) {
1562
+ const { uri, contents } = normalizeSource(source);
1563
+ const overwrite = Boolean(testOptions?.overwrite);
1564
+ const reporter = testOptions?.reporter ?? "spec";
1565
+ return this._runSync(testOptions, (t) =>
1566
+ this._native.evaluateTestSync(uri, contents, overwrite, reporter, t),
1567
+ );
1568
+ }
1569
+ }
1570
+
1571
+ function createEvaluatorSync(options = undefined) {
1572
+ const { nativeOpts, nativeProject, bridgeCallback, setBridgeTarget, signal } =
1573
+ buildNativeOptions(options);
1574
+ const nativeEval = unwrapOutcome(
1575
+ native.NativeEvaluator.create(nativeOpts, nativeProject, bridgeCallback),
1576
+ );
1577
+ setBridgeTarget(nativeEval);
1578
+ return new Evaluator(nativeEval, signal, () => setBridgeTarget(null));
1579
+ }
1580
+
1581
+ async function createEvaluator(options = undefined) {
1582
+ return createEvaluatorSync(options);
1583
+ }
1584
+
1585
+ class ReplSession {
1586
+ constructor(nativeRepl, signal = undefined, clearBridge = null) {
1587
+ this._native = nativeRepl;
1588
+ this._closed = false;
1589
+ this._closePromise = null;
1590
+ this._clearBridge = clearBridge;
1591
+ this._signal = signal || null;
1592
+ this._onAbort = null;
1593
+ if (this._signal && !this._signal.aborted) {
1594
+ this._onAbort = () => {
1595
+ this._native.cancel();
1596
+ };
1597
+ this._signal.addEventListener("abort", this._onAbort, { once: true });
1598
+ }
1599
+ }
1600
+
1601
+ get isClosed() {
1602
+ return this._closed || this._native.isClosed;
1603
+ }
1604
+
1605
+ _checkOpen() {
1606
+ if (this.isClosed) {
1607
+ throw new PklError("REPL session has been closed.", "closed");
1608
+ }
1609
+ if (this._signal?.aborted) {
1610
+ throw new PklError("Evaluation was cancelled.", "cancelled");
1611
+ }
1612
+ }
1613
+
1614
+ async eval(input, options = undefined) {
1615
+ this._checkOpen();
1616
+ if (typeof input !== "string") {
1617
+ throw new PklError("ReplSession.eval input must be a string.", "invalid-argument");
1618
+ }
1619
+ const force = Boolean(options?.force);
1620
+ const evalDefinitions = Boolean(options?.evalDefinitions);
1621
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1622
+ return unwrapOutcome(await this._native.eval(input, force, evalDefinitions, id));
1623
+ }
1624
+
1625
+ async load(uriOrSource, options = undefined) {
1626
+ this._checkOpen();
1627
+ let uri;
1628
+ let contents = undefined;
1629
+ if (typeof uriOrSource === "string") {
1630
+ if (uriOrSource.length === 0) {
1631
+ throw new PklError(
1632
+ "ReplSession.load requires a non-empty URI string or ModuleSource.",
1633
+ "invalid-argument",
1634
+ );
1635
+ }
1636
+ uri = uriOrSource;
1637
+ } else if (
1638
+ uriOrSource &&
1639
+ typeof uriOrSource === "object" &&
1640
+ typeof uriOrSource.uri === "string" &&
1641
+ uriOrSource.uri.length > 0
1642
+ ) {
1643
+ uri = uriOrSource.uri;
1644
+ if (uriOrSource.contents !== undefined && uriOrSource.contents !== null) {
1645
+ if (typeof uriOrSource.contents !== "string") {
1646
+ throw new PklError("ModuleSource.contents must be a string.", "invalid-argument");
1647
+ }
1648
+ contents = uriOrSource.contents;
1649
+ }
1650
+ } else {
1651
+ throw new PklError(
1652
+ "ReplSession.load requires a non-empty URI string or ModuleSource.",
1653
+ "invalid-argument",
1654
+ );
1655
+ }
1656
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1657
+ return unwrapOutcome(await this._native.load(uri, contents, id));
1658
+ }
1659
+
1660
+ async complete(prefix, options = undefined) {
1661
+ this._checkOpen();
1662
+ if (typeof prefix !== "string") {
1663
+ throw new PklError("ReplSession.complete prefix must be a string.", "invalid-argument");
1664
+ }
1665
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1666
+ return unwrapOutcome(await this._native.complete(prefix, id));
1667
+ }
1668
+
1669
+ async reset(options = undefined) {
1670
+ this._checkOpen();
1671
+ const id = options?.id !== undefined ? String(options.id) : undefined;
1672
+ unwrapOutcome(await this._native.reset(id));
1673
+ }
1674
+
1675
+ cancel() {
1676
+ if (!this._closed) {
1677
+ this._native.cancel();
1678
+ }
1679
+ }
1680
+
1681
+ close() {
1682
+ if (this._closed) {
1683
+ return this._closePromise || Promise.resolve();
1684
+ }
1685
+ this._closed = true;
1686
+ if (this._clearBridge) {
1687
+ this._clearBridge();
1688
+ this._clearBridge = null;
1689
+ }
1690
+ if (this._signal && this._onAbort) {
1691
+ this._signal.removeEventListener("abort", this._onAbort);
1692
+ this._onAbort = null;
1693
+ }
1694
+ if (this._native.close()) {
1695
+ this._closePromise = Promise.resolve();
1696
+ return this._closePromise;
1697
+ }
1698
+ this._closePromise = this._native.closeAsync();
1699
+ return this._closePromise;
1700
+ }
1701
+ }
1702
+
1703
+ async function createRepl(options = undefined) {
1704
+ const { nativeOpts, nativeProject, bridgeCallback, setBridgeTarget, signal } =
1705
+ buildNativeOptions(options);
1706
+ const nativeRepl = unwrapOutcome(
1707
+ native.NativeReplSession.create(nativeOpts, nativeProject, bridgeCallback),
1708
+ );
1709
+ setBridgeTarget(nativeRepl);
1710
+ return new ReplSession(nativeRepl, signal, () => setBridgeTarget(null));
1711
+ }
1712
+
1713
+ async function analyzeImportGraph(uris, options = undefined) {
1714
+ if (!Array.isArray(uris)) {
1715
+ throw new PklError("analyzeImportGraph uris must be an array.", "invalid-argument");
1716
+ }
1717
+ const normalized = uris.map((item) => {
1718
+ if (typeof item === "string") return item;
1719
+ if (item && typeof item === "object" && typeof item.uri === "string") return item.uri;
1720
+ throw new PklError(
1721
+ "analyzeImportGraph entries must be URI strings or ModuleSource instances.",
1722
+ "invalid-argument",
1723
+ );
1724
+ });
1725
+ const { nativeOpts, nativeProject, bridgeCallback, setBridgeTarget, signal } =
1726
+ buildNativeOptions(options);
1727
+ if (signal?.aborted) {
1728
+ throw new PklError("Import graph analysis was cancelled.", "cancelled");
1729
+ }
1730
+ const analyzer = unwrapOutcome(
1731
+ native.NativeAnalyzer.create(nativeOpts, nativeProject, bridgeCallback),
1732
+ );
1733
+ setBridgeTarget(analyzer);
1734
+ let onAbort = null;
1735
+ if (signal) {
1736
+ onAbort = () => analyzer.cancel();
1737
+ signal.addEventListener("abort", onAbort, { once: true });
1738
+ }
1739
+ try {
1740
+ return unwrapOutcome(await analyzer.importGraph(normalized));
1741
+ } finally {
1742
+ setBridgeTarget(null);
1743
+ if (typeof analyzer.close === "function") {
1744
+ analyzer.close();
1745
+ }
1746
+ if (signal && onAbort) {
1747
+ signal.removeEventListener("abort", onAbort);
1748
+ }
1749
+ }
1750
+ }
1751
+
1752
+ function format(source, options = undefined) {
1753
+ if (typeof source !== "string") {
1754
+ throw new PklError("format source must be a string.", "invalid-argument");
1755
+ }
1756
+ const grammarVersion = options?.grammarVersion;
1757
+ if (
1758
+ grammarVersion !== undefined &&
1759
+ grammarVersion !== null &&
1760
+ grammarVersion !== 1 &&
1761
+ grammarVersion !== 2
1762
+ ) {
1763
+ throw new PklError(
1764
+ `Invalid grammarVersion "${grammarVersion}". Expected 1 or 2.`,
1765
+ "invalid-argument",
1766
+ );
1767
+ }
1768
+ return unwrapOutcome(native.productFormat(source, grammarVersion ?? undefined));
1769
+ }
1770
+
1771
+ const DECODE_STATE = new Int32Array(1);
1772
+ const INTERN_OFF = new Int32Array(64);
1773
+ const INTERN_LEN = new Int32Array(64);
1774
+ const INTERN_STR = new Array(64);
1775
+ const KEY_CACHE = new Map();
1776
+
1777
+ function internPropKey(s) {
1778
+ let k = KEY_CACHE.get(s);
1779
+ if (k !== undefined) return k;
1780
+ const tmp = { [s]: 0 };
1781
+ k = Object.keys(tmp)[0];
1782
+ if (KEY_CACHE.size < 256) KEY_CACHE.set(k, k);
1783
+ return k;
1784
+ }
1785
+
1786
+ const SHORT_UTF8_CODES = new Uint16Array(64);
1787
+
1788
+ function fastDecodeShortUtf8(bytes, pos, end) {
1789
+ let outLen = 0;
1790
+ let i = pos;
1791
+ while (i < end) {
1792
+ const b0 = bytes[i++];
1793
+ if (b0 < 0x80) {
1794
+ SHORT_UTF8_CODES[outLen++] = b0;
1795
+ } else if (b0 >= 0xc2 && b0 <= 0xdf) {
1796
+ if (i >= end) return DECODE_FALLBACK;
1797
+ const b1 = bytes[i++];
1798
+ if ((b1 & 0xc0) !== 0x80) return DECODE_FALLBACK;
1799
+ SHORT_UTF8_CODES[outLen++] = ((b0 & 0x1f) << 6) | (b1 & 0x3f);
1800
+ } else if (b0 >= 0xe0 && b0 <= 0xef) {
1801
+ if (i + 1 >= end) return DECODE_FALLBACK;
1802
+ const b1 = bytes[i++];
1803
+ const b2 = bytes[i++];
1804
+ if ((b1 & 0xc0) !== 0x80 || (b2 & 0xc0) !== 0x80) return DECODE_FALLBACK;
1805
+ if (b0 === 0xe0 && b1 < 0xa0) return DECODE_FALLBACK;
1806
+ if (b0 === 0xed && b1 >= 0xa0) return DECODE_FALLBACK;
1807
+ SHORT_UTF8_CODES[outLen++] = ((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f);
1808
+ } else if (b0 >= 0xf0 && b0 <= 0xf4) {
1809
+ if (i + 2 >= end) return DECODE_FALLBACK;
1810
+ const b1 = bytes[i++];
1811
+ const b2 = bytes[i++];
1812
+ const b3 = bytes[i++];
1813
+ if ((b1 & 0xc0) !== 0x80 || (b2 & 0xc0) !== 0x80 || (b3 & 0xc0) !== 0x80) {
1814
+ return DECODE_FALLBACK;
1815
+ }
1816
+ if (b0 === 0xf0 && b1 < 0x90) return DECODE_FALLBACK;
1817
+ if (b0 === 0xf4 && b1 > 0x8f) return DECODE_FALLBACK;
1818
+ const cp =
1819
+ (((b0 & 0x07) << 18) | ((b1 & 0x3f) << 12) | ((b2 & 0x3f) << 6) | (b3 & 0x3f)) -
1820
+ 0x10000;
1821
+ SHORT_UTF8_CODES[outLen++] = 0xd800 | (cp >> 10);
1822
+ SHORT_UTF8_CODES[outLen++] = 0xdc00 | (cp & 0x3ff);
1823
+ } else {
1824
+ return DECODE_FALLBACK;
1825
+ }
1826
+ }
1827
+ return String.fromCharCode.apply(null, SHORT_UTF8_CODES.subarray(0, outLen));
1828
+ }
1829
+
1830
+ function fastReadStr(bytes, view, len, pos, asKey) {
1831
+ if (pos >= len) return DECODE_FALLBACK;
1832
+ const b = bytes[pos++];
1833
+ let n;
1834
+ if (b >= 0xa0 && b <= 0xbf) {
1835
+ n = b & 0x1f;
1836
+ } else if (b === 0xd9) {
1837
+ if (pos >= len) return DECODE_FALLBACK;
1838
+ n = bytes[pos++];
1839
+ } else if (b === 0xda) {
1840
+ if (pos + 2 > len) return DECODE_FALLBACK;
1841
+ n = view.getUint16(pos, false);
1842
+ pos += 2;
1843
+ } else if (b === 0xdb) {
1844
+ if (pos + 4 > len) return DECODE_FALLBACK;
1845
+ n = view.getUint32(pos, false);
1846
+ pos += 4;
1847
+ } else {
1848
+ return DECODE_FALLBACK;
1849
+ }
1850
+ const end = pos + n;
1851
+ if (end > len) return DECODE_FALLBACK;
1852
+ DECODE_STATE[0] = end;
1853
+ if (n === 0) return "";
1854
+ if (n <= 24) {
1855
+ const slot = (bytes[pos] * 31 + bytes[end - 1] * 17 + n * 7) & 63;
1856
+ if (INTERN_LEN[slot] === n) {
1857
+ const prev = INTERN_OFF[slot];
1858
+ let eq = true;
1859
+ for (let k = 0; k < n; k += 1) {
1860
+ if (bytes[prev + k] !== bytes[pos + k]) {
1861
+ eq = false;
1862
+ break;
1863
+ }
1864
+ }
1865
+ if (eq) return INTERN_STR[slot];
1866
+ }
1867
+ let ascii = true;
1868
+ for (let i = pos; i < end; i += 1) {
1869
+ if (bytes[i] >= 0x80) {
1870
+ ascii = false;
1871
+ break;
1872
+ }
1873
+ }
1874
+ if (ascii) {
1875
+ let s;
1876
+ if (n === 1) s = String.fromCharCode(bytes[pos]);
1877
+ else if (n === 2) s = String.fromCharCode(bytes[pos], bytes[pos + 1]);
1878
+ else if (n === 3) s = String.fromCharCode(bytes[pos], bytes[pos + 1], bytes[pos + 2]);
1879
+ else if (n === 4) {
1880
+ s = String.fromCharCode(bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]);
1881
+ } else if (n === 5) {
1882
+ s = String.fromCharCode(
1883
+ bytes[pos],
1884
+ bytes[pos + 1],
1885
+ bytes[pos + 2],
1886
+ bytes[pos + 3],
1887
+ bytes[pos + 4],
1888
+ );
1889
+ } else if (n === 6) {
1890
+ s = String.fromCharCode(
1891
+ bytes[pos],
1892
+ bytes[pos + 1],
1893
+ bytes[pos + 2],
1894
+ bytes[pos + 3],
1895
+ bytes[pos + 4],
1896
+ bytes[pos + 5],
1897
+ );
1898
+ } else if (n === 7) {
1899
+ s = String.fromCharCode(
1900
+ bytes[pos],
1901
+ bytes[pos + 1],
1902
+ bytes[pos + 2],
1903
+ bytes[pos + 3],
1904
+ bytes[pos + 4],
1905
+ bytes[pos + 5],
1906
+ bytes[pos + 6],
1907
+ );
1908
+ } else if (n === 8) {
1909
+ s = String.fromCharCode(
1910
+ bytes[pos],
1911
+ bytes[pos + 1],
1912
+ bytes[pos + 2],
1913
+ bytes[pos + 3],
1914
+ bytes[pos + 4],
1915
+ bytes[pos + 5],
1916
+ bytes[pos + 6],
1917
+ bytes[pos + 7],
1918
+ );
1919
+ } else {
1920
+ s = "";
1921
+ for (let i = pos; i < end; i += 1) s += String.fromCharCode(bytes[i]);
1922
+ }
1923
+ if (asKey) s = internPropKey(s);
1924
+ INTERN_OFF[slot] = pos;
1925
+ INTERN_LEN[slot] = n;
1926
+ INTERN_STR[slot] = s;
1927
+ return s;
1928
+ }
1929
+ }
1930
+ if (n <= 64) {
1931
+ const decoded = fastDecodeShortUtf8(bytes, pos, end);
1932
+ if (decoded === DECODE_FALLBACK) return DECODE_FALLBACK;
1933
+ return asKey ? internPropKey(decoded) : decoded;
1934
+ }
1935
+ try {
1936
+ return FAST_UTF8_DECODER.decode(bytes.subarray(pos, end));
1937
+ } catch {
1938
+ return DECODE_FALLBACK;
1939
+ }
1940
+ }
1941
+
1942
+ function fastReadArrayLen(bytes, view, len, pos) {
1943
+ if (pos >= len) return -1;
1944
+ const b = bytes[pos++];
1945
+ if (b >= 0x90 && b <= 0x9f) {
1946
+ DECODE_STATE[0] = pos;
1947
+ return b & 0x0f;
1948
+ }
1949
+ if (b === 0xdc) {
1950
+ if (pos + 2 > len) return -1;
1951
+ DECODE_STATE[0] = pos + 2;
1952
+ return view.getUint16(pos, false);
1953
+ }
1954
+ if (b === 0xdd) {
1955
+ if (pos + 4 > len) return -1;
1956
+ DECODE_STATE[0] = pos + 4;
1957
+ return view.getUint32(pos, false);
1958
+ }
1959
+ return -1;
1960
+ }
1961
+
1962
+ function fastReadMapLen(bytes, view, len, pos) {
1963
+ if (pos >= len) return -1;
1964
+ const b = bytes[pos++];
1965
+ if (b >= 0x80 && b <= 0x8f) {
1966
+ DECODE_STATE[0] = pos;
1967
+ return b & 0x0f;
1968
+ }
1969
+ if (b === 0xde) {
1970
+ if (pos + 2 > len) return -1;
1971
+ DECODE_STATE[0] = pos + 2;
1972
+ return view.getUint16(pos, false);
1973
+ }
1974
+ if (b === 0xdf) {
1975
+ if (pos + 4 > len) return -1;
1976
+ DECODE_STATE[0] = pos + 4;
1977
+ return view.getUint32(pos, false);
1978
+ }
1979
+ return -1;
1980
+ }
1981
+
1982
+ function fastReadInt64(bytes, view, len, pos) {
1983
+ if (pos >= len) return DECODE_FALLBACK;
1984
+ const b = bytes[pos++];
1985
+ if (b <= 0x7f) {
1986
+ DECODE_STATE[0] = pos;
1987
+ return BigInt(b);
1988
+ }
1989
+ if (b >= 0xe0) {
1990
+ DECODE_STATE[0] = pos;
1991
+ return BigInt(b - 256);
1992
+ }
1993
+ if (b === 0xcc) {
1994
+ if (pos >= len) return DECODE_FALLBACK;
1995
+ DECODE_STATE[0] = pos + 1;
1996
+ return BigInt(bytes[pos]);
1997
+ }
1998
+ if (b === 0xcd) {
1999
+ if (pos + 2 > len) return DECODE_FALLBACK;
2000
+ DECODE_STATE[0] = pos + 2;
2001
+ return BigInt(view.getUint16(pos, false));
2002
+ }
2003
+ if (b === 0xce) {
2004
+ if (pos + 4 > len) return DECODE_FALLBACK;
2005
+ DECODE_STATE[0] = pos + 4;
2006
+ return BigInt(view.getUint32(pos, false));
2007
+ }
2008
+ if (b === 0xcf) {
2009
+ if (pos + 8 > len) return DECODE_FALLBACK;
2010
+ const v = view.getBigUint64(pos, false);
2011
+ if (v > MAX_I64) return DECODE_FALLBACK;
2012
+ DECODE_STATE[0] = pos + 8;
2013
+ return v;
2014
+ }
2015
+ if (b === 0xd0) {
2016
+ if (pos >= len) return DECODE_FALLBACK;
2017
+ DECODE_STATE[0] = pos + 1;
2018
+ return BigInt(view.getInt8(pos));
2019
+ }
2020
+ if (b === 0xd1) {
2021
+ if (pos + 2 > len) return DECODE_FALLBACK;
2022
+ DECODE_STATE[0] = pos + 2;
2023
+ return BigInt(view.getInt16(pos, false));
2024
+ }
2025
+ if (b === 0xd2) {
2026
+ if (pos + 4 > len) return DECODE_FALLBACK;
2027
+ DECODE_STATE[0] = pos + 4;
2028
+ return BigInt(view.getInt32(pos, false));
2029
+ }
2030
+ if (b === 0xd3) {
2031
+ if (pos + 8 > len) return DECODE_FALLBACK;
2032
+ DECODE_STATE[0] = pos + 8;
2033
+ return view.getBigInt64(pos, false);
2034
+ }
2035
+ return DECODE_FALLBACK;
2036
+ }
2037
+
2038
+ function fastReadFloat(bytes, view, len, pos) {
2039
+ if (pos >= len) return DECODE_FALLBACK;
2040
+ const b = bytes[pos++];
2041
+ if (b === 0xca) {
2042
+ if (pos + 4 > len) return DECODE_FALLBACK;
2043
+ DECODE_STATE[0] = pos + 4;
2044
+ return view.getFloat32(pos, false);
2045
+ }
2046
+ if (b === 0xcb) {
2047
+ if (pos + 8 > len) return DECODE_FALLBACK;
2048
+ DECODE_STATE[0] = pos + 8;
2049
+ return view.getFloat64(pos, false);
2050
+ }
2051
+ return DECODE_FALLBACK;
2052
+ }
2053
+
2054
+ function fastDecodeVal(bytes, view, len, depth) {
2055
+ let pos = DECODE_STATE[0];
2056
+ if (depth > 64 || pos >= len) return DECODE_FALLBACK;
2057
+ const b = bytes[pos];
2058
+ if (b <= 0x7f) {
2059
+ DECODE_STATE[0] = pos + 1;
2060
+ return BigInt(b);
2061
+ }
2062
+ if (b >= 0xe0) {
2063
+ DECODE_STATE[0] = pos + 1;
2064
+ return BigInt(b - 256);
2065
+ }
2066
+ if (b >= 0xa0 && b <= 0xbf) {
2067
+ return fastReadStr(bytes, view, len, pos, false);
2068
+ }
2069
+ if (b === 0xc0) {
2070
+ DECODE_STATE[0] = pos + 1;
2071
+ return null;
2072
+ }
2073
+ if (b === 0xc2) {
2074
+ DECODE_STATE[0] = pos + 1;
2075
+ return false;
2076
+ }
2077
+ if (b === 0xc3) {
2078
+ DECODE_STATE[0] = pos + 1;
2079
+ return true;
2080
+ }
2081
+ if (b === 0xca || b === 0xcb) {
2082
+ return fastReadFloat(bytes, view, len, pos);
2083
+ }
2084
+ if (b >= 0xcc && b <= 0xd3) {
2085
+ return fastReadInt64(bytes, view, len, pos);
2086
+ }
2087
+ if (b === 0xd9 || b === 0xda || b === 0xdb) {
2088
+ return fastReadStr(bytes, view, len, pos, false);
2089
+ }
2090
+ if ((b >= 0x90 && b <= 0x9f) || b === 0xdc || b === 0xdd) {
2091
+ const alen = fastReadArrayLen(bytes, view, len, pos);
2092
+ pos = DECODE_STATE[0];
2093
+ if (alen < 1 || pos >= len) return DECODE_FALLBACK;
2094
+ const code = bytes[pos++];
2095
+ if (code > 0x7f) return DECODE_FALLBACK;
2096
+
2097
+ if (code === 0x01) {
2098
+ if (alen !== 4) return DECODE_FALLBACK;
2099
+ const className = fastReadStr(bytes, view, len, pos, false);
2100
+ if (
2101
+ className === DECODE_FALLBACK ||
2102
+ className.length === 0 ||
2103
+ ((className.charCodeAt(0) <= 0x20 || className.charCodeAt(0) >= 0x80) &&
2104
+ BLANK_OR_CTRL_RE.test(className))
2105
+ ) {
2106
+ return DECODE_FALLBACK;
2107
+ }
2108
+ pos = DECODE_STATE[0];
2109
+ const moduleUri = fastReadStr(bytes, view, len, pos, false);
2110
+ if (
2111
+ moduleUri === DECODE_FALLBACK ||
2112
+ moduleUri.length === 0 ||
2113
+ (moduleUri !== "pkl:base" && !FAST_MODULE_URI_RE.test(moduleUri))
2114
+ ) {
2115
+ return DECODE_FALLBACK;
2116
+ }
2117
+ pos = DECODE_STATE[0];
2118
+ const mcount = fastReadArrayLen(bytes, view, len, pos);
2119
+ pos = DECODE_STATE[0];
2120
+ if (mcount < 0 || mcount * 3 > len - pos) return DECODE_FALLBACK;
2121
+ const props = {};
2122
+ const entries = new Map();
2123
+ const elements = [];
2124
+ const nextDepth = depth + 1;
2125
+ for (let i = 0; i < mcount; i += 1) {
2126
+ if (pos + 2 > len) return DECODE_FALLBACK;
2127
+ if (bytes[pos++] !== 0x93) return DECODE_FALLBACK;
2128
+ const mcode = bytes[pos++];
2129
+ if (mcode === 0x10) {
2130
+ const k = fastReadStr(bytes, view, len, pos, true);
2131
+ if (k === DECODE_FALLBACK) return DECODE_FALLBACK;
2132
+ pos = DECODE_STATE[0];
2133
+ if (pos >= len) return DECODE_FALLBACK;
2134
+ const vb = bytes[pos];
2135
+ let v;
2136
+ if (vb === 0xd3) {
2137
+ if (pos + 9 > len) return DECODE_FALLBACK;
2138
+ v = view.getBigInt64(pos + 1, false);
2139
+ pos += 9;
2140
+ } else if (vb === 0xcf) {
2141
+ if (pos + 9 > len) return DECODE_FALLBACK;
2142
+ v = view.getBigUint64(pos + 1, false);
2143
+ if (v > MAX_I64) return DECODE_FALLBACK;
2144
+ pos += 9;
2145
+ } else if (vb === 0xc2) {
2146
+ v = false;
2147
+ pos += 1;
2148
+ } else if (vb === 0xc3) {
2149
+ v = true;
2150
+ pos += 1;
2151
+ } else if (vb === 0xc0) {
2152
+ v = null;
2153
+ pos += 1;
2154
+ } else if (vb <= 0x7f) {
2155
+ v = BigInt(vb);
2156
+ pos += 1;
2157
+ } else if (vb >= 0xe0) {
2158
+ v = BigInt(vb - 256);
2159
+ pos += 1;
2160
+ } else if (vb >= 0xa0 && vb <= 0xbf) {
2161
+ v = fastReadStr(bytes, view, len, pos, false);
2162
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2163
+ pos = DECODE_STATE[0];
2164
+ } else if (
2165
+ pos + 4 <= len &&
2166
+ vb === 0x92 &&
2167
+ bytes[pos + 1] === 0x0f &&
2168
+ bytes[pos + 2] === 0xc4
2169
+ ) {
2170
+ const blen = bytes[pos + 3];
2171
+ const p = pos + 4;
2172
+ if (p + blen > len) return DECODE_FALLBACK;
2173
+ if (blen <= 16) {
2174
+ v = new Uint8Array(blen);
2175
+ for (let j = 0; j < blen; j += 1) v[j] = bytes[p + j];
2176
+ } else {
2177
+ v = bytes.slice(p, p + blen);
2178
+ }
2179
+ pos = p + blen;
2180
+ } else {
2181
+ DECODE_STATE[0] = pos;
2182
+ v = fastDecodeVal(bytes, view, len, nextDepth);
2183
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2184
+ pos = DECODE_STATE[0];
2185
+ }
2186
+ if (k === "__proto__") {
2187
+ Object.defineProperty(props, k, {
2188
+ value: v,
2189
+ enumerable: true,
2190
+ writable: true,
2191
+ configurable: true,
2192
+ });
2193
+ } else {
2194
+ props[k] = v;
2195
+ }
2196
+ } else if (mcode === 0x11) {
2197
+ DECODE_STATE[0] = pos;
2198
+ const k = fastDecodeVal(bytes, view, len, nextDepth);
2199
+ if (k === DECODE_FALLBACK) return DECODE_FALLBACK;
2200
+ const v = fastDecodeVal(bytes, view, len, nextDepth);
2201
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2202
+ pos = DECODE_STATE[0];
2203
+ entries.set(k, v);
2204
+ } else if (mcode === 0x12) {
2205
+ const idx = fastReadInt64(bytes, view, len, pos);
2206
+ if (idx === DECODE_FALLBACK) return DECODE_FALLBACK;
2207
+ const v = fastDecodeVal(bytes, view, len, nextDepth);
2208
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2209
+ pos = DECODE_STATE[0];
2210
+ elements.push(v);
2211
+ } else {
2212
+ return DECODE_FALLBACK;
2213
+ }
2214
+ }
2215
+ DECODE_STATE[0] = pos;
2216
+ return new PklObject(className, moduleUri, props, entries, elements);
2217
+ }
2218
+
2219
+ if (code === 0x04 || code === 0x05) {
2220
+ if (alen !== 2) return DECODE_FALLBACK;
2221
+ const count = fastReadArrayLen(bytes, view, len, pos);
2222
+ if (count < 0 || count > len - DECODE_STATE[0]) return DECODE_FALLBACK;
2223
+ const out = new Array(count);
2224
+ const nextDepth = depth + 1;
2225
+ for (let i = 0; i < count; i += 1) {
2226
+ const item = fastDecodeVal(bytes, view, len, nextDepth);
2227
+ if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
2228
+ out[i] = item;
2229
+ }
2230
+ return out;
2231
+ }
2232
+
2233
+ if (code === 0x02 || code === 0x03) {
2234
+ if (alen !== 2) return DECODE_FALLBACK;
2235
+ const count = fastReadMapLen(bytes, view, len, pos);
2236
+ if (count < 0 || count * 2 > len - DECODE_STATE[0]) return DECODE_FALLBACK;
2237
+ const out = new Map();
2238
+ const nextDepth = depth + 1;
2239
+ for (let i = 0; i < count; i += 1) {
2240
+ const k = fastDecodeVal(bytes, view, len, nextDepth);
2241
+ if (k === DECODE_FALLBACK) return DECODE_FALLBACK;
2242
+ const v = fastDecodeVal(bytes, view, len, nextDepth);
2243
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2244
+ out.set(k, v);
2245
+ }
2246
+ return out;
2247
+ }
2248
+
2249
+ if (code === 0x06) {
2250
+ if (alen !== 2) return DECODE_FALLBACK;
2251
+ const count = fastReadArrayLen(bytes, view, len, pos);
2252
+ if (count < 0 || count > len - DECODE_STATE[0]) return DECODE_FALLBACK;
2253
+ const out = new Set();
2254
+ const nextDepth = depth + 1;
2255
+ for (let i = 0; i < count; i += 1) {
2256
+ const item = fastDecodeVal(bytes, view, len, nextDepth);
2257
+ if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
2258
+ out.add(item);
2259
+ }
2260
+ return out;
2261
+ }
2262
+
2263
+ if (code === 0x0f) {
2264
+ if (alen !== 2 || pos >= len) return DECODE_FALLBACK;
2265
+ const bb = bytes[pos++];
2266
+ let blen;
2267
+ if (bb === 0xc4) {
2268
+ if (pos >= len) return DECODE_FALLBACK;
2269
+ blen = bytes[pos++];
2270
+ } else if (bb === 0xc5) {
2271
+ if (pos + 2 > len) return DECODE_FALLBACK;
2272
+ blen = view.getUint16(pos, false);
2273
+ pos += 2;
2274
+ } else if (bb === 0xc6) {
2275
+ if (pos + 4 > len) return DECODE_FALLBACK;
2276
+ blen = view.getUint32(pos, false);
2277
+ pos += 4;
2278
+ } else {
2279
+ return DECODE_FALLBACK;
2280
+ }
2281
+ if (pos + blen > len) return DECODE_FALLBACK;
2282
+ let owned;
2283
+ if (blen <= 16) {
2284
+ owned = new Uint8Array(blen);
2285
+ for (let j = 0; j < blen; j += 1) owned[j] = bytes[pos + j];
2286
+ } else {
2287
+ owned = bytes.slice(pos, pos + blen);
2288
+ }
2289
+ DECODE_STATE[0] = pos + blen;
2290
+ return owned;
2291
+ }
2292
+
2293
+ if (code === 0x07) {
2294
+ if (alen !== 3) return DECODE_FALLBACK;
2295
+ const val = fastReadFloat(bytes, view, len, pos);
2296
+ if (val === DECODE_FALLBACK) return DECODE_FALLBACK;
2297
+ const unit = fastReadStr(bytes, view, len, DECODE_STATE[0], false);
2298
+ if (unit === DECODE_FALLBACK || !VALID_DURATION_UNITS.has(unit)) {
2299
+ return DECODE_FALLBACK;
2300
+ }
2301
+ return new PklDuration(val, unit);
2302
+ }
2303
+
2304
+ if (code === 0x08) {
2305
+ if (alen !== 3) return DECODE_FALLBACK;
2306
+ const val = fastReadFloat(bytes, view, len, pos);
2307
+ if (val === DECODE_FALLBACK) return DECODE_FALLBACK;
2308
+ const unit = fastReadStr(bytes, view, len, DECODE_STATE[0], false);
2309
+ if (unit === DECODE_FALLBACK || !VALID_DATA_SIZE_UNITS.has(unit)) {
2310
+ return DECODE_FALLBACK;
2311
+ }
2312
+ return new PklDataSize(val, unit);
2313
+ }
2314
+
2315
+ if (code === 0x09) {
2316
+ if (alen !== 3) return DECODE_FALLBACK;
2317
+ DECODE_STATE[0] = pos;
2318
+ const nextDepth = depth + 1;
2319
+ const first = fastDecodeVal(bytes, view, len, nextDepth);
2320
+ if (first === DECODE_FALLBACK) return DECODE_FALLBACK;
2321
+ const second = fastDecodeVal(bytes, view, len, nextDepth);
2322
+ if (second === DECODE_FALLBACK) return DECODE_FALLBACK;
2323
+ return new PklPair(first, second);
2324
+ }
2325
+
2326
+ return DECODE_FALLBACK;
2327
+ }
2328
+ return DECODE_FALLBACK;
2329
+ }
2330
+
2331
+ function tryDecodePklBinaryFast(bytes) {
2332
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength === 0) {
2333
+ return DECODE_FALLBACK;
2334
+ }
2335
+ const len = bytes.byteLength;
2336
+ const view = new DataView(bytes.buffer, bytes.byteOffset, len);
2337
+ DECODE_STATE[0] = 0;
2338
+ INTERN_LEN.fill(-1);
2339
+ const out = fastDecodeVal(bytes, view, len, 0);
2340
+ if (out === DECODE_FALLBACK || DECODE_STATE[0] !== len) {
2341
+ return DECODE_FALLBACK;
2342
+ }
2343
+ return out;
2344
+ }
2345
+
2346
+ const COLUMNAR_MAGIC = 0x504b4c01;
2347
+ const MAX_COLUMNAR_DEPTH = 64;
2348
+ const IS_LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
2349
+ let canUseNewFunction = true;
2350
+ const SHAPE_PROPS_FACTORIES = new Map();
2351
+ const COLUMNAR_TABLE_READERS = new Map();
2352
+ let columnarAlignBuf = null;
2353
+ const COL_STATE = new Float64Array(7);
2354
+
2355
+ function isValidColumnarSection(off, count, elemSize, align, byteLen) {
2356
+ return (
2357
+ off >= 80 &&
2358
+ off <= byteLen &&
2359
+ (off & (align - 1)) === 0 &&
2360
+ count * elemSize <= byteLen - off
2361
+ );
2362
+ }
2363
+
2364
+ function getShapePropsFactory(keys) {
2365
+ if (!canUseNewFunction || keys.length === 0 || keys.length > 32) return null;
2366
+ for (let i = 0; i < keys.length; i += 1) {
2367
+ if (keys[i] === "__proto__") return null;
2368
+ }
2369
+ const sig = JSON.stringify(keys);
2370
+ let fn = SHAPE_PROPS_FACTORIES.get(sig);
2371
+ if (fn !== undefined) return fn;
2372
+ try {
2373
+ const params = new Array(keys.length);
2374
+ const fields = new Array(keys.length);
2375
+ for (let i = 0; i < keys.length; i += 1) {
2376
+ params[i] = `v${i}`;
2377
+ fields[i] = `${JSON.stringify(keys[i])}:v${i}`;
2378
+ }
2379
+ fn = new Function(params.join(","), `return {${fields.join(",")}};`);
2380
+ } catch {
2381
+ canUseNewFunction = false;
2382
+ return null;
2383
+ }
2384
+ if (SHAPE_PROPS_FACTORIES.size < 256) SHAPE_PROPS_FACTORIES.set(sig, fn);
2385
+ return fn;
2386
+ }
2387
+
2388
+ function getColumnarTableReader(keys, colTypes) {
2389
+ if (!canUseNewFunction || keys.length === 0 || keys.length > 32) return null;
2390
+ for (let i = 0; i < keys.length; i += 1) {
2391
+ if (keys[i] === "__proto__") return null;
2392
+ }
2393
+ const sig = `${JSON.stringify(keys)}|${colTypes.join(",")}`;
2394
+ let fn = COLUMNAR_TABLE_READERS.get(sig);
2395
+ if (fn !== undefined) return fn;
2396
+ try {
2397
+ const lines = [
2398
+ "const out = new Array(count);",
2399
+ "let bi = st[0], si = st[1], soff = st[2], bo = st[3], bli = st[4], fli = st[5], bbi = st[6];",
2400
+ "for (let i = 0; i < count; i += 1) {",
2401
+ ];
2402
+ const propExprs = new Array(keys.length);
2403
+ for (let c = 0; c < keys.length; c += 1) {
2404
+ const t = colTypes[c];
2405
+ const k = JSON.stringify(keys[c]);
2406
+ if (t === 1) {
2407
+ propExprs[c] = `${k}: bigs[bi++]`;
2408
+ } else if (t === 2) {
2409
+ propExprs[c] = `${k}: bools[bbi++] !== 0`;
2410
+ } else if (t === 3) {
2411
+ lines.push(
2412
+ ` const l${c} = lens[si++]; const s${c} = bigStr.slice(soff, soff + l${c}); soff += l${c};`,
2413
+ );
2414
+ propExprs[c] = `${k}: s${c}`;
2415
+ } else if (t === 4) {
2416
+ lines.push(
2417
+ ` const bn${c} = binLens[bli++]; let u${c}; if (bn${c} <= 16) { u${c} = new Uint8Array(bn${c}); for (let j = 0; j < bn${c}; j += 1) u${c}[j] = bins[bo + j]; } else { u${c} = bins.slice(bo, bo + bn${c}); } bo += bn${c};`,
2418
+ );
2419
+ propExprs[c] = `${k}: u${c}`;
2420
+ } else if (t === 5) {
2421
+ propExprs[c] = `${k}: floats[fli++]`;
2422
+ } else if (t === 6) {
2423
+ propExprs[c] = `${k}: null`;
2424
+ } else {
2425
+ return null;
2426
+ }
2427
+ }
2428
+ lines.push(
2429
+ ` out[i] = new PklObject(cls, uri, {${propExprs.join(",")}});`,
2430
+ );
2431
+ lines.push("}");
2432
+ lines.push(
2433
+ "st[0] = bi; st[1] = si; st[2] = soff; st[3] = bo; st[4] = bli; st[5] = fli; st[6] = bbi;",
2434
+ );
2435
+ lines.push("return out;");
2436
+ fn = new Function(
2437
+ "PklObject",
2438
+ "cls",
2439
+ "uri",
2440
+ "count",
2441
+ "bigs",
2442
+ "bools",
2443
+ "floats",
2444
+ "lens",
2445
+ "bigStr",
2446
+ "bins",
2447
+ "binLens",
2448
+ "st",
2449
+ lines.join("\n"),
2450
+ );
2451
+ } catch {
2452
+ canUseNewFunction = false;
2453
+ return null;
2454
+ }
2455
+ if (COLUMNAR_TABLE_READERS.size < 256) COLUMNAR_TABLE_READERS.set(sig, fn);
2456
+ return fn;
2457
+ }
2458
+
2459
+ function unpackColumnarBuffer(bytes) {
2460
+ if (!IS_LITTLE_ENDIAN || !(bytes instanceof Uint8Array) || bytes.byteLength < 80) {
2461
+ return DECODE_FALLBACK;
2462
+ }
2463
+ let src = bytes;
2464
+ let alignedCopyOversized = false;
2465
+ if ((bytes.byteOffset & 7) !== 0) {
2466
+ const need = bytes.byteLength;
2467
+ if (columnarAlignBuf === null || columnarAlignBuf.byteLength < need) {
2468
+ columnarAlignBuf = new Uint8Array(Math.max(need, 4096));
2469
+ }
2470
+ columnarAlignBuf.set(bytes, 0);
2471
+ src = columnarAlignBuf.subarray(0, need);
2472
+ alignedCopyOversized = columnarAlignBuf.byteLength > 262144;
2473
+ }
2474
+ try {
2475
+ return unpackColumnarAligned(src.buffer, src.byteOffset, src.byteLength);
2476
+ } finally {
2477
+ if (alignedCopyOversized) {
2478
+ columnarAlignBuf = null;
2479
+ }
2480
+ }
2481
+ }
2482
+
2483
+ function unpackColumnarAligned(ab, base, byteLen) {
2484
+ const header = new Uint32Array(ab, base, 20);
2485
+ if (header[0] !== COLUMNAR_MAGIC) {
2486
+ return DECODE_FALLBACK;
2487
+ }
2488
+ if (
2489
+ !isValidColumnarSection(header[1], header[2], 4, 4, byteLen) ||
2490
+ !isValidColumnarSection(header[3], header[4], 8, 8, byteLen) ||
2491
+ !isValidColumnarSection(header[5], header[6], 8, 8, byteLen) ||
2492
+ !isValidColumnarSection(header[7], header[8], 1, 1, byteLen) ||
2493
+ !isValidColumnarSection(header[9], header[10], 4, 4, byteLen) ||
2494
+ !isValidColumnarSection(header[11], header[12], 1, 1, byteLen) ||
2495
+ !isValidColumnarSection(header[13], header[14], 4, 4, byteLen) ||
2496
+ !isValidColumnarSection(header[15], header[16], 1, 1, byteLen)
2497
+ ) {
2498
+ return DECODE_FALLBACK;
2499
+ }
2500
+ const ops = new Int32Array(ab, base + header[1], header[2]);
2501
+ const bigs = new BigInt64Array(ab, base + header[3], header[4]);
2502
+ const floats = new Float64Array(ab, base + header[5], header[6]);
2503
+ const bools = new Uint8Array(ab, base + header[7], header[8]);
2504
+ const strLens = new Uint32Array(ab, base + header[9], header[10]);
2505
+ const strUtf8 = new Uint8Array(ab, base + header[11], header[12]);
2506
+ const binLens = new Uint32Array(ab, base + header[13], header[14]);
2507
+ const binBytes = new Uint8Array(ab, base + header[15], header[16]);
2508
+ const shapeCount = header[17];
2509
+ const shapeStrCount = header[18];
2510
+
2511
+ if (shapeStrCount > strLens.length || shapeCount * 3 > ops.length) {
2512
+ return DECODE_FALLBACK;
2513
+ }
2514
+
2515
+ let bigStr;
2516
+ if (strUtf8.byteLength === 0) {
2517
+ bigStr = "";
2518
+ } else {
2519
+ try {
2520
+ bigStr = FAST_UTF8_DECODER.decode(strUtf8);
2521
+ } catch {
2522
+ return DECODE_FALLBACK;
2523
+ }
2524
+ }
2525
+
2526
+ let soff = 0;
2527
+ const bigStrLen = bigStr.length;
2528
+ const shapeStrs = new Array(shapeStrCount);
2529
+ for (let i = 0; i < shapeStrCount; i += 1) {
2530
+ const l = strLens[i];
2531
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2532
+ shapeStrs[i] = bigStr.slice(soff, soff + l);
2533
+ soff += l;
2534
+ }
2535
+
2536
+ let op = 0;
2537
+ const opsLen = ops.length;
2538
+ const shapes = new Array(shapeCount);
2539
+ for (let s = 0; s < shapeCount; s += 1) {
2540
+ if (op + 3 > opsLen) return DECODE_FALLBACK;
2541
+ const clsIdx = ops[op++];
2542
+ const uriIdx = ops[op++];
2543
+ const klen = ops[op++];
2544
+ if (
2545
+ clsIdx < 0 ||
2546
+ clsIdx >= shapeStrCount ||
2547
+ uriIdx < 0 ||
2548
+ uriIdx >= shapeStrCount ||
2549
+ klen < 0 ||
2550
+ klen > opsLen - op
2551
+ ) {
2552
+ return DECODE_FALLBACK;
2553
+ }
2554
+ const cls = shapeStrs[clsIdx];
2555
+ const uri = shapeStrs[uriIdx];
2556
+ const keys = new Array(klen);
2557
+ for (let k = 0; k < klen; k += 1) {
2558
+ const keyIdx = ops[op++];
2559
+ if (keyIdx < 0 || keyIdx >= shapeStrCount) return DECODE_FALLBACK;
2560
+ keys[k] = shapeStrs[keyIdx];
2561
+ }
2562
+ shapes[s] = { cls, uri, keys, fn: getShapePropsFactory(keys) };
2563
+ }
2564
+
2565
+ let bi = 0;
2566
+ let fli = 0;
2567
+ let bbi = 0;
2568
+ let si = shapeStrCount;
2569
+ let bli = 0;
2570
+ let bo = 0;
2571
+ const bigsLen = bigs.length;
2572
+ const floatsLen = floats.length;
2573
+ const boolsLen = bools.length;
2574
+ const strLensLen = strLens.length;
2575
+ const binLensLen = binLens.length;
2576
+ const binBytesLen = binBytes.length;
2577
+ const shapesLen = shapes.length;
2578
+
2579
+ function readVal(depth) {
2580
+ if (depth > MAX_COLUMNAR_DEPTH || op >= opsLen) return DECODE_FALLBACK;
2581
+ const tag = ops[op++];
2582
+ if (tag === 0) return null;
2583
+ if (tag === 1) {
2584
+ if (bi >= bigsLen) return DECODE_FALLBACK;
2585
+ return bigs[bi++];
2586
+ }
2587
+ if (tag === 2) {
2588
+ if (fli >= floatsLen) return DECODE_FALLBACK;
2589
+ return floats[fli++];
2590
+ }
2591
+ if (tag === 3) return false;
2592
+ if (tag === 4) return true;
2593
+ if (tag === 5) {
2594
+ if (si >= strLensLen) return DECODE_FALLBACK;
2595
+ const l = strLens[si++];
2596
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2597
+ const s = bigStr.slice(soff, soff + l);
2598
+ soff += l;
2599
+ return s;
2600
+ }
2601
+ if (tag === 6) {
2602
+ if (bli >= binLensLen) return DECODE_FALLBACK;
2603
+ const n = binLens[bli++];
2604
+ if (bo + n > binBytesLen) return DECODE_FALLBACK;
2605
+ let owned;
2606
+ if (n <= 16) {
2607
+ owned = new Uint8Array(n);
2608
+ for (let j = 0; j < n; j += 1) owned[j] = binBytes[bo + j];
2609
+ } else {
2610
+ owned = binBytes.slice(bo, bo + n);
2611
+ }
2612
+ bo += n;
2613
+ return owned;
2614
+ }
2615
+ if (tag === 7) {
2616
+ if (op >= opsLen) return DECODE_FALLBACK;
2617
+ const n = ops[op++];
2618
+ if (n < 0 || n > opsLen - op) return DECODE_FALLBACK;
2619
+ const arr = new Array(n);
2620
+ const nextDepth = depth + 1;
2621
+ for (let i = 0; i < n; i += 1) {
2622
+ const item = readVal(nextDepth);
2623
+ if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
2624
+ arr[i] = item;
2625
+ }
2626
+ return arr;
2627
+ }
2628
+ if (tag === 10) {
2629
+ if (op >= opsLen) return DECODE_FALLBACK;
2630
+ const shIdx = ops[op++];
2631
+ if (shIdx < 0 || shIdx >= shapesLen) return DECODE_FALLBACK;
2632
+ const sh = shapes[shIdx];
2633
+ const keys = sh.keys;
2634
+ const klen = keys.length;
2635
+ const nextDepth = depth + 1;
2636
+ let props;
2637
+ if (sh.fn !== null) {
2638
+ if (klen === 4) {
2639
+ const a0 = readVal(nextDepth);
2640
+ const a1 = readVal(nextDepth);
2641
+ const a2 = readVal(nextDepth);
2642
+ const a3 = readVal(nextDepth);
2643
+ if (
2644
+ a0 === DECODE_FALLBACK ||
2645
+ a1 === DECODE_FALLBACK ||
2646
+ a2 === DECODE_FALLBACK ||
2647
+ a3 === DECODE_FALLBACK
2648
+ ) {
2649
+ return DECODE_FALLBACK;
2650
+ }
2651
+ props = sh.fn(a0, a1, a2, a3);
2652
+ } else if (klen === 5) {
2653
+ const a0 = readVal(nextDepth);
2654
+ const a1 = readVal(nextDepth);
2655
+ const a2 = readVal(nextDepth);
2656
+ const a3 = readVal(nextDepth);
2657
+ const a4 = readVal(nextDepth);
2658
+ if (
2659
+ a0 === DECODE_FALLBACK ||
2660
+ a1 === DECODE_FALLBACK ||
2661
+ a2 === DECODE_FALLBACK ||
2662
+ a3 === DECODE_FALLBACK ||
2663
+ a4 === DECODE_FALLBACK
2664
+ ) {
2665
+ return DECODE_FALLBACK;
2666
+ }
2667
+ props = sh.fn(a0, a1, a2, a3, a4);
2668
+ } else {
2669
+ const vals = new Array(klen);
2670
+ for (let i = 0; i < klen; i += 1) {
2671
+ const v = readVal(nextDepth);
2672
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2673
+ vals[i] = v;
2674
+ }
2675
+ props = sh.fn.apply(null, vals);
2676
+ }
2677
+ } else {
2678
+ props = {};
2679
+ for (let i = 0; i < klen; i += 1) {
2680
+ const v = readVal(nextDepth);
2681
+ if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2682
+ const k = keys[i];
2683
+ if (k === "__proto__") {
2684
+ definePropSafe(props, k, v);
2685
+ } else {
2686
+ props[k] = v;
2687
+ }
2688
+ }
2689
+ }
2690
+ return new PklObject(sh.cls, sh.uri, props);
2691
+ }
2692
+ if (tag === 12) {
2693
+ if (op + 2 > opsLen) return DECODE_FALLBACK;
2694
+ const shIdx = ops[op++];
2695
+ const count = ops[op++];
2696
+ if (shIdx < 0 || shIdx >= shapesLen || count < 0) return DECODE_FALLBACK;
2697
+ const sh = shapes[shIdx];
2698
+ const keys = sh.keys;
2699
+ const klen = keys.length;
2700
+ if (op + klen > opsLen) return DECODE_FALLBACK;
2701
+ const colTypes = new Array(klen);
2702
+ let needBigs = 0;
2703
+ let needBools = 0;
2704
+ let needStrs = 0;
2705
+ let needBins = 0;
2706
+ let needFloats = 0;
2707
+ for (let c = 0; c < klen; c += 1) {
2708
+ const t = ops[op++];
2709
+ colTypes[c] = t;
2710
+ if (t === 1) needBigs += count;
2711
+ else if (t === 2) needBools += count;
2712
+ else if (t === 3) needStrs += count;
2713
+ else if (t === 4) needBins += count;
2714
+ else if (t === 5) needFloats += count;
2715
+ else if (t !== 6) return DECODE_FALLBACK;
2716
+ }
2717
+ if (
2718
+ count > 2_000_000 ||
2719
+ bi + needBigs > bigsLen ||
2720
+ bbi + needBools > boolsLen ||
2721
+ si + needStrs > strLensLen ||
2722
+ bli + needBins > binLensLen ||
2723
+ fli + needFloats > floatsLen
2724
+ ) {
2725
+ return DECODE_FALLBACK;
2726
+ }
2727
+ if (needBins > 0) {
2728
+ let totalBinBytes = 0;
2729
+ for (let i = 0; i < needBins; i += 1) totalBinBytes += binLens[bli + i];
2730
+ if (bo + totalBinBytes > binBytesLen) return DECODE_FALLBACK;
2731
+ }
2732
+ const reader = getColumnarTableReader(keys, colTypes);
2733
+ if (reader !== null) {
2734
+ COL_STATE[0] = bi;
2735
+ COL_STATE[1] = si;
2736
+ COL_STATE[2] = soff;
2737
+ COL_STATE[3] = bo;
2738
+ COL_STATE[4] = bli;
2739
+ COL_STATE[5] = fli;
2740
+ COL_STATE[6] = bbi;
2741
+ const out = reader(
2742
+ PklObject,
2743
+ sh.cls,
2744
+ sh.uri,
2745
+ count,
2746
+ bigs,
2747
+ bools,
2748
+ floats,
2749
+ strLens,
2750
+ bigStr,
2751
+ binBytes,
2752
+ binLens,
2753
+ COL_STATE,
2754
+ );
2755
+ bi = COL_STATE[0];
2756
+ si = COL_STATE[1];
2757
+ soff = COL_STATE[2];
2758
+ bo = COL_STATE[3];
2759
+ bli = COL_STATE[4];
2760
+ fli = COL_STATE[5];
2761
+ bbi = COL_STATE[6];
2762
+ if (soff > bigStrLen || bo > binBytesLen) return DECODE_FALLBACK;
2763
+ return out;
2764
+ }
2765
+ const out = new Array(count);
2766
+ for (let i = 0; i < count; i += 1) {
2767
+ const props = {};
2768
+ for (let c = 0; c < klen; c += 1) {
2769
+ const t = colTypes[c];
2770
+ let v;
2771
+ if (t === 1) v = bigs[bi++];
2772
+ else if (t === 2) v = bools[bbi++] !== 0;
2773
+ else if (t === 3) {
2774
+ const l = strLens[si++];
2775
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2776
+ v = bigStr.slice(soff, soff + l);
2777
+ soff += l;
2778
+ } else if (t === 4) {
2779
+ const bn = binLens[bli++];
2780
+ if (bo + bn > binBytesLen) return DECODE_FALLBACK;
2781
+ if (bn <= 16) {
2782
+ v = new Uint8Array(bn);
2783
+ for (let j = 0; j < bn; j += 1) v[j] = binBytes[bo + j];
2784
+ } else {
2785
+ v = binBytes.slice(bo, bo + bn);
2786
+ }
2787
+ bo += bn;
2788
+ } else if (t === 5) v = floats[fli++];
2789
+ else if (t === 6) v = null;
2790
+ else return DECODE_FALLBACK;
2791
+ const k = keys[c];
2792
+ if (k === "__proto__") {
2793
+ definePropSafe(props, k, v);
2794
+ } else {
2795
+ props[k] = v;
2796
+ }
2797
+ }
2798
+ out[i] = new PklObject(sh.cls, sh.uri, props);
2799
+ }
2800
+ return out;
2801
+ }
2802
+ if (tag === 13) {
2803
+ if (fli >= floatsLen || si >= strLensLen) return DECODE_FALLBACK;
2804
+ const val = floats[fli++];
2805
+ const l = strLens[si++];
2806
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2807
+ const unit = bigStr.slice(soff, soff + l);
2808
+ soff += l;
2809
+ return new PklDuration(val, unit);
2810
+ }
2811
+ if (tag === 14) {
2812
+ if (fli >= floatsLen || si >= strLensLen) return DECODE_FALLBACK;
2813
+ const val = floats[fli++];
2814
+ const l = strLens[si++];
2815
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2816
+ const unit = bigStr.slice(soff, soff + l);
2817
+ soff += l;
2818
+ return new PklDataSize(val, unit);
2819
+ }
2820
+ if (tag === 15) {
2821
+ const nextDepth = depth + 1;
2822
+ const first = readVal(nextDepth);
2823
+ if (first === DECODE_FALLBACK) return DECODE_FALLBACK;
2824
+ const second = readVal(nextDepth);
2825
+ if (second === DECODE_FALLBACK) return DECODE_FALLBACK;
2826
+ return new PklPair(first, second);
2827
+ }
2828
+ if (tag === 16) {
2829
+ if (si >= strLensLen) return DECODE_FALLBACK;
2830
+ const l = strLens[si++];
2831
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2832
+ const pat = bigStr.slice(soff, soff + l);
2833
+ soff += l;
2834
+ return new PklRegex(pat);
2835
+ }
2836
+ if (tag === 17) {
2837
+ if (bi + 3 > bigsLen) return DECODE_FALLBACK;
2838
+ const start = bigs[bi++];
2839
+ const end = bigs[bi++];
2840
+ const step = bigs[bi++];
2841
+ return new PklIntSeq(start, end, step);
2842
+ }
2843
+ if (tag === 18) {
2844
+ return new PklFunction();
2845
+ }
2846
+ return DECODE_FALLBACK;
2847
+ }
2848
+
2849
+ const root = readVal(0);
2850
+ if (root === DECODE_FALLBACK || op !== opsLen || soff > bigStrLen || bo > binBytesLen) {
2851
+ return DECODE_FALLBACK;
2852
+ }
2853
+ return root;
2854
+ }
2855
+
2856
+ function decodePklBinary(bytes, options = undefined) {
2857
+ if (!(bytes instanceof Uint8Array)) {
2858
+ throw new PklError("decodePklBinary expects a Uint8Array.", "invalid-argument");
2859
+ }
2860
+ const strict = Boolean(options?.strict);
2861
+ if (!strict) {
2862
+ const fast = tryDecodePklBinaryFast(bytes);
2863
+ if (fast !== DECODE_FALLBACK) {
2864
+ return fast;
2865
+ }
2866
+ }
2867
+ const raw = unwrapOutcome(
2868
+ native.productDecodePklBinary(
2869
+ new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength),
2870
+ strict,
2871
+ ),
2872
+ );
2873
+ return hydrateValue(raw);
2874
+ }
2875
+
2876
+ function monotonicClockMs() {
2877
+ return native.productMonotonicClockMs();
2878
+ }
2879
+
2880
+ const publicExports = {
2881
+ PKL_VERSION,
2882
+ capabilities,
2883
+ PklError,
2884
+ ModuleSource,
2885
+ PklDuration,
2886
+ PklDataSize,
2887
+ PklPair,
2888
+ PklRegex,
2889
+ PklObject,
2890
+ PklClass,
2891
+ PklTypeAlias,
2892
+ PklIntSeq,
2893
+ PklFunction,
2894
+ PklReference,
2895
+ Evaluator,
2896
+ Project,
2897
+ ReplSession,
2898
+ createEvaluator,
2899
+ createEvaluatorSync,
2900
+ createRepl,
2901
+ analyzeImportGraph,
2902
+ format,
2903
+ decodePklBinary,
2904
+ monotonicClockMs,
2905
+ };
2906
+
2907
+ Object.defineProperty(publicExports, Symbol.for("@openedges/pkl-napi/testing-internals"), {
2908
+ value: Object.freeze({
2909
+ native,
2910
+ unwrapOutcome,
2911
+ dehydrateValue,
2912
+ hydrateValue,
2913
+ }),
2914
+ enumerable: false,
2915
+ configurable: false,
2916
+ writable: false,
2917
+ });
2918
+
2919
+ module.exports = publicExports;