capnweb 0.0.0-2a02db9 → 0.0.0-2b292e4

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/README.md CHANGED
@@ -199,7 +199,7 @@ The following types can be passed over RPC (in arguments or return values), and
199
199
  * Arrays
200
200
  * `bigint`
201
201
  * `Date`
202
- * `Uint8Array`
202
+ * `ArrayBuffer`, `DataView`, and typed arrays
203
203
  * `Error` and its well-known subclasses
204
204
  * `Blob`
205
205
  * `ReadableStream` and `WritableStream`, with automatic flow control.
@@ -207,7 +207,6 @@ The following types can be passed over RPC (in arguments or return values), and
207
207
 
208
208
  The following types are not supported as of this writing, but may be added in the future:
209
209
  * `Map` and `Set`
210
- * `ArrayBuffer` and typed arrays other than `Uint8Array`
211
210
  * `RegExp`
212
211
 
213
212
  The following are intentionally NOT supported:
@@ -379,6 +378,40 @@ Sometimes you need to pass a stub somewhere where it will be disposed, but also
379
378
 
380
379
  Hint: You can call `.dup()` on a property of a stub or promise, in order to create a stub backed by that property. This is particularly useful when you know in advance that the property is going to resolve to a stub: calling `.dup()` on it gives you a stub you can start using immediately, that otherwise behaves exactly the same as the eventual stub would if you awaited it.
381
380
 
381
+ #### Holding on to a callback past the call that delivered it
382
+
383
+ A common bidirectional-calling pattern is for the client to pass a callback to the server, which the server then invokes later (for example from a timer, an event handler, or a subsequent RPC). Because the callback parameter is a stub, and stubs in params are implicitly disposed when the call returns, the server must duplicate the stub with `.dup()` if it wants to invoke the callback after the call completes:
384
+
385
+ ```ts
386
+ import { type RpcStub, RpcTarget } from 'capnweb';
387
+
388
+ // A callback the client passes in: a stub wrapping a function.
389
+ type Listener = RpcStub<(msg: string) => void>;
390
+
391
+ class Api extends RpcTarget {
392
+ #listener?: Listener;
393
+
394
+ // Stubs passed as params are disposed when the call returns, so `.dup()`
395
+ // to keep a reference that outlives registerListener().
396
+ registerListener(listener: Listener) {
397
+ this.#listener?.[Symbol.dispose](); // release any previous listener
398
+ this.#listener = listener.dup();
399
+ }
400
+
401
+ // A *later* call can invoke the retained callback -- still valid thanks to .dup().
402
+ notify(msg: string) {
403
+ this.#listener?.(msg);
404
+ }
405
+
406
+ // Dispose our duplicate when done so the client-side stub can be freed.
407
+ [Symbol.dispose]() {
408
+ this.#listener?.[Symbol.dispose]();
409
+ }
410
+ }
411
+ ```
412
+
413
+ The same rule applies in the other direction: if the server returns a stub to the client and the client wants to keep using it after disposing the result, the client should `.dup()` the stub before the result is disposed.
414
+
382
415
  ### Listening for disposal
383
416
 
384
417
  An `RpcTarget` may declare a `Symbol.dispose` method. If it does, the RPC system will automatically invoke it when a stub pointing at it (and all its duplicates) has been disposed.
@@ -43,7 +43,19 @@ 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";
49
61
  case Headers.prototype: return "headers";
@@ -513,6 +525,30 @@ var RpcPayload = class RpcPayload {
513
525
  this.dispose();
514
526
  }
515
527
  }
528
+ async deliverStreamWrite(writer) {
529
+ try {
530
+ let promises = [];
531
+ this.deliverTo(this, "value", promises);
532
+ if (promises.length > 0) await Promise.all(promises);
533
+ let chunk = this.value[0];
534
+ if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {
535
+ if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {
536
+ value: () => this.dispose(),
537
+ writable: true,
538
+ enumerable: false,
539
+ configurable: true
540
+ });
541
+ await writer.write(chunk);
542
+ return RpcPayload.fromAppReturn(void 0);
543
+ }
544
+ await writer.write(chunk);
545
+ this.dispose();
546
+ return RpcPayload.fromAppReturn(void 0);
547
+ } catch (err) {
548
+ this.dispose();
549
+ throw err;
550
+ }
551
+ }
516
552
  async deliverResolve() {
517
553
  try {
518
554
  let promises = [];
@@ -937,6 +973,71 @@ const DEFAULT_LIMITS = {
937
973
  maxDepth: 256,
938
974
  maxMessageSize: 32 * 1024 * 1024
939
975
  };
976
+ const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
977
+ const BYTE_CONTAINER_TYPE_NAMES = [
978
+ "ArrayBuffer",
979
+ "DataView",
980
+ "Int8Array",
981
+ "Uint8Array",
982
+ "Uint8ClampedArray",
983
+ "Int16Array",
984
+ "Uint16Array",
985
+ "Int32Array",
986
+ "Uint32Array",
987
+ "BigInt64Array",
988
+ "BigUint64Array",
989
+ "Float32Array",
990
+ "Float64Array"
991
+ ];
992
+ function isValidByteContainerName(value) {
993
+ return BYTE_CONTAINER_TYPE_NAMES.includes(value);
994
+ }
995
+ const TYPED_ARRAY_ELEMENT_SIZE = {
996
+ ArrayBuffer: void 0,
997
+ DataView: void 0,
998
+ Int8Array: void 0,
999
+ Uint8Array: void 0,
1000
+ Uint8ClampedArray: void 0,
1001
+ Int16Array: 2,
1002
+ Uint16Array: 2,
1003
+ Int32Array: 4,
1004
+ Uint32Array: 4,
1005
+ BigInt64Array: 8,
1006
+ BigUint64Array: 8,
1007
+ Float32Array: 4,
1008
+ Float64Array: 8
1009
+ };
1010
+ const BYTE_CONTAINER_PROTOTYPES = {
1011
+ ArrayBuffer: ArrayBuffer.prototype,
1012
+ DataView: DataView.prototype,
1013
+ Int8Array: Int8Array.prototype,
1014
+ Uint8ClampedArray: Uint8ClampedArray.prototype,
1015
+ Int16Array: Int16Array.prototype,
1016
+ Uint16Array: Uint16Array.prototype,
1017
+ Int32Array: Int32Array.prototype,
1018
+ Uint32Array: Uint32Array.prototype,
1019
+ BigInt64Array: BigInt64Array.prototype,
1020
+ BigUint64Array: BigUint64Array.prototype,
1021
+ Float32Array: Float32Array.prototype,
1022
+ Float64Array: Float64Array.prototype
1023
+ };
1024
+ const BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();
1025
+ for (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);
1026
+ function swapByteOrder(bytes, elementSize) {
1027
+ if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);
1028
+ let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1029
+ for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {
1030
+ case 2:
1031
+ view.setUint16(offset, view.getUint16(offset, false), true);
1032
+ break;
1033
+ case 4:
1034
+ view.setUint32(offset, view.getUint32(offset, false), true);
1035
+ break;
1036
+ case 8:
1037
+ view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1038
+ break;
1039
+ }
1040
+ }
940
1041
  var NullExporter = class {
941
1042
  exportStub(stub) {
942
1043
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -1028,17 +1129,38 @@ var Devaluator = class Devaluator {
1028
1129
  return ["date", Number.isNaN(time) ? null : time];
1029
1130
  }
1030
1131
  case "bytes": {
1031
- let bytes = value;
1032
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1033
- if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1132
+ let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1133
+ let bytes;
1134
+ if (alternateTypeName === "ArrayBuffer") bytes = new Uint8Array(value);
1135
+ else if (alternateTypeName === void 0) bytes = value;
1136
+ else {
1137
+ let view = value;
1138
+ bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1139
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];
1140
+ if (!NATIVE_LITTLE_ENDIAN && elementSize) {
1141
+ bytes = bytes.slice();
1142
+ swapByteOrder(bytes, elementSize);
1143
+ }
1144
+ }
1145
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1146
+ "bytes",
1147
+ bytes,
1148
+ alternateTypeName
1149
+ ];
1034
1150
  let b64;
1035
- if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1151
+ if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1152
+ else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1036
1153
  else {
1037
1154
  let binary = "";
1038
1155
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1039
1156
  b64 = btoa(binary);
1040
1157
  }
1041
- return ["bytes", b64.replace(/=+$/, "")];
1158
+ b64 = b64.replace(/=+$/, "");
1159
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1160
+ "bytes",
1161
+ b64,
1162
+ alternateTypeName
1163
+ ];
1042
1164
  }
1043
1165
  case "headers": return ["headers", [...value]];
1044
1166
  case "request": {
@@ -1291,18 +1413,46 @@ var Evaluator = class Evaluator {
1291
1413
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1292
1414
  if (typeof value[1] == "number") return new Date(value[1]);
1293
1415
  break;
1294
- case "bytes":
1295
- if (value[1] instanceof Uint8Array) return value[1];
1296
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1297
- else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1416
+ case "bytes": {
1417
+ let bytes;
1418
+ if (value[1] instanceof Uint8Array) bytes = value[1];
1419
+ else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1420
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1298
1421
  else {
1299
1422
  let bs = atob(value[1]);
1300
1423
  let len = bs.length;
1301
- let bytes = new Uint8Array(len);
1424
+ bytes = new Uint8Array(len);
1302
1425
  for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1303
- return bytes;
1304
1426
  }
1305
- break;
1427
+ else break;
1428
+ if (value.length === 2) return bytes;
1429
+ if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1430
+ if (!isValidByteContainerName(value[2])) {
1431
+ let marker = value[2].slice(0, 64);
1432
+ throw new TypeError(`Unknown bytes type marker: ${marker}`);
1433
+ }
1434
+ let marker = value[2];
1435
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];
1436
+ if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);
1437
+ let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1438
+ if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);
1439
+ switch (marker) {
1440
+ case "ArrayBuffer": return buffer;
1441
+ case "DataView": return new DataView(buffer);
1442
+ case "Int8Array": return new Int8Array(buffer);
1443
+ case "Uint8Array": return new Uint8Array(buffer);
1444
+ case "Uint8ClampedArray": return new Uint8ClampedArray(buffer);
1445
+ case "Int16Array": return new Int16Array(buffer);
1446
+ case "Uint16Array": return new Uint16Array(buffer);
1447
+ case "Int32Array": return new Int32Array(buffer);
1448
+ case "Uint32Array": return new Uint32Array(buffer);
1449
+ case "BigInt64Array": return new BigInt64Array(buffer);
1450
+ case "BigUint64Array": return new BigUint64Array(buffer);
1451
+ case "Float32Array": return new Float32Array(buffer);
1452
+ case "Float64Array": return new Float64Array(buffer);
1453
+ default:
1454
+ }
1455
+ }
1306
1456
  case "error":
1307
1457
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1308
1458
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -2247,6 +2397,7 @@ var WebSocketTransport = class {
2247
2397
 
2248
2398
  //#endregion
2249
2399
  //#region src/batch.ts
2400
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2250
2401
  var BatchClientTransport = class {
2251
2402
  constructor(sendBatch) {
2252
2403
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2268,7 +2419,7 @@ var BatchClientTransport = class {
2268
2419
  this.#aborted = reason;
2269
2420
  }
2270
2421
  async #scheduleBatch(sendBatch) {
2271
- await new Promise((resolve) => setTimeout(resolve, 0));
2422
+ await yieldToMacrotask();
2272
2423
  if (this.#aborted !== void 0) throw this.#aborted;
2273
2424
  let batch = this.#batchToSend;
2274
2425
  this.#batchToSend = null;
@@ -2678,8 +2829,7 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2678
2829
  throw new Error(`Unknown WritableStream method: ${method}`);
2679
2830
  }
2680
2831
  if (method === "close" || method === "abort") state.closed = true;
2681
- let func = state.writer[method];
2682
- return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2832
+ return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2683
2833
  } catch (err) {
2684
2834
  return new ErrorStubHook(err);
2685
2835
  }