capnweb 0.0.0-667958e → 0.0.0-66ed2fd

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.
@@ -1,5 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
-
3
2
  //#region src/symbols.ts
4
3
  let WORKERS_MODULE_SYMBOL = Symbol("workers-module");
5
4
 
@@ -42,6 +41,9 @@ function typeForRpc(value) {
42
41
  case AsyncFunction.prototype: return "function";
43
42
  case Array.prototype: return "array";
44
43
  case Date.prototype: return "date";
44
+ case RegExp.prototype: return "regexp";
45
+ case Set.prototype: return "set";
46
+ case Map.prototype: return "map";
45
47
  case Uint8Array.prototype:
46
48
  case BUFFER_PROTOTYPE:
47
49
  case ArrayBuffer.prototype:
@@ -92,7 +94,14 @@ let streamImpl = {
92
94
  };
93
95
  var StubHook = class {
94
96
  stream(path, args) {
95
- let pulled = this.call(path, args).pull();
97
+ let hook = this.call(path, args);
98
+ let pulled;
99
+ try {
100
+ pulled = hook.pull();
101
+ } catch (err) {
102
+ hook.dispose();
103
+ throw err;
104
+ }
96
105
  let promise;
97
106
  if (pulled instanceof Promise) promise = pulled.then((p) => {
98
107
  p.dispose();
@@ -111,9 +120,11 @@ var ErrorStubHook = class extends StubHook {
111
120
  this.error = error;
112
121
  }
113
122
  call(path, args) {
123
+ args.dispose();
114
124
  return this;
115
125
  }
116
126
  map(path, captures, instructions) {
127
+ for (let cap of captures) cap.dispose();
117
128
  return this;
118
129
  }
119
130
  get(path) {
@@ -237,7 +248,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
237
248
  };
238
249
  var RpcPromise$1 = class extends RpcStub$1 {
239
250
  constructor(hook, pathIfPromise) {
240
- super(hook, pathIfPromise);
251
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
252
+ else {
253
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
254
+ let kind = typeForRpc(hook);
255
+ if (kind === "rpc-promise") {
256
+ let raw = unwrapStubAndPath(hook);
257
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
258
+ else {
259
+ let adopted = raw.hook;
260
+ raw.hook = DISPOSED_HOOK;
261
+ super(adopted, []);
262
+ }
263
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
264
+ else {
265
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
266
+ promiseHook.ignoreUnhandledRejections();
267
+ super(promiseHook, []);
268
+ }
269
+ }
241
270
  }
242
271
  then(onfulfilled, onrejected) {
243
272
  return pullPromise(this).then(...arguments);
@@ -278,6 +307,9 @@ async function pullPromise(promise) {
278
307
  if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);
279
308
  return (await hook.pull()).deliverResolve();
280
309
  }
310
+ function mapKeyToPropertyName(key) {
311
+ return typeof key === "string" || typeof key === "number" ? key : { mapKey: key };
312
+ }
281
313
  var RpcPayload = class RpcPayload {
282
314
  value;
283
315
  source;
@@ -332,12 +364,13 @@ var RpcPayload = class RpcPayload {
332
364
  return TargetStubHook.create(target, parent);
333
365
  } else if (this.source === "return") {
334
366
  let hook = this.rpcTargets?.get(target);
335
- if (hook) if (dupStubs) return hook.dup();
336
- else {
337
- this.rpcTargets?.delete(target);
338
- return hook;
339
- }
340
- else {
367
+ if (hook) {
368
+ if (dupStubs) return hook.dup();
369
+ else {
370
+ this.rpcTargets?.delete(target);
371
+ return hook;
372
+ }
373
+ } else {
341
374
  hook = TargetStubHook.create(target, parent);
342
375
  if (dupStubs) {
343
376
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -351,12 +384,13 @@ var RpcPayload = class RpcPayload {
351
384
  if (this.source === "params") return streamImpl.createWritableStreamHook(stream);
352
385
  else if (this.source === "return") {
353
386
  let hook = this.rpcTargets?.get(stream);
354
- if (hook) if (dupStubs) return hook.dup();
355
- else {
356
- this.rpcTargets?.delete(stream);
357
- return hook;
358
- }
359
- else {
387
+ if (hook) {
388
+ if (dupStubs) return hook.dup();
389
+ else {
390
+ this.rpcTargets?.delete(stream);
391
+ return hook;
392
+ }
393
+ } else {
360
394
  hook = streamImpl.createWritableStreamHook(stream);
361
395
  if (dupStubs) {
362
396
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -370,12 +404,13 @@ var RpcPayload = class RpcPayload {
370
404
  if (this.source === "params") return streamImpl.createReadableStreamHook(stream);
371
405
  else if (this.source === "return") {
372
406
  let hook = this.rpcTargets?.get(stream);
373
- if (hook) if (dupStubs) return hook.dup();
374
- else {
375
- this.rpcTargets?.delete(stream);
376
- return hook;
377
- }
378
- else {
407
+ if (hook) {
408
+ if (dupStubs) return hook.dup();
409
+ else {
410
+ this.rpcTargets?.delete(stream);
411
+ return hook;
412
+ }
413
+ } else {
379
414
  hook = streamImpl.createReadableStreamHook(stream);
380
415
  if (dupStubs) {
381
416
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -383,7 +418,7 @@ var RpcPayload = class RpcPayload {
383
418
  return hook.dup();
384
419
  } else return hook;
385
420
  }
386
- } else throw new Error("owned payload shouldn't contain raw ReadableStreams");
421
+ } else return streamImpl.createReadableStreamHook(stream);
387
422
  }
388
423
  deepCopy(value, oldParent, property, parent, dupStubs, owner) {
389
424
  switch (typeForRpc(value)) {
@@ -394,6 +429,7 @@ var RpcPayload = class RpcPayload {
394
429
  case "bytes":
395
430
  case "blob":
396
431
  case "url":
432
+ case "regexp":
397
433
  case "error":
398
434
  case "undefined": return value;
399
435
  case "array": {
@@ -403,6 +439,35 @@ var RpcPayload = class RpcPayload {
403
439
  for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
404
440
  return result;
405
441
  }
442
+ case "set": {
443
+ let set = value;
444
+ let elements = [...set];
445
+ for (let val of elements) {
446
+ let kind = typeForRpc(val);
447
+ if (kind === "rpc-promise" || kind === "rpc-thenable") throw new TypeError("Cannot pass a promise as an element of a Set. Await the value before adding it to the Set.");
448
+ }
449
+ let result = /* @__PURE__ */ new Set();
450
+ let index = 0;
451
+ for (let val of elements) {
452
+ let copy = this.deepCopy(val, set, index++, result, dupStubs, owner);
453
+ result.add(copy);
454
+ }
455
+ return result;
456
+ }
457
+ case "map": {
458
+ let map = value;
459
+ let entries = [...map];
460
+ for (let [key] of entries) {
461
+ let kind = typeForRpc(key);
462
+ if (kind === "rpc-promise" || kind === "rpc-thenable") throw new TypeError("Cannot pass a promise as a key of a Map. Await the value before using it as a key.");
463
+ }
464
+ let result = /* @__PURE__ */ new Map();
465
+ for (let [key, val] of entries) {
466
+ let keyCopy = this.deepCopy(key, map, -1, result, dupStubs, owner);
467
+ result.set(keyCopy, this.deepCopy(val, map, mapKeyToPropertyName(keyCopy), result, dupStubs, owner));
468
+ }
469
+ return result;
470
+ }
406
471
  case "object": {
407
472
  let result = {};
408
473
  let object = value;
@@ -460,8 +525,10 @@ var RpcPayload = class RpcPayload {
460
525
  case "readable": {
461
526
  let stream = value;
462
527
  let hook;
463
- if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
464
- else hook = streamImpl.createReadableStreamHook(stream);
528
+ if (owner) {
529
+ if (owner.source === "owned") throw new Error("Can't copy a ReadableStream.");
530
+ hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
531
+ } else hook = streamImpl.createReadableStreamHook(stream);
465
532
  this.hooks.push(hook);
466
533
  return stream;
467
534
  }
@@ -487,6 +554,10 @@ var RpcPayload = class RpcPayload {
487
554
  try {
488
555
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
489
556
  } catch (err) {
557
+ if (dupStubs) {
558
+ this.hooks.forEach((hook) => hook.dispose());
559
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
560
+ }
490
561
  this.hooks = void 0;
491
562
  this.promises = void 0;
492
563
  throw err;
@@ -500,7 +571,8 @@ var RpcPayload = class RpcPayload {
500
571
  this.ensureDeepCopied();
501
572
  if (this.value instanceof RpcPromise$1) RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);
502
573
  else {
503
- parent[property] = this.value;
574
+ if (parent instanceof Map) parent.set(typeof property === "object" ? property.mapKey : property, this.value);
575
+ else parent[property] = this.value;
504
576
  for (let record of this.promises) RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);
505
577
  }
506
578
  }
@@ -592,6 +664,7 @@ var RpcPayload = class RpcPayload {
592
664
  case "blob":
593
665
  case "date":
594
666
  case "url":
667
+ case "regexp":
595
668
  case "error":
596
669
  case "undefined": return;
597
670
  case "array": {
@@ -600,6 +673,19 @@ var RpcPayload = class RpcPayload {
600
673
  for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
601
674
  return;
602
675
  }
676
+ case "set": {
677
+ let set = value;
678
+ for (let element of set) this.disposeImpl(element, set);
679
+ return;
680
+ }
681
+ case "map": {
682
+ let map = value;
683
+ for (let [key, val] of map) {
684
+ this.disposeImpl(key, map);
685
+ this.disposeImpl(val, map);
686
+ }
687
+ return;
688
+ }
603
689
  case "object": {
604
690
  let object = value;
605
691
  for (let i in object) this.disposeImpl(object[i], object);
@@ -675,6 +761,7 @@ var RpcPayload = class RpcPayload {
675
761
  case "writable":
676
762
  case "readable":
677
763
  case "url":
764
+ case "regexp":
678
765
  case "headers":
679
766
  case "request":
680
767
  case "response": return;
@@ -684,6 +771,19 @@ var RpcPayload = class RpcPayload {
684
771
  for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
685
772
  return;
686
773
  }
774
+ case "set": {
775
+ let set = value;
776
+ for (let element of set) this.ignoreUnhandledRejectionsImpl(element);
777
+ return;
778
+ }
779
+ case "map": {
780
+ let map = value;
781
+ for (let [key, val] of map) {
782
+ this.ignoreUnhandledRejectionsImpl(key);
783
+ this.ignoreUnhandledRejectionsImpl(val);
784
+ }
785
+ return;
786
+ }
687
787
  case "object": {
688
788
  let object = value;
689
789
  for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
@@ -743,8 +843,11 @@ function followPath(value, parent, path, owner) {
743
843
  case "bytes":
744
844
  case "blob":
745
845
  case "date":
846
+ case "set":
847
+ case "map":
746
848
  case "error":
747
849
  case "url":
850
+ case "regexp":
748
851
  case "headers":
749
852
  case "request":
750
853
  case "response":
@@ -777,17 +880,23 @@ function followPath(value, parent, path, owner) {
777
880
  }
778
881
  var ValueStubHook = class extends StubHook {
779
882
  call(path, args) {
883
+ let followResult;
780
884
  try {
781
885
  let { value, owner } = this.getValue();
782
- let followResult = followPath(value, void 0, path, owner);
783
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
784
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
785
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
786
- return new PayloadStubHook(payload);
787
- }));
886
+ followResult = followPath(value, void 0, path, owner);
788
887
  } catch (err) {
888
+ args.dispose();
789
889
  return new ErrorStubHook(err);
790
890
  }
891
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
892
+ if (typeof followResult.value != "function") {
893
+ args.dispose();
894
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
895
+ }
896
+ let promise = args.deliverCall(followResult.value, followResult.parent);
897
+ return new PromiseStubHook(promise.then((payload) => {
898
+ return new PayloadStubHook(payload);
899
+ }));
791
900
  }
792
901
  map(path, captures, instructions) {
793
902
  try {
@@ -808,7 +917,10 @@ var ValueStubHook = class extends StubHook {
808
917
  get(path) {
809
918
  try {
810
919
  let { value, owner } = this.getValue();
811
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
920
+ if (path.length === 0 && owner === null) {
921
+ if (value instanceof Object && "then" in value) return this.dup();
922
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
923
+ }
812
924
  let followResult = followPath(value, void 0, path, owner);
813
925
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
814
926
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -911,7 +1023,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
911
1023
  this.target = void 0;
912
1024
  }
913
1025
  }
914
- onBroken(callback) {}
1026
+ onBroken(callback) {
1027
+ let target = this.target;
1028
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
1029
+ }
915
1030
  };
916
1031
  var PromiseStubHook = class PromiseStubHook extends StubHook {
917
1032
  promise;
@@ -925,12 +1040,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
925
1040
  }
926
1041
  call(path, args) {
927
1042
  args.ensureDeepCopied();
928
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
1043
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
1044
+ args.dispose();
1045
+ throw err;
1046
+ }));
929
1047
  }
930
1048
  stream(path, args) {
931
1049
  args.ensureDeepCopied();
932
- return { promise: this.promise.then((hook) => {
933
- return hook.stream(path, args).promise;
1050
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
1051
+ args.dispose();
1052
+ throw err;
934
1053
  }) };
935
1054
  }
936
1055
  map(path, captures, instructions) {
@@ -957,10 +1076,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
957
1076
  }, (err) => {});
958
1077
  }
959
1078
  dispose() {
960
- if (this.resolution) this.resolution.dispose();
961
- else this.promise.then((hook) => {
962
- hook.dispose();
963
- }, (err) => {});
1079
+ this.promise.then((hook) => hook.dispose(), () => {});
964
1080
  }
965
1081
  onBroken(callback) {
966
1082
  if (this.resolution) this.resolution.onBroken(callback);
@@ -976,7 +1092,7 @@ const DEFAULT_MAX_DEPTH = 256;
976
1092
  const DEFAULT_LIMITS = {
977
1093
  maxBigIntDigits: 16384,
978
1094
  maxDepth: 256,
979
- maxMessageSize: 32 * 1024 * 1024
1095
+ maxMessageSize: 33554432
980
1096
  };
981
1097
  const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
982
1098
  const BYTE_CONTAINER_TYPE_NAMES = [
@@ -1038,9 +1154,7 @@ function swapByteOrder(bytes, elementSize) {
1038
1154
  case 4:
1039
1155
  view.setUint32(offset, view.getUint32(offset, false), true);
1040
1156
  break;
1041
- case 8:
1042
- view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1043
- break;
1157
+ case 8: view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1044
1158
  }
1045
1159
  }
1046
1160
  var NullExporter = class {
@@ -1125,6 +1239,30 @@ var Devaluator = class Devaluator {
1125
1239
  for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
1126
1240
  return [result];
1127
1241
  }
1242
+ case "set": {
1243
+ let set = value;
1244
+ let setElements = [...set];
1245
+ let elements = [];
1246
+ for (let element of setElements) switch (typeForRpc(element)) {
1247
+ case "blob": throw new TypeError("Cannot serialize a Blob as an element of a Set.");
1248
+ case "rpc-promise":
1249
+ case "rpc-thenable": throw new TypeError("Cannot serialize a promise as an element of a Set. Await the value before adding it to the Set.");
1250
+ }
1251
+ for (let element of setElements) elements.push(this.devaluateImpl(element, set, depth + 1));
1252
+ return ["set", elements];
1253
+ }
1254
+ case "map": {
1255
+ let map = value;
1256
+ let mapEntries = [...map];
1257
+ let entries = [];
1258
+ for (let [key] of mapEntries) switch (typeForRpc(key)) {
1259
+ case "blob": throw new TypeError("Cannot serialize a Blob as a key of a Map.");
1260
+ case "rpc-promise":
1261
+ case "rpc-thenable": throw new TypeError("Cannot serialize a promise as a key of a Map. Await the value before using it as a key.");
1262
+ }
1263
+ for (let [key, val] of mapEntries) entries.push([this.devaluateImpl(key, map, depth + 1), this.devaluateImpl(val, map, depth + 1)]);
1264
+ return ["map", entries];
1265
+ }
1128
1266
  case "bigint":
1129
1267
  if (this.encodingLevel === "structuredClonable") return value;
1130
1268
  return ["bigint", value.toString()];
@@ -1133,6 +1271,15 @@ var Devaluator = class Devaluator {
1133
1271
  const time = value.getTime();
1134
1272
  return ["date", Number.isNaN(time) ? null : time];
1135
1273
  }
1274
+ case "regexp": {
1275
+ if (this.encodingLevel === "structuredClonable") return value;
1276
+ let re = value;
1277
+ return re.flags ? [
1278
+ "regexp",
1279
+ re.source,
1280
+ re.flags
1281
+ ] : ["regexp", re.source];
1282
+ }
1136
1283
  case "bytes": {
1137
1284
  let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1138
1285
  let bytes;
@@ -1147,11 +1294,14 @@ var Devaluator = class Devaluator {
1147
1294
  swapByteOrder(bytes, elementSize);
1148
1295
  }
1149
1296
  }
1150
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1151
- "bytes",
1152
- bytes,
1153
- alternateTypeName
1154
- ];
1297
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") {
1298
+ if (bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
1299
+ return alternateTypeName === void 0 ? ["bytes", bytes] : [
1300
+ "bytes",
1301
+ bytes,
1302
+ alternateTypeName
1303
+ ];
1304
+ }
1155
1305
  let b64;
1156
1306
  if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1157
1307
  else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
@@ -1290,13 +1440,16 @@ var Devaluator = class Devaluator {
1290
1440
  if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1291
1441
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
1292
1442
  let importId = this.exporter.getImport(hook);
1293
- if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [
1294
- "pipeline",
1295
- importId,
1296
- pathIfPromise
1297
- ];
1298
- else return ["pipeline", importId];
1299
- else return ["import", importId];
1443
+ if (importId !== void 0) {
1444
+ if (pathIfPromise) {
1445
+ if (pathIfPromise.length > 0) return [
1446
+ "pipeline",
1447
+ importId,
1448
+ pathIfPromise
1449
+ ];
1450
+ else return ["pipeline", importId];
1451
+ } else return ["import", importId];
1452
+ }
1300
1453
  if (pathIfPromise) hook = hook.get(pathIfPromise);
1301
1454
  else hook = hook.dup();
1302
1455
  return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
@@ -1357,16 +1510,18 @@ var NullImporter = class {
1357
1510
  };
1358
1511
  const NULL_IMPORTER = new NullImporter();
1359
1512
  function fixBrokenRequestBody(request, body) {
1360
- return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {
1513
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1361
1514
  let bytes = new Uint8Array(arrayBuffer);
1362
1515
  let result = new Request(request, { body: bytes });
1363
1516
  return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1364
- })), []);
1517
+ });
1518
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1365
1519
  }
1366
1520
  function streamToBlobPromise(stream, type) {
1367
- return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {
1521
+ let promise = streamToBlob(stream, type).then((blob) => {
1368
1522
  return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1369
- })), []);
1523
+ });
1524
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1370
1525
  }
1371
1526
  var Evaluator = class Evaluator {
1372
1527
  importer;
@@ -1399,7 +1554,7 @@ var Evaluator = class Evaluator {
1399
1554
  let maxDepth = this.limits.maxDepth;
1400
1555
  if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1401
1556
  if (this.encodingLevel === "structuredClonable") {
1402
- if (value instanceof Date || typeof value === "bigint") return value;
1557
+ if (value instanceof Date || value instanceof RegExp || typeof value === "bigint") return value;
1403
1558
  }
1404
1559
  if (value instanceof Array) {
1405
1560
  if (value.length == 1 && value[0] instanceof Array) {
@@ -1419,18 +1574,48 @@ var Evaluator = class Evaluator {
1419
1574
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1420
1575
  if (typeof value[1] == "number") return new Date(value[1]);
1421
1576
  break;
1577
+ case "regexp":
1578
+ if (typeof value[1] === "string" && (value.length === 2 || value.length === 3 && typeof value[2] === "string")) return new RegExp(value[1], value[2]);
1579
+ break;
1580
+ case "set":
1581
+ if (value.length === 2 && value[1] instanceof Array) {
1582
+ let elements = value[1];
1583
+ let set = /* @__PURE__ */ new Set();
1584
+ for (let i = 0; i < elements.length; i++) {
1585
+ let copy = this.evaluateImpl(elements[i], set, i, depth + 1);
1586
+ if (copy instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as an element of a Set.");
1587
+ set.add(copy);
1588
+ }
1589
+ return set;
1590
+ }
1591
+ break;
1592
+ case "map":
1593
+ if (value.length === 2 && value[1] instanceof Array) {
1594
+ let entries = value[1];
1595
+ let map = /* @__PURE__ */ new Map();
1596
+ for (let i = 0; i < entries.length; i++) {
1597
+ let entry = entries[i];
1598
+ if (!(entry instanceof Array) || entry.length !== 2) throw new TypeError("Map entries must be serialized as key/value pairs.");
1599
+ let key = this.evaluateImpl(entry[0], map, i, depth + 1);
1600
+ if (key instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as a key of a Map.");
1601
+ map.set(key, this.evaluateImpl(entry[1], map, mapKeyToPropertyName(key), depth + 1));
1602
+ }
1603
+ return map;
1604
+ }
1605
+ break;
1422
1606
  case "bytes": {
1423
1607
  let bytes;
1424
1608
  if (value[1] instanceof Uint8Array) bytes = value[1];
1425
- else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1426
- else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1427
- else {
1428
- let bs = atob(value[1]);
1429
- let len = bs.length;
1430
- bytes = new Uint8Array(len);
1431
- for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1432
- }
1433
- else break;
1609
+ else if (typeof value[1] == "string") {
1610
+ if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1611
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1612
+ else {
1613
+ let bs = atob(value[1]);
1614
+ let len = bs.length;
1615
+ bytes = new Uint8Array(len);
1616
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1617
+ }
1618
+ } else break;
1434
1619
  if (value.length === 2) return bytes;
1435
1620
  if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1436
1621
  if (!isValidByteContainerName(value[2])) {
@@ -1456,7 +1641,6 @@ var Evaluator = class Evaluator {
1456
1641
  case "BigUint64Array": return new BigUint64Array(buffer);
1457
1642
  case "Float32Array": return new Float32Array(buffer);
1458
1643
  case "Float64Array": return new Float64Array(buffer);
1459
- default:
1460
1644
  }
1461
1645
  }
1462
1646
  case "error":
@@ -1559,11 +1743,13 @@ var Evaluator = class Evaluator {
1559
1743
  return promise;
1560
1744
  } else {
1561
1745
  this.hooks.push(hook);
1562
- return new RpcPromise$1(hook, []);
1746
+ return new RpcStub$1(hook);
1563
1747
  }
1564
1748
  };
1565
- if (value.length == 2) if (isPromise) return addStub(hook.get([]));
1566
- else return addStub(hook.dup());
1749
+ if (value.length == 2) {
1750
+ if (isPromise) return addStub(hook.get([]));
1751
+ else return addStub(hook.dup());
1752
+ }
1567
1753
  let path = value[2];
1568
1754
  if (!(path instanceof Array)) break;
1569
1755
  if (!path.every((part) => {
@@ -1593,7 +1779,8 @@ var Evaluator = class Evaluator {
1593
1779
  }
1594
1780
  });
1595
1781
  let instructions = value[4];
1596
- let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);
1782
+ let resultHook = hook.map(path, captures, instructions);
1783
+ let promise = new RpcPromise$1(resultHook, []);
1597
1784
  this.promises.push({
1598
1785
  promise,
1599
1786
  parent,
@@ -1603,18 +1790,21 @@ var Evaluator = class Evaluator {
1603
1790
  }
1604
1791
  case "export":
1605
1792
  case "promise":
1606
- if (typeof value[1] == "number") if (value[0] == "promise") {
1607
- let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);
1608
- this.promises.push({
1609
- parent,
1610
- property,
1611
- promise
1612
- });
1613
- return promise;
1614
- } else {
1615
- let hook = this.importer.importStub(value[1]);
1616
- this.hooks.push(hook);
1617
- return new RpcStub$1(hook);
1793
+ if (typeof value[1] == "number") {
1794
+ if (value[0] == "promise") {
1795
+ let hook = this.importer.importPromise(value[1]);
1796
+ let promise = new RpcPromise$1(hook, []);
1797
+ this.promises.push({
1798
+ parent,
1799
+ property,
1800
+ promise
1801
+ });
1802
+ return promise;
1803
+ } else {
1804
+ let hook = this.importer.importStub(value[1]);
1805
+ this.hooks.push(hook);
1806
+ return new RpcStub$1(hook);
1807
+ }
1618
1808
  }
1619
1809
  break;
1620
1810
  case "writable":
@@ -1625,14 +1815,12 @@ var Evaluator = class Evaluator {
1625
1815
  return stream;
1626
1816
  }
1627
1817
  break;
1628
- case "readable":
1629
- if (typeof value[1] == "number") {
1630
- let stream = this.importer.getPipeReadable(value[1]);
1631
- let hook = streamImpl.createReadableStreamHook(stream);
1632
- this.hooks.push(hook);
1633
- return stream;
1634
- }
1635
- break;
1818
+ case "readable": if (typeof value[1] == "number") {
1819
+ let stream = this.importer.getPipeReadable(value[1]);
1820
+ let hook = streamImpl.createReadableStreamHook(stream);
1821
+ this.hooks.push(hook);
1822
+ return stream;
1823
+ }
1636
1824
  }
1637
1825
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1638
1826
  } else if (value instanceof Object) {
@@ -1677,6 +1865,7 @@ function estimateEncodedSize(value, seen, depth = 0) {
1677
1865
  if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1678
1866
  if (typeof Blob !== "undefined" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;
1679
1867
  if (value instanceof Date) return 16;
1868
+ if (value instanceof RegExp) return ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.source) + estimateStringSize(value.flags);
1680
1869
  seen ??= /* @__PURE__ */ new WeakSet();
1681
1870
  if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;
1682
1871
  seen.add(value);
@@ -1789,24 +1978,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1789
1978
  if (this.entry) return this.entry;
1790
1979
  else throw new Error("This RpcImportHook was already disposed.");
1791
1980
  }
1981
+ getEntryTakingOwnership(disposeOwned) {
1982
+ try {
1983
+ return this.getEntry();
1984
+ } catch (err) {
1985
+ disposeOwned();
1986
+ throw err;
1987
+ }
1988
+ }
1792
1989
  call(path, args) {
1793
- let entry = this.getEntry();
1990
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1794
1991
  if (entry.resolution) return entry.resolution.call(path, args);
1795
1992
  else return entry.session.sendCall(entry.importId, path, args);
1796
1993
  }
1797
1994
  stream(path, args) {
1798
- let entry = this.getEntry();
1995
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1799
1996
  if (entry.resolution) return entry.resolution.stream(path, args);
1800
1997
  else return entry.session.sendStream(entry.importId, path, args);
1801
1998
  }
1802
1999
  map(path, captures, instructions) {
1803
- let entry;
1804
- try {
1805
- entry = this.getEntry();
1806
- } catch (err) {
2000
+ let entry = this.getEntryTakingOwnership(() => {
1807
2001
  for (let cap of captures) cap.dispose();
1808
- throw err;
1809
- }
2002
+ });
1810
2003
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1811
2004
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1812
2005
  }
@@ -1993,7 +2186,7 @@ var RpcSessionImpl = class {
1993
2186
  }
1994
2187
  }
1995
2188
  getImport(hook) {
1996
- if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;
2189
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this && !hook.entry.resolution) return hook.entry.importId;
1997
2190
  else return;
1998
2191
  }
1999
2192
  importStub(idx) {
@@ -2067,14 +2260,23 @@ var RpcSessionImpl = class {
2067
2260
  }
2068
2261
  }
2069
2262
  sendCall(id, path, args) {
2070
- if (this.abortReason) throw this.abortReason;
2263
+ if (this.abortReason) {
2264
+ args?.dispose();
2265
+ throw this.abortReason;
2266
+ }
2071
2267
  let value = [
2072
2268
  "pipeline",
2073
2269
  id,
2074
2270
  path
2075
2271
  ];
2076
2272
  if (args) {
2077
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2273
+ let devalue;
2274
+ try {
2275
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2276
+ } catch (err) {
2277
+ args.dispose();
2278
+ throw err;
2279
+ }
2078
2280
  value.push(devalue[0]);
2079
2281
  }
2080
2282
  this.send(["push", value]);
@@ -2083,13 +2285,22 @@ var RpcSessionImpl = class {
2083
2285
  return new RpcImportHook(true, entry);
2084
2286
  }
2085
2287
  sendStream(id, path, args) {
2086
- if (this.abortReason) throw this.abortReason;
2288
+ if (this.abortReason) {
2289
+ args.dispose();
2290
+ throw this.abortReason;
2291
+ }
2087
2292
  let value = [
2088
2293
  "pipeline",
2089
2294
  id,
2090
2295
  path
2091
2296
  ];
2092
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2297
+ let devalue;
2298
+ try {
2299
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2300
+ } catch (err) {
2301
+ args.dispose();
2302
+ throw err;
2303
+ }
2093
2304
  value.push(devalue[0]);
2094
2305
  let msg = ["stream", value];
2095
2306
  let size = this.send(msg);
@@ -2190,7 +2401,8 @@ var RpcSessionImpl = class {
2190
2401
  if (msg instanceof Array) switch (msg[0]) {
2191
2402
  case "push":
2192
2403
  if (msg.length > 1) {
2193
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2404
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2405
+ let hook = new PayloadStubHook(payload);
2194
2406
  hook.ignoreUnhandledRejections();
2195
2407
  this.exports.push({
2196
2408
  hook,
@@ -2201,7 +2413,8 @@ var RpcSessionImpl = class {
2201
2413
  break;
2202
2414
  case "stream":
2203
2415
  if (msg.length > 1) {
2204
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2416
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2417
+ let hook = new PayloadStubHook(payload);
2205
2418
  hook.ignoreUnhandledRejections();
2206
2419
  let exportId = this.exports.length;
2207
2420
  this.exports.push({
@@ -2236,13 +2449,14 @@ var RpcSessionImpl = class {
2236
2449
  let importId = msg[1];
2237
2450
  if (typeof importId == "number" && msg.length > 2) {
2238
2451
  let imp = this.imports[importId];
2239
- if (imp) if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2240
- else {
2241
- let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2242
- payload.dispose();
2243
- imp.resolve(new ErrorStubHook(payload.value));
2244
- }
2245
- else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2452
+ if (imp) {
2453
+ if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2454
+ else {
2455
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2456
+ payload.dispose();
2457
+ imp.resolve(new ErrorStubHook(payload.value));
2458
+ }
2459
+ } else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2246
2460
  continue;
2247
2461
  }
2248
2462
  break;
@@ -2314,7 +2528,8 @@ var RpcSession$1 = class {
2314
2528
  const MAX_CLOSE_REASON_BYTES = 123;
2315
2529
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2316
2530
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2317
- return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
2531
+ let transport = new WebSocketTransport(webSocket);
2532
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2318
2533
  }
2319
2534
  /**
2320
2535
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
@@ -2351,12 +2566,13 @@ var WebSocketTransport = class {
2351
2566
  });
2352
2567
  }
2353
2568
  webSocket.addEventListener("message", (event) => {
2354
- if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {
2355
- this.#receiveResolver(event.data);
2356
- this.#receiveResolver = void 0;
2357
- this.#receiveRejecter = void 0;
2358
- } else this.#receiveQueue.push(event.data);
2359
- else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2569
+ if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) {
2570
+ if (this.#receiveResolver) {
2571
+ this.#receiveResolver(event.data);
2572
+ this.#receiveResolver = void 0;
2573
+ this.#receiveRejecter = void 0;
2574
+ } else this.#receiveQueue.push(event.data);
2575
+ } else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2360
2576
  });
2361
2577
  webSocket.addEventListener("close", (event) => {
2362
2578
  this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
@@ -2448,7 +2664,8 @@ function newHttpBatchRpcSession$1(urlOrRequest, options) {
2448
2664
  let body = await response.text();
2449
2665
  return body == "" ? [] : body.split("\n");
2450
2666
  };
2451
- return new RpcSession$1(new BatchClientTransport(sendBatch), void 0, options).getRemoteMain();
2667
+ let transport = new BatchClientTransport(sendBatch);
2668
+ return new RpcSession$1(transport, void 0, options).getRemoteMain();
2452
2669
  }
2453
2670
  var BatchServerTransport = class {
2454
2671
  constructor(batch) {
@@ -2491,7 +2708,8 @@ var BatchServerTransport = class {
2491
2708
  async function newHttpBatchRpcResponse(request, localMain, options) {
2492
2709
  if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
2493
2710
  let body = await request.text();
2494
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2711
+ let batch = body === "" ? [] : body.split("\n");
2712
+ let transport = new BatchServerTransport(batch);
2495
2713
  let rpc = new RpcSession$1(transport, localMain, options);
2496
2714
  await transport.whenAllReceived();
2497
2715
  await rpc.drain();
@@ -2521,7 +2739,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2521
2739
  });
2522
2740
  request.on("error", reject);
2523
2741
  });
2524
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2742
+ let batch = body === "" ? [] : body.split("\n");
2743
+ let transport = new BatchServerTransport(batch);
2525
2744
  let rpc = new RpcSession$1(transport, localMain, options);
2526
2745
  await transport.whenAllReceived();
2527
2746
  await rpc.drain();
@@ -2532,7 +2751,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2532
2751
  //#endregion
2533
2752
  //#region src/messageport.ts
2534
2753
  function newMessagePortRpcSession$1(port, localMain, options) {
2535
- return new RpcSession$1(new MessagePortTransport(port), localMain, options).getRemoteMain();
2754
+ let transport = new MessagePortTransport(port);
2755
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2536
2756
  }
2537
2757
  var MessagePortTransport = class {
2538
2758
  encodingLevel = "structuredClonable";
@@ -2720,9 +2940,11 @@ var MapVariableHook = class extends StubHook {
2720
2940
  else throwMapperBuilderUseError();
2721
2941
  }
2722
2942
  call(path, args) {
2943
+ args.dispose();
2723
2944
  throwMapperBuilderUseError();
2724
2945
  }
2725
2946
  map(path, captures, instructions) {
2947
+ for (let cap of captures) cap.dispose();
2726
2948
  throwMapperBuilderUseError();
2727
2949
  }
2728
2950
  pull() {
@@ -2780,7 +3002,8 @@ var MapApplicator = class {
2780
3002
  }
2781
3003
  };
2782
3004
  function applyMapToElement(input, parent, owner, captures, instructions) {
2783
- let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
3005
+ let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
3006
+ let mapper = new MapApplicator(captures, inputHook);
2784
3007
  try {
2785
3008
  return mapper.apply(instructions);
2786
3009
  } finally {
@@ -2813,9 +3036,10 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2813
3036
  var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2814
3037
  state;
2815
3038
  static create(stream) {
3039
+ let writer = stream.getWriter();
2816
3040
  return new WritableStreamStubHook({
2817
3041
  refcount: 1,
2818
- writer: stream.getWriter(),
3042
+ writer,
2819
3043
  closed: false
2820
3044
  });
2821
3045
  }
@@ -2833,13 +3057,12 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2833
3057
  let state = this.getState();
2834
3058
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2835
3059
  const method = path[0];
2836
- if (method !== "write" && method !== "close" && method !== "abort") {
2837
- args.dispose();
2838
- throw new Error(`Unknown WritableStream method: ${method}`);
2839
- }
3060
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2840
3061
  if (method === "close" || method === "abort") state.closed = true;
2841
- return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
3062
+ let promise = method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer);
3063
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2842
3064
  } catch (err) {
3065
+ args.dispose();
2843
3066
  return new ErrorStubHook(err);
2844
3067
  }
2845
3068
  }
@@ -2851,7 +3074,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2851
3074
  return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a WritableStream stub"));
2852
3075
  }
2853
3076
  dup() {
2854
- return new WritableStreamStubHook(this.getState(), this);
3077
+ let state = this.getState();
3078
+ return new WritableStreamStubHook(state, this);
2855
3079
  }
2856
3080
  pull() {
2857
3081
  return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a WritableStream stub"));
@@ -2869,9 +3093,9 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2869
3093
  }
2870
3094
  onBroken(callback) {}
2871
3095
  };
2872
- const INITIAL_WINDOW = 256 * 1024;
2873
- const MAX_WINDOW = 1024 * 1024 * 1024;
2874
- const MIN_WINDOW = 64 * 1024;
3096
+ const INITIAL_WINDOW = 262144;
3097
+ const MAX_WINDOW = 1073741824;
3098
+ const MIN_WINDOW = 65536;
2875
3099
  const STARTUP_GROWTH_FACTOR = 2;
2876
3100
  const STEADY_GROWTH_FACTOR = 1.25;
2877
3101
  const DECAY_FACTOR = .9;