capnweb 0.12.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -46,6 +46,9 @@ function typeForRpc(value) {
46
46
  case AsyncFunction.prototype: return "function";
47
47
  case Array.prototype: return "array";
48
48
  case Date.prototype: return "date";
49
+ case RegExp.prototype: return "regexp";
50
+ case Set.prototype: return "set";
51
+ case Map.prototype: return "map";
49
52
  case Uint8Array.prototype:
50
53
  case BUFFER_PROTOTYPE:
51
54
  case ArrayBuffer.prototype:
@@ -309,6 +312,9 @@ async function pullPromise(promise) {
309
312
  if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);
310
313
  return (await hook.pull()).deliverResolve();
311
314
  }
315
+ function mapKeyToPropertyName(key) {
316
+ return typeof key === "string" || typeof key === "number" ? key : { mapKey: key };
317
+ }
312
318
  var RpcPayload = class RpcPayload {
313
319
  value;
314
320
  source;
@@ -363,12 +369,13 @@ var RpcPayload = class RpcPayload {
363
369
  return TargetStubHook.create(target, parent);
364
370
  } else if (this.source === "return") {
365
371
  let hook = this.rpcTargets?.get(target);
366
- if (hook) if (dupStubs) return hook.dup();
367
- else {
368
- this.rpcTargets?.delete(target);
369
- return hook;
370
- }
371
- else {
372
+ if (hook) {
373
+ if (dupStubs) return hook.dup();
374
+ else {
375
+ this.rpcTargets?.delete(target);
376
+ return hook;
377
+ }
378
+ } else {
372
379
  hook = TargetStubHook.create(target, parent);
373
380
  if (dupStubs) {
374
381
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -382,12 +389,13 @@ var RpcPayload = class RpcPayload {
382
389
  if (this.source === "params") return streamImpl.createWritableStreamHook(stream);
383
390
  else if (this.source === "return") {
384
391
  let hook = this.rpcTargets?.get(stream);
385
- if (hook) if (dupStubs) return hook.dup();
386
- else {
387
- this.rpcTargets?.delete(stream);
388
- return hook;
389
- }
390
- else {
392
+ if (hook) {
393
+ if (dupStubs) return hook.dup();
394
+ else {
395
+ this.rpcTargets?.delete(stream);
396
+ return hook;
397
+ }
398
+ } else {
391
399
  hook = streamImpl.createWritableStreamHook(stream);
392
400
  if (dupStubs) {
393
401
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -401,12 +409,13 @@ var RpcPayload = class RpcPayload {
401
409
  if (this.source === "params") return streamImpl.createReadableStreamHook(stream);
402
410
  else if (this.source === "return") {
403
411
  let hook = this.rpcTargets?.get(stream);
404
- if (hook) if (dupStubs) return hook.dup();
405
- else {
406
- this.rpcTargets?.delete(stream);
407
- return hook;
408
- }
409
- else {
412
+ if (hook) {
413
+ if (dupStubs) return hook.dup();
414
+ else {
415
+ this.rpcTargets?.delete(stream);
416
+ return hook;
417
+ }
418
+ } else {
410
419
  hook = streamImpl.createReadableStreamHook(stream);
411
420
  if (dupStubs) {
412
421
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -414,7 +423,7 @@ var RpcPayload = class RpcPayload {
414
423
  return hook.dup();
415
424
  } else return hook;
416
425
  }
417
- } else throw new Error("owned payload shouldn't contain raw ReadableStreams");
426
+ } else return streamImpl.createReadableStreamHook(stream);
418
427
  }
419
428
  deepCopy(value, oldParent, property, parent, dupStubs, owner) {
420
429
  switch (typeForRpc(value)) {
@@ -425,6 +434,7 @@ var RpcPayload = class RpcPayload {
425
434
  case "bytes":
426
435
  case "blob":
427
436
  case "url":
437
+ case "regexp":
428
438
  case "error":
429
439
  case "undefined": return value;
430
440
  case "array": {
@@ -434,6 +444,35 @@ var RpcPayload = class RpcPayload {
434
444
  for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
435
445
  return result;
436
446
  }
447
+ case "set": {
448
+ let set = value;
449
+ let elements = [...set];
450
+ for (let val of elements) {
451
+ let kind = typeForRpc(val);
452
+ 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.");
453
+ }
454
+ let result = /* @__PURE__ */ new Set();
455
+ let index = 0;
456
+ for (let val of elements) {
457
+ let copy = this.deepCopy(val, set, index++, result, dupStubs, owner);
458
+ result.add(copy);
459
+ }
460
+ return result;
461
+ }
462
+ case "map": {
463
+ let map = value;
464
+ let entries = [...map];
465
+ for (let [key] of entries) {
466
+ let kind = typeForRpc(key);
467
+ 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.");
468
+ }
469
+ let result = /* @__PURE__ */ new Map();
470
+ for (let [key, val] of entries) {
471
+ let keyCopy = this.deepCopy(key, map, -1, result, dupStubs, owner);
472
+ result.set(keyCopy, this.deepCopy(val, map, mapKeyToPropertyName(keyCopy), result, dupStubs, owner));
473
+ }
474
+ return result;
475
+ }
437
476
  case "object": {
438
477
  let result = {};
439
478
  let object = value;
@@ -491,8 +530,10 @@ var RpcPayload = class RpcPayload {
491
530
  case "readable": {
492
531
  let stream = value;
493
532
  let hook;
494
- if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
495
- else hook = streamImpl.createReadableStreamHook(stream);
533
+ if (owner) {
534
+ if (owner.source === "owned") throw new Error("Can't copy a ReadableStream.");
535
+ hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
536
+ } else hook = streamImpl.createReadableStreamHook(stream);
496
537
  this.hooks.push(hook);
497
538
  return stream;
498
539
  }
@@ -518,6 +559,10 @@ var RpcPayload = class RpcPayload {
518
559
  try {
519
560
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
520
561
  } catch (err) {
562
+ if (dupStubs) {
563
+ this.hooks.forEach((hook) => hook.dispose());
564
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
565
+ }
521
566
  this.hooks = void 0;
522
567
  this.promises = void 0;
523
568
  throw err;
@@ -531,7 +576,8 @@ var RpcPayload = class RpcPayload {
531
576
  this.ensureDeepCopied();
532
577
  if (this.value instanceof RpcPromise$1) RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);
533
578
  else {
534
- parent[property] = this.value;
579
+ if (parent instanceof Map) parent.set(typeof property === "object" ? property.mapKey : property, this.value);
580
+ else parent[property] = this.value;
535
581
  for (let record of this.promises) RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);
536
582
  }
537
583
  }
@@ -623,6 +669,7 @@ var RpcPayload = class RpcPayload {
623
669
  case "blob":
624
670
  case "date":
625
671
  case "url":
672
+ case "regexp":
626
673
  case "error":
627
674
  case "undefined": return;
628
675
  case "array": {
@@ -631,6 +678,19 @@ var RpcPayload = class RpcPayload {
631
678
  for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
632
679
  return;
633
680
  }
681
+ case "set": {
682
+ let set = value;
683
+ for (let element of set) this.disposeImpl(element, set);
684
+ return;
685
+ }
686
+ case "map": {
687
+ let map = value;
688
+ for (let [key, val] of map) {
689
+ this.disposeImpl(key, map);
690
+ this.disposeImpl(val, map);
691
+ }
692
+ return;
693
+ }
634
694
  case "object": {
635
695
  let object = value;
636
696
  for (let i in object) this.disposeImpl(object[i], object);
@@ -706,6 +766,7 @@ var RpcPayload = class RpcPayload {
706
766
  case "writable":
707
767
  case "readable":
708
768
  case "url":
769
+ case "regexp":
709
770
  case "headers":
710
771
  case "request":
711
772
  case "response": return;
@@ -715,6 +776,19 @@ var RpcPayload = class RpcPayload {
715
776
  for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
716
777
  return;
717
778
  }
779
+ case "set": {
780
+ let set = value;
781
+ for (let element of set) this.ignoreUnhandledRejectionsImpl(element);
782
+ return;
783
+ }
784
+ case "map": {
785
+ let map = value;
786
+ for (let [key, val] of map) {
787
+ this.ignoreUnhandledRejectionsImpl(key);
788
+ this.ignoreUnhandledRejectionsImpl(val);
789
+ }
790
+ return;
791
+ }
718
792
  case "object": {
719
793
  let object = value;
720
794
  for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
@@ -774,8 +848,11 @@ function followPath(value, parent, path, owner) {
774
848
  case "bytes":
775
849
  case "blob":
776
850
  case "date":
851
+ case "set":
852
+ case "map":
777
853
  case "error":
778
854
  case "url":
855
+ case "regexp":
779
856
  case "headers":
780
857
  case "request":
781
858
  case "response":
@@ -821,7 +898,8 @@ var ValueStubHook = class extends StubHook {
821
898
  args.dispose();
822
899
  return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
823
900
  }
824
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
901
+ let promise = args.deliverCall(followResult.value, followResult.parent);
902
+ return new PromiseStubHook(promise.then((payload) => {
825
903
  return new PayloadStubHook(payload);
826
904
  }));
827
905
  }
@@ -1019,7 +1097,7 @@ const DEFAULT_MAX_DEPTH = 256;
1019
1097
  const DEFAULT_LIMITS = {
1020
1098
  maxBigIntDigits: 16384,
1021
1099
  maxDepth: 256,
1022
- maxMessageSize: 32 * 1024 * 1024
1100
+ maxMessageSize: 33554432
1023
1101
  };
1024
1102
  const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
1025
1103
  const BYTE_CONTAINER_TYPE_NAMES = [
@@ -1081,9 +1159,7 @@ function swapByteOrder(bytes, elementSize) {
1081
1159
  case 4:
1082
1160
  view.setUint32(offset, view.getUint32(offset, false), true);
1083
1161
  break;
1084
- case 8:
1085
- view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1086
- break;
1162
+ case 8: view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1087
1163
  }
1088
1164
  }
1089
1165
  var NullExporter = class {
@@ -1168,6 +1244,30 @@ var Devaluator = class Devaluator {
1168
1244
  for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
1169
1245
  return [result];
1170
1246
  }
1247
+ case "set": {
1248
+ let set = value;
1249
+ let setElements = [...set];
1250
+ let elements = [];
1251
+ for (let element of setElements) switch (typeForRpc(element)) {
1252
+ case "blob": throw new TypeError("Cannot serialize a Blob as an element of a Set.");
1253
+ case "rpc-promise":
1254
+ 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.");
1255
+ }
1256
+ for (let element of setElements) elements.push(this.devaluateImpl(element, set, depth + 1));
1257
+ return ["set", elements];
1258
+ }
1259
+ case "map": {
1260
+ let map = value;
1261
+ let mapEntries = [...map];
1262
+ let entries = [];
1263
+ for (let [key] of mapEntries) switch (typeForRpc(key)) {
1264
+ case "blob": throw new TypeError("Cannot serialize a Blob as a key of a Map.");
1265
+ case "rpc-promise":
1266
+ 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.");
1267
+ }
1268
+ for (let [key, val] of mapEntries) entries.push([this.devaluateImpl(key, map, depth + 1), this.devaluateImpl(val, map, depth + 1)]);
1269
+ return ["map", entries];
1270
+ }
1171
1271
  case "bigint":
1172
1272
  if (this.encodingLevel === "structuredClonable") return value;
1173
1273
  return ["bigint", value.toString()];
@@ -1176,6 +1276,15 @@ var Devaluator = class Devaluator {
1176
1276
  const time = value.getTime();
1177
1277
  return ["date", Number.isNaN(time) ? null : time];
1178
1278
  }
1279
+ case "regexp": {
1280
+ if (this.encodingLevel === "structuredClonable") return value;
1281
+ let re = value;
1282
+ return re.flags ? [
1283
+ "regexp",
1284
+ re.source,
1285
+ re.flags
1286
+ ] : ["regexp", re.source];
1287
+ }
1179
1288
  case "bytes": {
1180
1289
  let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1181
1290
  let bytes;
@@ -1190,11 +1299,14 @@ var Devaluator = class Devaluator {
1190
1299
  swapByteOrder(bytes, elementSize);
1191
1300
  }
1192
1301
  }
1193
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1194
- "bytes",
1195
- bytes,
1196
- alternateTypeName
1197
- ];
1302
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") {
1303
+ if (bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
1304
+ return alternateTypeName === void 0 ? ["bytes", bytes] : [
1305
+ "bytes",
1306
+ bytes,
1307
+ alternateTypeName
1308
+ ];
1309
+ }
1198
1310
  let b64;
1199
1311
  if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1200
1312
  else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
@@ -1333,13 +1445,16 @@ var Devaluator = class Devaluator {
1333
1445
  if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1334
1446
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
1335
1447
  let importId = this.exporter.getImport(hook);
1336
- if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [
1337
- "pipeline",
1338
- importId,
1339
- pathIfPromise
1340
- ];
1341
- else return ["pipeline", importId];
1342
- else return ["import", importId];
1448
+ if (importId !== void 0) {
1449
+ if (pathIfPromise) {
1450
+ if (pathIfPromise.length > 0) return [
1451
+ "pipeline",
1452
+ importId,
1453
+ pathIfPromise
1454
+ ];
1455
+ else return ["pipeline", importId];
1456
+ } else return ["import", importId];
1457
+ }
1343
1458
  if (pathIfPromise) hook = hook.get(pathIfPromise);
1344
1459
  else hook = hook.dup();
1345
1460
  return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
@@ -1400,16 +1515,18 @@ var NullImporter = class {
1400
1515
  };
1401
1516
  const NULL_IMPORTER = new NullImporter();
1402
1517
  function fixBrokenRequestBody(request, body) {
1403
- return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {
1518
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1404
1519
  let bytes = new Uint8Array(arrayBuffer);
1405
1520
  let result = new Request(request, { body: bytes });
1406
1521
  return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1407
- })), []);
1522
+ });
1523
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1408
1524
  }
1409
1525
  function streamToBlobPromise(stream, type) {
1410
- return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {
1526
+ let promise = streamToBlob(stream, type).then((blob) => {
1411
1527
  return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1412
- })), []);
1528
+ });
1529
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1413
1530
  }
1414
1531
  var Evaluator = class Evaluator {
1415
1532
  importer;
@@ -1442,7 +1559,7 @@ var Evaluator = class Evaluator {
1442
1559
  let maxDepth = this.limits.maxDepth;
1443
1560
  if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1444
1561
  if (this.encodingLevel === "structuredClonable") {
1445
- if (value instanceof Date || typeof value === "bigint") return value;
1562
+ if (value instanceof Date || value instanceof RegExp || typeof value === "bigint") return value;
1446
1563
  }
1447
1564
  if (value instanceof Array) {
1448
1565
  if (value.length == 1 && value[0] instanceof Array) {
@@ -1462,18 +1579,48 @@ var Evaluator = class Evaluator {
1462
1579
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1463
1580
  if (typeof value[1] == "number") return new Date(value[1]);
1464
1581
  break;
1582
+ case "regexp":
1583
+ if (typeof value[1] === "string" && (value.length === 2 || value.length === 3 && typeof value[2] === "string")) return new RegExp(value[1], value[2]);
1584
+ break;
1585
+ case "set":
1586
+ if (value.length === 2 && value[1] instanceof Array) {
1587
+ let elements = value[1];
1588
+ let set = /* @__PURE__ */ new Set();
1589
+ for (let i = 0; i < elements.length; i++) {
1590
+ let copy = this.evaluateImpl(elements[i], set, i, depth + 1);
1591
+ if (copy instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as an element of a Set.");
1592
+ set.add(copy);
1593
+ }
1594
+ return set;
1595
+ }
1596
+ break;
1597
+ case "map":
1598
+ if (value.length === 2 && value[1] instanceof Array) {
1599
+ let entries = value[1];
1600
+ let map = /* @__PURE__ */ new Map();
1601
+ for (let i = 0; i < entries.length; i++) {
1602
+ let entry = entries[i];
1603
+ if (!(entry instanceof Array) || entry.length !== 2) throw new TypeError("Map entries must be serialized as key/value pairs.");
1604
+ let key = this.evaluateImpl(entry[0], map, i, depth + 1);
1605
+ if (key instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as a key of a Map.");
1606
+ map.set(key, this.evaluateImpl(entry[1], map, mapKeyToPropertyName(key), depth + 1));
1607
+ }
1608
+ return map;
1609
+ }
1610
+ break;
1465
1611
  case "bytes": {
1466
1612
  let bytes;
1467
1613
  if (value[1] instanceof Uint8Array) bytes = value[1];
1468
- else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1469
- else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1470
- else {
1471
- let bs = atob(value[1]);
1472
- let len = bs.length;
1473
- bytes = new Uint8Array(len);
1474
- for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1475
- }
1476
- else break;
1614
+ else if (typeof value[1] == "string") {
1615
+ if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1616
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1617
+ else {
1618
+ let bs = atob(value[1]);
1619
+ let len = bs.length;
1620
+ bytes = new Uint8Array(len);
1621
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1622
+ }
1623
+ } else break;
1477
1624
  if (value.length === 2) return bytes;
1478
1625
  if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1479
1626
  if (!isValidByteContainerName(value[2])) {
@@ -1499,7 +1646,6 @@ var Evaluator = class Evaluator {
1499
1646
  case "BigUint64Array": return new BigUint64Array(buffer);
1500
1647
  case "Float32Array": return new Float32Array(buffer);
1501
1648
  case "Float64Array": return new Float64Array(buffer);
1502
- default:
1503
1649
  }
1504
1650
  }
1505
1651
  case "error":
@@ -1602,11 +1748,13 @@ var Evaluator = class Evaluator {
1602
1748
  return promise;
1603
1749
  } else {
1604
1750
  this.hooks.push(hook);
1605
- return new RpcPromise$1(hook, []);
1751
+ return new RpcStub$1(hook);
1606
1752
  }
1607
1753
  };
1608
- if (value.length == 2) if (isPromise) return addStub(hook.get([]));
1609
- else return addStub(hook.dup());
1754
+ if (value.length == 2) {
1755
+ if (isPromise) return addStub(hook.get([]));
1756
+ else return addStub(hook.dup());
1757
+ }
1610
1758
  let path = value[2];
1611
1759
  if (!(path instanceof Array)) break;
1612
1760
  if (!path.every((part) => {
@@ -1636,7 +1784,8 @@ var Evaluator = class Evaluator {
1636
1784
  }
1637
1785
  });
1638
1786
  let instructions = value[4];
1639
- let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);
1787
+ let resultHook = hook.map(path, captures, instructions);
1788
+ let promise = new RpcPromise$1(resultHook, []);
1640
1789
  this.promises.push({
1641
1790
  promise,
1642
1791
  parent,
@@ -1646,18 +1795,21 @@ var Evaluator = class Evaluator {
1646
1795
  }
1647
1796
  case "export":
1648
1797
  case "promise":
1649
- if (typeof value[1] == "number") if (value[0] == "promise") {
1650
- let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);
1651
- this.promises.push({
1652
- parent,
1653
- property,
1654
- promise
1655
- });
1656
- return promise;
1657
- } else {
1658
- let hook = this.importer.importStub(value[1]);
1659
- this.hooks.push(hook);
1660
- return new RpcStub$1(hook);
1798
+ if (typeof value[1] == "number") {
1799
+ if (value[0] == "promise") {
1800
+ let hook = this.importer.importPromise(value[1]);
1801
+ let promise = new RpcPromise$1(hook, []);
1802
+ this.promises.push({
1803
+ parent,
1804
+ property,
1805
+ promise
1806
+ });
1807
+ return promise;
1808
+ } else {
1809
+ let hook = this.importer.importStub(value[1]);
1810
+ this.hooks.push(hook);
1811
+ return new RpcStub$1(hook);
1812
+ }
1661
1813
  }
1662
1814
  break;
1663
1815
  case "writable":
@@ -1668,14 +1820,12 @@ var Evaluator = class Evaluator {
1668
1820
  return stream;
1669
1821
  }
1670
1822
  break;
1671
- case "readable":
1672
- if (typeof value[1] == "number") {
1673
- let stream = this.importer.getPipeReadable(value[1]);
1674
- let hook = streamImpl.createReadableStreamHook(stream);
1675
- this.hooks.push(hook);
1676
- return stream;
1677
- }
1678
- break;
1823
+ case "readable": if (typeof value[1] == "number") {
1824
+ let stream = this.importer.getPipeReadable(value[1]);
1825
+ let hook = streamImpl.createReadableStreamHook(stream);
1826
+ this.hooks.push(hook);
1827
+ return stream;
1828
+ }
1679
1829
  }
1680
1830
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1681
1831
  } else if (value instanceof Object) {
@@ -1720,6 +1870,7 @@ function estimateEncodedSize(value, seen, depth = 0) {
1720
1870
  if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1721
1871
  if (typeof Blob !== "undefined" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;
1722
1872
  if (value instanceof Date) return 16;
1873
+ if (value instanceof RegExp) return ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.source) + estimateStringSize(value.flags);
1723
1874
  seen ??= /* @__PURE__ */ new WeakSet();
1724
1875
  if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;
1725
1876
  seen.add(value);
@@ -1743,10 +1894,11 @@ function estimateEncodedSize(value, seen, depth = 0) {
1743
1894
  var ImportTableEntry = class {
1744
1895
  session;
1745
1896
  importId;
1897
+ pulling;
1746
1898
  constructor(session, importId, pulling) {
1747
1899
  this.session = session;
1748
1900
  this.importId = importId;
1749
- if (pulling) this.activePull = Promise.withResolvers();
1901
+ this.pulling = pulling;
1750
1902
  }
1751
1903
  localRefcount = 0;
1752
1904
  remoteRefcount = 1;
@@ -1777,7 +1929,7 @@ var ImportTableEntry = class {
1777
1929
  }
1778
1930
  async awaitResolution() {
1779
1931
  if (!this.activePull) {
1780
- this.session.sendPull(this.importId);
1932
+ if (!this.pulling) this.session.sendPull(this.importId);
1781
1933
  this.activePull = Promise.withResolvers();
1782
1934
  }
1783
1935
  await this.activePull.promise;
@@ -2007,6 +2159,7 @@ var RpcSessionImpl = class {
2007
2159
  let autoRelease = exp.autoRelease;
2008
2160
  ++this.pullCount;
2009
2161
  exp.pull = resolve().then((payload) => {
2162
+ if (this.exports[exportId] !== exp) return;
2010
2163
  let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);
2011
2164
  this.send([
2012
2165
  "resolve",
@@ -2015,6 +2168,7 @@ var RpcSessionImpl = class {
2015
2168
  ]);
2016
2169
  if (autoRelease) this.releaseExport(exportId, 1);
2017
2170
  }, (error) => {
2171
+ if (this.exports[exportId] !== exp) return;
2018
2172
  this.send([
2019
2173
  "reject",
2020
2174
  exportId,
@@ -2040,7 +2194,7 @@ var RpcSessionImpl = class {
2040
2194
  }
2041
2195
  }
2042
2196
  getImport(hook) {
2043
- if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;
2197
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this && !hook.entry.resolution) return hook.entry.importId;
2044
2198
  else return;
2045
2199
  }
2046
2200
  importStub(idx) {
@@ -2134,6 +2288,7 @@ var RpcSessionImpl = class {
2134
2288
  value.push(devalue[0]);
2135
2289
  }
2136
2290
  this.send(["push", value]);
2291
+ args?.dispose();
2137
2292
  let entry = new ImportTableEntry(this, this.imports.length, false);
2138
2293
  this.imports.push(entry);
2139
2294
  return new RpcImportHook(true, entry);
@@ -2158,6 +2313,7 @@ var RpcSessionImpl = class {
2158
2313
  value.push(devalue[0]);
2159
2314
  let msg = ["stream", value];
2160
2315
  let size = this.send(msg);
2316
+ args.dispose();
2161
2317
  if (size === void 0) size = estimateEncodedSize(msg);
2162
2318
  let importId = this.imports.length;
2163
2319
  let entry = new ImportTableEntry(this, importId, true);
@@ -2255,7 +2411,8 @@ var RpcSessionImpl = class {
2255
2411
  if (msg instanceof Array) switch (msg[0]) {
2256
2412
  case "push":
2257
2413
  if (msg.length > 1) {
2258
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2414
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2415
+ let hook = new PayloadStubHook(payload);
2259
2416
  hook.ignoreUnhandledRejections();
2260
2417
  this.exports.push({
2261
2418
  hook,
@@ -2266,7 +2423,8 @@ var RpcSessionImpl = class {
2266
2423
  break;
2267
2424
  case "stream":
2268
2425
  if (msg.length > 1) {
2269
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2426
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2427
+ let hook = new PayloadStubHook(payload);
2270
2428
  hook.ignoreUnhandledRejections();
2271
2429
  let exportId = this.exports.length;
2272
2430
  this.exports.push({
@@ -2301,13 +2459,14 @@ var RpcSessionImpl = class {
2301
2459
  let importId = msg[1];
2302
2460
  if (typeof importId == "number" && msg.length > 2) {
2303
2461
  let imp = this.imports[importId];
2304
- if (imp) if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2305
- else {
2306
- let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2307
- payload.dispose();
2308
- imp.resolve(new ErrorStubHook(payload.value));
2309
- }
2310
- else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2462
+ if (imp) {
2463
+ if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2464
+ else {
2465
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2466
+ payload.dispose();
2467
+ imp.resolve(new ErrorStubHook(payload.value));
2468
+ }
2469
+ } else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2311
2470
  continue;
2312
2471
  }
2313
2472
  break;
@@ -2379,7 +2538,8 @@ var RpcSession$1 = class {
2379
2538
  const MAX_CLOSE_REASON_BYTES = 123;
2380
2539
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2381
2540
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2382
- return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
2541
+ let transport = new WebSocketTransport(webSocket);
2542
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2383
2543
  }
2384
2544
  /**
2385
2545
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
@@ -2416,12 +2576,13 @@ var WebSocketTransport = class {
2416
2576
  });
2417
2577
  }
2418
2578
  webSocket.addEventListener("message", (event) => {
2419
- if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {
2420
- this.#receiveResolver(event.data);
2421
- this.#receiveResolver = void 0;
2422
- this.#receiveRejecter = void 0;
2423
- } else this.#receiveQueue.push(event.data);
2424
- else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2579
+ if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) {
2580
+ if (this.#receiveResolver) {
2581
+ this.#receiveResolver(event.data);
2582
+ this.#receiveResolver = void 0;
2583
+ this.#receiveRejecter = void 0;
2584
+ } else this.#receiveQueue.push(event.data);
2585
+ } else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2425
2586
  });
2426
2587
  webSocket.addEventListener("close", (event) => {
2427
2588
  this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
@@ -2513,7 +2674,8 @@ function newHttpBatchRpcSession$1(urlOrRequest, options) {
2513
2674
  let body = await response.text();
2514
2675
  return body == "" ? [] : body.split("\n");
2515
2676
  };
2516
- return new RpcSession$1(new BatchClientTransport(sendBatch), void 0, options).getRemoteMain();
2677
+ let transport = new BatchClientTransport(sendBatch);
2678
+ return new RpcSession$1(transport, void 0, options).getRemoteMain();
2517
2679
  }
2518
2680
  var BatchServerTransport = class {
2519
2681
  constructor(batch) {
@@ -2556,7 +2718,8 @@ var BatchServerTransport = class {
2556
2718
  async function newHttpBatchRpcResponse(request, localMain, options) {
2557
2719
  if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
2558
2720
  let body = await request.text();
2559
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2721
+ let batch = body === "" ? [] : body.split("\n");
2722
+ let transport = new BatchServerTransport(batch);
2560
2723
  let rpc = new RpcSession$1(transport, localMain, options);
2561
2724
  await transport.whenAllReceived();
2562
2725
  await rpc.drain();
@@ -2586,7 +2749,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2586
2749
  });
2587
2750
  request.on("error", reject);
2588
2751
  });
2589
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2752
+ let batch = body === "" ? [] : body.split("\n");
2753
+ let transport = new BatchServerTransport(batch);
2590
2754
  let rpc = new RpcSession$1(transport, localMain, options);
2591
2755
  await transport.whenAllReceived();
2592
2756
  await rpc.drain();
@@ -2597,7 +2761,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2597
2761
  //#endregion
2598
2762
  //#region src/messageport.ts
2599
2763
  function newMessagePortRpcSession$1(port, localMain, options) {
2600
- return new RpcSession$1(new MessagePortTransport(port), localMain, options).getRemoteMain();
2764
+ let transport = new MessagePortTransport(port);
2765
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2601
2766
  }
2602
2767
  var MessagePortTransport = class {
2603
2768
  encodingLevel = "structuredClonable";
@@ -2847,7 +3012,8 @@ var MapApplicator = class {
2847
3012
  }
2848
3013
  };
2849
3014
  function applyMapToElement(input, parent, owner, captures, instructions) {
2850
- let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
3015
+ let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
3016
+ let mapper = new MapApplicator(captures, inputHook);
2851
3017
  try {
2852
3018
  return mapper.apply(instructions);
2853
3019
  } finally {
@@ -2880,9 +3046,10 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2880
3046
  var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2881
3047
  state;
2882
3048
  static create(stream) {
3049
+ let writer = stream.getWriter();
2883
3050
  return new WritableStreamStubHook({
2884
3051
  refcount: 1,
2885
- writer: stream.getWriter(),
3052
+ writer,
2886
3053
  closed: false
2887
3054
  });
2888
3055
  }
@@ -2902,7 +3069,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2902
3069
  const method = path[0];
2903
3070
  if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2904
3071
  if (method === "close" || method === "abort") state.closed = true;
2905
- return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
3072
+ let promise = method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer);
3073
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2906
3074
  } catch (err) {
2907
3075
  args.dispose();
2908
3076
  return new ErrorStubHook(err);
@@ -2916,7 +3084,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2916
3084
  return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a WritableStream stub"));
2917
3085
  }
2918
3086
  dup() {
2919
- return new WritableStreamStubHook(this.getState(), this);
3087
+ let state = this.getState();
3088
+ return new WritableStreamStubHook(state, this);
2920
3089
  }
2921
3090
  pull() {
2922
3091
  return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a WritableStream stub"));
@@ -2934,9 +3103,9 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2934
3103
  }
2935
3104
  onBroken(callback) {}
2936
3105
  };
2937
- const INITIAL_WINDOW = 256 * 1024;
2938
- const MAX_WINDOW = 1024 * 1024 * 1024;
2939
- const MIN_WINDOW = 64 * 1024;
3106
+ const INITIAL_WINDOW = 262144;
3107
+ const MAX_WINDOW = 1073741824;
3108
+ const MIN_WINDOW = 65536;
2940
3109
  const STARTUP_GROWTH_FACTOR = 2;
2941
3110
  const STEADY_GROWTH_FACTOR = 1.25;
2942
3111
  const DECAY_FACTOR = .9;