capnweb 0.0.0-79bc296 → 0.0.0-7a6e5da

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.
@@ -43,9 +43,22 @@ function typeForRpc(value) {
43
43
  case Array.prototype: return "array";
44
44
  case Date.prototype: return "date";
45
45
  case Uint8Array.prototype:
46
- case BUFFER_PROTOTYPE: return "bytes";
46
+ case BUFFER_PROTOTYPE:
47
+ case ArrayBuffer.prototype:
48
+ case DataView.prototype:
49
+ case Int8Array.prototype:
50
+ case Uint8ClampedArray.prototype:
51
+ case Int16Array.prototype:
52
+ case Uint16Array.prototype:
53
+ case Int32Array.prototype:
54
+ case Uint32Array.prototype:
55
+ case BigInt64Array.prototype:
56
+ case BigUint64Array.prototype:
57
+ case Float32Array.prototype:
58
+ case Float64Array.prototype: return "bytes";
47
59
  case WritableStream.prototype: return "writable";
48
60
  case ReadableStream.prototype: return "readable";
61
+ case URL.prototype: return "url";
49
62
  case Headers.prototype: return "headers";
50
63
  case Request.prototype: return "request";
51
64
  case Response.prototype: return "response";
@@ -79,7 +92,14 @@ let streamImpl = {
79
92
  };
80
93
  var StubHook = class {
81
94
  stream(path, args) {
82
- let pulled = this.call(path, args).pull();
95
+ let hook = this.call(path, args);
96
+ let pulled;
97
+ try {
98
+ pulled = hook.pull();
99
+ } catch (err) {
100
+ hook.dispose();
101
+ throw err;
102
+ }
83
103
  let promise;
84
104
  if (pulled instanceof Promise) promise = pulled.then((p) => {
85
105
  p.dispose();
@@ -98,9 +118,11 @@ var ErrorStubHook = class extends StubHook {
98
118
  this.error = error;
99
119
  }
100
120
  call(path, args) {
121
+ args.dispose();
101
122
  return this;
102
123
  }
103
124
  map(path, captures, instructions) {
125
+ for (let cap of captures) cap.dispose();
104
126
  return this;
105
127
  }
106
128
  get(path) {
@@ -224,7 +246,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
224
246
  };
225
247
  var RpcPromise$1 = class extends RpcStub$1 {
226
248
  constructor(hook, pathIfPromise) {
227
- super(hook, pathIfPromise);
249
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
250
+ else {
251
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
252
+ let kind = typeForRpc(hook);
253
+ if (kind === "rpc-promise") {
254
+ let raw = unwrapStubAndPath(hook);
255
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
256
+ else {
257
+ let adopted = raw.hook;
258
+ raw.hook = DISPOSED_HOOK;
259
+ super(adopted, []);
260
+ }
261
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
262
+ else {
263
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
264
+ promiseHook.ignoreUnhandledRejections();
265
+ super(promiseHook, []);
266
+ }
267
+ }
228
268
  }
229
269
  then(onfulfilled, onrejected) {
230
270
  return pullPromise(this).then(...arguments);
@@ -380,6 +420,7 @@ var RpcPayload = class RpcPayload {
380
420
  case "date":
381
421
  case "bytes":
382
422
  case "blob":
423
+ case "url":
383
424
  case "error":
384
425
  case "undefined": return value;
385
426
  case "array": {
@@ -513,6 +554,30 @@ var RpcPayload = class RpcPayload {
513
554
  this.dispose();
514
555
  }
515
556
  }
557
+ async deliverStreamWrite(writer) {
558
+ try {
559
+ let promises = [];
560
+ this.deliverTo(this, "value", promises);
561
+ if (promises.length > 0) await Promise.all(promises);
562
+ let chunk = this.value[0];
563
+ if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {
564
+ if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {
565
+ value: () => this.dispose(),
566
+ writable: true,
567
+ enumerable: false,
568
+ configurable: true
569
+ });
570
+ await writer.write(chunk);
571
+ return RpcPayload.fromAppReturn(void 0);
572
+ }
573
+ await writer.write(chunk);
574
+ this.dispose();
575
+ return RpcPayload.fromAppReturn(void 0);
576
+ } catch (err) {
577
+ this.dispose();
578
+ throw err;
579
+ }
580
+ }
516
581
  async deliverResolve() {
517
582
  try {
518
583
  let promises = [];
@@ -553,6 +618,7 @@ var RpcPayload = class RpcPayload {
553
618
  case "bytes":
554
619
  case "blob":
555
620
  case "date":
621
+ case "url":
556
622
  case "error":
557
623
  case "undefined": return;
558
624
  case "array": {
@@ -635,6 +701,7 @@ var RpcPayload = class RpcPayload {
635
701
  case "rpc-target":
636
702
  case "writable":
637
703
  case "readable":
704
+ case "url":
638
705
  case "headers":
639
706
  case "request":
640
707
  case "response": return;
@@ -704,6 +771,7 @@ function followPath(value, parent, path, owner) {
704
771
  case "blob":
705
772
  case "date":
706
773
  case "error":
774
+ case "url":
707
775
  case "headers":
708
776
  case "request":
709
777
  case "response":
@@ -736,17 +804,22 @@ function followPath(value, parent, path, owner) {
736
804
  }
737
805
  var ValueStubHook = class extends StubHook {
738
806
  call(path, args) {
807
+ let followResult;
739
808
  try {
740
809
  let { value, owner } = this.getValue();
741
- let followResult = followPath(value, void 0, path, owner);
742
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
743
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
744
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
745
- return new PayloadStubHook(payload);
746
- }));
810
+ followResult = followPath(value, void 0, path, owner);
747
811
  } catch (err) {
812
+ args.dispose();
748
813
  return new ErrorStubHook(err);
749
814
  }
815
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
816
+ if (typeof followResult.value != "function") {
817
+ args.dispose();
818
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
819
+ }
820
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
821
+ return new PayloadStubHook(payload);
822
+ }));
750
823
  }
751
824
  map(path, captures, instructions) {
752
825
  try {
@@ -767,7 +840,10 @@ var ValueStubHook = class extends StubHook {
767
840
  get(path) {
768
841
  try {
769
842
  let { value, owner } = this.getValue();
770
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
843
+ if (path.length === 0 && owner === null) {
844
+ if (value instanceof Object && "then" in value) return this.dup();
845
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
846
+ }
771
847
  let followResult = followPath(value, void 0, path, owner);
772
848
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
773
849
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -870,7 +946,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
870
946
  this.target = void 0;
871
947
  }
872
948
  }
873
- onBroken(callback) {}
949
+ onBroken(callback) {
950
+ let target = this.target;
951
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
952
+ }
874
953
  };
875
954
  var PromiseStubHook = class PromiseStubHook extends StubHook {
876
955
  promise;
@@ -884,12 +963,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
884
963
  }
885
964
  call(path, args) {
886
965
  args.ensureDeepCopied();
887
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
966
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
967
+ args.dispose();
968
+ throw err;
969
+ }));
888
970
  }
889
971
  stream(path, args) {
890
972
  args.ensureDeepCopied();
891
- return { promise: this.promise.then((hook) => {
892
- return hook.stream(path, args).promise;
973
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
974
+ args.dispose();
975
+ throw err;
893
976
  }) };
894
977
  }
895
978
  map(path, captures, instructions) {
@@ -916,10 +999,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
916
999
  }, (err) => {});
917
1000
  }
918
1001
  dispose() {
919
- if (this.resolution) this.resolution.dispose();
920
- else this.promise.then((hook) => {
921
- hook.dispose();
922
- }, (err) => {});
1002
+ this.promise.then((hook) => hook.dispose(), () => {});
923
1003
  }
924
1004
  onBroken(callback) {
925
1005
  if (this.resolution) this.resolution.onBroken(callback);
@@ -931,6 +1011,77 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
931
1011
 
932
1012
  //#endregion
933
1013
  //#region src/serialize.ts
1014
+ const DEFAULT_MAX_DEPTH = 256;
1015
+ const DEFAULT_LIMITS = {
1016
+ maxBigIntDigits: 16384,
1017
+ maxDepth: 256,
1018
+ maxMessageSize: 32 * 1024 * 1024
1019
+ };
1020
+ const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
1021
+ const BYTE_CONTAINER_TYPE_NAMES = [
1022
+ "ArrayBuffer",
1023
+ "DataView",
1024
+ "Int8Array",
1025
+ "Uint8Array",
1026
+ "Uint8ClampedArray",
1027
+ "Int16Array",
1028
+ "Uint16Array",
1029
+ "Int32Array",
1030
+ "Uint32Array",
1031
+ "BigInt64Array",
1032
+ "BigUint64Array",
1033
+ "Float32Array",
1034
+ "Float64Array"
1035
+ ];
1036
+ function isValidByteContainerName(value) {
1037
+ return BYTE_CONTAINER_TYPE_NAMES.includes(value);
1038
+ }
1039
+ const TYPED_ARRAY_ELEMENT_SIZE = {
1040
+ ArrayBuffer: void 0,
1041
+ DataView: void 0,
1042
+ Int8Array: void 0,
1043
+ Uint8Array: void 0,
1044
+ Uint8ClampedArray: void 0,
1045
+ Int16Array: 2,
1046
+ Uint16Array: 2,
1047
+ Int32Array: 4,
1048
+ Uint32Array: 4,
1049
+ BigInt64Array: 8,
1050
+ BigUint64Array: 8,
1051
+ Float32Array: 4,
1052
+ Float64Array: 8
1053
+ };
1054
+ const BYTE_CONTAINER_PROTOTYPES = {
1055
+ ArrayBuffer: ArrayBuffer.prototype,
1056
+ DataView: DataView.prototype,
1057
+ Int8Array: Int8Array.prototype,
1058
+ Uint8ClampedArray: Uint8ClampedArray.prototype,
1059
+ Int16Array: Int16Array.prototype,
1060
+ Uint16Array: Uint16Array.prototype,
1061
+ Int32Array: Int32Array.prototype,
1062
+ Uint32Array: Uint32Array.prototype,
1063
+ BigInt64Array: BigInt64Array.prototype,
1064
+ BigUint64Array: BigUint64Array.prototype,
1065
+ Float32Array: Float32Array.prototype,
1066
+ Float64Array: Float64Array.prototype
1067
+ };
1068
+ const BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();
1069
+ for (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);
1070
+ function swapByteOrder(bytes, elementSize) {
1071
+ if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);
1072
+ let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1073
+ for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {
1074
+ case 2:
1075
+ view.setUint16(offset, view.getUint16(offset, false), true);
1076
+ break;
1077
+ case 4:
1078
+ view.setUint32(offset, view.getUint32(offset, false), true);
1079
+ break;
1080
+ case 8:
1081
+ view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1082
+ break;
1083
+ }
1084
+ }
934
1085
  var NullExporter = class {
935
1086
  exportStub(stub) {
936
1087
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -951,6 +1102,7 @@ async function streamToBlob(stream, type) {
951
1102
  return b.type === type ? b : b.slice(0, b.size, type);
952
1103
  }
953
1104
  const ERROR_TYPES = {
1105
+ __proto__: null,
954
1106
  Error,
955
1107
  EvalError,
956
1108
  RangeError,
@@ -982,7 +1134,7 @@ var Devaluator = class Devaluator {
982
1134
  }
983
1135
  exports;
984
1136
  devaluateImpl(value, parent, depth) {
985
- if (depth >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
1137
+ if (depth >= 256) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
986
1138
  switch (typeForRpc(value)) {
987
1139
  case "unsupported": {
988
1140
  let msg;
@@ -1021,18 +1173,40 @@ var Devaluator = class Devaluator {
1021
1173
  return ["date", Number.isNaN(time) ? null : time];
1022
1174
  }
1023
1175
  case "bytes": {
1024
- let bytes = value;
1025
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1026
- if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1176
+ let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1177
+ let bytes;
1178
+ if (alternateTypeName === "ArrayBuffer") bytes = new Uint8Array(value);
1179
+ else if (alternateTypeName === void 0) bytes = value;
1180
+ else {
1181
+ let view = value;
1182
+ bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1183
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];
1184
+ if (!NATIVE_LITTLE_ENDIAN && elementSize) {
1185
+ bytes = bytes.slice();
1186
+ swapByteOrder(bytes, elementSize);
1187
+ }
1188
+ }
1189
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1190
+ "bytes",
1191
+ bytes,
1192
+ alternateTypeName
1193
+ ];
1027
1194
  let b64;
1028
- if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1195
+ if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1196
+ else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1029
1197
  else {
1030
1198
  let binary = "";
1031
1199
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1032
1200
  b64 = btoa(binary);
1033
1201
  }
1034
- return ["bytes", b64.replace(/=+$/, "")];
1202
+ b64 = b64.replace(/=+$/, "");
1203
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1204
+ "bytes",
1205
+ b64,
1206
+ alternateTypeName
1207
+ ];
1035
1208
  }
1209
+ case "url": return ["url", value.href];
1036
1210
  case "headers": return ["headers", [...value]];
1037
1211
  case "request": {
1038
1212
  let req = value;
@@ -1216,6 +1390,9 @@ var NullImporter = class {
1216
1390
  getPipeReadable(exportId) {
1217
1391
  throw new Error("Cannot retrieve pipe readable without an RPC session.");
1218
1392
  }
1393
+ getLimits() {
1394
+ return DEFAULT_LIMITS;
1395
+ }
1219
1396
  };
1220
1397
  const NULL_IMPORTER = new NullImporter();
1221
1398
  function fixBrokenRequestBody(request, body) {
@@ -1233,16 +1410,21 @@ function streamToBlobPromise(stream, type) {
1233
1410
  var Evaluator = class Evaluator {
1234
1411
  importer;
1235
1412
  encodingLevel;
1413
+ limits;
1236
1414
  constructor(importer, encodingLevel = "string") {
1237
1415
  this.importer = importer;
1238
1416
  this.encodingLevel = encodingLevel;
1417
+ this.limits = importer.getLimits();
1239
1418
  }
1240
1419
  hooks = [];
1241
1420
  promises = [];
1242
1421
  evaluate(value) {
1422
+ return this.evaluateWithDepth(value, 0);
1423
+ }
1424
+ evaluateWithDepth(value, depth) {
1243
1425
  let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1244
1426
  try {
1245
- payload.value = this.evaluateImpl(value, payload, "value");
1427
+ payload.value = this.evaluateImpl(value, payload, "value", depth);
1246
1428
  return payload;
1247
1429
  } catch (err) {
1248
1430
  payload.dispose();
@@ -1252,35 +1434,70 @@ var Evaluator = class Evaluator {
1252
1434
  evaluateCopy(value) {
1253
1435
  return this.evaluate(structuredClone(value));
1254
1436
  }
1255
- evaluateImpl(value, parent, property) {
1437
+ evaluateImpl(value, parent, property, depth) {
1438
+ let maxDepth = this.limits.maxDepth;
1439
+ if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1256
1440
  if (this.encodingLevel === "structuredClonable") {
1257
1441
  if (value instanceof Date || typeof value === "bigint") return value;
1258
1442
  }
1259
1443
  if (value instanceof Array) {
1260
1444
  if (value.length == 1 && value[0] instanceof Array) {
1261
1445
  let result = value[0];
1262
- for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i);
1446
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);
1263
1447
  return result;
1264
1448
  } else switch (value[0]) {
1265
1449
  case "bigint":
1266
- if (typeof value[1] == "string") return BigInt(value[1]);
1450
+ if (typeof value[1] == "string") {
1451
+ let digits = value[1];
1452
+ let maxBigIntDigits = this.limits.maxBigIntDigits;
1453
+ if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);
1454
+ return BigInt(digits);
1455
+ }
1267
1456
  break;
1268
1457
  case "date":
1269
1458
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1270
1459
  if (typeof value[1] == "number") return new Date(value[1]);
1271
1460
  break;
1272
- case "bytes":
1273
- if (value[1] instanceof Uint8Array) return value[1];
1274
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1275
- else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1461
+ case "bytes": {
1462
+ let bytes;
1463
+ if (value[1] instanceof Uint8Array) bytes = value[1];
1464
+ else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1465
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1276
1466
  else {
1277
1467
  let bs = atob(value[1]);
1278
1468
  let len = bs.length;
1279
- let bytes = new Uint8Array(len);
1469
+ bytes = new Uint8Array(len);
1280
1470
  for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1281
- return bytes;
1282
1471
  }
1283
- break;
1472
+ else break;
1473
+ if (value.length === 2) return bytes;
1474
+ if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1475
+ if (!isValidByteContainerName(value[2])) {
1476
+ let marker = value[2].slice(0, 64);
1477
+ throw new TypeError(`Unknown bytes type marker: ${marker}`);
1478
+ }
1479
+ let marker = value[2];
1480
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];
1481
+ if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);
1482
+ let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1483
+ if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);
1484
+ switch (marker) {
1485
+ case "ArrayBuffer": return buffer;
1486
+ case "DataView": return new DataView(buffer);
1487
+ case "Int8Array": return new Int8Array(buffer);
1488
+ case "Uint8Array": return new Uint8Array(buffer);
1489
+ case "Uint8ClampedArray": return new Uint8ClampedArray(buffer);
1490
+ case "Int16Array": return new Int16Array(buffer);
1491
+ case "Uint16Array": return new Uint16Array(buffer);
1492
+ case "Int32Array": return new Int32Array(buffer);
1493
+ case "Uint32Array": return new Uint32Array(buffer);
1494
+ case "BigInt64Array": return new BigInt64Array(buffer);
1495
+ case "BigUint64Array": return new BigUint64Array(buffer);
1496
+ case "Float32Array": return new Float32Array(buffer);
1497
+ case "Float64Array": return new Float64Array(buffer);
1498
+ default:
1499
+ }
1500
+ }
1284
1501
  case "error":
1285
1502
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1286
1503
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -1293,7 +1510,11 @@ var Evaluator = class Evaluator {
1293
1510
  let propsObj = props;
1294
1511
  for (let key of Object.keys(propsObj)) {
1295
1512
  if (key === "name" || key === "message" || key === "stack") continue;
1296
- anyResult[key] = this.evaluateImpl(propsObj[key], result, key);
1513
+ if (key in Object.prototype || key === "toJSON") {
1514
+ this.evaluateImpl(propsObj[key], result, key, depth + 1);
1515
+ continue;
1516
+ }
1517
+ anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);
1297
1518
  }
1298
1519
  }
1299
1520
  return result;
@@ -1305,6 +1526,9 @@ var Evaluator = class Evaluator {
1305
1526
  case "inf": return Infinity;
1306
1527
  case "-inf": return -Infinity;
1307
1528
  case "nan": return NaN;
1529
+ case "url":
1530
+ if (value.length === 2 && typeof value[1] === "string") return new URL(value[1]);
1531
+ break;
1308
1532
  case "headers":
1309
1533
  if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1310
1534
  break;
@@ -1314,11 +1538,11 @@ var Evaluator = class Evaluator {
1314
1538
  let init = value[2];
1315
1539
  if (typeof init !== "object" || init === null) break;
1316
1540
  if (init.body) {
1317
- init.body = this.evaluateImpl(init.body, init, "body");
1541
+ init.body = this.evaluateImpl(init.body, init, "body", depth + 1);
1318
1542
  if (init.body === null || typeof init.body === "string" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) {} else throw new TypeError("Request body must be of type ReadableStream.");
1319
1543
  }
1320
1544
  if (init.signal) {
1321
- init.signal = this.evaluateImpl(init.signal, init, "signal");
1545
+ init.signal = this.evaluateImpl(init.signal, init, "signal", depth + 1);
1322
1546
  if (!(init.signal instanceof AbortSignal)) throw new TypeError("Request siganl must be of type AbortSignal.");
1323
1547
  }
1324
1548
  if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
@@ -1335,7 +1559,7 @@ var Evaluator = class Evaluator {
1335
1559
  }
1336
1560
  case "response": {
1337
1561
  if (value.length !== 3) break;
1338
- let body = this.evaluateImpl(value[1], parent, property);
1562
+ let body = this.evaluateImpl(value[1], parent, property, depth + 1);
1339
1563
  if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) {} else throw new TypeError("Response body must be of type ReadableStream.");
1340
1564
  let init = value[2];
1341
1565
  if (typeof init !== "object" || init === null) break;
@@ -1346,7 +1570,7 @@ var Evaluator = class Evaluator {
1346
1570
  case "blob": {
1347
1571
  if (value.length !== 3 || typeof value[1] !== "string") break;
1348
1572
  let contentType = value[1];
1349
- let content = this.evaluateImpl(value[2], parent, property);
1573
+ let content = this.evaluateImpl(value[2], parent, property, depth + 1);
1350
1574
  if (!(content instanceof ReadableStream)) throw new TypeError("Blob content must be serialized as a ReadableStream.");
1351
1575
  let promise = streamToBlobPromise(content, contentType);
1352
1576
  this.promises.push({
@@ -1387,7 +1611,7 @@ var Evaluator = class Evaluator {
1387
1611
  if (value.length == 3) return addStub(hook.get(path));
1388
1612
  let args = value[3];
1389
1613
  if (!(args instanceof Array)) break;
1390
- args = new Evaluator(this.importer).evaluate([args]);
1614
+ args = new Evaluator(this.importer).evaluateWithDepth([args], depth);
1391
1615
  return addStub(hook.call(path, args));
1392
1616
  }
1393
1617
  case "remap": {
@@ -1453,9 +1677,9 @@ var Evaluator = class Evaluator {
1453
1677
  } else if (value instanceof Object) {
1454
1678
  let result = value;
1455
1679
  for (let key in result) if (key in Object.prototype || key === "toJSON") {
1456
- this.evaluateImpl(result[key], result, key);
1680
+ this.evaluateImpl(result[key], result, key, depth + 1);
1457
1681
  delete result[key];
1458
- } else result[key] = this.evaluateImpl(result[key], result, key);
1682
+ } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);
1459
1683
  return result;
1460
1684
  } else return value;
1461
1685
  }
@@ -1604,24 +1828,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1604
1828
  if (this.entry) return this.entry;
1605
1829
  else throw new Error("This RpcImportHook was already disposed.");
1606
1830
  }
1831
+ getEntryTakingOwnership(disposeOwned) {
1832
+ try {
1833
+ return this.getEntry();
1834
+ } catch (err) {
1835
+ disposeOwned();
1836
+ throw err;
1837
+ }
1838
+ }
1607
1839
  call(path, args) {
1608
- let entry = this.getEntry();
1840
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1609
1841
  if (entry.resolution) return entry.resolution.call(path, args);
1610
1842
  else return entry.session.sendCall(entry.importId, path, args);
1611
1843
  }
1612
1844
  stream(path, args) {
1613
- let entry = this.getEntry();
1845
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1614
1846
  if (entry.resolution) return entry.resolution.stream(path, args);
1615
1847
  else return entry.session.sendStream(entry.importId, path, args);
1616
1848
  }
1617
1849
  map(path, captures, instructions) {
1618
- let entry;
1619
- try {
1620
- entry = this.getEntry();
1621
- } catch (err) {
1850
+ let entry = this.getEntryTakingOwnership(() => {
1622
1851
  for (let cap of captures) cap.dispose();
1623
- throw err;
1624
- }
1852
+ });
1625
1853
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1626
1854
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1627
1855
  }
@@ -1678,6 +1906,7 @@ var RpcSessionImpl = class {
1678
1906
  pullCount = 0;
1679
1907
  onBrokenCallbacks = [];
1680
1908
  encodingLevel;
1909
+ limits;
1681
1910
  constructor(transport, mainHook, options) {
1682
1911
  this.transport = transport;
1683
1912
  this.options = options;
@@ -1690,6 +1919,10 @@ var RpcSessionImpl = class {
1690
1919
  }
1691
1920
  }
1692
1921
  this.encodingLevel = level;
1922
+ this.limits = {
1923
+ ...DEFAULT_LIMITS,
1924
+ ...options.limits
1925
+ };
1693
1926
  this.exports.push({
1694
1927
  hook: mainHook,
1695
1928
  refcount: 1
@@ -1832,6 +2065,9 @@ var RpcSessionImpl = class {
1832
2065
  entry.pipeReadable = void 0;
1833
2066
  return readable;
1834
2067
  }
2068
+ getLimits() {
2069
+ return this.limits;
2070
+ }
1835
2071
  createPipe(readable, readableHook) {
1836
2072
  if (this.abortReason) throw this.abortReason;
1837
2073
  this.send(["pipe"]);
@@ -1874,14 +2110,23 @@ var RpcSessionImpl = class {
1874
2110
  }
1875
2111
  }
1876
2112
  sendCall(id, path, args) {
1877
- if (this.abortReason) throw this.abortReason;
2113
+ if (this.abortReason) {
2114
+ args?.dispose();
2115
+ throw this.abortReason;
2116
+ }
1878
2117
  let value = [
1879
2118
  "pipeline",
1880
2119
  id,
1881
2120
  path
1882
2121
  ];
1883
2122
  if (args) {
1884
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2123
+ let devalue;
2124
+ try {
2125
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2126
+ } catch (err) {
2127
+ args.dispose();
2128
+ throw err;
2129
+ }
1885
2130
  value.push(devalue[0]);
1886
2131
  }
1887
2132
  this.send(["push", value]);
@@ -1890,13 +2135,22 @@ var RpcSessionImpl = class {
1890
2135
  return new RpcImportHook(true, entry);
1891
2136
  }
1892
2137
  sendStream(id, path, args) {
1893
- if (this.abortReason) throw this.abortReason;
2138
+ if (this.abortReason) {
2139
+ args.dispose();
2140
+ throw this.abortReason;
2141
+ }
1894
2142
  let value = [
1895
2143
  "pipeline",
1896
2144
  id,
1897
2145
  path
1898
2146
  ];
1899
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2147
+ let devalue;
2148
+ try {
2149
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2150
+ } catch (err) {
2151
+ args.dispose();
2152
+ throw err;
2153
+ }
1900
2154
  value.push(devalue[0]);
1901
2155
  let msg = ["stream", value];
1902
2156
  let size = this.send(msg);
@@ -1991,6 +2245,7 @@ var RpcSessionImpl = class {
1991
2245
  } finally {
1992
2246
  if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;
1993
2247
  }
2248
+ if (this.encodingLevel === "string" && raw.length > this.limits.maxMessageSize) throw new TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);
1994
2249
  if (this.abortReason) break;
1995
2250
  let msg = this.encodingLevel === "string" ? JSON.parse(raw) : raw;
1996
2251
  if (msg instanceof Array) switch (msg[0]) {
@@ -2065,7 +2320,7 @@ var RpcSessionImpl = class {
2065
2320
  case "abort": {
2066
2321
  let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2067
2322
  payload.dispose();
2068
- this.abort(payload, false);
2323
+ this.abort(payload.value, false);
2069
2324
  break;
2070
2325
  }
2071
2326
  }
@@ -2116,6 +2371,8 @@ var RpcSession$1 = class {
2116
2371
 
2117
2372
  //#endregion
2118
2373
  //#region src/websocket.ts
2374
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2375
+ const MAX_CLOSE_REASON_BYTES = 123;
2119
2376
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2120
2377
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2121
2378
  return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
@@ -2191,6 +2448,8 @@ var WebSocketTransport = class {
2191
2448
  let message;
2192
2449
  if (reason instanceof Error) message = reason.message;
2193
2450
  else message = `${reason}`;
2451
+ let reasonBytes = new TextEncoder().encode(message);
2452
+ if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });
2194
2453
  this.#webSocket.close(3e3, message);
2195
2454
  if (!this.#error) this.#error = reason;
2196
2455
  }
@@ -2208,6 +2467,7 @@ var WebSocketTransport = class {
2208
2467
 
2209
2468
  //#endregion
2210
2469
  //#region src/batch.ts
2470
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2211
2471
  var BatchClientTransport = class {
2212
2472
  constructor(sendBatch) {
2213
2473
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2229,7 +2489,7 @@ var BatchClientTransport = class {
2229
2489
  this.#aborted = reason;
2230
2490
  }
2231
2491
  async #scheduleBatch(sendBatch) {
2232
- await new Promise((resolve) => setTimeout(resolve, 0));
2492
+ await yieldToMacrotask();
2233
2493
  if (this.#aborted !== void 0) throw this.#aborted;
2234
2494
  let batch = this.#batchToSend;
2235
2495
  this.#batchToSend = null;
@@ -2307,7 +2567,11 @@ async function newHttpBatchRpcResponse(request, localMain, options) {
2307
2567
  * @param options Optional RPC session options. You can also pass headers to set on the response.
2308
2568
  */
2309
2569
  async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2310
- if (request.method !== "POST") response.writeHead(405, "This endpoint only accepts POST requests.");
2570
+ if (request.method !== "POST") {
2571
+ response.writeHead(405, "This endpoint only accepts POST requests.", options?.headers);
2572
+ response.end();
2573
+ return;
2574
+ }
2311
2575
  let body = await new Promise((resolve, reject) => {
2312
2576
  let chunks = [];
2313
2577
  request.on("data", (chunk) => {
@@ -2517,9 +2781,11 @@ var MapVariableHook = class extends StubHook {
2517
2781
  else throwMapperBuilderUseError();
2518
2782
  }
2519
2783
  call(path, args) {
2784
+ args.dispose();
2520
2785
  throwMapperBuilderUseError();
2521
2786
  }
2522
2787
  map(path, captures, instructions) {
2788
+ for (let cap of captures) cap.dispose();
2523
2789
  throwMapperBuilderUseError();
2524
2790
  }
2525
2791
  pull() {
@@ -2572,6 +2838,9 @@ var MapApplicator = class {
2572
2838
  getPipeReadable(exportId) {
2573
2839
  throw new Error("A mapper function cannot use pipe readables.");
2574
2840
  }
2841
+ getLimits() {
2842
+ return DEFAULT_LIMITS;
2843
+ }
2575
2844
  };
2576
2845
  function applyMapToElement(input, parent, owner, captures, instructions) {
2577
2846
  let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
@@ -2627,14 +2896,11 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2627
2896
  let state = this.getState();
2628
2897
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2629
2898
  const method = path[0];
2630
- if (method !== "write" && method !== "close" && method !== "abort") {
2631
- args.dispose();
2632
- throw new Error(`Unknown WritableStream method: ${method}`);
2633
- }
2899
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2634
2900
  if (method === "close" || method === "abort") state.closed = true;
2635
- let func = state.writer[method];
2636
- return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2901
+ return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2637
2902
  } catch (err) {
2903
+ args.dispose();
2638
2904
  return new ErrorStubHook(err);
2639
2905
  }
2640
2906
  }
@@ -2910,12 +3176,12 @@ let newMessagePortRpcSession = newMessagePortRpcSession$1;
2910
3176
  * credentials as parameters and returns the authorized API), then cross-origin requests should
2911
3177
  * be safe.
2912
3178
  */
2913
- async function newWorkersRpcResponse(request, localMain) {
3179
+ async function newWorkersRpcResponse(request, localMain, options) {
2914
3180
  if (request.method === "POST") {
2915
- let response = await newHttpBatchRpcResponse(request, localMain);
3181
+ let response = await newHttpBatchRpcResponse(request, localMain, options);
2916
3182
  response.headers.set("Access-Control-Allow-Origin", "*");
2917
3183
  return response;
2918
- } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain);
3184
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain, options);
2919
3185
  else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
2920
3186
  }
2921
3187
 
@@ -3037,6 +3303,8 @@ let newBunWebSocketRpcSession = newBunWebSocketRpcSession$1;
3037
3303
 
3038
3304
  //#endregion
3039
3305
  exports.BunWebSocketTransport = BunWebSocketTransport;
3306
+ exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
3307
+ exports.DEFAULT_MAX_DEPTH = DEFAULT_MAX_DEPTH;
3040
3308
  exports.RpcPromise = RpcPromise;
3041
3309
  exports.RpcSession = RpcSession;
3042
3310
  exports.RpcStub = RpcStub;