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.
package/dist/index-bun.js CHANGED
@@ -40,6 +40,9 @@ function typeForRpc(value) {
40
40
  case AsyncFunction.prototype: return "function";
41
41
  case Array.prototype: return "array";
42
42
  case Date.prototype: return "date";
43
+ case RegExp.prototype: return "regexp";
44
+ case Set.prototype: return "set";
45
+ case Map.prototype: return "map";
43
46
  case Uint8Array.prototype:
44
47
  case BUFFER_PROTOTYPE:
45
48
  case ArrayBuffer.prototype:
@@ -303,6 +306,9 @@ async function pullPromise(promise) {
303
306
  if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);
304
307
  return (await hook.pull()).deliverResolve();
305
308
  }
309
+ function mapKeyToPropertyName(key) {
310
+ return typeof key === "string" || typeof key === "number" ? key : { mapKey: key };
311
+ }
306
312
  var RpcPayload = class RpcPayload {
307
313
  value;
308
314
  source;
@@ -357,12 +363,13 @@ var RpcPayload = class RpcPayload {
357
363
  return TargetStubHook.create(target, parent);
358
364
  } else if (this.source === "return") {
359
365
  let hook = this.rpcTargets?.get(target);
360
- if (hook) if (dupStubs) return hook.dup();
361
- else {
362
- this.rpcTargets?.delete(target);
363
- return hook;
364
- }
365
- else {
366
+ if (hook) {
367
+ if (dupStubs) return hook.dup();
368
+ else {
369
+ this.rpcTargets?.delete(target);
370
+ return hook;
371
+ }
372
+ } else {
366
373
  hook = TargetStubHook.create(target, parent);
367
374
  if (dupStubs) {
368
375
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -376,12 +383,13 @@ var RpcPayload = class RpcPayload {
376
383
  if (this.source === "params") return streamImpl.createWritableStreamHook(stream);
377
384
  else if (this.source === "return") {
378
385
  let hook = this.rpcTargets?.get(stream);
379
- if (hook) if (dupStubs) return hook.dup();
380
- else {
381
- this.rpcTargets?.delete(stream);
382
- return hook;
383
- }
384
- else {
386
+ if (hook) {
387
+ if (dupStubs) return hook.dup();
388
+ else {
389
+ this.rpcTargets?.delete(stream);
390
+ return hook;
391
+ }
392
+ } else {
385
393
  hook = streamImpl.createWritableStreamHook(stream);
386
394
  if (dupStubs) {
387
395
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -395,12 +403,13 @@ var RpcPayload = class RpcPayload {
395
403
  if (this.source === "params") return streamImpl.createReadableStreamHook(stream);
396
404
  else if (this.source === "return") {
397
405
  let hook = this.rpcTargets?.get(stream);
398
- if (hook) if (dupStubs) return hook.dup();
399
- else {
400
- this.rpcTargets?.delete(stream);
401
- return hook;
402
- }
403
- else {
406
+ if (hook) {
407
+ if (dupStubs) return hook.dup();
408
+ else {
409
+ this.rpcTargets?.delete(stream);
410
+ return hook;
411
+ }
412
+ } else {
404
413
  hook = streamImpl.createReadableStreamHook(stream);
405
414
  if (dupStubs) {
406
415
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -408,7 +417,7 @@ var RpcPayload = class RpcPayload {
408
417
  return hook.dup();
409
418
  } else return hook;
410
419
  }
411
- } else throw new Error("owned payload shouldn't contain raw ReadableStreams");
420
+ } else return streamImpl.createReadableStreamHook(stream);
412
421
  }
413
422
  deepCopy(value, oldParent, property, parent, dupStubs, owner) {
414
423
  switch (typeForRpc(value)) {
@@ -419,6 +428,7 @@ var RpcPayload = class RpcPayload {
419
428
  case "bytes":
420
429
  case "blob":
421
430
  case "url":
431
+ case "regexp":
422
432
  case "error":
423
433
  case "undefined": return value;
424
434
  case "array": {
@@ -428,6 +438,35 @@ var RpcPayload = class RpcPayload {
428
438
  for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
429
439
  return result;
430
440
  }
441
+ case "set": {
442
+ let set = value;
443
+ let elements = [...set];
444
+ for (let val of elements) {
445
+ let kind = typeForRpc(val);
446
+ 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.");
447
+ }
448
+ let result = /* @__PURE__ */ new Set();
449
+ let index = 0;
450
+ for (let val of elements) {
451
+ let copy = this.deepCopy(val, set, index++, result, dupStubs, owner);
452
+ result.add(copy);
453
+ }
454
+ return result;
455
+ }
456
+ case "map": {
457
+ let map = value;
458
+ let entries = [...map];
459
+ for (let [key] of entries) {
460
+ let kind = typeForRpc(key);
461
+ 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.");
462
+ }
463
+ let result = /* @__PURE__ */ new Map();
464
+ for (let [key, val] of entries) {
465
+ let keyCopy = this.deepCopy(key, map, -1, result, dupStubs, owner);
466
+ result.set(keyCopy, this.deepCopy(val, map, mapKeyToPropertyName(keyCopy), result, dupStubs, owner));
467
+ }
468
+ return result;
469
+ }
431
470
  case "object": {
432
471
  let result = {};
433
472
  let object = value;
@@ -485,8 +524,10 @@ var RpcPayload = class RpcPayload {
485
524
  case "readable": {
486
525
  let stream = value;
487
526
  let hook;
488
- if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
489
- else hook = streamImpl.createReadableStreamHook(stream);
527
+ if (owner) {
528
+ if (owner.source === "owned") throw new Error("Can't copy a ReadableStream.");
529
+ hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
530
+ } else hook = streamImpl.createReadableStreamHook(stream);
490
531
  this.hooks.push(hook);
491
532
  return stream;
492
533
  }
@@ -512,6 +553,10 @@ var RpcPayload = class RpcPayload {
512
553
  try {
513
554
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
514
555
  } catch (err) {
556
+ if (dupStubs) {
557
+ this.hooks.forEach((hook) => hook.dispose());
558
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
559
+ }
515
560
  this.hooks = void 0;
516
561
  this.promises = void 0;
517
562
  throw err;
@@ -525,7 +570,8 @@ var RpcPayload = class RpcPayload {
525
570
  this.ensureDeepCopied();
526
571
  if (this.value instanceof RpcPromise$1) RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);
527
572
  else {
528
- parent[property] = this.value;
573
+ if (parent instanceof Map) parent.set(typeof property === "object" ? property.mapKey : property, this.value);
574
+ else parent[property] = this.value;
529
575
  for (let record of this.promises) RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);
530
576
  }
531
577
  }
@@ -617,6 +663,7 @@ var RpcPayload = class RpcPayload {
617
663
  case "blob":
618
664
  case "date":
619
665
  case "url":
666
+ case "regexp":
620
667
  case "error":
621
668
  case "undefined": return;
622
669
  case "array": {
@@ -625,6 +672,19 @@ var RpcPayload = class RpcPayload {
625
672
  for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
626
673
  return;
627
674
  }
675
+ case "set": {
676
+ let set = value;
677
+ for (let element of set) this.disposeImpl(element, set);
678
+ return;
679
+ }
680
+ case "map": {
681
+ let map = value;
682
+ for (let [key, val] of map) {
683
+ this.disposeImpl(key, map);
684
+ this.disposeImpl(val, map);
685
+ }
686
+ return;
687
+ }
628
688
  case "object": {
629
689
  let object = value;
630
690
  for (let i in object) this.disposeImpl(object[i], object);
@@ -700,6 +760,7 @@ var RpcPayload = class RpcPayload {
700
760
  case "writable":
701
761
  case "readable":
702
762
  case "url":
763
+ case "regexp":
703
764
  case "headers":
704
765
  case "request":
705
766
  case "response": return;
@@ -709,6 +770,19 @@ var RpcPayload = class RpcPayload {
709
770
  for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
710
771
  return;
711
772
  }
773
+ case "set": {
774
+ let set = value;
775
+ for (let element of set) this.ignoreUnhandledRejectionsImpl(element);
776
+ return;
777
+ }
778
+ case "map": {
779
+ let map = value;
780
+ for (let [key, val] of map) {
781
+ this.ignoreUnhandledRejectionsImpl(key);
782
+ this.ignoreUnhandledRejectionsImpl(val);
783
+ }
784
+ return;
785
+ }
712
786
  case "object": {
713
787
  let object = value;
714
788
  for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
@@ -768,8 +842,11 @@ function followPath(value, parent, path, owner) {
768
842
  case "bytes":
769
843
  case "blob":
770
844
  case "date":
845
+ case "set":
846
+ case "map":
771
847
  case "error":
772
848
  case "url":
849
+ case "regexp":
773
850
  case "headers":
774
851
  case "request":
775
852
  case "response":
@@ -815,7 +892,8 @@ var ValueStubHook = class extends StubHook {
815
892
  args.dispose();
816
893
  return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
817
894
  }
818
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
895
+ let promise = args.deliverCall(followResult.value, followResult.parent);
896
+ return new PromiseStubHook(promise.then((payload) => {
819
897
  return new PayloadStubHook(payload);
820
898
  }));
821
899
  }
@@ -1013,7 +1091,7 @@ const DEFAULT_MAX_DEPTH = 256;
1013
1091
  const DEFAULT_LIMITS = {
1014
1092
  maxBigIntDigits: 16384,
1015
1093
  maxDepth: 256,
1016
- maxMessageSize: 32 * 1024 * 1024
1094
+ maxMessageSize: 33554432
1017
1095
  };
1018
1096
  const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
1019
1097
  const BYTE_CONTAINER_TYPE_NAMES = [
@@ -1075,9 +1153,7 @@ function swapByteOrder(bytes, elementSize) {
1075
1153
  case 4:
1076
1154
  view.setUint32(offset, view.getUint32(offset, false), true);
1077
1155
  break;
1078
- case 8:
1079
- view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1080
- break;
1156
+ case 8: view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1081
1157
  }
1082
1158
  }
1083
1159
  var NullExporter = class {
@@ -1162,6 +1238,30 @@ var Devaluator = class Devaluator {
1162
1238
  for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
1163
1239
  return [result];
1164
1240
  }
1241
+ case "set": {
1242
+ let set = value;
1243
+ let setElements = [...set];
1244
+ let elements = [];
1245
+ for (let element of setElements) switch (typeForRpc(element)) {
1246
+ case "blob": throw new TypeError("Cannot serialize a Blob as an element of a Set.");
1247
+ case "rpc-promise":
1248
+ 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.");
1249
+ }
1250
+ for (let element of setElements) elements.push(this.devaluateImpl(element, set, depth + 1));
1251
+ return ["set", elements];
1252
+ }
1253
+ case "map": {
1254
+ let map = value;
1255
+ let mapEntries = [...map];
1256
+ let entries = [];
1257
+ for (let [key] of mapEntries) switch (typeForRpc(key)) {
1258
+ case "blob": throw new TypeError("Cannot serialize a Blob as a key of a Map.");
1259
+ case "rpc-promise":
1260
+ 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.");
1261
+ }
1262
+ for (let [key, val] of mapEntries) entries.push([this.devaluateImpl(key, map, depth + 1), this.devaluateImpl(val, map, depth + 1)]);
1263
+ return ["map", entries];
1264
+ }
1165
1265
  case "bigint":
1166
1266
  if (this.encodingLevel === "structuredClonable") return value;
1167
1267
  return ["bigint", value.toString()];
@@ -1170,6 +1270,15 @@ var Devaluator = class Devaluator {
1170
1270
  const time = value.getTime();
1171
1271
  return ["date", Number.isNaN(time) ? null : time];
1172
1272
  }
1273
+ case "regexp": {
1274
+ if (this.encodingLevel === "structuredClonable") return value;
1275
+ let re = value;
1276
+ return re.flags ? [
1277
+ "regexp",
1278
+ re.source,
1279
+ re.flags
1280
+ ] : ["regexp", re.source];
1281
+ }
1173
1282
  case "bytes": {
1174
1283
  let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1175
1284
  let bytes;
@@ -1184,11 +1293,14 @@ var Devaluator = class Devaluator {
1184
1293
  swapByteOrder(bytes, elementSize);
1185
1294
  }
1186
1295
  }
1187
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1188
- "bytes",
1189
- bytes,
1190
- alternateTypeName
1191
- ];
1296
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") {
1297
+ if (bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
1298
+ return alternateTypeName === void 0 ? ["bytes", bytes] : [
1299
+ "bytes",
1300
+ bytes,
1301
+ alternateTypeName
1302
+ ];
1303
+ }
1192
1304
  let b64;
1193
1305
  if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1194
1306
  else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
@@ -1327,13 +1439,16 @@ var Devaluator = class Devaluator {
1327
1439
  if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1328
1440
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
1329
1441
  let importId = this.exporter.getImport(hook);
1330
- if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [
1331
- "pipeline",
1332
- importId,
1333
- pathIfPromise
1334
- ];
1335
- else return ["pipeline", importId];
1336
- else return ["import", importId];
1442
+ if (importId !== void 0) {
1443
+ if (pathIfPromise) {
1444
+ if (pathIfPromise.length > 0) return [
1445
+ "pipeline",
1446
+ importId,
1447
+ pathIfPromise
1448
+ ];
1449
+ else return ["pipeline", importId];
1450
+ } else return ["import", importId];
1451
+ }
1337
1452
  if (pathIfPromise) hook = hook.get(pathIfPromise);
1338
1453
  else hook = hook.dup();
1339
1454
  return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
@@ -1394,16 +1509,18 @@ var NullImporter = class {
1394
1509
  };
1395
1510
  const NULL_IMPORTER = new NullImporter();
1396
1511
  function fixBrokenRequestBody(request, body) {
1397
- return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {
1512
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1398
1513
  let bytes = new Uint8Array(arrayBuffer);
1399
1514
  let result = new Request(request, { body: bytes });
1400
1515
  return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1401
- })), []);
1516
+ });
1517
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1402
1518
  }
1403
1519
  function streamToBlobPromise(stream, type) {
1404
- return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {
1520
+ let promise = streamToBlob(stream, type).then((blob) => {
1405
1521
  return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1406
- })), []);
1522
+ });
1523
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1407
1524
  }
1408
1525
  var Evaluator = class Evaluator {
1409
1526
  importer;
@@ -1436,7 +1553,7 @@ var Evaluator = class Evaluator {
1436
1553
  let maxDepth = this.limits.maxDepth;
1437
1554
  if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1438
1555
  if (this.encodingLevel === "structuredClonable") {
1439
- if (value instanceof Date || typeof value === "bigint") return value;
1556
+ if (value instanceof Date || value instanceof RegExp || typeof value === "bigint") return value;
1440
1557
  }
1441
1558
  if (value instanceof Array) {
1442
1559
  if (value.length == 1 && value[0] instanceof Array) {
@@ -1456,18 +1573,48 @@ var Evaluator = class Evaluator {
1456
1573
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1457
1574
  if (typeof value[1] == "number") return new Date(value[1]);
1458
1575
  break;
1576
+ case "regexp":
1577
+ if (typeof value[1] === "string" && (value.length === 2 || value.length === 3 && typeof value[2] === "string")) return new RegExp(value[1], value[2]);
1578
+ break;
1579
+ case "set":
1580
+ if (value.length === 2 && value[1] instanceof Array) {
1581
+ let elements = value[1];
1582
+ let set = /* @__PURE__ */ new Set();
1583
+ for (let i = 0; i < elements.length; i++) {
1584
+ let copy = this.evaluateImpl(elements[i], set, i, depth + 1);
1585
+ if (copy instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as an element of a Set.");
1586
+ set.add(copy);
1587
+ }
1588
+ return set;
1589
+ }
1590
+ break;
1591
+ case "map":
1592
+ if (value.length === 2 && value[1] instanceof Array) {
1593
+ let entries = value[1];
1594
+ let map = /* @__PURE__ */ new Map();
1595
+ for (let i = 0; i < entries.length; i++) {
1596
+ let entry = entries[i];
1597
+ if (!(entry instanceof Array) || entry.length !== 2) throw new TypeError("Map entries must be serialized as key/value pairs.");
1598
+ let key = this.evaluateImpl(entry[0], map, i, depth + 1);
1599
+ if (key instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as a key of a Map.");
1600
+ map.set(key, this.evaluateImpl(entry[1], map, mapKeyToPropertyName(key), depth + 1));
1601
+ }
1602
+ return map;
1603
+ }
1604
+ break;
1459
1605
  case "bytes": {
1460
1606
  let bytes;
1461
1607
  if (value[1] instanceof Uint8Array) bytes = value[1];
1462
- else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1463
- else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1464
- else {
1465
- let bs = atob(value[1]);
1466
- let len = bs.length;
1467
- bytes = new Uint8Array(len);
1468
- for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1469
- }
1470
- else break;
1608
+ else if (typeof value[1] == "string") {
1609
+ if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1610
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1611
+ else {
1612
+ let bs = atob(value[1]);
1613
+ let len = bs.length;
1614
+ bytes = new Uint8Array(len);
1615
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1616
+ }
1617
+ } else break;
1471
1618
  if (value.length === 2) return bytes;
1472
1619
  if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1473
1620
  if (!isValidByteContainerName(value[2])) {
@@ -1493,7 +1640,6 @@ var Evaluator = class Evaluator {
1493
1640
  case "BigUint64Array": return new BigUint64Array(buffer);
1494
1641
  case "Float32Array": return new Float32Array(buffer);
1495
1642
  case "Float64Array": return new Float64Array(buffer);
1496
- default:
1497
1643
  }
1498
1644
  }
1499
1645
  case "error":
@@ -1596,11 +1742,13 @@ var Evaluator = class Evaluator {
1596
1742
  return promise;
1597
1743
  } else {
1598
1744
  this.hooks.push(hook);
1599
- return new RpcPromise$1(hook, []);
1745
+ return new RpcStub$1(hook);
1600
1746
  }
1601
1747
  };
1602
- if (value.length == 2) if (isPromise) return addStub(hook.get([]));
1603
- else return addStub(hook.dup());
1748
+ if (value.length == 2) {
1749
+ if (isPromise) return addStub(hook.get([]));
1750
+ else return addStub(hook.dup());
1751
+ }
1604
1752
  let path = value[2];
1605
1753
  if (!(path instanceof Array)) break;
1606
1754
  if (!path.every((part) => {
@@ -1630,7 +1778,8 @@ var Evaluator = class Evaluator {
1630
1778
  }
1631
1779
  });
1632
1780
  let instructions = value[4];
1633
- let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);
1781
+ let resultHook = hook.map(path, captures, instructions);
1782
+ let promise = new RpcPromise$1(resultHook, []);
1634
1783
  this.promises.push({
1635
1784
  promise,
1636
1785
  parent,
@@ -1640,18 +1789,21 @@ var Evaluator = class Evaluator {
1640
1789
  }
1641
1790
  case "export":
1642
1791
  case "promise":
1643
- if (typeof value[1] == "number") if (value[0] == "promise") {
1644
- let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);
1645
- this.promises.push({
1646
- parent,
1647
- property,
1648
- promise
1649
- });
1650
- return promise;
1651
- } else {
1652
- let hook = this.importer.importStub(value[1]);
1653
- this.hooks.push(hook);
1654
- return new RpcStub$1(hook);
1792
+ if (typeof value[1] == "number") {
1793
+ if (value[0] == "promise") {
1794
+ let hook = this.importer.importPromise(value[1]);
1795
+ let promise = new RpcPromise$1(hook, []);
1796
+ this.promises.push({
1797
+ parent,
1798
+ property,
1799
+ promise
1800
+ });
1801
+ return promise;
1802
+ } else {
1803
+ let hook = this.importer.importStub(value[1]);
1804
+ this.hooks.push(hook);
1805
+ return new RpcStub$1(hook);
1806
+ }
1655
1807
  }
1656
1808
  break;
1657
1809
  case "writable":
@@ -1662,14 +1814,12 @@ var Evaluator = class Evaluator {
1662
1814
  return stream;
1663
1815
  }
1664
1816
  break;
1665
- case "readable":
1666
- if (typeof value[1] == "number") {
1667
- let stream = this.importer.getPipeReadable(value[1]);
1668
- let hook = streamImpl.createReadableStreamHook(stream);
1669
- this.hooks.push(hook);
1670
- return stream;
1671
- }
1672
- break;
1817
+ case "readable": if (typeof value[1] == "number") {
1818
+ let stream = this.importer.getPipeReadable(value[1]);
1819
+ let hook = streamImpl.createReadableStreamHook(stream);
1820
+ this.hooks.push(hook);
1821
+ return stream;
1822
+ }
1673
1823
  }
1674
1824
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1675
1825
  } else if (value instanceof Object) {
@@ -1714,6 +1864,7 @@ function estimateEncodedSize(value, seen, depth = 0) {
1714
1864
  if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1715
1865
  if (typeof Blob !== "undefined" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;
1716
1866
  if (value instanceof Date) return 16;
1867
+ if (value instanceof RegExp) return ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.source) + estimateStringSize(value.flags);
1717
1868
  seen ??= /* @__PURE__ */ new WeakSet();
1718
1869
  if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;
1719
1870
  seen.add(value);
@@ -1737,10 +1888,11 @@ function estimateEncodedSize(value, seen, depth = 0) {
1737
1888
  var ImportTableEntry = class {
1738
1889
  session;
1739
1890
  importId;
1891
+ pulling;
1740
1892
  constructor(session, importId, pulling) {
1741
1893
  this.session = session;
1742
1894
  this.importId = importId;
1743
- if (pulling) this.activePull = Promise.withResolvers();
1895
+ this.pulling = pulling;
1744
1896
  }
1745
1897
  localRefcount = 0;
1746
1898
  remoteRefcount = 1;
@@ -1771,7 +1923,7 @@ var ImportTableEntry = class {
1771
1923
  }
1772
1924
  async awaitResolution() {
1773
1925
  if (!this.activePull) {
1774
- this.session.sendPull(this.importId);
1926
+ if (!this.pulling) this.session.sendPull(this.importId);
1775
1927
  this.activePull = Promise.withResolvers();
1776
1928
  }
1777
1929
  await this.activePull.promise;
@@ -2001,6 +2153,7 @@ var RpcSessionImpl = class {
2001
2153
  let autoRelease = exp.autoRelease;
2002
2154
  ++this.pullCount;
2003
2155
  exp.pull = resolve().then((payload) => {
2156
+ if (this.exports[exportId] !== exp) return;
2004
2157
  let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);
2005
2158
  this.send([
2006
2159
  "resolve",
@@ -2009,6 +2162,7 @@ var RpcSessionImpl = class {
2009
2162
  ]);
2010
2163
  if (autoRelease) this.releaseExport(exportId, 1);
2011
2164
  }, (error) => {
2165
+ if (this.exports[exportId] !== exp) return;
2012
2166
  this.send([
2013
2167
  "reject",
2014
2168
  exportId,
@@ -2034,7 +2188,7 @@ var RpcSessionImpl = class {
2034
2188
  }
2035
2189
  }
2036
2190
  getImport(hook) {
2037
- if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;
2191
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this && !hook.entry.resolution) return hook.entry.importId;
2038
2192
  else return;
2039
2193
  }
2040
2194
  importStub(idx) {
@@ -2128,6 +2282,7 @@ var RpcSessionImpl = class {
2128
2282
  value.push(devalue[0]);
2129
2283
  }
2130
2284
  this.send(["push", value]);
2285
+ args?.dispose();
2131
2286
  let entry = new ImportTableEntry(this, this.imports.length, false);
2132
2287
  this.imports.push(entry);
2133
2288
  return new RpcImportHook(true, entry);
@@ -2152,6 +2307,7 @@ var RpcSessionImpl = class {
2152
2307
  value.push(devalue[0]);
2153
2308
  let msg = ["stream", value];
2154
2309
  let size = this.send(msg);
2310
+ args.dispose();
2155
2311
  if (size === void 0) size = estimateEncodedSize(msg);
2156
2312
  let importId = this.imports.length;
2157
2313
  let entry = new ImportTableEntry(this, importId, true);
@@ -2249,7 +2405,8 @@ var RpcSessionImpl = class {
2249
2405
  if (msg instanceof Array) switch (msg[0]) {
2250
2406
  case "push":
2251
2407
  if (msg.length > 1) {
2252
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2408
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2409
+ let hook = new PayloadStubHook(payload);
2253
2410
  hook.ignoreUnhandledRejections();
2254
2411
  this.exports.push({
2255
2412
  hook,
@@ -2260,7 +2417,8 @@ var RpcSessionImpl = class {
2260
2417
  break;
2261
2418
  case "stream":
2262
2419
  if (msg.length > 1) {
2263
- let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2420
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2421
+ let hook = new PayloadStubHook(payload);
2264
2422
  hook.ignoreUnhandledRejections();
2265
2423
  let exportId = this.exports.length;
2266
2424
  this.exports.push({
@@ -2295,13 +2453,14 @@ var RpcSessionImpl = class {
2295
2453
  let importId = msg[1];
2296
2454
  if (typeof importId == "number" && msg.length > 2) {
2297
2455
  let imp = this.imports[importId];
2298
- if (imp) if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2299
- else {
2300
- let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2301
- payload.dispose();
2302
- imp.resolve(new ErrorStubHook(payload.value));
2303
- }
2304
- else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2456
+ if (imp) {
2457
+ if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2458
+ else {
2459
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2460
+ payload.dispose();
2461
+ imp.resolve(new ErrorStubHook(payload.value));
2462
+ }
2463
+ } else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2305
2464
  continue;
2306
2465
  }
2307
2466
  break;
@@ -2373,7 +2532,8 @@ var RpcSession$1 = class {
2373
2532
  const MAX_CLOSE_REASON_BYTES = 123;
2374
2533
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2375
2534
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2376
- return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
2535
+ let transport = new WebSocketTransport(webSocket);
2536
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2377
2537
  }
2378
2538
  /**
2379
2539
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
@@ -2410,12 +2570,13 @@ var WebSocketTransport = class {
2410
2570
  });
2411
2571
  }
2412
2572
  webSocket.addEventListener("message", (event) => {
2413
- if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {
2414
- this.#receiveResolver(event.data);
2415
- this.#receiveResolver = void 0;
2416
- this.#receiveRejecter = void 0;
2417
- } else this.#receiveQueue.push(event.data);
2418
- else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2573
+ if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) {
2574
+ if (this.#receiveResolver) {
2575
+ this.#receiveResolver(event.data);
2576
+ this.#receiveResolver = void 0;
2577
+ this.#receiveRejecter = void 0;
2578
+ } else this.#receiveQueue.push(event.data);
2579
+ } else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2419
2580
  });
2420
2581
  webSocket.addEventListener("close", (event) => {
2421
2582
  this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
@@ -2507,7 +2668,8 @@ function newHttpBatchRpcSession$1(urlOrRequest, options) {
2507
2668
  let body = await response.text();
2508
2669
  return body == "" ? [] : body.split("\n");
2509
2670
  };
2510
- return new RpcSession$1(new BatchClientTransport(sendBatch), void 0, options).getRemoteMain();
2671
+ let transport = new BatchClientTransport(sendBatch);
2672
+ return new RpcSession$1(transport, void 0, options).getRemoteMain();
2511
2673
  }
2512
2674
  var BatchServerTransport = class {
2513
2675
  constructor(batch) {
@@ -2550,7 +2712,8 @@ var BatchServerTransport = class {
2550
2712
  async function newHttpBatchRpcResponse(request, localMain, options) {
2551
2713
  if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
2552
2714
  let body = await request.text();
2553
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2715
+ let batch = body === "" ? [] : body.split("\n");
2716
+ let transport = new BatchServerTransport(batch);
2554
2717
  let rpc = new RpcSession$1(transport, localMain, options);
2555
2718
  await transport.whenAllReceived();
2556
2719
  await rpc.drain();
@@ -2580,7 +2743,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2580
2743
  });
2581
2744
  request.on("error", reject);
2582
2745
  });
2583
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2746
+ let batch = body === "" ? [] : body.split("\n");
2747
+ let transport = new BatchServerTransport(batch);
2584
2748
  let rpc = new RpcSession$1(transport, localMain, options);
2585
2749
  await transport.whenAllReceived();
2586
2750
  await rpc.drain();
@@ -2591,7 +2755,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2591
2755
  //#endregion
2592
2756
  //#region src/messageport.ts
2593
2757
  function newMessagePortRpcSession$1(port, localMain, options) {
2594
- return new RpcSession$1(new MessagePortTransport(port), localMain, options).getRemoteMain();
2758
+ let transport = new MessagePortTransport(port);
2759
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2595
2760
  }
2596
2761
  var MessagePortTransport = class {
2597
2762
  encodingLevel = "structuredClonable";
@@ -2841,7 +3006,8 @@ var MapApplicator = class {
2841
3006
  }
2842
3007
  };
2843
3008
  function applyMapToElement(input, parent, owner, captures, instructions) {
2844
- let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
3009
+ let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
3010
+ let mapper = new MapApplicator(captures, inputHook);
2845
3011
  try {
2846
3012
  return mapper.apply(instructions);
2847
3013
  } finally {
@@ -2874,9 +3040,10 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2874
3040
  var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2875
3041
  state;
2876
3042
  static create(stream) {
3043
+ let writer = stream.getWriter();
2877
3044
  return new WritableStreamStubHook({
2878
3045
  refcount: 1,
2879
- writer: stream.getWriter(),
3046
+ writer,
2880
3047
  closed: false
2881
3048
  });
2882
3049
  }
@@ -2896,7 +3063,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2896
3063
  const method = path[0];
2897
3064
  if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2898
3065
  if (method === "close" || method === "abort") state.closed = true;
2899
- return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
3066
+ let promise = method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer);
3067
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2900
3068
  } catch (err) {
2901
3069
  args.dispose();
2902
3070
  return new ErrorStubHook(err);
@@ -2910,7 +3078,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2910
3078
  return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a WritableStream stub"));
2911
3079
  }
2912
3080
  dup() {
2913
- return new WritableStreamStubHook(this.getState(), this);
3081
+ let state = this.getState();
3082
+ return new WritableStreamStubHook(state, this);
2914
3083
  }
2915
3084
  pull() {
2916
3085
  return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a WritableStream stub"));
@@ -2928,9 +3097,9 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2928
3097
  }
2929
3098
  onBroken(callback) {}
2930
3099
  };
2931
- const INITIAL_WINDOW = 256 * 1024;
2932
- const MAX_WINDOW = 1024 * 1024 * 1024;
2933
- const MIN_WINDOW = 64 * 1024;
3100
+ const INITIAL_WINDOW = 262144;
3101
+ const MAX_WINDOW = 1073741824;
3102
+ const MIN_WINDOW = 65536;
2934
3103
  const STARTUP_GROWTH_FACTOR = 2;
2935
3104
  const STEADY_GROWTH_FACTOR = 1.25;
2936
3105
  const DECAY_FACTOR = .9;