capnweb 0.0.0-064b0f3 → 0.0.0-07032e2

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,8 @@ 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";
45
46
  case Uint8Array.prototype:
46
47
  case BUFFER_PROTOTYPE:
47
48
  case ArrayBuffer.prototype:
@@ -92,7 +93,14 @@ let streamImpl = {
92
93
  };
93
94
  var StubHook = class {
94
95
  stream(path, args) {
95
- let pulled = this.call(path, args).pull();
96
+ let hook = this.call(path, args);
97
+ let pulled;
98
+ try {
99
+ pulled = hook.pull();
100
+ } catch (err) {
101
+ hook.dispose();
102
+ throw err;
103
+ }
96
104
  let promise;
97
105
  if (pulled instanceof Promise) promise = pulled.then((p) => {
98
106
  p.dispose();
@@ -111,9 +119,11 @@ var ErrorStubHook = class extends StubHook {
111
119
  this.error = error;
112
120
  }
113
121
  call(path, args) {
122
+ args.dispose();
114
123
  return this;
115
124
  }
116
125
  map(path, captures, instructions) {
126
+ for (let cap of captures) cap.dispose();
117
127
  return this;
118
128
  }
119
129
  get(path) {
@@ -237,7 +247,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
237
247
  };
238
248
  var RpcPromise$1 = class extends RpcStub$1 {
239
249
  constructor(hook, pathIfPromise) {
240
- super(hook, pathIfPromise);
250
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
251
+ else {
252
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
253
+ let kind = typeForRpc(hook);
254
+ if (kind === "rpc-promise") {
255
+ let raw = unwrapStubAndPath(hook);
256
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
257
+ else {
258
+ let adopted = raw.hook;
259
+ raw.hook = DISPOSED_HOOK;
260
+ super(adopted, []);
261
+ }
262
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
263
+ else {
264
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
265
+ promiseHook.ignoreUnhandledRejections();
266
+ super(promiseHook, []);
267
+ }
268
+ }
241
269
  }
242
270
  then(onfulfilled, onrejected) {
243
271
  return pullPromise(this).then(...arguments);
@@ -332,12 +360,13 @@ var RpcPayload = class RpcPayload {
332
360
  return TargetStubHook.create(target, parent);
333
361
  } else if (this.source === "return") {
334
362
  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 {
363
+ if (hook) {
364
+ if (dupStubs) return hook.dup();
365
+ else {
366
+ this.rpcTargets?.delete(target);
367
+ return hook;
368
+ }
369
+ } else {
341
370
  hook = TargetStubHook.create(target, parent);
342
371
  if (dupStubs) {
343
372
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -351,12 +380,13 @@ var RpcPayload = class RpcPayload {
351
380
  if (this.source === "params") return streamImpl.createWritableStreamHook(stream);
352
381
  else if (this.source === "return") {
353
382
  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 {
383
+ if (hook) {
384
+ if (dupStubs) return hook.dup();
385
+ else {
386
+ this.rpcTargets?.delete(stream);
387
+ return hook;
388
+ }
389
+ } else {
360
390
  hook = streamImpl.createWritableStreamHook(stream);
361
391
  if (dupStubs) {
362
392
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -370,12 +400,13 @@ var RpcPayload = class RpcPayload {
370
400
  if (this.source === "params") return streamImpl.createReadableStreamHook(stream);
371
401
  else if (this.source === "return") {
372
402
  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 {
403
+ if (hook) {
404
+ if (dupStubs) return hook.dup();
405
+ else {
406
+ this.rpcTargets?.delete(stream);
407
+ return hook;
408
+ }
409
+ } else {
379
410
  hook = streamImpl.createReadableStreamHook(stream);
380
411
  if (dupStubs) {
381
412
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -394,6 +425,7 @@ var RpcPayload = class RpcPayload {
394
425
  case "bytes":
395
426
  case "blob":
396
427
  case "url":
428
+ case "regexp":
397
429
  case "error":
398
430
  case "undefined": return value;
399
431
  case "array": {
@@ -403,6 +435,21 @@ var RpcPayload = class RpcPayload {
403
435
  for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
404
436
  return result;
405
437
  }
438
+ case "set": {
439
+ let set = value;
440
+ let elements = [...set];
441
+ for (let val of elements) {
442
+ let kind = typeForRpc(val);
443
+ 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.");
444
+ }
445
+ let result = /* @__PURE__ */ new Set();
446
+ let index = 0;
447
+ for (let val of elements) {
448
+ let copy = this.deepCopy(val, set, index++, result, dupStubs, owner);
449
+ result.add(copy);
450
+ }
451
+ return result;
452
+ }
406
453
  case "object": {
407
454
  let result = {};
408
455
  let object = value;
@@ -487,6 +534,10 @@ var RpcPayload = class RpcPayload {
487
534
  try {
488
535
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
489
536
  } catch (err) {
537
+ if (dupStubs) {
538
+ this.hooks.forEach((hook) => hook.dispose());
539
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
540
+ }
490
541
  this.hooks = void 0;
491
542
  this.promises = void 0;
492
543
  throw err;
@@ -592,6 +643,7 @@ var RpcPayload = class RpcPayload {
592
643
  case "blob":
593
644
  case "date":
594
645
  case "url":
646
+ case "regexp":
595
647
  case "error":
596
648
  case "undefined": return;
597
649
  case "array": {
@@ -600,6 +652,11 @@ var RpcPayload = class RpcPayload {
600
652
  for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
601
653
  return;
602
654
  }
655
+ case "set": {
656
+ let set = value;
657
+ for (let element of set) this.disposeImpl(element, set);
658
+ return;
659
+ }
603
660
  case "object": {
604
661
  let object = value;
605
662
  for (let i in object) this.disposeImpl(object[i], object);
@@ -675,6 +732,7 @@ var RpcPayload = class RpcPayload {
675
732
  case "writable":
676
733
  case "readable":
677
734
  case "url":
735
+ case "regexp":
678
736
  case "headers":
679
737
  case "request":
680
738
  case "response": return;
@@ -684,6 +742,11 @@ var RpcPayload = class RpcPayload {
684
742
  for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
685
743
  return;
686
744
  }
745
+ case "set": {
746
+ let set = value;
747
+ for (let element of set) this.ignoreUnhandledRejectionsImpl(element);
748
+ return;
749
+ }
687
750
  case "object": {
688
751
  let object = value;
689
752
  for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
@@ -743,8 +806,10 @@ function followPath(value, parent, path, owner) {
743
806
  case "bytes":
744
807
  case "blob":
745
808
  case "date":
809
+ case "set":
746
810
  case "error":
747
811
  case "url":
812
+ case "regexp":
748
813
  case "headers":
749
814
  case "request":
750
815
  case "response":
@@ -777,17 +842,23 @@ function followPath(value, parent, path, owner) {
777
842
  }
778
843
  var ValueStubHook = class extends StubHook {
779
844
  call(path, args) {
845
+ let followResult;
780
846
  try {
781
847
  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
- }));
848
+ followResult = followPath(value, void 0, path, owner);
788
849
  } catch (err) {
850
+ args.dispose();
789
851
  return new ErrorStubHook(err);
790
852
  }
853
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
854
+ if (typeof followResult.value != "function") {
855
+ args.dispose();
856
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
857
+ }
858
+ let promise = args.deliverCall(followResult.value, followResult.parent);
859
+ return new PromiseStubHook(promise.then((payload) => {
860
+ return new PayloadStubHook(payload);
861
+ }));
791
862
  }
792
863
  map(path, captures, instructions) {
793
864
  try {
@@ -808,7 +879,10 @@ var ValueStubHook = class extends StubHook {
808
879
  get(path) {
809
880
  try {
810
881
  let { value, owner } = this.getValue();
811
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
882
+ if (path.length === 0 && owner === null) {
883
+ if (value instanceof Object && "then" in value) return this.dup();
884
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
885
+ }
812
886
  let followResult = followPath(value, void 0, path, owner);
813
887
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
814
888
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -911,7 +985,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
911
985
  this.target = void 0;
912
986
  }
913
987
  }
914
- onBroken(callback) {}
988
+ onBroken(callback) {
989
+ let target = this.target;
990
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
991
+ }
915
992
  };
916
993
  var PromiseStubHook = class PromiseStubHook extends StubHook {
917
994
  promise;
@@ -925,12 +1002,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
925
1002
  }
926
1003
  call(path, args) {
927
1004
  args.ensureDeepCopied();
928
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
1005
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
1006
+ args.dispose();
1007
+ throw err;
1008
+ }));
929
1009
  }
930
1010
  stream(path, args) {
931
1011
  args.ensureDeepCopied();
932
- return { promise: this.promise.then((hook) => {
933
- return hook.stream(path, args).promise;
1012
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
1013
+ args.dispose();
1014
+ throw err;
934
1015
  }) };
935
1016
  }
936
1017
  map(path, captures, instructions) {
@@ -957,10 +1038,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
957
1038
  }, (err) => {});
958
1039
  }
959
1040
  dispose() {
960
- if (this.resolution) this.resolution.dispose();
961
- else this.promise.then((hook) => {
962
- hook.dispose();
963
- }, (err) => {});
1041
+ this.promise.then((hook) => hook.dispose(), () => {});
964
1042
  }
965
1043
  onBroken(callback) {
966
1044
  if (this.resolution) this.resolution.onBroken(callback);
@@ -976,7 +1054,7 @@ const DEFAULT_MAX_DEPTH = 256;
976
1054
  const DEFAULT_LIMITS = {
977
1055
  maxBigIntDigits: 16384,
978
1056
  maxDepth: 256,
979
- maxMessageSize: 32 * 1024 * 1024
1057
+ maxMessageSize: 33554432
980
1058
  };
981
1059
  const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
982
1060
  const BYTE_CONTAINER_TYPE_NAMES = [
@@ -1038,9 +1116,7 @@ function swapByteOrder(bytes, elementSize) {
1038
1116
  case 4:
1039
1117
  view.setUint32(offset, view.getUint32(offset, false), true);
1040
1118
  break;
1041
- case 8:
1042
- view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1043
- break;
1119
+ case 8: view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1044
1120
  }
1045
1121
  }
1046
1122
  var NullExporter = class {
@@ -1125,6 +1201,18 @@ var Devaluator = class Devaluator {
1125
1201
  for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
1126
1202
  return [result];
1127
1203
  }
1204
+ case "set": {
1205
+ let set = value;
1206
+ let setElements = [...set];
1207
+ let elements = [];
1208
+ for (let element of setElements) switch (typeForRpc(element)) {
1209
+ case "blob": throw new TypeError("Cannot serialize a Blob as an element of a Set.");
1210
+ case "rpc-promise":
1211
+ 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.");
1212
+ }
1213
+ for (let element of setElements) elements.push(this.devaluateImpl(element, set, depth + 1));
1214
+ return ["set", elements];
1215
+ }
1128
1216
  case "bigint":
1129
1217
  if (this.encodingLevel === "structuredClonable") return value;
1130
1218
  return ["bigint", value.toString()];
@@ -1133,6 +1221,15 @@ var Devaluator = class Devaluator {
1133
1221
  const time = value.getTime();
1134
1222
  return ["date", Number.isNaN(time) ? null : time];
1135
1223
  }
1224
+ case "regexp": {
1225
+ if (this.encodingLevel === "structuredClonable") return value;
1226
+ let re = value;
1227
+ return re.flags ? [
1228
+ "regexp",
1229
+ re.source,
1230
+ re.flags
1231
+ ] : ["regexp", re.source];
1232
+ }
1136
1233
  case "bytes": {
1137
1234
  let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1138
1235
  let bytes;
@@ -1147,11 +1244,14 @@ var Devaluator = class Devaluator {
1147
1244
  swapByteOrder(bytes, elementSize);
1148
1245
  }
1149
1246
  }
1150
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1151
- "bytes",
1152
- bytes,
1153
- alternateTypeName
1154
- ];
1247
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") {
1248
+ if (bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
1249
+ return alternateTypeName === void 0 ? ["bytes", bytes] : [
1250
+ "bytes",
1251
+ bytes,
1252
+ alternateTypeName
1253
+ ];
1254
+ }
1155
1255
  let b64;
1156
1256
  if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1157
1257
  else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
@@ -1290,13 +1390,16 @@ var Devaluator = class Devaluator {
1290
1390
  if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1291
1391
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
1292
1392
  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];
1393
+ if (importId !== void 0) {
1394
+ if (pathIfPromise) {
1395
+ if (pathIfPromise.length > 0) return [
1396
+ "pipeline",
1397
+ importId,
1398
+ pathIfPromise
1399
+ ];
1400
+ else return ["pipeline", importId];
1401
+ } else return ["import", importId];
1402
+ }
1300
1403
  if (pathIfPromise) hook = hook.get(pathIfPromise);
1301
1404
  else hook = hook.dup();
1302
1405
  return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
@@ -1357,16 +1460,18 @@ var NullImporter = class {
1357
1460
  };
1358
1461
  const NULL_IMPORTER = new NullImporter();
1359
1462
  function fixBrokenRequestBody(request, body) {
1360
- return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {
1463
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1361
1464
  let bytes = new Uint8Array(arrayBuffer);
1362
1465
  let result = new Request(request, { body: bytes });
1363
1466
  return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1364
- })), []);
1467
+ });
1468
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1365
1469
  }
1366
1470
  function streamToBlobPromise(stream, type) {
1367
- return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {
1471
+ let promise = streamToBlob(stream, type).then((blob) => {
1368
1472
  return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1369
- })), []);
1473
+ });
1474
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1370
1475
  }
1371
1476
  var Evaluator = class Evaluator {
1372
1477
  importer;
@@ -1399,7 +1504,7 @@ var Evaluator = class Evaluator {
1399
1504
  let maxDepth = this.limits.maxDepth;
1400
1505
  if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1401
1506
  if (this.encodingLevel === "structuredClonable") {
1402
- if (value instanceof Date || typeof value === "bigint") return value;
1507
+ if (value instanceof Date || value instanceof RegExp || typeof value === "bigint") return value;
1403
1508
  }
1404
1509
  if (value instanceof Array) {
1405
1510
  if (value.length == 1 && value[0] instanceof Array) {
@@ -1419,18 +1524,34 @@ var Evaluator = class Evaluator {
1419
1524
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1420
1525
  if (typeof value[1] == "number") return new Date(value[1]);
1421
1526
  break;
1527
+ case "regexp":
1528
+ if (typeof value[1] === "string" && (value.length === 2 || value.length === 3 && typeof value[2] === "string")) return new RegExp(value[1], value[2]);
1529
+ break;
1530
+ case "set":
1531
+ if (value.length === 2 && value[1] instanceof Array) {
1532
+ let elements = value[1];
1533
+ let set = /* @__PURE__ */ new Set();
1534
+ for (let i = 0; i < elements.length; i++) {
1535
+ let copy = this.evaluateImpl(elements[i], set, i, depth + 1);
1536
+ if (copy instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as an element of a Set.");
1537
+ set.add(copy);
1538
+ }
1539
+ return set;
1540
+ }
1541
+ break;
1422
1542
  case "bytes": {
1423
1543
  let bytes;
1424
1544
  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;
1545
+ else if (typeof value[1] == "string") {
1546
+ if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1547
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1548
+ else {
1549
+ let bs = atob(value[1]);
1550
+ let len = bs.length;
1551
+ bytes = new Uint8Array(len);
1552
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1553
+ }
1554
+ } else break;
1434
1555
  if (value.length === 2) return bytes;
1435
1556
  if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1436
1557
  if (!isValidByteContainerName(value[2])) {
@@ -1456,7 +1577,6 @@ var Evaluator = class Evaluator {
1456
1577
  case "BigUint64Array": return new BigUint64Array(buffer);
1457
1578
  case "Float32Array": return new Float32Array(buffer);
1458
1579
  case "Float64Array": return new Float64Array(buffer);
1459
- default:
1460
1580
  }
1461
1581
  }
1462
1582
  case "error":
@@ -1559,11 +1679,13 @@ var Evaluator = class Evaluator {
1559
1679
  return promise;
1560
1680
  } else {
1561
1681
  this.hooks.push(hook);
1562
- return new RpcPromise$1(hook, []);
1682
+ return new RpcStub$1(hook);
1563
1683
  }
1564
1684
  };
1565
- if (value.length == 2) if (isPromise) return addStub(hook.get([]));
1566
- else return addStub(hook.dup());
1685
+ if (value.length == 2) {
1686
+ if (isPromise) return addStub(hook.get([]));
1687
+ else return addStub(hook.dup());
1688
+ }
1567
1689
  let path = value[2];
1568
1690
  if (!(path instanceof Array)) break;
1569
1691
  if (!path.every((part) => {
@@ -1593,7 +1715,8 @@ var Evaluator = class Evaluator {
1593
1715
  }
1594
1716
  });
1595
1717
  let instructions = value[4];
1596
- let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);
1718
+ let resultHook = hook.map(path, captures, instructions);
1719
+ let promise = new RpcPromise$1(resultHook, []);
1597
1720
  this.promises.push({
1598
1721
  promise,
1599
1722
  parent,
@@ -1603,18 +1726,21 @@ var Evaluator = class Evaluator {
1603
1726
  }
1604
1727
  case "export":
1605
1728
  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);
1729
+ if (typeof value[1] == "number") {
1730
+ if (value[0] == "promise") {
1731
+ let hook = this.importer.importPromise(value[1]);
1732
+ let promise = new RpcPromise$1(hook, []);
1733
+ this.promises.push({
1734
+ parent,
1735
+ property,
1736
+ promise
1737
+ });
1738
+ return promise;
1739
+ } else {
1740
+ let hook = this.importer.importStub(value[1]);
1741
+ this.hooks.push(hook);
1742
+ return new RpcStub$1(hook);
1743
+ }
1618
1744
  }
1619
1745
  break;
1620
1746
  case "writable":
@@ -1625,14 +1751,12 @@ var Evaluator = class Evaluator {
1625
1751
  return stream;
1626
1752
  }
1627
1753
  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;
1754
+ case "readable": if (typeof value[1] == "number") {
1755
+ let stream = this.importer.getPipeReadable(value[1]);
1756
+ let hook = streamImpl.createReadableStreamHook(stream);
1757
+ this.hooks.push(hook);
1758
+ return stream;
1759
+ }
1636
1760
  }
1637
1761
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1638
1762
  } else if (value instanceof Object) {
@@ -1677,6 +1801,7 @@ function estimateEncodedSize(value, seen, depth = 0) {
1677
1801
  if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1678
1802
  if (typeof Blob !== "undefined" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;
1679
1803
  if (value instanceof Date) return 16;
1804
+ if (value instanceof RegExp) return ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.source) + estimateStringSize(value.flags);
1680
1805
  seen ??= /* @__PURE__ */ new WeakSet();
1681
1806
  if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;
1682
1807
  seen.add(value);
@@ -1789,24 +1914,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1789
1914
  if (this.entry) return this.entry;
1790
1915
  else throw new Error("This RpcImportHook was already disposed.");
1791
1916
  }
1917
+ getEntryTakingOwnership(disposeOwned) {
1918
+ try {
1919
+ return this.getEntry();
1920
+ } catch (err) {
1921
+ disposeOwned();
1922
+ throw err;
1923
+ }
1924
+ }
1792
1925
  call(path, args) {
1793
- let entry = this.getEntry();
1926
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1794
1927
  if (entry.resolution) return entry.resolution.call(path, args);
1795
1928
  else return entry.session.sendCall(entry.importId, path, args);
1796
1929
  }
1797
1930
  stream(path, args) {
1798
- let entry = this.getEntry();
1931
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1799
1932
  if (entry.resolution) return entry.resolution.stream(path, args);
1800
1933
  else return entry.session.sendStream(entry.importId, path, args);
1801
1934
  }
1802
1935
  map(path, captures, instructions) {
1803
- let entry;
1804
- try {
1805
- entry = this.getEntry();
1806
- } catch (err) {
1936
+ let entry = this.getEntryTakingOwnership(() => {
1807
1937
  for (let cap of captures) cap.dispose();
1808
- throw err;
1809
- }
1938
+ });
1810
1939
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1811
1940
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1812
1941
  }
@@ -1993,7 +2122,7 @@ var RpcSessionImpl = class {
1993
2122
  }
1994
2123
  }
1995
2124
  getImport(hook) {
1996
- if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;
2125
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this && !hook.entry.resolution) return hook.entry.importId;
1997
2126
  else return;
1998
2127
  }
1999
2128
  importStub(idx) {
@@ -2067,14 +2196,23 @@ var RpcSessionImpl = class {
2067
2196
  }
2068
2197
  }
2069
2198
  sendCall(id, path, args) {
2070
- if (this.abortReason) throw this.abortReason;
2199
+ if (this.abortReason) {
2200
+ args?.dispose();
2201
+ throw this.abortReason;
2202
+ }
2071
2203
  let value = [
2072
2204
  "pipeline",
2073
2205
  id,
2074
2206
  path
2075
2207
  ];
2076
2208
  if (args) {
2077
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2209
+ let devalue;
2210
+ try {
2211
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2212
+ } catch (err) {
2213
+ args.dispose();
2214
+ throw err;
2215
+ }
2078
2216
  value.push(devalue[0]);
2079
2217
  }
2080
2218
  this.send(["push", value]);
@@ -2083,13 +2221,22 @@ var RpcSessionImpl = class {
2083
2221
  return new RpcImportHook(true, entry);
2084
2222
  }
2085
2223
  sendStream(id, path, args) {
2086
- if (this.abortReason) throw this.abortReason;
2224
+ if (this.abortReason) {
2225
+ args.dispose();
2226
+ throw this.abortReason;
2227
+ }
2087
2228
  let value = [
2088
2229
  "pipeline",
2089
2230
  id,
2090
2231
  path
2091
2232
  ];
2092
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2233
+ let devalue;
2234
+ try {
2235
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2236
+ } catch (err) {
2237
+ args.dispose();
2238
+ throw err;
2239
+ }
2093
2240
  value.push(devalue[0]);
2094
2241
  let msg = ["stream", value];
2095
2242
  let size = this.send(msg);
@@ -2190,7 +2337,8 @@ var RpcSessionImpl = class {
2190
2337
  if (msg instanceof Array) switch (msg[0]) {
2191
2338
  case "push":
2192
2339
  if (msg.length > 1) {
2193
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2340
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2341
+ let hook = new PayloadStubHook(payload);
2194
2342
  hook.ignoreUnhandledRejections();
2195
2343
  this.exports.push({
2196
2344
  hook,
@@ -2201,7 +2349,8 @@ var RpcSessionImpl = class {
2201
2349
  break;
2202
2350
  case "stream":
2203
2351
  if (msg.length > 1) {
2204
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2352
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2353
+ let hook = new PayloadStubHook(payload);
2205
2354
  hook.ignoreUnhandledRejections();
2206
2355
  let exportId = this.exports.length;
2207
2356
  this.exports.push({
@@ -2236,13 +2385,14 @@ var RpcSessionImpl = class {
2236
2385
  let importId = msg[1];
2237
2386
  if (typeof importId == "number" && msg.length > 2) {
2238
2387
  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();
2388
+ if (imp) {
2389
+ if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2390
+ else {
2391
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2392
+ payload.dispose();
2393
+ imp.resolve(new ErrorStubHook(payload.value));
2394
+ }
2395
+ } else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2246
2396
  continue;
2247
2397
  }
2248
2398
  break;
@@ -2310,11 +2460,12 @@ var RpcSession$1 = class {
2310
2460
 
2311
2461
  //#endregion
2312
2462
  //#region src/websocket.ts
2313
- /** Close-frame reason max UTF-8 bytes: 125 payload − 2-byte status (RFC 6455 §5.5). */
2463
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2314
2464
  const MAX_CLOSE_REASON_BYTES = 123;
2315
2465
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2316
2466
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2317
- return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
2467
+ let transport = new WebSocketTransport(webSocket);
2468
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2318
2469
  }
2319
2470
  /**
2320
2471
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
@@ -2351,12 +2502,13 @@ var WebSocketTransport = class {
2351
2502
  });
2352
2503
  }
2353
2504
  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."));
2505
+ if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) {
2506
+ if (this.#receiveResolver) {
2507
+ this.#receiveResolver(event.data);
2508
+ this.#receiveResolver = void 0;
2509
+ this.#receiveRejecter = void 0;
2510
+ } else this.#receiveQueue.push(event.data);
2511
+ } else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2360
2512
  });
2361
2513
  webSocket.addEventListener("close", (event) => {
2362
2514
  this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
@@ -2448,7 +2600,8 @@ function newHttpBatchRpcSession$1(urlOrRequest, options) {
2448
2600
  let body = await response.text();
2449
2601
  return body == "" ? [] : body.split("\n");
2450
2602
  };
2451
- return new RpcSession$1(new BatchClientTransport(sendBatch), void 0, options).getRemoteMain();
2603
+ let transport = new BatchClientTransport(sendBatch);
2604
+ return new RpcSession$1(transport, void 0, options).getRemoteMain();
2452
2605
  }
2453
2606
  var BatchServerTransport = class {
2454
2607
  constructor(batch) {
@@ -2491,7 +2644,8 @@ var BatchServerTransport = class {
2491
2644
  async function newHttpBatchRpcResponse(request, localMain, options) {
2492
2645
  if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
2493
2646
  let body = await request.text();
2494
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2647
+ let batch = body === "" ? [] : body.split("\n");
2648
+ let transport = new BatchServerTransport(batch);
2495
2649
  let rpc = new RpcSession$1(transport, localMain, options);
2496
2650
  await transport.whenAllReceived();
2497
2651
  await rpc.drain();
@@ -2521,7 +2675,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2521
2675
  });
2522
2676
  request.on("error", reject);
2523
2677
  });
2524
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2678
+ let batch = body === "" ? [] : body.split("\n");
2679
+ let transport = new BatchServerTransport(batch);
2525
2680
  let rpc = new RpcSession$1(transport, localMain, options);
2526
2681
  await transport.whenAllReceived();
2527
2682
  await rpc.drain();
@@ -2532,7 +2687,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2532
2687
  //#endregion
2533
2688
  //#region src/messageport.ts
2534
2689
  function newMessagePortRpcSession$1(port, localMain, options) {
2535
- return new RpcSession$1(new MessagePortTransport(port), localMain, options).getRemoteMain();
2690
+ let transport = new MessagePortTransport(port);
2691
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2536
2692
  }
2537
2693
  var MessagePortTransport = class {
2538
2694
  encodingLevel = "structuredClonable";
@@ -2720,9 +2876,11 @@ var MapVariableHook = class extends StubHook {
2720
2876
  else throwMapperBuilderUseError();
2721
2877
  }
2722
2878
  call(path, args) {
2879
+ args.dispose();
2723
2880
  throwMapperBuilderUseError();
2724
2881
  }
2725
2882
  map(path, captures, instructions) {
2883
+ for (let cap of captures) cap.dispose();
2726
2884
  throwMapperBuilderUseError();
2727
2885
  }
2728
2886
  pull() {
@@ -2780,7 +2938,8 @@ var MapApplicator = class {
2780
2938
  }
2781
2939
  };
2782
2940
  function applyMapToElement(input, parent, owner, captures, instructions) {
2783
- let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
2941
+ let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
2942
+ let mapper = new MapApplicator(captures, inputHook);
2784
2943
  try {
2785
2944
  return mapper.apply(instructions);
2786
2945
  } finally {
@@ -2813,9 +2972,10 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2813
2972
  var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2814
2973
  state;
2815
2974
  static create(stream) {
2975
+ let writer = stream.getWriter();
2816
2976
  return new WritableStreamStubHook({
2817
2977
  refcount: 1,
2818
- writer: stream.getWriter(),
2978
+ writer,
2819
2979
  closed: false
2820
2980
  });
2821
2981
  }
@@ -2833,13 +2993,12 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2833
2993
  let state = this.getState();
2834
2994
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2835
2995
  const method = path[0];
2836
- if (method !== "write" && method !== "close" && method !== "abort") {
2837
- args.dispose();
2838
- throw new Error(`Unknown WritableStream method: ${method}`);
2839
- }
2996
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2840
2997
  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)));
2998
+ let promise = method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer);
2999
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2842
3000
  } catch (err) {
3001
+ args.dispose();
2843
3002
  return new ErrorStubHook(err);
2844
3003
  }
2845
3004
  }
@@ -2851,7 +3010,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2851
3010
  return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a WritableStream stub"));
2852
3011
  }
2853
3012
  dup() {
2854
- return new WritableStreamStubHook(this.getState(), this);
3013
+ let state = this.getState();
3014
+ return new WritableStreamStubHook(state, this);
2855
3015
  }
2856
3016
  pull() {
2857
3017
  return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a WritableStream stub"));
@@ -2869,9 +3029,9 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2869
3029
  }
2870
3030
  onBroken(callback) {}
2871
3031
  };
2872
- const INITIAL_WINDOW = 256 * 1024;
2873
- const MAX_WINDOW = 1024 * 1024 * 1024;
2874
- const MIN_WINDOW = 64 * 1024;
3032
+ const INITIAL_WINDOW = 262144;
3033
+ const MAX_WINDOW = 1073741824;
3034
+ const MIN_WINDOW = 65536;
2875
3035
  const STARTUP_GROWTH_FACTOR = 2;
2876
3036
  const STEADY_GROWTH_FACTOR = 1.25;
2877
3037
  const DECAY_FACTOR = .9;