@openedges/pkl-napi 0.32.0-rc.3 → 0.32.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -52,11 +52,13 @@ function loadNativeAddon() {
52
52
 
53
53
  const native = loadNativeAddon();
54
54
 
55
- const PKL_VERSION = native.productPklVersion ? native.productPklVersion() : "0.32.0";
55
+ const PKL_VERSION = native.productPklVersion ? native.productPklVersion() : "0.32.1";
56
56
  const MAX_U64 = (1n << 64n) - 1n;
57
57
  const MIN_I64 = -(1n << 63n);
58
58
  const MAX_I64 = (1n << 63n) - 1n;
59
- const FAST_UTF8_DECODER = new TextDecoder("utf-8", { fatal: true });
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\-._~/$&'()*+,;=]*)$/;
60
62
  const VALID_DURATION_UNITS = new Set(["ns", "us", "ms", "s", "min", "h", "d"]);
61
63
  const VALID_DATA_SIZE_UNITS = new Set([
62
64
  "b", "kb", "mb", "gb", "tb", "pb", "kib", "mib", "gib", "tib", "pib",
@@ -161,14 +163,12 @@ class ModuleSource {
161
163
  "invalid-argument",
162
164
  );
163
165
  }
164
- let uri;
165
- if (modulePath.startsWith("modulepath:")) {
166
- uri = modulePath;
167
- } else if (modulePath.startsWith("/")) {
168
- uri = `modulepath:${modulePath}`;
169
- } else {
170
- uri = `modulepath:/${modulePath}`;
171
- }
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
172
  return new ModuleSource(uri, undefined);
173
173
  }
174
174
  }
@@ -177,7 +177,7 @@ function normalizeSource(source) {
177
177
  if (source instanceof ModuleSource) {
178
178
  return { uri: source.uri, contents: source.contents };
179
179
  }
180
- if (source && typeof source === "object" && typeof source.uri === "string") {
180
+ if (source && typeof source === "object" && typeof source.uri === "string" && source.uri.length > 0) {
181
181
  if (source.contents !== undefined && typeof source.contents !== "string") {
182
182
  throw new PklError("ModuleSource.contents must be a string.", "invalid-argument");
183
183
  }
@@ -213,13 +213,93 @@ class PklRegex {
213
213
  }
214
214
  }
215
215
 
216
+ const SYM_ENTRIES = Symbol("pklEntries");
217
+ const SYM_ELEMENTS = Symbol("pklElements");
218
+
216
219
  class PklObject {
217
- constructor(className, moduleUri, properties = {}, entries = new Map(), elements = []) {
220
+ constructor(className, moduleUri, properties = {}, entries = undefined, elements = undefined) {
218
221
  this.className = className;
219
222
  this.moduleUri = moduleUri;
220
223
  this.properties = properties;
221
- this.entries = entries instanceof Map ? entries : new Map(entries);
222
- this.elements = Array.isArray(elements) ? elements : Array.from(elements);
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;
223
303
  }
224
304
  }
225
305
 
@@ -239,9 +319,15 @@ class PklTypeAlias {
239
319
 
240
320
  class PklIntSeq {
241
321
  constructor(start, end, step) {
242
- this.start = BigInt(start);
243
- this.end = BigInt(end);
244
- this.step = BigInt(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;
245
331
  }
246
332
  }
247
333
 
@@ -251,7 +337,13 @@ class PklReference {
251
337
  constructor(domain, data, path = []) {
252
338
  this.domain = domain;
253
339
  this.data = data;
254
- this.path = Array.isArray(path) ? path : Array.from(path);
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
+ }
255
347
  }
256
348
  }
257
349
 
@@ -264,7 +356,13 @@ function definePropSafe(obj, key, value) {
264
356
  });
265
357
  }
266
358
 
267
- function hydrateValue(raw) {
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
+ }
268
366
  if (
269
367
  raw === null ||
270
368
  raw === undefined ||
@@ -278,22 +376,27 @@ function hydrateValue(raw) {
278
376
  if (raw instanceof Uint8Array) {
279
377
  return raw;
280
378
  }
379
+ const nextDepth = depth + 1;
281
380
  if (Array.isArray(raw)) {
282
- return raw.map(hydrateValue);
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;
283
386
  }
284
387
  if (typeof raw === "object" && typeof raw.__pklTag === "string") {
285
388
  switch (raw.__pklTag) {
286
389
  case "set": {
287
390
  const set = new Set();
288
391
  for (const item of raw.items) {
289
- set.add(hydrateValue(item));
392
+ set.add(hydrateValue(item, nextDepth));
290
393
  }
291
394
  return set;
292
395
  }
293
396
  case "map": {
294
397
  const map = new Map();
295
398
  for (const [k, v] of raw.entries) {
296
- map.set(hydrateValue(k), hydrateValue(v));
399
+ map.set(hydrateValue(k, nextDepth), hydrateValue(v, nextDepth));
297
400
  }
298
401
  return map;
299
402
  }
@@ -304,17 +407,17 @@ function hydrateValue(raw) {
304
407
  case "regex":
305
408
  return new PklRegex(raw.pattern);
306
409
  case "pair":
307
- return new PklPair(hydrateValue(raw.first), hydrateValue(raw.second));
410
+ return new PklPair(hydrateValue(raw.first, nextDepth), hydrateValue(raw.second, nextDepth));
308
411
  case "object": {
309
412
  const properties = {};
310
413
  for (const [k, v] of raw.properties) {
311
- definePropSafe(properties, k, hydrateValue(v));
414
+ definePropSafe(properties, k, hydrateValue(v, nextDepth));
312
415
  }
313
416
  const entries = new Map();
314
417
  for (const [k, v] of raw.entries) {
315
- entries.set(hydrateValue(k), hydrateValue(v));
418
+ entries.set(hydrateValue(k, nextDepth), hydrateValue(v, nextDepth));
316
419
  }
317
- const elements = raw.elements.map(hydrateValue);
420
+ const elements = raw.elements.map((item) => hydrateValue(item, nextDepth));
318
421
  return new PklObject(raw.className, raw.moduleUri, properties, entries, elements);
319
422
  }
320
423
  case "class":
@@ -327,9 +430,9 @@ function hydrateValue(raw) {
327
430
  return new PklFunction();
328
431
  case "reference":
329
432
  return new PklReference(
330
- hydrateValue(raw.domain),
331
- hydrateValue(raw.data),
332
- raw.path.map(hydrateValue),
433
+ hydrateValue(raw.domain, nextDepth),
434
+ hydrateValue(raw.data, nextDepth),
435
+ raw.path.map((item) => hydrateValue(item, nextDepth)),
333
436
  );
334
437
  default:
335
438
  throw new PklError(`Unknown Pkl tag: ${raw.__pklTag}`, "decode");
@@ -340,8 +443,9 @@ function hydrateValue(raw) {
340
443
 
341
444
  function hydrateSchema(schema) {
342
445
  if (!schema || typeof schema !== "object") return schema;
446
+ const hydrateAnnList = (list) => list.map((item) => hydrateValue(item, 0));
343
447
  if (Array.isArray(schema.annotations)) {
344
- schema.annotations = schema.annotations.map(hydrateValue);
448
+ schema.annotations = hydrateAnnList(schema.annotations);
345
449
  }
346
450
  if (schema.supermodule) {
347
451
  hydrateSchema(schema.supermodule);
@@ -349,14 +453,14 @@ function hydrateSchema(schema) {
349
453
  const hydrateClass = (cls) => {
350
454
  if (!cls) return;
351
455
  if (Array.isArray(cls.annotations)) {
352
- cls.annotations = cls.annotations.map(hydrateValue);
456
+ cls.annotations = hydrateAnnList(cls.annotations);
353
457
  }
354
458
  for (const mapName of ["properties", "allProperties", "methods", "allMethods"]) {
355
459
  const m = cls[mapName];
356
460
  if (m && typeof m === "object") {
357
461
  for (const member of Object.values(m)) {
358
462
  if (member && Array.isArray(member.annotations)) {
359
- member.annotations = member.annotations.map(hydrateValue);
463
+ member.annotations = hydrateAnnList(member.annotations);
360
464
  }
361
465
  }
362
466
  }
@@ -376,7 +480,7 @@ function hydrateSchema(schema) {
376
480
  if (m && typeof m === "object") {
377
481
  for (const alias of Object.values(m)) {
378
482
  if (alias && Array.isArray(alias.annotations)) {
379
- alias.annotations = alias.annotations.map(hydrateValue);
483
+ alias.annotations = hydrateAnnList(alias.annotations);
380
484
  }
381
485
  }
382
486
  }
@@ -384,7 +488,10 @@ function hydrateSchema(schema) {
384
488
  return schema;
385
489
  }
386
490
 
387
- function dehydrateValue(val) {
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
+ }
388
495
  if (val === null) return null;
389
496
  if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") {
390
497
  return val;
@@ -401,18 +508,6 @@ function dehydrateValue(val) {
401
508
  if (val instanceof Uint8Array) {
402
509
  return new Uint8Array(val.buffer, val.byteOffset, val.byteLength);
403
510
  }
404
- if (Array.isArray(val)) {
405
- return val.map(dehydrateValue);
406
- }
407
- if (val instanceof Set) {
408
- return { __pklTag: "set", items: Array.from(val, dehydrateValue) };
409
- }
410
- if (val instanceof Map) {
411
- return {
412
- __pklTag: "map",
413
- entries: Array.from(val.entries(), ([k, v]) => [dehydrateValue(k), dehydrateValue(v)]),
414
- };
415
- }
416
511
  if (val instanceof PklDuration) {
417
512
  return { __pklTag: "duration", value: val.value, unit: val.unit };
418
513
  }
@@ -422,29 +517,6 @@ function dehydrateValue(val) {
422
517
  if (val instanceof PklRegex) {
423
518
  return { __pklTag: "regex", pattern: val.pattern };
424
519
  }
425
- if (val instanceof PklPair) {
426
- return {
427
- __pklTag: "pair",
428
- first: dehydrateValue(val.first),
429
- second: dehydrateValue(val.second),
430
- };
431
- }
432
- if (val instanceof PklObject) {
433
- const properties = Object.entries(val.properties).map(([k, v]) => [k, dehydrateValue(v)]);
434
- const entries = Array.from(val.entries.entries(), ([k, v]) => [
435
- dehydrateValue(k),
436
- dehydrateValue(v),
437
- ]);
438
- const elements = val.elements.map(dehydrateValue);
439
- return {
440
- __pklTag: "object",
441
- className: val.className,
442
- moduleUri: val.moduleUri,
443
- properties,
444
- entries,
445
- elements,
446
- };
447
- }
448
520
  if (val instanceof PklClass) {
449
521
  return { __pklTag: "class", name: val.name, moduleUri: val.moduleUri };
450
522
  }
@@ -454,32 +526,104 @@ function dehydrateValue(val) {
454
526
  if (val instanceof PklIntSeq) {
455
527
  return {
456
528
  __pklTag: "intSeq",
457
- start: dehydrateValue(val.start),
458
- end: dehydrateValue(val.end),
459
- step: dehydrateValue(val.step),
529
+ start: dehydrateValue(val.start, depth + 1, seen),
530
+ end: dehydrateValue(val.end, depth + 1, seen),
531
+ step: dehydrateValue(val.step, depth + 1, seen),
460
532
  };
461
533
  }
462
534
  if (val instanceof PklFunction) {
463
535
  return { __pklTag: "function" };
464
536
  }
465
- if (val instanceof PklReference) {
466
- return {
467
- __pklTag: "reference",
468
- domain: dehydrateValue(val.domain),
469
- data: dehydrateValue(val.data),
470
- path: val.path.map(dehydrateValue),
471
- };
472
- }
473
537
  if (typeof val === "object") {
474
- const properties = Object.entries(val).map(([k, v]) => [k, dehydrateValue(v)]);
475
- return {
476
- __pklTag: "object",
477
- className: "Dynamic",
478
- moduleUri: "pkl:base",
479
- properties,
480
- entries: [],
481
- elements: [],
482
- };
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
+ }
483
627
  }
484
628
  throw new PklError(`Unsupported JS value type for Pkl conversion: ${typeof val}`, "invalid-argument");
485
629
  }
@@ -637,7 +781,11 @@ function buildNativeOptions(options = {}) {
637
781
  if (opts.noCache === true || opts.cacheDir === null) {
638
782
  nativeOpts.noCache = true;
639
783
  } else if (opts.cacheDir !== undefined) {
640
- nativeOpts.cacheDir = String(opts.cacheDir);
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;
641
789
  }
642
790
  if (opts.projectDir !== undefined && opts.projectDir !== null) {
643
791
  nativeOpts.projectDir = String(opts.projectDir);
@@ -718,27 +866,47 @@ function buildNativeOptions(options = {}) {
718
866
  nativeHttp.headers = entries;
719
867
  }
720
868
  if (http.testPort !== undefined && http.testPort !== null) {
721
- nativeHttp.testPort = Number(http.testPort);
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;
722
874
  }
723
875
  nativeOpts.http = nativeHttp;
724
876
  }
725
877
 
726
878
  if (opts.externalModuleReaders && typeof opts.externalModuleReaders === "object") {
727
879
  nativeOpts.externalModuleReaders = Object.entries(opts.externalModuleReaders).map(
728
- ([scheme, cfg]) => ({
729
- scheme: scheme.replace(/:$/, ""),
730
- executable: String(cfg.executable),
731
- arguments: Array.isArray(cfg.arguments) ? cfg.arguments.map(String) : [],
732
- }),
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
+ },
733
893
  );
734
894
  }
735
895
  if (opts.externalResourceReaders && typeof opts.externalResourceReaders === "object") {
736
896
  nativeOpts.externalResourceReaders = Object.entries(opts.externalResourceReaders).map(
737
- ([scheme, cfg]) => ({
738
- scheme: scheme.replace(/:$/, ""),
739
- executable: String(cfg.executable),
740
- arguments: Array.isArray(cfg.arguments) ? cfg.arguments.map(String) : [],
741
- }),
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
+ },
742
910
  );
743
911
  }
744
912
 
@@ -757,6 +925,7 @@ function buildNativeOptions(options = {}) {
757
925
  isLocal: Boolean(r.isLocal),
758
926
  isGlobbable: Boolean(r.isGlobbable),
759
927
  hasHierarchicalUris: Boolean(r.hasHierarchicalUris),
928
+ hasFragmentPaths: Boolean(r.hasFragmentPaths),
760
929
  isCached: r.isCached === undefined ? true : Boolean(r.isCached),
761
930
  hasHasElement: typeof r.hasElement === "function",
762
931
  hasListElements: typeof r.listElements === "function",
@@ -831,6 +1000,15 @@ function buildNativeOptions(options = {}) {
831
1000
  bridgeTarget = target;
832
1001
  };
833
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
+
834
1012
  const bridgeCallback = hasCallbacks
835
1013
  ? (req) => {
836
1014
  void (async () => {
@@ -844,16 +1022,32 @@ function buildNativeOptions(options = {}) {
844
1022
  moduleReaders,
845
1023
  resourceReaders,
846
1024
  });
847
- target.completeBridgeCallback(req.id, { ok: true, ...payload });
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
+ }
848
1038
  } catch (err) {
849
1039
  const isSecurity = err instanceof PklError && err.kind === "security";
850
1040
  const isIo = err instanceof PklError && err.kind === "io";
851
- const msg = err instanceof Error ? err.message : String(err);
852
- target.completeBridgeCallback(req.id, {
853
- ok: false,
854
- errorKind: isSecurity ? "security" : isIo ? "io" : "evaluation",
855
- errorMessage: msg,
856
- });
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
+ }
857
1051
  }
858
1052
  })();
859
1053
  }
@@ -886,15 +1080,15 @@ async function dispatchBridgeRequest(req, hooks) {
886
1080
  if (!transformed || typeof transformed !== "object") {
887
1081
  return {};
888
1082
  }
1083
+ const resolvedMemberName =
1084
+ transformed.memberName !== undefined ? transformed.memberName : frame.memberName;
889
1085
  return {
890
1086
  frame: {
891
1087
  moduleUri: String(transformed.moduleUri ?? frame.moduleUri),
892
1088
  memberName:
893
- transformed.memberName === undefined
894
- ? frame.memberName
895
- : transformed.memberName === null
896
- ? undefined
897
- : String(transformed.memberName),
1089
+ resolvedMemberName === null || resolvedMemberName === undefined
1090
+ ? undefined
1091
+ : String(resolvedMemberName),
898
1092
  sourceLines: Array.isArray(transformed.sourceLines)
899
1093
  ? transformed.sourceLines.map(String)
900
1094
  : frame.sourceLines,
@@ -930,6 +1124,9 @@ async function dispatchBridgeRequest(req, hooks) {
930
1124
  if (text === null || text === undefined) {
931
1125
  return { text: undefined };
932
1126
  }
1127
+ if (text instanceof Uint8Array) {
1128
+ return { text: FAST_UTF8_DECODER.decode(text) };
1129
+ }
933
1130
  return { text: String(text) };
934
1131
  }
935
1132
  case "moduleHasElement": {
@@ -1037,11 +1234,13 @@ class Project {
1037
1234
  }
1038
1235
 
1039
1236
  class Evaluator {
1040
- constructor(nativeEval, signal = undefined) {
1237
+ constructor(nativeEval, signal = undefined, clearBridge = null) {
1041
1238
  this._native = nativeEval;
1042
1239
  this._closed = false;
1043
1240
  this._closePromise = null;
1044
1241
  this._nextCallId = 1n;
1242
+ this._pendingFastContinue = 0;
1243
+ this._clearBridge = clearBridge;
1045
1244
  this._signal = signal || null;
1046
1245
  this._onAbort = null;
1047
1246
  if (this._signal && !this._signal.aborted) {
@@ -1067,6 +1266,10 @@ class Evaluator {
1067
1266
  return this._closePromise || Promise.resolve();
1068
1267
  }
1069
1268
  this._closed = true;
1269
+ if (this._clearBridge) {
1270
+ this._clearBridge();
1271
+ this._clearBridge = null;
1272
+ }
1070
1273
  if (this._signal && this._onAbort) {
1071
1274
  this._signal.removeEventListener("abort", this._onAbort);
1072
1275
  this._onAbort = null;
@@ -1080,6 +1283,26 @@ class Evaluator {
1080
1283
  return this._closePromise;
1081
1284
  }
1082
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
+
1083
1306
  async _runAsync(callOptions, invoke) {
1084
1307
  if (this.isClosed) {
1085
1308
  throw new PklError("Evaluator has been closed.", "closed");
@@ -1121,7 +1344,9 @@ class Evaluator {
1121
1344
  async evaluateOutputText(source, callOptions = undefined) {
1122
1345
  const { uri, contents } = normalizeSource(source);
1123
1346
  if (
1347
+ !(contents !== undefined && uri === "repl:text") &&
1124
1348
  !this.isClosed &&
1349
+ this._pendingFastContinue === 0 &&
1125
1350
  !this._signal?.aborted &&
1126
1351
  !callOptions?.signal &&
1127
1352
  callOptions?.timeoutMs === undefined
@@ -1129,9 +1354,7 @@ class Evaluator {
1129
1354
  const fast = this._native.tryEvaluateOutputTextFast(uri, contents);
1130
1355
  if (fast !== null && fast !== undefined) {
1131
1356
  if (fast.__continueAsync) {
1132
- return this._runAsync(callOptions, (t, id) =>
1133
- this._native.continuePendingFast(false, t, id),
1134
- );
1357
+ return this._continueFastAsync(false, callOptions);
1135
1358
  }
1136
1359
  return unwrapOutcome(fast);
1137
1360
  }
@@ -1201,7 +1424,9 @@ class Evaluator {
1201
1424
  throw new PklError("Expression must be a string.", "invalid-argument");
1202
1425
  }
1203
1426
  if (
1427
+ !(contents !== undefined && uri === "repl:text") &&
1204
1428
  !this.isClosed &&
1429
+ this._pendingFastContinue === 0 &&
1205
1430
  !this._signal?.aborted &&
1206
1431
  !callOptions?.signal &&
1207
1432
  callOptions?.timeoutMs === undefined
@@ -1209,9 +1434,7 @@ class Evaluator {
1209
1434
  const fast = this._native.tryEvaluateExpressionFast(uri, contents, expr);
1210
1435
  if (fast !== null && fast !== undefined) {
1211
1436
  if (fast.__continueAsync) {
1212
- return this._runAsync(callOptions, (t, id) =>
1213
- this._native.continuePendingFast(false, t, id),
1214
- );
1437
+ return this._continueFastAsync(false, callOptions);
1215
1438
  }
1216
1439
  return unwrapOutcome(fast);
1217
1440
  }
@@ -1237,7 +1460,9 @@ class Evaluator {
1237
1460
  throw new PklError("Expression must be a string.", "invalid-argument");
1238
1461
  }
1239
1462
  if (
1463
+ !(contents !== undefined && uri === "repl:text") &&
1240
1464
  !this.isClosed &&
1465
+ this._pendingFastContinue === 0 &&
1241
1466
  !this._signal?.aborted &&
1242
1467
  !callOptions?.signal &&
1243
1468
  callOptions?.timeoutMs === undefined
@@ -1254,9 +1479,7 @@ class Evaluator {
1254
1479
  const fast = this._native.tryEvaluateExpressionPklBinaryFast(uri, contents, expr);
1255
1480
  if (fast !== null && fast !== undefined) {
1256
1481
  if (fast.__continueAsync) {
1257
- const bytes = await this._runAsync(callOptions, (t, id) =>
1258
- this._native.continuePendingFast(true, t, id),
1259
- );
1482
+ const bytes = await this._continueFastAsync(true, callOptions);
1260
1483
  return decodePklBinary(bytes);
1261
1484
  }
1262
1485
  return decodePklBinary(unwrapOutcome(fast));
@@ -1279,7 +1502,9 @@ class Evaluator {
1279
1502
  throw new PklError("Expression must be a string.", "invalid-argument");
1280
1503
  }
1281
1504
  if (
1505
+ !(contents !== undefined && uri === "repl:text") &&
1282
1506
  !this.isClosed &&
1507
+ this._pendingFastContinue === 0 &&
1283
1508
  !this._signal?.aborted &&
1284
1509
  !callOptions?.signal &&
1285
1510
  callOptions?.timeoutMs === undefined
@@ -1287,12 +1512,10 @@ class Evaluator {
1287
1512
  const fast = this._native.tryEvaluateExpressionPklBinaryFast(uri, contents, expr);
1288
1513
  if (fast !== null && fast !== undefined) {
1289
1514
  if (fast.__continueAsync) {
1290
- return this._runAsync(callOptions, (t, id) =>
1291
- this._native.continuePendingFast(true, t, id),
1292
- );
1515
+ return this._continueFastAsync(true, callOptions);
1293
1516
  }
1294
1517
  const buf = unwrapOutcome(fast);
1295
- return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
1518
+ return new Uint8Array(buf);
1296
1519
  }
1297
1520
  }
1298
1521
  return this._runAsync(callOptions, (t, id) =>
@@ -1352,7 +1575,7 @@ function createEvaluatorSync(options = undefined) {
1352
1575
  native.NativeEvaluator.create(nativeOpts, nativeProject, bridgeCallback),
1353
1576
  );
1354
1577
  setBridgeTarget(nativeEval);
1355
- return new Evaluator(nativeEval, signal);
1578
+ return new Evaluator(nativeEval, signal, () => setBridgeTarget(null));
1356
1579
  }
1357
1580
 
1358
1581
  async function createEvaluator(options = undefined) {
@@ -1360,10 +1583,11 @@ async function createEvaluator(options = undefined) {
1360
1583
  }
1361
1584
 
1362
1585
  class ReplSession {
1363
- constructor(nativeRepl, signal = undefined) {
1586
+ constructor(nativeRepl, signal = undefined, clearBridge = null) {
1364
1587
  this._native = nativeRepl;
1365
1588
  this._closed = false;
1366
1589
  this._closePromise = null;
1590
+ this._clearBridge = clearBridge;
1367
1591
  this._signal = signal || null;
1368
1592
  this._onAbort = null;
1369
1593
  if (this._signal && !this._signal.aborted) {
@@ -1393,25 +1617,44 @@ class ReplSession {
1393
1617
  throw new PklError("ReplSession.eval input must be a string.", "invalid-argument");
1394
1618
  }
1395
1619
  const force = Boolean(options?.force);
1620
+ const evalDefinitions = Boolean(options?.evalDefinitions);
1396
1621
  const id = options?.id !== undefined ? String(options.id) : undefined;
1397
- return unwrapOutcome(await this._native.eval(input, force, id));
1622
+ return unwrapOutcome(await this._native.eval(input, force, evalDefinitions, id));
1398
1623
  }
1399
1624
 
1400
1625
  async load(uriOrSource, options = undefined) {
1401
1626
  this._checkOpen();
1402
1627
  let uri;
1628
+ let contents = undefined;
1403
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
+ }
1404
1636
  uri = uriOrSource;
1405
- } else if (uriOrSource && typeof uriOrSource === "object" && typeof uriOrSource.uri === "string") {
1637
+ } else if (
1638
+ uriOrSource &&
1639
+ typeof uriOrSource === "object" &&
1640
+ typeof uriOrSource.uri === "string" &&
1641
+ uriOrSource.uri.length > 0
1642
+ ) {
1406
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
+ }
1407
1650
  } else {
1408
1651
  throw new PklError(
1409
- "ReplSession.load requires a URI string or ModuleSource.",
1652
+ "ReplSession.load requires a non-empty URI string or ModuleSource.",
1410
1653
  "invalid-argument",
1411
1654
  );
1412
1655
  }
1413
1656
  const id = options?.id !== undefined ? String(options.id) : undefined;
1414
- return unwrapOutcome(await this._native.load(uri, id));
1657
+ return unwrapOutcome(await this._native.load(uri, contents, id));
1415
1658
  }
1416
1659
 
1417
1660
  async complete(prefix, options = undefined) {
@@ -1429,11 +1672,21 @@ class ReplSession {
1429
1672
  unwrapOutcome(await this._native.reset(id));
1430
1673
  }
1431
1674
 
1675
+ cancel() {
1676
+ if (!this._closed) {
1677
+ this._native.cancel();
1678
+ }
1679
+ }
1680
+
1432
1681
  close() {
1433
1682
  if (this._closed) {
1434
1683
  return this._closePromise || Promise.resolve();
1435
1684
  }
1436
1685
  this._closed = true;
1686
+ if (this._clearBridge) {
1687
+ this._clearBridge();
1688
+ this._clearBridge = null;
1689
+ }
1437
1690
  if (this._signal && this._onAbort) {
1438
1691
  this._signal.removeEventListener("abort", this._onAbort);
1439
1692
  this._onAbort = null;
@@ -1454,7 +1707,7 @@ async function createRepl(options = undefined) {
1454
1707
  native.NativeReplSession.create(nativeOpts, nativeProject, bridgeCallback),
1455
1708
  );
1456
1709
  setBridgeTarget(nativeRepl);
1457
- return new ReplSession(nativeRepl, signal);
1710
+ return new ReplSession(nativeRepl, signal, () => setBridgeTarget(null));
1458
1711
  }
1459
1712
 
1460
1713
  async function analyzeImportGraph(uris, options = undefined) {
@@ -1486,6 +1739,10 @@ async function analyzeImportGraph(uris, options = undefined) {
1486
1739
  try {
1487
1740
  return unwrapOutcome(await analyzer.importGraph(normalized));
1488
1741
  } finally {
1742
+ setBridgeTarget(null);
1743
+ if (typeof analyzer.close === "function") {
1744
+ analyzer.close();
1745
+ }
1489
1746
  if (signal && onAbort) {
1490
1747
  signal.removeEventListener("abort", onAbort);
1491
1748
  }
@@ -1497,13 +1754,18 @@ function format(source, options = undefined) {
1497
1754
  throw new PklError("format source must be a string.", "invalid-argument");
1498
1755
  }
1499
1756
  const grammarVersion = options?.grammarVersion;
1500
- if (grammarVersion !== undefined && grammarVersion !== 1 && grammarVersion !== 2) {
1757
+ if (
1758
+ grammarVersion !== undefined &&
1759
+ grammarVersion !== null &&
1760
+ grammarVersion !== 1 &&
1761
+ grammarVersion !== 2
1762
+ ) {
1501
1763
  throw new PklError(
1502
1764
  `Invalid grammarVersion "${grammarVersion}". Expected 1 or 2.`,
1503
1765
  "invalid-argument",
1504
1766
  );
1505
1767
  }
1506
- return unwrapOutcome(native.productFormat(source, grammarVersion));
1768
+ return unwrapOutcome(native.productFormat(source, grammarVersion ?? undefined));
1507
1769
  }
1508
1770
 
1509
1771
  const DECODE_STATE = new Int32Array(1);
@@ -1838,7 +2100,8 @@ function fastDecodeVal(bytes, view, len, depth) {
1838
2100
  if (
1839
2101
  className === DECODE_FALLBACK ||
1840
2102
  className.length === 0 ||
1841
- (className.charCodeAt(0) <= 0x20 && BLANK_OR_CTRL_RE.test(className))
2103
+ ((className.charCodeAt(0) <= 0x20 || className.charCodeAt(0) >= 0x80) &&
2104
+ BLANK_OR_CTRL_RE.test(className))
1842
2105
  ) {
1843
2106
  return DECODE_FALLBACK;
1844
2107
  }
@@ -1847,14 +2110,14 @@ function fastDecodeVal(bytes, view, len, depth) {
1847
2110
  if (
1848
2111
  moduleUri === DECODE_FALLBACK ||
1849
2112
  moduleUri.length === 0 ||
1850
- (moduleUri.charCodeAt(0) <= 0x20 && BLANK_OR_CTRL_RE.test(moduleUri))
2113
+ (moduleUri !== "pkl:base" && !FAST_MODULE_URI_RE.test(moduleUri))
1851
2114
  ) {
1852
2115
  return DECODE_FALLBACK;
1853
2116
  }
1854
2117
  pos = DECODE_STATE[0];
1855
2118
  const mcount = fastReadArrayLen(bytes, view, len, pos);
1856
- if (mcount < 0) return DECODE_FALLBACK;
1857
2119
  pos = DECODE_STATE[0];
2120
+ if (mcount < 0 || mcount * 3 > len - pos) return DECODE_FALLBACK;
1858
2121
  const props = {};
1859
2122
  const entries = new Map();
1860
2123
  const elements = [];
@@ -1956,7 +2219,7 @@ function fastDecodeVal(bytes, view, len, depth) {
1956
2219
  if (code === 0x04 || code === 0x05) {
1957
2220
  if (alen !== 2) return DECODE_FALLBACK;
1958
2221
  const count = fastReadArrayLen(bytes, view, len, pos);
1959
- if (count < 0) return DECODE_FALLBACK;
2222
+ if (count < 0 || count > len - DECODE_STATE[0]) return DECODE_FALLBACK;
1960
2223
  const out = new Array(count);
1961
2224
  const nextDepth = depth + 1;
1962
2225
  for (let i = 0; i < count; i += 1) {
@@ -1970,7 +2233,7 @@ function fastDecodeVal(bytes, view, len, depth) {
1970
2233
  if (code === 0x02 || code === 0x03) {
1971
2234
  if (alen !== 2) return DECODE_FALLBACK;
1972
2235
  const count = fastReadMapLen(bytes, view, len, pos);
1973
- if (count < 0) return DECODE_FALLBACK;
2236
+ if (count < 0 || count * 2 > len - DECODE_STATE[0]) return DECODE_FALLBACK;
1974
2237
  const out = new Map();
1975
2238
  const nextDepth = depth + 1;
1976
2239
  for (let i = 0; i < count; i += 1) {
@@ -1986,7 +2249,7 @@ function fastDecodeVal(bytes, view, len, depth) {
1986
2249
  if (code === 0x06) {
1987
2250
  if (alen !== 2) return DECODE_FALLBACK;
1988
2251
  const count = fastReadArrayLen(bytes, view, len, pos);
1989
- if (count < 0) return DECODE_FALLBACK;
2252
+ if (count < 0 || count > len - DECODE_STATE[0]) return DECODE_FALLBACK;
1990
2253
  const out = new Set();
1991
2254
  const nextDepth = depth + 1;
1992
2255
  for (let i = 0; i < count; i += 1) {
@@ -2081,19 +2344,29 @@ function tryDecodePklBinaryFast(bytes) {
2081
2344
  }
2082
2345
 
2083
2346
  const COLUMNAR_MAGIC = 0x504b4c01;
2347
+ const MAX_COLUMNAR_DEPTH = 64;
2084
2348
  const IS_LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
2085
2349
  let canUseNewFunction = true;
2086
2350
  const SHAPE_PROPS_FACTORIES = new Map();
2087
2351
  const COLUMNAR_TABLE_READERS = new Map();
2088
2352
  let columnarAlignBuf = null;
2089
- const COL_STATE = new Int32Array(7);
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
+ }
2090
2363
 
2091
2364
  function getShapePropsFactory(keys) {
2092
2365
  if (!canUseNewFunction || keys.length === 0 || keys.length > 32) return null;
2093
2366
  for (let i = 0; i < keys.length; i += 1) {
2094
2367
  if (keys[i] === "__proto__") return null;
2095
2368
  }
2096
- const sig = keys.join("\0");
2369
+ const sig = JSON.stringify(keys);
2097
2370
  let fn = SHAPE_PROPS_FACTORIES.get(sig);
2098
2371
  if (fn !== undefined) return fn;
2099
2372
  try {
@@ -2117,7 +2390,7 @@ function getColumnarTableReader(keys, colTypes) {
2117
2390
  for (let i = 0; i < keys.length; i += 1) {
2118
2391
  if (keys[i] === "__proto__") return null;
2119
2392
  }
2120
- const sig = `${keys.join("\0")}|${colTypes.join(",")}`;
2393
+ const sig = `${JSON.stringify(keys)}|${colTypes.join(",")}`;
2121
2394
  let fn = COLUMNAR_TABLE_READERS.get(sig);
2122
2395
  if (fn !== undefined) return fn;
2123
2396
  try {
@@ -2153,7 +2426,7 @@ function getColumnarTableReader(keys, colTypes) {
2153
2426
  }
2154
2427
  }
2155
2428
  lines.push(
2156
- ` out[i] = new PklObject(cls, uri, {${propExprs.join(",")}}, new Map(), []);`,
2429
+ ` out[i] = new PklObject(cls, uri, {${propExprs.join(",")}});`,
2157
2430
  );
2158
2431
  lines.push("}");
2159
2432
  lines.push(
@@ -2198,12 +2471,32 @@ function unpackColumnarBuffer(bytes) {
2198
2471
  src = columnarAlignBuf.subarray(0, need);
2199
2472
  alignedCopyOversized = columnarAlignBuf.byteLength > 262144;
2200
2473
  }
2201
- const ab = src.buffer;
2202
- const base = src.byteOffset;
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) {
2203
2484
  const header = new Uint32Array(ab, base, 20);
2204
2485
  if (header[0] !== COLUMNAR_MAGIC) {
2205
2486
  return DECODE_FALLBACK;
2206
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
+ }
2207
2500
  const ops = new Int32Array(ab, base + header[1], header[2]);
2208
2501
  const bigs = new BigInt64Array(ab, base + header[3], header[4]);
2209
2502
  const floats = new Float64Array(ab, base + header[5], header[6]);
@@ -2215,6 +2508,10 @@ function unpackColumnarBuffer(bytes) {
2215
2508
  const shapeCount = header[17];
2216
2509
  const shapeStrCount = header[18];
2217
2510
 
2511
+ if (shapeStrCount > strLens.length || shapeCount * 3 > ops.length) {
2512
+ return DECODE_FALLBACK;
2513
+ }
2514
+
2218
2515
  let bigStr;
2219
2516
  if (strUtf8.byteLength === 0) {
2220
2517
  bigStr = "";
@@ -2227,22 +2524,40 @@ function unpackColumnarBuffer(bytes) {
2227
2524
  }
2228
2525
 
2229
2526
  let soff = 0;
2527
+ const bigStrLen = bigStr.length;
2230
2528
  const shapeStrs = new Array(shapeStrCount);
2231
2529
  for (let i = 0; i < shapeStrCount; i += 1) {
2232
2530
  const l = strLens[i];
2531
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2233
2532
  shapeStrs[i] = bigStr.slice(soff, soff + l);
2234
2533
  soff += l;
2235
2534
  }
2236
2535
 
2237
2536
  let op = 0;
2537
+ const opsLen = ops.length;
2238
2538
  const shapes = new Array(shapeCount);
2239
2539
  for (let s = 0; s < shapeCount; s += 1) {
2240
- const cls = shapeStrs[ops[op++]];
2241
- const uri = shapeStrs[ops[op++]];
2540
+ if (op + 3 > opsLen) return DECODE_FALLBACK;
2541
+ const clsIdx = ops[op++];
2542
+ const uriIdx = ops[op++];
2242
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];
2243
2556
  const keys = new Array(klen);
2244
2557
  for (let k = 0; k < klen; k += 1) {
2245
- keys[k] = shapeStrs[ops[op++]];
2558
+ const keyIdx = ops[op++];
2559
+ if (keyIdx < 0 || keyIdx >= shapeStrCount) return DECODE_FALLBACK;
2560
+ keys[k] = shapeStrs[keyIdx];
2246
2561
  }
2247
2562
  shapes[s] = { cls, uri, keys, fn: getShapePropsFactory(keys) };
2248
2563
  }
@@ -2253,22 +2568,40 @@ function unpackColumnarBuffer(bytes) {
2253
2568
  let si = shapeStrCount;
2254
2569
  let bli = 0;
2255
2570
  let bo = 0;
2256
-
2257
- function readVal() {
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;
2258
2581
  const tag = ops[op++];
2259
2582
  if (tag === 0) return null;
2260
- if (tag === 1) return bigs[bi++];
2261
- if (tag === 2) return floats[fli++];
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
+ }
2262
2591
  if (tag === 3) return false;
2263
2592
  if (tag === 4) return true;
2264
2593
  if (tag === 5) {
2594
+ if (si >= strLensLen) return DECODE_FALLBACK;
2265
2595
  const l = strLens[si++];
2596
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2266
2597
  const s = bigStr.slice(soff, soff + l);
2267
2598
  soff += l;
2268
2599
  return s;
2269
2600
  }
2270
2601
  if (tag === 6) {
2602
+ if (bli >= binLensLen) return DECODE_FALLBACK;
2271
2603
  const n = binLens[bli++];
2604
+ if (bo + n > binBytesLen) return DECODE_FALLBACK;
2272
2605
  let owned;
2273
2606
  if (n <= 16) {
2274
2607
  owned = new Uint8Array(n);
@@ -2280,26 +2613,33 @@ function unpackColumnarBuffer(bytes) {
2280
2613
  return owned;
2281
2614
  }
2282
2615
  if (tag === 7) {
2616
+ if (op >= opsLen) return DECODE_FALLBACK;
2283
2617
  const n = ops[op++];
2618
+ if (n < 0 || n > opsLen - op) return DECODE_FALLBACK;
2284
2619
  const arr = new Array(n);
2620
+ const nextDepth = depth + 1;
2285
2621
  for (let i = 0; i < n; i += 1) {
2286
- const item = readVal();
2622
+ const item = readVal(nextDepth);
2287
2623
  if (item === DECODE_FALLBACK) return DECODE_FALLBACK;
2288
2624
  arr[i] = item;
2289
2625
  }
2290
2626
  return arr;
2291
2627
  }
2292
2628
  if (tag === 10) {
2293
- const sh = shapes[ops[op++]];
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];
2294
2633
  const keys = sh.keys;
2295
2634
  const klen = keys.length;
2635
+ const nextDepth = depth + 1;
2296
2636
  let props;
2297
2637
  if (sh.fn !== null) {
2298
2638
  if (klen === 4) {
2299
- const a0 = readVal();
2300
- const a1 = readVal();
2301
- const a2 = readVal();
2302
- const a3 = readVal();
2639
+ const a0 = readVal(nextDepth);
2640
+ const a1 = readVal(nextDepth);
2641
+ const a2 = readVal(nextDepth);
2642
+ const a3 = readVal(nextDepth);
2303
2643
  if (
2304
2644
  a0 === DECODE_FALLBACK ||
2305
2645
  a1 === DECODE_FALLBACK ||
@@ -2310,11 +2650,11 @@ function unpackColumnarBuffer(bytes) {
2310
2650
  }
2311
2651
  props = sh.fn(a0, a1, a2, a3);
2312
2652
  } else if (klen === 5) {
2313
- const a0 = readVal();
2314
- const a1 = readVal();
2315
- const a2 = readVal();
2316
- const a3 = readVal();
2317
- const a4 = readVal();
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);
2318
2658
  if (
2319
2659
  a0 === DECODE_FALLBACK ||
2320
2660
  a1 === DECODE_FALLBACK ||
@@ -2328,7 +2668,7 @@ function unpackColumnarBuffer(bytes) {
2328
2668
  } else {
2329
2669
  const vals = new Array(klen);
2330
2670
  for (let i = 0; i < klen; i += 1) {
2331
- const v = readVal();
2671
+ const v = readVal(nextDepth);
2332
2672
  if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2333
2673
  vals[i] = v;
2334
2674
  }
@@ -2337,7 +2677,7 @@ function unpackColumnarBuffer(bytes) {
2337
2677
  } else {
2338
2678
  props = {};
2339
2679
  for (let i = 0; i < klen; i += 1) {
2340
- const v = readVal();
2680
+ const v = readVal(nextDepth);
2341
2681
  if (v === DECODE_FALLBACK) return DECODE_FALLBACK;
2342
2682
  const k = keys[i];
2343
2683
  if (k === "__proto__") {
@@ -2347,15 +2687,48 @@ function unpackColumnarBuffer(bytes) {
2347
2687
  }
2348
2688
  }
2349
2689
  }
2350
- return new PklObject(sh.cls, sh.uri, props, new Map(), []);
2690
+ return new PklObject(sh.cls, sh.uri, props);
2351
2691
  }
2352
2692
  if (tag === 12) {
2353
- const sh = shapes[ops[op++]];
2693
+ if (op + 2 > opsLen) return DECODE_FALLBACK;
2694
+ const shIdx = ops[op++];
2354
2695
  const count = ops[op++];
2696
+ if (shIdx < 0 || shIdx >= shapesLen || count < 0) return DECODE_FALLBACK;
2697
+ const sh = shapes[shIdx];
2355
2698
  const keys = sh.keys;
2356
2699
  const klen = keys.length;
2700
+ if (op + klen > opsLen) return DECODE_FALLBACK;
2357
2701
  const colTypes = new Array(klen);
2358
- for (let c = 0; c < klen; c += 1) colTypes[c] = ops[op++];
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
+ }
2359
2732
  const reader = getColumnarTableReader(keys, colTypes);
2360
2733
  if (reader !== null) {
2361
2734
  COL_STATE[0] = bi;
@@ -2386,6 +2759,7 @@ function unpackColumnarBuffer(bytes) {
2386
2759
  bli = COL_STATE[4];
2387
2760
  fli = COL_STATE[5];
2388
2761
  bbi = COL_STATE[6];
2762
+ if (soff > bigStrLen || bo > binBytesLen) return DECODE_FALLBACK;
2389
2763
  return out;
2390
2764
  }
2391
2765
  const out = new Array(count);
@@ -2398,10 +2772,12 @@ function unpackColumnarBuffer(bytes) {
2398
2772
  else if (t === 2) v = bools[bbi++] !== 0;
2399
2773
  else if (t === 3) {
2400
2774
  const l = strLens[si++];
2775
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2401
2776
  v = bigStr.slice(soff, soff + l);
2402
2777
  soff += l;
2403
2778
  } else if (t === 4) {
2404
2779
  const bn = binLens[bli++];
2780
+ if (bo + bn > binBytesLen) return DECODE_FALLBACK;
2405
2781
  if (bn <= 16) {
2406
2782
  v = new Uint8Array(bn);
2407
2783
  for (let j = 0; j < bn; j += 1) v[j] = binBytes[bo + j];
@@ -2419,38 +2795,46 @@ function unpackColumnarBuffer(bytes) {
2419
2795
  props[k] = v;
2420
2796
  }
2421
2797
  }
2422
- out[i] = new PklObject(sh.cls, sh.uri, props, new Map(), []);
2798
+ out[i] = new PklObject(sh.cls, sh.uri, props);
2423
2799
  }
2424
2800
  return out;
2425
2801
  }
2426
2802
  if (tag === 13) {
2803
+ if (fli >= floatsLen || si >= strLensLen) return DECODE_FALLBACK;
2427
2804
  const val = floats[fli++];
2428
2805
  const l = strLens[si++];
2806
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2429
2807
  const unit = bigStr.slice(soff, soff + l);
2430
2808
  soff += l;
2431
2809
  return new PklDuration(val, unit);
2432
2810
  }
2433
2811
  if (tag === 14) {
2812
+ if (fli >= floatsLen || si >= strLensLen) return DECODE_FALLBACK;
2434
2813
  const val = floats[fli++];
2435
2814
  const l = strLens[si++];
2815
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2436
2816
  const unit = bigStr.slice(soff, soff + l);
2437
2817
  soff += l;
2438
2818
  return new PklDataSize(val, unit);
2439
2819
  }
2440
2820
  if (tag === 15) {
2441
- const first = readVal();
2821
+ const nextDepth = depth + 1;
2822
+ const first = readVal(nextDepth);
2442
2823
  if (first === DECODE_FALLBACK) return DECODE_FALLBACK;
2443
- const second = readVal();
2824
+ const second = readVal(nextDepth);
2444
2825
  if (second === DECODE_FALLBACK) return DECODE_FALLBACK;
2445
2826
  return new PklPair(first, second);
2446
2827
  }
2447
2828
  if (tag === 16) {
2829
+ if (si >= strLensLen) return DECODE_FALLBACK;
2448
2830
  const l = strLens[si++];
2831
+ if (soff + l > bigStrLen) return DECODE_FALLBACK;
2449
2832
  const pat = bigStr.slice(soff, soff + l);
2450
2833
  soff += l;
2451
2834
  return new PklRegex(pat);
2452
2835
  }
2453
2836
  if (tag === 17) {
2837
+ if (bi + 3 > bigsLen) return DECODE_FALLBACK;
2454
2838
  const start = bigs[bi++];
2455
2839
  const end = bigs[bi++];
2456
2840
  const step = bigs[bi++];
@@ -2462,26 +2846,29 @@ function unpackColumnarBuffer(bytes) {
2462
2846
  return DECODE_FALLBACK;
2463
2847
  }
2464
2848
 
2465
- const root = readVal();
2466
- if (alignedCopyOversized) {
2467
- columnarAlignBuf = null;
2468
- }
2469
- if (root === DECODE_FALLBACK || op !== ops.length) {
2849
+ const root = readVal(0);
2850
+ if (root === DECODE_FALLBACK || op !== opsLen || soff > bigStrLen || bo > binBytesLen) {
2470
2851
  return DECODE_FALLBACK;
2471
2852
  }
2472
2853
  return root;
2473
2854
  }
2474
2855
 
2475
- function decodePklBinary(bytes) {
2856
+ function decodePklBinary(bytes, options = undefined) {
2476
2857
  if (!(bytes instanceof Uint8Array)) {
2477
2858
  throw new PklError("decodePklBinary expects a Uint8Array.", "invalid-argument");
2478
2859
  }
2479
- const fast = tryDecodePklBinaryFast(bytes);
2480
- if (fast !== DECODE_FALLBACK) {
2481
- return fast;
2860
+ const strict = Boolean(options?.strict);
2861
+ if (!strict) {
2862
+ const fast = tryDecodePklBinaryFast(bytes);
2863
+ if (fast !== DECODE_FALLBACK) {
2864
+ return fast;
2865
+ }
2482
2866
  }
2483
2867
  const raw = unwrapOutcome(
2484
- native.productDecodePklBinary(new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength)),
2868
+ native.productDecodePklBinary(
2869
+ new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength),
2870
+ strict,
2871
+ ),
2485
2872
  );
2486
2873
  return hydrateValue(raw);
2487
2874
  }
@@ -2490,90 +2877,7 @@ function monotonicClockMs() {
2490
2877
  return native.productMonotonicClockMs();
2491
2878
  }
2492
2879
 
2493
- function roundtripValue(val) {
2494
- const dehydrated = dehydrateValue(val);
2495
- const raw = unwrapOutcome(native.productRoundtripValue(dehydrated));
2496
- return hydrateValue(raw);
2497
- }
2498
-
2499
- function roundtripInteger(val) {
2500
- if (typeof val !== "bigint") {
2501
- throw new PklError("roundtripInteger expects a BigInt.", "invalid-argument");
2502
- }
2503
- return unwrapOutcome(native.productRoundtripInteger(val));
2504
- }
2505
-
2506
- function roundtripBytes(val) {
2507
- if (!(val instanceof Uint8Array)) {
2508
- throw new PklError("roundtripBytes expects a Uint8Array.", "invalid-argument");
2509
- }
2510
- return native.roundtripBytes(new Uint8Array(val.buffer, val.byteOffset, val.byteLength));
2511
- }
2512
-
2513
- function roundtripString(val) {
2514
- if (typeof val !== "string") {
2515
- throw new PklError("roundtripString expects a string.", "invalid-argument");
2516
- }
2517
- return native.roundtripString(val);
2518
- }
2519
-
2520
- function defaultBenchmarkPayload() {
2521
- return new PklObject(
2522
- "Bench#Payload",
2523
- "repl:bench",
2524
- {
2525
- intMin: MIN_I64,
2526
- intMax: MAX_I64,
2527
- floatVal: 3.141592653589793,
2528
- text: "hello-pkl-🚀-utf16",
2529
- bytes: new Uint8Array([0, 1, 2, 127, 128, 255]),
2530
- duration: new PklDuration(5, "s"),
2531
- dataSize: new PklDataSize(16, "mib"),
2532
- pair: new PklPair("left", 42n),
2533
- list: [1n, 2n, 3n, true, null],
2534
- set: new Set(["a", "b", "c"]),
2535
- map: new Map([
2536
- ["k1", 100n],
2537
- ["k2", "v2"],
2538
- ]),
2539
- },
2540
- new Map(),
2541
- [],
2542
- );
2543
- }
2544
-
2545
- function measureConversion(valOrIterations = 1000, maybeIterations = undefined) {
2546
- let value;
2547
- let iterations;
2548
- if (typeof valOrIterations === "number" && maybeIterations === undefined) {
2549
- value = defaultBenchmarkPayload();
2550
- iterations = valOrIterations;
2551
- } else {
2552
- value = valOrIterations;
2553
- iterations = maybeIterations === undefined ? 1000 : maybeIterations;
2554
- }
2555
- if (!Number.isInteger(iterations) || iterations < 1 || iterations > 1_000_000) {
2556
- throw new PklError(
2557
- `iterations must be an integer between 1 and 1000000, got ${iterations}.`,
2558
- "invalid-argument",
2559
- );
2560
- }
2561
- const dehydrated = dehydrateValue(value);
2562
- const startNs = process.hrtime.bigint();
2563
- const nativeStats = unwrapOutcome(native.productMeasureConversion(dehydrated, iterations));
2564
- const hydrated = hydrateValue(nativeStats.lastValue);
2565
- const totalElapsedMs = Number(process.hrtime.bigint() - startNs) / 1e6;
2566
- return {
2567
- iterations: nativeStats.iterations,
2568
- elapsedMs: totalElapsedMs,
2569
- nativeElapsedMs: nativeStats.elapsedMs,
2570
- perIterationUs: (totalElapsedMs * 1000) / nativeStats.iterations,
2571
- nativePerIterationUs: nativeStats.perIterationUs,
2572
- lastValue: hydrated,
2573
- };
2574
- }
2575
-
2576
- module.exports = {
2880
+ const publicExports = {
2577
2881
  PKL_VERSION,
2578
2882
  capabilities,
2579
2883
  PklError,
@@ -2598,9 +2902,18 @@ module.exports = {
2598
2902
  format,
2599
2903
  decodePklBinary,
2600
2904
  monotonicClockMs,
2601
- roundtripValue,
2602
- roundtripInteger,
2603
- roundtripBytes,
2604
- roundtripString,
2605
- measureConversion,
2606
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;