capnweb 0.0.0-0d6b2ff → 0.0.0-143d13d

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,10 +40,25 @@ 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";
43
45
  case Uint8Array.prototype:
44
- 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";
45
59
  case WritableStream.prototype: return "writable";
46
60
  case ReadableStream.prototype: return "readable";
61
+ case URL.prototype: return "url";
47
62
  case Headers.prototype: return "headers";
48
63
  case Request.prototype: return "request";
49
64
  case Response.prototype: return "response";
@@ -77,7 +92,14 @@ let streamImpl = {
77
92
  };
78
93
  var StubHook = class {
79
94
  stream(path, args) {
80
- 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
+ }
81
103
  let promise;
82
104
  if (pulled instanceof Promise) promise = pulled.then((p) => {
83
105
  p.dispose();
@@ -96,9 +118,11 @@ var ErrorStubHook = class extends StubHook {
96
118
  this.error = error;
97
119
  }
98
120
  call(path, args) {
121
+ args.dispose();
99
122
  return this;
100
123
  }
101
124
  map(path, captures, instructions) {
125
+ for (let cap of captures) cap.dispose();
102
126
  return this;
103
127
  }
104
128
  get(path) {
@@ -222,7 +246,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
222
246
  };
223
247
  var RpcPromise$1 = class extends RpcStub$1 {
224
248
  constructor(hook, pathIfPromise) {
225
- 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
+ }
226
268
  }
227
269
  then(onfulfilled, onrejected) {
228
270
  return pullPromise(this).then(...arguments);
@@ -317,12 +359,13 @@ var RpcPayload = class RpcPayload {
317
359
  return TargetStubHook.create(target, parent);
318
360
  } else if (this.source === "return") {
319
361
  let hook = this.rpcTargets?.get(target);
320
- if (hook) if (dupStubs) return hook.dup();
321
- else {
322
- this.rpcTargets?.delete(target);
323
- return hook;
324
- }
325
- else {
362
+ if (hook) {
363
+ if (dupStubs) return hook.dup();
364
+ else {
365
+ this.rpcTargets?.delete(target);
366
+ return hook;
367
+ }
368
+ } else {
326
369
  hook = TargetStubHook.create(target, parent);
327
370
  if (dupStubs) {
328
371
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -336,12 +379,13 @@ var RpcPayload = class RpcPayload {
336
379
  if (this.source === "params") return streamImpl.createWritableStreamHook(stream);
337
380
  else if (this.source === "return") {
338
381
  let hook = this.rpcTargets?.get(stream);
339
- if (hook) if (dupStubs) return hook.dup();
340
- else {
341
- this.rpcTargets?.delete(stream);
342
- return hook;
343
- }
344
- else {
382
+ if (hook) {
383
+ if (dupStubs) return hook.dup();
384
+ else {
385
+ this.rpcTargets?.delete(stream);
386
+ return hook;
387
+ }
388
+ } else {
345
389
  hook = streamImpl.createWritableStreamHook(stream);
346
390
  if (dupStubs) {
347
391
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -355,12 +399,13 @@ var RpcPayload = class RpcPayload {
355
399
  if (this.source === "params") return streamImpl.createReadableStreamHook(stream);
356
400
  else if (this.source === "return") {
357
401
  let hook = this.rpcTargets?.get(stream);
358
- if (hook) if (dupStubs) return hook.dup();
359
- else {
360
- this.rpcTargets?.delete(stream);
361
- return hook;
362
- }
363
- else {
402
+ if (hook) {
403
+ if (dupStubs) return hook.dup();
404
+ else {
405
+ this.rpcTargets?.delete(stream);
406
+ return hook;
407
+ }
408
+ } else {
364
409
  hook = streamImpl.createReadableStreamHook(stream);
365
410
  if (dupStubs) {
366
411
  if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
@@ -378,6 +423,8 @@ var RpcPayload = class RpcPayload {
378
423
  case "date":
379
424
  case "bytes":
380
425
  case "blob":
426
+ case "url":
427
+ case "regexp":
381
428
  case "error":
382
429
  case "undefined": return value;
383
430
  case "array": {
@@ -387,6 +434,21 @@ var RpcPayload = class RpcPayload {
387
434
  for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
388
435
  return result;
389
436
  }
437
+ case "set": {
438
+ let set = value;
439
+ let elements = [...set];
440
+ for (let val of elements) {
441
+ let kind = typeForRpc(val);
442
+ 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.");
443
+ }
444
+ let result = /* @__PURE__ */ new Set();
445
+ let index = 0;
446
+ for (let val of elements) {
447
+ let copy = this.deepCopy(val, set, index++, result, dupStubs, owner);
448
+ result.add(copy);
449
+ }
450
+ return result;
451
+ }
390
452
  case "object": {
391
453
  let result = {};
392
454
  let object = value;
@@ -471,6 +533,10 @@ var RpcPayload = class RpcPayload {
471
533
  try {
472
534
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
473
535
  } catch (err) {
536
+ if (dupStubs) {
537
+ this.hooks.forEach((hook) => hook.dispose());
538
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
539
+ }
474
540
  this.hooks = void 0;
475
541
  this.promises = void 0;
476
542
  throw err;
@@ -511,6 +577,30 @@ var RpcPayload = class RpcPayload {
511
577
  this.dispose();
512
578
  }
513
579
  }
580
+ async deliverStreamWrite(writer) {
581
+ try {
582
+ let promises = [];
583
+ this.deliverTo(this, "value", promises);
584
+ if (promises.length > 0) await Promise.all(promises);
585
+ let chunk = this.value[0];
586
+ if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {
587
+ if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {
588
+ value: () => this.dispose(),
589
+ writable: true,
590
+ enumerable: false,
591
+ configurable: true
592
+ });
593
+ await writer.write(chunk);
594
+ return RpcPayload.fromAppReturn(void 0);
595
+ }
596
+ await writer.write(chunk);
597
+ this.dispose();
598
+ return RpcPayload.fromAppReturn(void 0);
599
+ } catch (err) {
600
+ this.dispose();
601
+ throw err;
602
+ }
603
+ }
514
604
  async deliverResolve() {
515
605
  try {
516
606
  let promises = [];
@@ -551,6 +641,8 @@ var RpcPayload = class RpcPayload {
551
641
  case "bytes":
552
642
  case "blob":
553
643
  case "date":
644
+ case "url":
645
+ case "regexp":
554
646
  case "error":
555
647
  case "undefined": return;
556
648
  case "array": {
@@ -559,6 +651,11 @@ var RpcPayload = class RpcPayload {
559
651
  for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
560
652
  return;
561
653
  }
654
+ case "set": {
655
+ let set = value;
656
+ for (let element of set) this.disposeImpl(element, set);
657
+ return;
658
+ }
562
659
  case "object": {
563
660
  let object = value;
564
661
  for (let i in object) this.disposeImpl(object[i], object);
@@ -633,6 +730,8 @@ var RpcPayload = class RpcPayload {
633
730
  case "rpc-target":
634
731
  case "writable":
635
732
  case "readable":
733
+ case "url":
734
+ case "regexp":
636
735
  case "headers":
637
736
  case "request":
638
737
  case "response": return;
@@ -642,6 +741,11 @@ var RpcPayload = class RpcPayload {
642
741
  for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
643
742
  return;
644
743
  }
744
+ case "set": {
745
+ let set = value;
746
+ for (let element of set) this.ignoreUnhandledRejectionsImpl(element);
747
+ return;
748
+ }
645
749
  case "object": {
646
750
  let object = value;
647
751
  for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
@@ -701,7 +805,10 @@ function followPath(value, parent, path, owner) {
701
805
  case "bytes":
702
806
  case "blob":
703
807
  case "date":
808
+ case "set":
704
809
  case "error":
810
+ case "url":
811
+ case "regexp":
705
812
  case "headers":
706
813
  case "request":
707
814
  case "response":
@@ -734,17 +841,23 @@ function followPath(value, parent, path, owner) {
734
841
  }
735
842
  var ValueStubHook = class extends StubHook {
736
843
  call(path, args) {
844
+ let followResult;
737
845
  try {
738
846
  let { value, owner } = this.getValue();
739
- let followResult = followPath(value, void 0, path, owner);
740
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
741
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
742
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
743
- return new PayloadStubHook(payload);
744
- }));
847
+ followResult = followPath(value, void 0, path, owner);
745
848
  } catch (err) {
849
+ args.dispose();
746
850
  return new ErrorStubHook(err);
747
851
  }
852
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
853
+ if (typeof followResult.value != "function") {
854
+ args.dispose();
855
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
856
+ }
857
+ let promise = args.deliverCall(followResult.value, followResult.parent);
858
+ return new PromiseStubHook(promise.then((payload) => {
859
+ return new PayloadStubHook(payload);
860
+ }));
748
861
  }
749
862
  map(path, captures, instructions) {
750
863
  try {
@@ -765,7 +878,10 @@ var ValueStubHook = class extends StubHook {
765
878
  get(path) {
766
879
  try {
767
880
  let { value, owner } = this.getValue();
768
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
881
+ if (path.length === 0 && owner === null) {
882
+ if (value instanceof Object && "then" in value) return this.dup();
883
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
884
+ }
769
885
  let followResult = followPath(value, void 0, path, owner);
770
886
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
771
887
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -868,7 +984,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
868
984
  this.target = void 0;
869
985
  }
870
986
  }
871
- onBroken(callback) {}
987
+ onBroken(callback) {
988
+ let target = this.target;
989
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
990
+ }
872
991
  };
873
992
  var PromiseStubHook = class PromiseStubHook extends StubHook {
874
993
  promise;
@@ -882,12 +1001,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
882
1001
  }
883
1002
  call(path, args) {
884
1003
  args.ensureDeepCopied();
885
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
1004
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
1005
+ args.dispose();
1006
+ throw err;
1007
+ }));
886
1008
  }
887
1009
  stream(path, args) {
888
1010
  args.ensureDeepCopied();
889
- return { promise: this.promise.then((hook) => {
890
- return hook.stream(path, args).promise;
1011
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
1012
+ args.dispose();
1013
+ throw err;
891
1014
  }) };
892
1015
  }
893
1016
  map(path, captures, instructions) {
@@ -914,10 +1037,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
914
1037
  }, (err) => {});
915
1038
  }
916
1039
  dispose() {
917
- if (this.resolution) this.resolution.dispose();
918
- else this.promise.then((hook) => {
919
- hook.dispose();
920
- }, (err) => {});
1040
+ this.promise.then((hook) => hook.dispose(), () => {});
921
1041
  }
922
1042
  onBroken(callback) {
923
1043
  if (this.resolution) this.resolution.onBroken(callback);
@@ -929,6 +1049,75 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
929
1049
 
930
1050
  //#endregion
931
1051
  //#region src/serialize.ts
1052
+ const DEFAULT_MAX_DEPTH = 256;
1053
+ const DEFAULT_LIMITS = {
1054
+ maxBigIntDigits: 16384,
1055
+ maxDepth: 256,
1056
+ maxMessageSize: 33554432
1057
+ };
1058
+ const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
1059
+ const BYTE_CONTAINER_TYPE_NAMES = [
1060
+ "ArrayBuffer",
1061
+ "DataView",
1062
+ "Int8Array",
1063
+ "Uint8Array",
1064
+ "Uint8ClampedArray",
1065
+ "Int16Array",
1066
+ "Uint16Array",
1067
+ "Int32Array",
1068
+ "Uint32Array",
1069
+ "BigInt64Array",
1070
+ "BigUint64Array",
1071
+ "Float32Array",
1072
+ "Float64Array"
1073
+ ];
1074
+ function isValidByteContainerName(value) {
1075
+ return BYTE_CONTAINER_TYPE_NAMES.includes(value);
1076
+ }
1077
+ const TYPED_ARRAY_ELEMENT_SIZE = {
1078
+ ArrayBuffer: void 0,
1079
+ DataView: void 0,
1080
+ Int8Array: void 0,
1081
+ Uint8Array: void 0,
1082
+ Uint8ClampedArray: void 0,
1083
+ Int16Array: 2,
1084
+ Uint16Array: 2,
1085
+ Int32Array: 4,
1086
+ Uint32Array: 4,
1087
+ BigInt64Array: 8,
1088
+ BigUint64Array: 8,
1089
+ Float32Array: 4,
1090
+ Float64Array: 8
1091
+ };
1092
+ const BYTE_CONTAINER_PROTOTYPES = {
1093
+ ArrayBuffer: ArrayBuffer.prototype,
1094
+ DataView: DataView.prototype,
1095
+ Int8Array: Int8Array.prototype,
1096
+ Uint8ClampedArray: Uint8ClampedArray.prototype,
1097
+ Int16Array: Int16Array.prototype,
1098
+ Uint16Array: Uint16Array.prototype,
1099
+ Int32Array: Int32Array.prototype,
1100
+ Uint32Array: Uint32Array.prototype,
1101
+ BigInt64Array: BigInt64Array.prototype,
1102
+ BigUint64Array: BigUint64Array.prototype,
1103
+ Float32Array: Float32Array.prototype,
1104
+ Float64Array: Float64Array.prototype
1105
+ };
1106
+ const BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();
1107
+ for (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);
1108
+ function swapByteOrder(bytes, elementSize) {
1109
+ if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);
1110
+ let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1111
+ for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {
1112
+ case 2:
1113
+ view.setUint16(offset, view.getUint16(offset, false), true);
1114
+ break;
1115
+ case 4:
1116
+ view.setUint32(offset, view.getUint32(offset, false), true);
1117
+ break;
1118
+ case 8: view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1119
+ }
1120
+ }
932
1121
  var NullExporter = class {
933
1122
  exportStub(stub) {
934
1123
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -949,6 +1138,7 @@ async function streamToBlob(stream, type) {
949
1138
  return b.type === type ? b : b.slice(0, b.size, type);
950
1139
  }
951
1140
  const ERROR_TYPES = {
1141
+ __proto__: null,
952
1142
  Error,
953
1143
  EvalError,
954
1144
  RangeError,
@@ -961,12 +1151,14 @@ const ERROR_TYPES = {
961
1151
  var Devaluator = class Devaluator {
962
1152
  exporter;
963
1153
  source;
964
- constructor(exporter, source) {
1154
+ encodingLevel;
1155
+ constructor(exporter, source, encodingLevel) {
965
1156
  this.exporter = exporter;
966
1157
  this.source = source;
1158
+ this.encodingLevel = encodingLevel;
967
1159
  }
968
- static devaluate(value, parent, exporter = NULL_EXPORTER, source) {
969
- let devaluator = new Devaluator(exporter, source);
1160
+ static devaluate(value, parent, exporter = NULL_EXPORTER, source, encodingLevel = "string") {
1161
+ let devaluator = new Devaluator(exporter, source, encodingLevel);
970
1162
  try {
971
1163
  return devaluator.devaluateImpl(value, parent, 0);
972
1164
  } catch (err) {
@@ -978,7 +1170,7 @@ var Devaluator = class Devaluator {
978
1170
  }
979
1171
  exports;
980
1172
  devaluateImpl(value, parent, depth) {
981
- if (depth >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
1173
+ if (depth >= 256) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
982
1174
  switch (typeForRpc(value)) {
983
1175
  case "unsupported": {
984
1176
  let msg;
@@ -989,10 +1181,12 @@ var Devaluator = class Devaluator {
989
1181
  }
990
1182
  throw new TypeError(msg);
991
1183
  }
992
- case "primitive": if (typeof value === "number" && !isFinite(value)) if (value === Infinity) return ["inf"];
993
- else if (value === -Infinity) return ["-inf"];
994
- else return ["nan"];
995
- else return value;
1184
+ case "primitive": if (typeof value === "number" && !isFinite(value)) {
1185
+ if (this.encodingLevel === "structuredClonable") return value;
1186
+ if (value === Infinity) return ["inf"];
1187
+ else if (value === -Infinity) return ["-inf"];
1188
+ else return ["nan"];
1189
+ } else return value;
996
1190
  case "object": {
997
1191
  let object = value;
998
1192
  let result = {};
@@ -1006,23 +1200,73 @@ var Devaluator = class Devaluator {
1006
1200
  for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
1007
1201
  return [result];
1008
1202
  }
1009
- case "bigint": return ["bigint", value.toString()];
1203
+ case "set": {
1204
+ let set = value;
1205
+ let setElements = [...set];
1206
+ let elements = [];
1207
+ for (let element of setElements) switch (typeForRpc(element)) {
1208
+ case "blob": throw new TypeError("Cannot serialize a Blob as an element of a Set.");
1209
+ case "rpc-promise":
1210
+ 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.");
1211
+ }
1212
+ for (let element of setElements) elements.push(this.devaluateImpl(element, set, depth + 1));
1213
+ return ["set", elements];
1214
+ }
1215
+ case "bigint":
1216
+ if (this.encodingLevel === "structuredClonable") return value;
1217
+ return ["bigint", value.toString()];
1010
1218
  case "date": {
1219
+ if (this.encodingLevel === "structuredClonable") return value;
1011
1220
  const time = value.getTime();
1012
1221
  return ["date", Number.isNaN(time) ? null : time];
1013
1222
  }
1223
+ case "regexp": {
1224
+ if (this.encodingLevel === "structuredClonable") return value;
1225
+ let re = value;
1226
+ return re.flags ? [
1227
+ "regexp",
1228
+ re.source,
1229
+ re.flags
1230
+ ] : ["regexp", re.source];
1231
+ }
1014
1232
  case "bytes": {
1015
- let bytes = value;
1016
- if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1233
+ let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1234
+ let bytes;
1235
+ if (alternateTypeName === "ArrayBuffer") bytes = new Uint8Array(value);
1236
+ else if (alternateTypeName === void 0) bytes = value;
1237
+ else {
1238
+ let view = value;
1239
+ bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1240
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];
1241
+ if (!NATIVE_LITTLE_ENDIAN && elementSize) {
1242
+ bytes = bytes.slice();
1243
+ swapByteOrder(bytes, elementSize);
1244
+ }
1245
+ }
1246
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") {
1247
+ if (bytes.byteLength !== bytes.buffer.byteLength) bytes = new Uint8Array(bytes);
1248
+ return alternateTypeName === void 0 ? ["bytes", bytes] : [
1249
+ "bytes",
1250
+ bytes,
1251
+ alternateTypeName
1252
+ ];
1253
+ }
1017
1254
  let b64;
1018
- if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1255
+ if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1256
+ else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1019
1257
  else {
1020
1258
  let binary = "";
1021
1259
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1022
1260
  b64 = btoa(binary);
1023
1261
  }
1024
- return ["bytes", b64.replace(/=+$/, "")];
1262
+ b64 = b64.replace(/=+$/, "");
1263
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1264
+ "bytes",
1265
+ b64,
1266
+ alternateTypeName
1267
+ ];
1025
1268
  }
1269
+ case "url": return ["url", value.href];
1026
1270
  case "headers": return ["headers", [...value]];
1027
1271
  case "request": {
1028
1272
  let req = value;
@@ -1137,19 +1381,24 @@ var Devaluator = class Devaluator {
1137
1381
  } else if (rewritten && rewritten.stack) result.push(rewritten.stack);
1138
1382
  return result;
1139
1383
  }
1140
- case "undefined": return ["undefined"];
1384
+ case "undefined":
1385
+ if (this.encodingLevel === "structuredClonable") return;
1386
+ return ["undefined"];
1141
1387
  case "stub":
1142
1388
  case "rpc-promise": {
1143
1389
  if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1144
1390
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
1145
1391
  let importId = this.exporter.getImport(hook);
1146
- if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [
1147
- "pipeline",
1148
- importId,
1149
- pathIfPromise
1150
- ];
1151
- else return ["pipeline", importId];
1152
- else return ["import", importId];
1392
+ if (importId !== void 0) {
1393
+ if (pathIfPromise) {
1394
+ if (pathIfPromise.length > 0) return [
1395
+ "pipeline",
1396
+ importId,
1397
+ pathIfPromise
1398
+ ];
1399
+ else return ["pipeline", importId];
1400
+ } else return ["import", importId];
1401
+ }
1153
1402
  if (pathIfPromise) hook = hook.get(pathIfPromise);
1154
1403
  else hook = hook.dup();
1155
1404
  return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
@@ -1204,31 +1453,43 @@ var NullImporter = class {
1204
1453
  getPipeReadable(exportId) {
1205
1454
  throw new Error("Cannot retrieve pipe readable without an RPC session.");
1206
1455
  }
1456
+ getLimits() {
1457
+ return DEFAULT_LIMITS;
1458
+ }
1207
1459
  };
1208
1460
  const NULL_IMPORTER = new NullImporter();
1209
1461
  function fixBrokenRequestBody(request, body) {
1210
- return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {
1462
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1211
1463
  let bytes = new Uint8Array(arrayBuffer);
1212
1464
  let result = new Request(request, { body: bytes });
1213
1465
  return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1214
- })), []);
1466
+ });
1467
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1215
1468
  }
1216
1469
  function streamToBlobPromise(stream, type) {
1217
- return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {
1470
+ let promise = streamToBlob(stream, type).then((blob) => {
1218
1471
  return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1219
- })), []);
1472
+ });
1473
+ return new RpcPromise$1(new PromiseStubHook(promise), []);
1220
1474
  }
1221
1475
  var Evaluator = class Evaluator {
1222
1476
  importer;
1223
- constructor(importer) {
1477
+ encodingLevel;
1478
+ limits;
1479
+ constructor(importer, encodingLevel = "string") {
1224
1480
  this.importer = importer;
1481
+ this.encodingLevel = encodingLevel;
1482
+ this.limits = importer.getLimits();
1225
1483
  }
1226
1484
  hooks = [];
1227
1485
  promises = [];
1228
1486
  evaluate(value) {
1487
+ return this.evaluateWithDepth(value, 0);
1488
+ }
1489
+ evaluateWithDepth(value, depth) {
1229
1490
  let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1230
1491
  try {
1231
- payload.value = this.evaluateImpl(value, payload, "value");
1492
+ payload.value = this.evaluateImpl(value, payload, "value", depth);
1232
1493
  return payload;
1233
1494
  } catch (err) {
1234
1495
  payload.dispose();
@@ -1238,31 +1499,85 @@ var Evaluator = class Evaluator {
1238
1499
  evaluateCopy(value) {
1239
1500
  return this.evaluate(structuredClone(value));
1240
1501
  }
1241
- evaluateImpl(value, parent, property) {
1502
+ evaluateImpl(value, parent, property, depth) {
1503
+ let maxDepth = this.limits.maxDepth;
1504
+ if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1505
+ if (this.encodingLevel === "structuredClonable") {
1506
+ if (value instanceof Date || value instanceof RegExp || typeof value === "bigint") return value;
1507
+ }
1242
1508
  if (value instanceof Array) {
1243
1509
  if (value.length == 1 && value[0] instanceof Array) {
1244
1510
  let result = value[0];
1245
- for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i);
1511
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);
1246
1512
  return result;
1247
1513
  } else switch (value[0]) {
1248
1514
  case "bigint":
1249
- if (typeof value[1] == "string") return BigInt(value[1]);
1515
+ if (typeof value[1] == "string") {
1516
+ let digits = value[1];
1517
+ let maxBigIntDigits = this.limits.maxBigIntDigits;
1518
+ if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);
1519
+ return BigInt(digits);
1520
+ }
1250
1521
  break;
1251
1522
  case "date":
1252
1523
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1253
1524
  if (typeof value[1] == "number") return new Date(value[1]);
1254
1525
  break;
1255
- case "bytes":
1256
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1257
- else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1258
- else {
1259
- let bs = atob(value[1]);
1260
- let len = bs.length;
1261
- let bytes = new Uint8Array(len);
1262
- for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1263
- return bytes;
1526
+ case "regexp":
1527
+ if (typeof value[1] === "string" && (value.length === 2 || value.length === 3 && typeof value[2] === "string")) return new RegExp(value[1], value[2]);
1528
+ break;
1529
+ case "set":
1530
+ if (value.length === 2 && value[1] instanceof Array) {
1531
+ let elements = value[1];
1532
+ let set = /* @__PURE__ */ new Set();
1533
+ for (let i = 0; i < elements.length; i++) {
1534
+ let copy = this.evaluateImpl(elements[i], set, i, depth + 1);
1535
+ if (copy instanceof RpcPromise$1) throw new TypeError("Cannot deserialize a promise as an element of a Set.");
1536
+ set.add(copy);
1537
+ }
1538
+ return set;
1264
1539
  }
1265
1540
  break;
1541
+ case "bytes": {
1542
+ let bytes;
1543
+ if (value[1] instanceof Uint8Array) bytes = value[1];
1544
+ else if (typeof value[1] == "string") {
1545
+ if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1546
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1547
+ else {
1548
+ let bs = atob(value[1]);
1549
+ let len = bs.length;
1550
+ bytes = new Uint8Array(len);
1551
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1552
+ }
1553
+ } else break;
1554
+ if (value.length === 2) return bytes;
1555
+ if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1556
+ if (!isValidByteContainerName(value[2])) {
1557
+ let marker = value[2].slice(0, 64);
1558
+ throw new TypeError(`Unknown bytes type marker: ${marker}`);
1559
+ }
1560
+ let marker = value[2];
1561
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];
1562
+ if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);
1563
+ let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1564
+ if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);
1565
+ switch (marker) {
1566
+ case "ArrayBuffer": return buffer;
1567
+ case "DataView": return new DataView(buffer);
1568
+ case "Int8Array": return new Int8Array(buffer);
1569
+ case "Uint8Array": return new Uint8Array(buffer);
1570
+ case "Uint8ClampedArray": return new Uint8ClampedArray(buffer);
1571
+ case "Int16Array": return new Int16Array(buffer);
1572
+ case "Uint16Array": return new Uint16Array(buffer);
1573
+ case "Int32Array": return new Int32Array(buffer);
1574
+ case "Uint32Array": return new Uint32Array(buffer);
1575
+ case "BigInt64Array": return new BigInt64Array(buffer);
1576
+ case "BigUint64Array": return new BigUint64Array(buffer);
1577
+ case "Float32Array": return new Float32Array(buffer);
1578
+ case "Float64Array": return new Float64Array(buffer);
1579
+ }
1580
+ }
1266
1581
  case "error":
1267
1582
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1268
1583
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -1275,7 +1590,11 @@ var Evaluator = class Evaluator {
1275
1590
  let propsObj = props;
1276
1591
  for (let key of Object.keys(propsObj)) {
1277
1592
  if (key === "name" || key === "message" || key === "stack") continue;
1278
- anyResult[key] = this.evaluateImpl(propsObj[key], result, key);
1593
+ if (key in Object.prototype || key === "toJSON") {
1594
+ this.evaluateImpl(propsObj[key], result, key, depth + 1);
1595
+ continue;
1596
+ }
1597
+ anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);
1279
1598
  }
1280
1599
  }
1281
1600
  return result;
@@ -1287,6 +1606,9 @@ var Evaluator = class Evaluator {
1287
1606
  case "inf": return Infinity;
1288
1607
  case "-inf": return -Infinity;
1289
1608
  case "nan": return NaN;
1609
+ case "url":
1610
+ if (value.length === 2 && typeof value[1] === "string") return new URL(value[1]);
1611
+ break;
1290
1612
  case "headers":
1291
1613
  if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1292
1614
  break;
@@ -1296,11 +1618,11 @@ var Evaluator = class Evaluator {
1296
1618
  let init = value[2];
1297
1619
  if (typeof init !== "object" || init === null) break;
1298
1620
  if (init.body) {
1299
- init.body = this.evaluateImpl(init.body, init, "body");
1621
+ init.body = this.evaluateImpl(init.body, init, "body", depth + 1);
1300
1622
  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.");
1301
1623
  }
1302
1624
  if (init.signal) {
1303
- init.signal = this.evaluateImpl(init.signal, init, "signal");
1625
+ init.signal = this.evaluateImpl(init.signal, init, "signal", depth + 1);
1304
1626
  if (!(init.signal instanceof AbortSignal)) throw new TypeError("Request siganl must be of type AbortSignal.");
1305
1627
  }
1306
1628
  if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
@@ -1317,7 +1639,7 @@ var Evaluator = class Evaluator {
1317
1639
  }
1318
1640
  case "response": {
1319
1641
  if (value.length !== 3) break;
1320
- let body = this.evaluateImpl(value[1], parent, property);
1642
+ let body = this.evaluateImpl(value[1], parent, property, depth + 1);
1321
1643
  if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) {} else throw new TypeError("Response body must be of type ReadableStream.");
1322
1644
  let init = value[2];
1323
1645
  if (typeof init !== "object" || init === null) break;
@@ -1328,7 +1650,7 @@ var Evaluator = class Evaluator {
1328
1650
  case "blob": {
1329
1651
  if (value.length !== 3 || typeof value[1] !== "string") break;
1330
1652
  let contentType = value[1];
1331
- let content = this.evaluateImpl(value[2], parent, property);
1653
+ let content = this.evaluateImpl(value[2], parent, property, depth + 1);
1332
1654
  if (!(content instanceof ReadableStream)) throw new TypeError("Blob content must be serialized as a ReadableStream.");
1333
1655
  let promise = streamToBlobPromise(content, contentType);
1334
1656
  this.promises.push({
@@ -1356,11 +1678,13 @@ var Evaluator = class Evaluator {
1356
1678
  return promise;
1357
1679
  } else {
1358
1680
  this.hooks.push(hook);
1359
- return new RpcPromise$1(hook, []);
1681
+ return new RpcStub$1(hook);
1360
1682
  }
1361
1683
  };
1362
- if (value.length == 2) if (isPromise) return addStub(hook.get([]));
1363
- else return addStub(hook.dup());
1684
+ if (value.length == 2) {
1685
+ if (isPromise) return addStub(hook.get([]));
1686
+ else return addStub(hook.dup());
1687
+ }
1364
1688
  let path = value[2];
1365
1689
  if (!(path instanceof Array)) break;
1366
1690
  if (!path.every((part) => {
@@ -1369,7 +1693,7 @@ var Evaluator = class Evaluator {
1369
1693
  if (value.length == 3) return addStub(hook.get(path));
1370
1694
  let args = value[3];
1371
1695
  if (!(args instanceof Array)) break;
1372
- args = new Evaluator(this.importer).evaluate([args]);
1696
+ args = new Evaluator(this.importer).evaluateWithDepth([args], depth);
1373
1697
  return addStub(hook.call(path, args));
1374
1698
  }
1375
1699
  case "remap": {
@@ -1390,7 +1714,8 @@ var Evaluator = class Evaluator {
1390
1714
  }
1391
1715
  });
1392
1716
  let instructions = value[4];
1393
- let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);
1717
+ let resultHook = hook.map(path, captures, instructions);
1718
+ let promise = new RpcPromise$1(resultHook, []);
1394
1719
  this.promises.push({
1395
1720
  promise,
1396
1721
  parent,
@@ -1400,18 +1725,21 @@ var Evaluator = class Evaluator {
1400
1725
  }
1401
1726
  case "export":
1402
1727
  case "promise":
1403
- if (typeof value[1] == "number") if (value[0] == "promise") {
1404
- let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);
1405
- this.promises.push({
1406
- parent,
1407
- property,
1408
- promise
1409
- });
1410
- return promise;
1411
- } else {
1412
- let hook = this.importer.importStub(value[1]);
1413
- this.hooks.push(hook);
1414
- return new RpcStub$1(hook);
1728
+ if (typeof value[1] == "number") {
1729
+ if (value[0] == "promise") {
1730
+ let hook = this.importer.importPromise(value[1]);
1731
+ let promise = new RpcPromise$1(hook, []);
1732
+ this.promises.push({
1733
+ parent,
1734
+ property,
1735
+ promise
1736
+ });
1737
+ return promise;
1738
+ } else {
1739
+ let hook = this.importer.importStub(value[1]);
1740
+ this.hooks.push(hook);
1741
+ return new RpcStub$1(hook);
1742
+ }
1415
1743
  }
1416
1744
  break;
1417
1745
  case "writable":
@@ -1422,22 +1750,20 @@ var Evaluator = class Evaluator {
1422
1750
  return stream;
1423
1751
  }
1424
1752
  break;
1425
- case "readable":
1426
- if (typeof value[1] == "number") {
1427
- let stream = this.importer.getPipeReadable(value[1]);
1428
- let hook = streamImpl.createReadableStreamHook(stream);
1429
- this.hooks.push(hook);
1430
- return stream;
1431
- }
1432
- break;
1753
+ case "readable": if (typeof value[1] == "number") {
1754
+ let stream = this.importer.getPipeReadable(value[1]);
1755
+ let hook = streamImpl.createReadableStreamHook(stream);
1756
+ this.hooks.push(hook);
1757
+ return stream;
1758
+ }
1433
1759
  }
1434
1760
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1435
1761
  } else if (value instanceof Object) {
1436
1762
  let result = value;
1437
1763
  for (let key in result) if (key in Object.prototype || key === "toJSON") {
1438
- this.evaluateImpl(result[key], result, key);
1764
+ this.evaluateImpl(result[key], result, key, depth + 1);
1439
1765
  delete result[key];
1440
- } else result[key] = this.evaluateImpl(result[key], result, key);
1766
+ } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);
1441
1767
  return result;
1442
1768
  } else return value;
1443
1769
  }
@@ -1453,6 +1779,48 @@ function deserialize(value) {
1453
1779
 
1454
1780
  //#endregion
1455
1781
  //#region src/rpc.ts
1782
+ const ESTIMATED_OBJECT_OVERHEAD = 16;
1783
+ const ESTIMATED_ENTRY_OVERHEAD = 8;
1784
+ const ESTIMATED_BINARY_OVERHEAD = 16;
1785
+ const MAX_ESTIMATE_DEPTH = 64;
1786
+ function estimateStringSize(value) {
1787
+ return 2 + value.length * 3;
1788
+ }
1789
+ function estimateEncodedSize(value, seen, depth = 0) {
1790
+ if (depth >= MAX_ESTIMATE_DEPTH) return ESTIMATED_ENTRY_OVERHEAD;
1791
+ switch (typeof value) {
1792
+ case "string": return estimateStringSize(value);
1793
+ case "number": return 16;
1794
+ case "bigint": return 16;
1795
+ case "boolean": return 8;
1796
+ case "undefined": return 16;
1797
+ case "object": {
1798
+ if (value === null) return 8;
1799
+ if (ArrayBuffer.isView(value)) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1800
+ if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1801
+ if (typeof Blob !== "undefined" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;
1802
+ if (value instanceof Date) return 16;
1803
+ if (value instanceof RegExp) return ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.source) + estimateStringSize(value.flags);
1804
+ seen ??= /* @__PURE__ */ new WeakSet();
1805
+ if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;
1806
+ seen.add(value);
1807
+ if (value instanceof Array) {
1808
+ let size = ESTIMATED_OBJECT_OVERHEAD;
1809
+ for (let item of value) size += ESTIMATED_ENTRY_OVERHEAD + estimateEncodedSize(item, seen, depth + 1);
1810
+ return size;
1811
+ }
1812
+ if (value instanceof Error) {
1813
+ let size = ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.name) + estimateStringSize(value.message) + estimateStringSize(value.stack ?? "");
1814
+ for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);
1815
+ return size;
1816
+ }
1817
+ let size = ESTIMATED_OBJECT_OVERHEAD;
1818
+ for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);
1819
+ return size;
1820
+ }
1821
+ default: return 16;
1822
+ }
1823
+ }
1456
1824
  var ImportTableEntry = class {
1457
1825
  session;
1458
1826
  importId;
@@ -1545,24 +1913,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1545
1913
  if (this.entry) return this.entry;
1546
1914
  else throw new Error("This RpcImportHook was already disposed.");
1547
1915
  }
1916
+ getEntryTakingOwnership(disposeOwned) {
1917
+ try {
1918
+ return this.getEntry();
1919
+ } catch (err) {
1920
+ disposeOwned();
1921
+ throw err;
1922
+ }
1923
+ }
1548
1924
  call(path, args) {
1549
- let entry = this.getEntry();
1925
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1550
1926
  if (entry.resolution) return entry.resolution.call(path, args);
1551
1927
  else return entry.session.sendCall(entry.importId, path, args);
1552
1928
  }
1553
1929
  stream(path, args) {
1554
- let entry = this.getEntry();
1930
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1555
1931
  if (entry.resolution) return entry.resolution.stream(path, args);
1556
1932
  else return entry.session.sendStream(entry.importId, path, args);
1557
1933
  }
1558
1934
  map(path, captures, instructions) {
1559
- let entry;
1560
- try {
1561
- entry = this.getEntry();
1562
- } catch (err) {
1935
+ let entry = this.getEntryTakingOwnership(() => {
1563
1936
  for (let cap of captures) cap.dispose();
1564
- throw err;
1565
- }
1937
+ });
1566
1938
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1567
1939
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1568
1940
  }
@@ -1618,9 +1990,24 @@ var RpcSessionImpl = class {
1618
1990
  onBatchDone;
1619
1991
  pullCount = 0;
1620
1992
  onBrokenCallbacks = [];
1993
+ encodingLevel;
1994
+ limits;
1621
1995
  constructor(transport, mainHook, options) {
1622
1996
  this.transport = transport;
1623
1997
  this.options = options;
1998
+ let level = "string";
1999
+ if ("encodingLevel" in transport) {
2000
+ let raw = transport.encodingLevel;
2001
+ if (raw !== void 0) {
2002
+ if (raw !== "string" && raw !== "jsonCompatible" && raw !== "jsonCompatibleWithBytes" && raw !== "structuredClonable") throw new TypeError(`Unknown transport encodingLevel: ${String(raw)}`);
2003
+ level = raw;
2004
+ }
2005
+ }
2006
+ this.encodingLevel = level;
2007
+ this.limits = {
2008
+ ...DEFAULT_LIMITS,
2009
+ ...options.limits
2010
+ };
1624
2011
  this.exports.push({
1625
2012
  hook: mainHook,
1626
2013
  refcount: 1
@@ -1701,7 +2088,7 @@ var RpcSessionImpl = class {
1701
2088
  let autoRelease = exp.autoRelease;
1702
2089
  ++this.pullCount;
1703
2090
  exp.pull = resolve().then((payload) => {
1704
- let value = Devaluator.devaluate(payload.value, void 0, this, payload);
2091
+ let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);
1705
2092
  this.send([
1706
2093
  "resolve",
1707
2094
  exportId,
@@ -1712,7 +2099,7 @@ var RpcSessionImpl = class {
1712
2099
  this.send([
1713
2100
  "reject",
1714
2101
  exportId,
1715
- Devaluator.devaluate(error, void 0, this)
2102
+ Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)
1716
2103
  ]);
1717
2104
  if (autoRelease) this.releaseExport(exportId, 1);
1718
2105
  }).catch((error) => {
@@ -1720,7 +2107,7 @@ var RpcSessionImpl = class {
1720
2107
  this.send([
1721
2108
  "reject",
1722
2109
  exportId,
1723
- Devaluator.devaluate(error, void 0, this)
2110
+ Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)
1724
2111
  ]);
1725
2112
  if (autoRelease) this.releaseExport(exportId, 1);
1726
2113
  } catch (error2) {
@@ -1763,6 +2150,9 @@ var RpcSessionImpl = class {
1763
2150
  entry.pipeReadable = void 0;
1764
2151
  return readable;
1765
2152
  }
2153
+ getLimits() {
2154
+ return this.limits;
2155
+ }
1766
2156
  createPipe(readable, readableHook) {
1767
2157
  if (this.abortReason) throw this.abortReason;
1768
2158
  this.send(["pipe"]);
@@ -1776,27 +2166,52 @@ var RpcSessionImpl = class {
1776
2166
  }
1777
2167
  send(msg) {
1778
2168
  if (this.abortReason !== void 0) return 0;
1779
- let msgText;
1780
- try {
1781
- msgText = JSON.stringify(msg);
1782
- } catch (err) {
2169
+ if (this.encodingLevel === "string") {
2170
+ let msgText;
1783
2171
  try {
1784
- this.abort(err);
1785
- } catch (err2) {}
1786
- throw err;
2172
+ msgText = JSON.stringify(msg);
2173
+ } catch (err) {
2174
+ try {
2175
+ this.abort(err);
2176
+ } catch (err2) {}
2177
+ throw err;
2178
+ }
2179
+ try {
2180
+ let sent = this.transport.send(msgText);
2181
+ if (sent !== void 0 && typeof sent.catch === "function") sent.catch((err) => this.abort(err, false));
2182
+ } catch (err) {
2183
+ queueMicrotask(() => this.abort(err, false));
2184
+ }
2185
+ return msgText.length;
2186
+ } else try {
2187
+ let size = this.transport.send(msg);
2188
+ if (typeof size === "number") return size;
2189
+ let thenable = size;
2190
+ if (thenable && typeof thenable.then === "function") Promise.resolve(thenable).catch((err) => this.abort(err, false));
2191
+ return;
2192
+ } catch (err) {
2193
+ queueMicrotask(() => this.abort(err, false));
2194
+ return;
1787
2195
  }
1788
- this.transport.send(msgText).catch((err) => this.abort(err, false));
1789
- return msgText.length;
1790
2196
  }
1791
2197
  sendCall(id, path, args) {
1792
- if (this.abortReason) throw this.abortReason;
2198
+ if (this.abortReason) {
2199
+ args?.dispose();
2200
+ throw this.abortReason;
2201
+ }
1793
2202
  let value = [
1794
2203
  "pipeline",
1795
2204
  id,
1796
2205
  path
1797
2206
  ];
1798
2207
  if (args) {
1799
- let devalue = Devaluator.devaluate(args.value, void 0, this, args);
2208
+ let devalue;
2209
+ try {
2210
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2211
+ } catch (err) {
2212
+ args.dispose();
2213
+ throw err;
2214
+ }
1800
2215
  value.push(devalue[0]);
1801
2216
  }
1802
2217
  this.send(["push", value]);
@@ -1805,15 +2220,26 @@ var RpcSessionImpl = class {
1805
2220
  return new RpcImportHook(true, entry);
1806
2221
  }
1807
2222
  sendStream(id, path, args) {
1808
- if (this.abortReason) throw this.abortReason;
2223
+ if (this.abortReason) {
2224
+ args.dispose();
2225
+ throw this.abortReason;
2226
+ }
1809
2227
  let value = [
1810
2228
  "pipeline",
1811
2229
  id,
1812
2230
  path
1813
2231
  ];
1814
- let devalue = Devaluator.devaluate(args.value, void 0, this, args);
2232
+ let devalue;
2233
+ try {
2234
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2235
+ } catch (err) {
2236
+ args.dispose();
2237
+ throw err;
2238
+ }
1815
2239
  value.push(devalue[0]);
1816
- let size = this.send(["stream", value]);
2240
+ let msg = ["stream", value];
2241
+ let size = this.send(msg);
2242
+ if (size === void 0) size = estimateEncodedSize(msg);
1817
2243
  let importId = this.imports.length;
1818
2244
  let entry = new ImportTableEntry(this, importId, true);
1819
2245
  entry.remoteRefcount = 0;
@@ -1869,7 +2295,14 @@ var RpcSessionImpl = class {
1869
2295
  this.cancelReadLoop?.(error);
1870
2296
  this.cancelReadLoop = void 0;
1871
2297
  if (trySendAbortMessage) try {
1872
- this.transport.send(JSON.stringify(["abort", Devaluator.devaluate(error, void 0, this)])).catch((err) => {});
2298
+ let abortMsg = ["abort", Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)];
2299
+ if (this.encodingLevel === "string") {
2300
+ let sent = this.transport.send(JSON.stringify(abortMsg));
2301
+ if (sent !== void 0 && typeof sent.catch === "function") sent.catch((err) => {});
2302
+ } else {
2303
+ let result = this.transport.send(abortMsg);
2304
+ if (result && typeof result.then === "function") Promise.resolve(result).catch((err) => {});
2305
+ }
1873
2306
  } catch (err) {}
1874
2307
  if (error === void 0) error = "undefined";
1875
2308
  this.abortReason = error;
@@ -1891,18 +2324,20 @@ var RpcSessionImpl = class {
1891
2324
  while (!this.abortReason) {
1892
2325
  let readCanceled = Promise.withResolvers();
1893
2326
  this.cancelReadLoop = readCanceled.reject;
1894
- let msgText;
2327
+ let raw;
1895
2328
  try {
1896
- msgText = await Promise.race([this.transport.receive(), readCanceled.promise]);
2329
+ raw = await Promise.race([this.transport.receive(), readCanceled.promise]);
1897
2330
  } finally {
1898
2331
  if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;
1899
2332
  }
1900
- let msg = JSON.parse(msgText);
2333
+ 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.`);
1901
2334
  if (this.abortReason) break;
2335
+ let msg = this.encodingLevel === "string" ? JSON.parse(raw) : raw;
1902
2336
  if (msg instanceof Array) switch (msg[0]) {
1903
2337
  case "push":
1904
2338
  if (msg.length > 1) {
1905
- let hook = new PayloadStubHook(new Evaluator(this).evaluate(msg[1]));
2339
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2340
+ let hook = new PayloadStubHook(payload);
1906
2341
  hook.ignoreUnhandledRejections();
1907
2342
  this.exports.push({
1908
2343
  hook,
@@ -1913,7 +2348,8 @@ var RpcSessionImpl = class {
1913
2348
  break;
1914
2349
  case "stream":
1915
2350
  if (msg.length > 1) {
1916
- let hook = new PayloadStubHook(new Evaluator(this).evaluate(msg[1]));
2351
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2352
+ let hook = new PayloadStubHook(payload);
1917
2353
  hook.ignoreUnhandledRejections();
1918
2354
  let exportId = this.exports.length;
1919
2355
  this.exports.push({
@@ -1948,13 +2384,14 @@ var RpcSessionImpl = class {
1948
2384
  let importId = msg[1];
1949
2385
  if (typeof importId == "number" && msg.length > 2) {
1950
2386
  let imp = this.imports[importId];
1951
- if (imp) if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));
1952
- else {
1953
- let payload = new Evaluator(this).evaluate(msg[2]);
1954
- payload.dispose();
1955
- imp.resolve(new ErrorStubHook(payload.value));
1956
- }
1957
- else if (msg[0] == "resolve") new Evaluator(this).evaluate(msg[2]).dispose();
2387
+ if (imp) {
2388
+ if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2389
+ else {
2390
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2391
+ payload.dispose();
2392
+ imp.resolve(new ErrorStubHook(payload.value));
2393
+ }
2394
+ } else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
1958
2395
  continue;
1959
2396
  }
1960
2397
  break;
@@ -1969,9 +2406,9 @@ var RpcSessionImpl = class {
1969
2406
  break;
1970
2407
  }
1971
2408
  case "abort": {
1972
- let payload = new Evaluator(this).evaluate(msg[1]);
2409
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
1973
2410
  payload.dispose();
1974
- this.abort(payload, false);
2411
+ this.abort(payload.value, false);
1975
2412
  break;
1976
2413
  }
1977
2414
  }
@@ -2022,9 +2459,12 @@ var RpcSession$1 = class {
2022
2459
 
2023
2460
  //#endregion
2024
2461
  //#region src/websocket.ts
2462
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2463
+ const MAX_CLOSE_REASON_BYTES = 123;
2025
2464
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2026
2465
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2027
- return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
2466
+ let transport = new WebSocketTransport(webSocket);
2467
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2028
2468
  }
2029
2469
  /**
2030
2470
  * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
@@ -2041,9 +2481,14 @@ function newWorkersWebSocketRpcResponse(request, localMain, options) {
2041
2481
  webSocket: pair[1]
2042
2482
  });
2043
2483
  }
2484
+ /**
2485
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
2486
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
2487
+ */
2044
2488
  var WebSocketTransport = class {
2045
2489
  constructor(webSocket) {
2046
2490
  this.#webSocket = webSocket;
2491
+ webSocket.binaryType = "arraybuffer";
2047
2492
  if (webSocket.readyState === WebSocket.CONNECTING) {
2048
2493
  this.#sendQueue = [];
2049
2494
  webSocket.addEventListener("open", (event) => {
@@ -2056,12 +2501,13 @@ var WebSocketTransport = class {
2056
2501
  });
2057
2502
  }
2058
2503
  webSocket.addEventListener("message", (event) => {
2059
- if (this.#error) {} else if (typeof event.data === "string") if (this.#receiveResolver) {
2060
- this.#receiveResolver(event.data);
2061
- this.#receiveResolver = void 0;
2062
- this.#receiveRejecter = void 0;
2063
- } else this.#receiveQueue.push(event.data);
2064
- else this.#receivedError(/* @__PURE__ */ new TypeError("Received non-string message from WebSocket."));
2504
+ if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) {
2505
+ if (this.#receiveResolver) {
2506
+ this.#receiveResolver(event.data);
2507
+ this.#receiveResolver = void 0;
2508
+ this.#receiveRejecter = void 0;
2509
+ } else this.#receiveQueue.push(event.data);
2510
+ } else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2065
2511
  });
2066
2512
  webSocket.addEventListener("close", (event) => {
2067
2513
  this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
@@ -2076,13 +2522,13 @@ var WebSocketTransport = class {
2076
2522
  #receiveRejecter;
2077
2523
  #receiveQueue = [];
2078
2524
  #error;
2079
- async send(message) {
2525
+ send(message) {
2080
2526
  if (this.#sendQueue === void 0) this.#webSocket.send(message);
2081
2527
  else this.#sendQueue.push(message);
2082
2528
  }
2083
- async receive() {
2084
- if (this.#receiveQueue.length > 0) return this.#receiveQueue.shift();
2085
- else if (this.#error) throw this.#error;
2529
+ receive() {
2530
+ if (this.#receiveQueue.length > 0) return Promise.resolve(this.#receiveQueue.shift());
2531
+ else if (this.#error) return Promise.reject(this.#error);
2086
2532
  else return new Promise((resolve, reject) => {
2087
2533
  this.#receiveResolver = resolve;
2088
2534
  this.#receiveRejecter = reject;
@@ -2092,6 +2538,8 @@ var WebSocketTransport = class {
2092
2538
  let message;
2093
2539
  if (reason instanceof Error) message = reason.message;
2094
2540
  else message = `${reason}`;
2541
+ let reasonBytes = new TextEncoder().encode(message);
2542
+ if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });
2095
2543
  this.#webSocket.close(3e3, message);
2096
2544
  if (!this.#error) this.#error = reason;
2097
2545
  }
@@ -2109,6 +2557,7 @@ var WebSocketTransport = class {
2109
2557
 
2110
2558
  //#endregion
2111
2559
  //#region src/batch.ts
2560
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2112
2561
  var BatchClientTransport = class {
2113
2562
  constructor(sendBatch) {
2114
2563
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2117,7 +2566,7 @@ var BatchClientTransport = class {
2117
2566
  #aborted;
2118
2567
  #batchToSend = [];
2119
2568
  #batchToReceive = null;
2120
- async send(message) {
2569
+ send(message) {
2121
2570
  if (this.#batchToSend !== null) this.#batchToSend.push(message);
2122
2571
  }
2123
2572
  async receive() {
@@ -2130,7 +2579,7 @@ var BatchClientTransport = class {
2130
2579
  this.#aborted = reason;
2131
2580
  }
2132
2581
  async #scheduleBatch(sendBatch) {
2133
- await new Promise((resolve) => setTimeout(resolve, 0));
2582
+ await yieldToMacrotask();
2134
2583
  if (this.#aborted !== void 0) throw this.#aborted;
2135
2584
  let batch = this.#batchToSend;
2136
2585
  this.#batchToSend = null;
@@ -2150,7 +2599,8 @@ function newHttpBatchRpcSession$1(urlOrRequest, options) {
2150
2599
  let body = await response.text();
2151
2600
  return body == "" ? [] : body.split("\n");
2152
2601
  };
2153
- return new RpcSession$1(new BatchClientTransport(sendBatch), void 0, options).getRemoteMain();
2602
+ let transport = new BatchClientTransport(sendBatch);
2603
+ return new RpcSession$1(transport, void 0, options).getRemoteMain();
2154
2604
  }
2155
2605
  var BatchServerTransport = class {
2156
2606
  constructor(batch) {
@@ -2159,7 +2609,7 @@ var BatchServerTransport = class {
2159
2609
  #batchToSend = [];
2160
2610
  #batchToReceive;
2161
2611
  #allReceived = Promise.withResolvers();
2162
- async send(message) {
2612
+ send(message) {
2163
2613
  this.#batchToSend.push(message);
2164
2614
  }
2165
2615
  async receive() {
@@ -2193,7 +2643,8 @@ var BatchServerTransport = class {
2193
2643
  async function newHttpBatchRpcResponse(request, localMain, options) {
2194
2644
  if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
2195
2645
  let body = await request.text();
2196
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2646
+ let batch = body === "" ? [] : body.split("\n");
2647
+ let transport = new BatchServerTransport(batch);
2197
2648
  let rpc = new RpcSession$1(transport, localMain, options);
2198
2649
  await transport.whenAllReceived();
2199
2650
  await rpc.drain();
@@ -2208,7 +2659,11 @@ async function newHttpBatchRpcResponse(request, localMain, options) {
2208
2659
  * @param options Optional RPC session options. You can also pass headers to set on the response.
2209
2660
  */
2210
2661
  async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2211
- if (request.method !== "POST") response.writeHead(405, "This endpoint only accepts POST requests.");
2662
+ if (request.method !== "POST") {
2663
+ response.writeHead(405, "This endpoint only accepts POST requests.", options?.headers);
2664
+ response.end();
2665
+ return;
2666
+ }
2212
2667
  let body = await new Promise((resolve, reject) => {
2213
2668
  let chunks = [];
2214
2669
  request.on("data", (chunk) => {
@@ -2219,7 +2674,8 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2219
2674
  });
2220
2675
  request.on("error", reject);
2221
2676
  });
2222
- let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2677
+ let batch = body === "" ? [] : body.split("\n");
2678
+ let transport = new BatchServerTransport(batch);
2223
2679
  let rpc = new RpcSession$1(transport, localMain, options);
2224
2680
  await transport.whenAllReceived();
2225
2681
  await rpc.drain();
@@ -2230,20 +2686,21 @@ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2230
2686
  //#endregion
2231
2687
  //#region src/messageport.ts
2232
2688
  function newMessagePortRpcSession$1(port, localMain, options) {
2233
- return new RpcSession$1(new MessagePortTransport(port), localMain, options).getRemoteMain();
2689
+ let transport = new MessagePortTransport(port);
2690
+ return new RpcSession$1(transport, localMain, options).getRemoteMain();
2234
2691
  }
2235
2692
  var MessagePortTransport = class {
2693
+ encodingLevel = "structuredClonable";
2236
2694
  constructor(port) {
2237
2695
  this.#port = port;
2238
2696
  port.start();
2239
2697
  port.addEventListener("message", (event) => {
2240
2698
  if (this.#error) {} else if (event.data === null) this.#receivedError(/* @__PURE__ */ new Error("Peer closed MessagePort connection."));
2241
- else if (typeof event.data === "string") if (this.#receiveResolver) {
2699
+ else if (this.#receiveResolver) {
2242
2700
  this.#receiveResolver(event.data);
2243
2701
  this.#receiveResolver = void 0;
2244
2702
  this.#receiveRejecter = void 0;
2245
2703
  } else this.#receiveQueue.push(event.data);
2246
- else this.#receivedError(/* @__PURE__ */ new TypeError("Received non-string message from MessagePort."));
2247
2704
  });
2248
2705
  port.addEventListener("messageerror", (event) => {
2249
2706
  this.#receivedError(/* @__PURE__ */ new Error("MessagePort message error."));
@@ -2254,7 +2711,7 @@ var MessagePortTransport = class {
2254
2711
  #receiveRejecter;
2255
2712
  #receiveQueue = [];
2256
2713
  #error;
2257
- async send(message) {
2714
+ send(message) {
2258
2715
  if (this.#error) throw this.#error;
2259
2716
  this.#port.postMessage(message);
2260
2717
  }
@@ -2418,9 +2875,11 @@ var MapVariableHook = class extends StubHook {
2418
2875
  else throwMapperBuilderUseError();
2419
2876
  }
2420
2877
  call(path, args) {
2878
+ args.dispose();
2421
2879
  throwMapperBuilderUseError();
2422
2880
  }
2423
2881
  map(path, captures, instructions) {
2882
+ for (let cap of captures) cap.dispose();
2424
2883
  throwMapperBuilderUseError();
2425
2884
  }
2426
2885
  pull() {
@@ -2473,9 +2932,13 @@ var MapApplicator = class {
2473
2932
  getPipeReadable(exportId) {
2474
2933
  throw new Error("A mapper function cannot use pipe readables.");
2475
2934
  }
2935
+ getLimits() {
2936
+ return DEFAULT_LIMITS;
2937
+ }
2476
2938
  };
2477
2939
  function applyMapToElement(input, parent, owner, captures, instructions) {
2478
- let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
2940
+ let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
2941
+ let mapper = new MapApplicator(captures, inputHook);
2479
2942
  try {
2480
2943
  return mapper.apply(instructions);
2481
2944
  } finally {
@@ -2508,9 +2971,10 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2508
2971
  var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2509
2972
  state;
2510
2973
  static create(stream) {
2974
+ let writer = stream.getWriter();
2511
2975
  return new WritableStreamStubHook({
2512
2976
  refcount: 1,
2513
- writer: stream.getWriter(),
2977
+ writer,
2514
2978
  closed: false
2515
2979
  });
2516
2980
  }
@@ -2528,14 +2992,12 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2528
2992
  let state = this.getState();
2529
2993
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2530
2994
  const method = path[0];
2531
- if (method !== "write" && method !== "close" && method !== "abort") {
2532
- args.dispose();
2533
- throw new Error(`Unknown WritableStream method: ${method}`);
2534
- }
2995
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2535
2996
  if (method === "close" || method === "abort") state.closed = true;
2536
- let func = state.writer[method];
2537
- return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2997
+ let promise = method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer);
2998
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2538
2999
  } catch (err) {
3000
+ args.dispose();
2539
3001
  return new ErrorStubHook(err);
2540
3002
  }
2541
3003
  }
@@ -2547,7 +3009,8 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2547
3009
  return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a WritableStream stub"));
2548
3010
  }
2549
3011
  dup() {
2550
- return new WritableStreamStubHook(this.getState(), this);
3012
+ let state = this.getState();
3013
+ return new WritableStreamStubHook(state, this);
2551
3014
  }
2552
3015
  pull() {
2553
3016
  return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a WritableStream stub"));
@@ -2565,9 +3028,9 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2565
3028
  }
2566
3029
  onBroken(callback) {}
2567
3030
  };
2568
- const INITIAL_WINDOW = 256 * 1024;
2569
- const MAX_WINDOW = 1024 * 1024 * 1024;
2570
- const MIN_WINDOW = 64 * 1024;
3031
+ const INITIAL_WINDOW = 262144;
3032
+ const MAX_WINDOW = 1073741824;
3033
+ const MIN_WINDOW = 65536;
2571
3034
  const STARTUP_GROWTH_FACTOR = 2;
2572
3035
  const STEADY_GROWTH_FACTOR = 1.25;
2573
3036
  const DECAY_FACTOR = .9;
@@ -2811,12 +3274,12 @@ let newMessagePortRpcSession = newMessagePortRpcSession$1;
2811
3274
  * credentials as parameters and returns the authorized API), then cross-origin requests should
2812
3275
  * be safe.
2813
3276
  */
2814
- async function newWorkersRpcResponse(request, localMain) {
3277
+ async function newWorkersRpcResponse(request, localMain, options) {
2815
3278
  if (request.method === "POST") {
2816
- let response = await newHttpBatchRpcResponse(request, localMain);
3279
+ let response = await newHttpBatchRpcResponse(request, localMain, options);
2817
3280
  response.headers.set("Access-Control-Allow-Origin", "*");
2818
3281
  return response;
2819
- } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain);
3282
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain, options);
2820
3283
  else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
2821
3284
  }
2822
3285
 
@@ -2937,5 +3400,5 @@ var BunWebSocketTransport = class {
2937
3400
  let newBunWebSocketRpcSession = newBunWebSocketRpcSession$1;
2938
3401
 
2939
3402
  //#endregion
2940
- export { BunWebSocketTransport, RpcPromise, RpcSession, RpcStub, RpcTarget, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
3403
+ export { BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, RpcPromise, RpcSession, RpcStub, RpcTarget, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
2941
3404
  //# sourceMappingURL=index-bun.js.map