capnweb 0.0.0-aa4fe30 → 0.0.0-c2bb17b

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.js CHANGED
@@ -1,12 +1,12 @@
1
1
  // src/symbols.ts
2
- var WORKERS_MODULE_SYMBOL = Symbol("workers-module");
2
+ var WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol("workers-module");
3
3
 
4
4
  // src/core.ts
5
5
  if (!Symbol.dispose) {
6
- Symbol.dispose = Symbol.for("dispose");
6
+ Symbol.dispose = /* @__PURE__ */ Symbol.for("dispose");
7
7
  }
8
8
  if (!Symbol.asyncDispose) {
9
- Symbol.asyncDispose = Symbol.for("asyncDispose");
9
+ Symbol.asyncDispose = /* @__PURE__ */ Symbol.for("asyncDispose");
10
10
  }
11
11
  if (!Promise.withResolvers) {
12
12
  Promise.withResolvers = function() {
@@ -22,6 +22,8 @@ if (!Promise.withResolvers) {
22
22
  var workersModule = globalThis[WORKERS_MODULE_SYMBOL];
23
23
  var RpcTarget = workersModule ? workersModule.RpcTarget : class {
24
24
  };
25
+ var AsyncFunction = (async function() {
26
+ }).constructor;
25
27
  function typeForRpc(value) {
26
28
  switch (typeof value) {
27
29
  case "boolean":
@@ -46,6 +48,7 @@ function typeForRpc(value) {
46
48
  case Object.prototype:
47
49
  return "object";
48
50
  case Function.prototype:
51
+ case AsyncFunction.prototype:
49
52
  return "function";
50
53
  case Array.prototype:
51
54
  return "array";
@@ -53,6 +56,10 @@ function typeForRpc(value) {
53
56
  return "date";
54
57
  case Uint8Array.prototype:
55
58
  return "bytes";
59
+ case WritableStream.prototype:
60
+ return "writable";
61
+ case ReadableStream.prototype:
62
+ return "readable";
56
63
  // TODO: All other structured clone types.
57
64
  case RpcStub.prototype:
58
65
  return "stub";
@@ -80,7 +87,34 @@ function mapNotLoaded() {
80
87
  throw new Error("RPC map() implementation was not loaded.");
81
88
  }
82
89
  var mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };
90
+ function streamNotLoaded() {
91
+ throw new Error("Stream implementation was not loaded.");
92
+ }
93
+ var streamImpl = {
94
+ createWritableStreamHook: streamNotLoaded,
95
+ createWritableStreamFromHook: streamNotLoaded,
96
+ createReadableStreamHook: streamNotLoaded
97
+ };
83
98
  var StubHook = class {
99
+ // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:
100
+ // - promise: A Promise<void> for the completion of the call.
101
+ // - size: If the call was remote, the byte size of the serialized message. For local calls,
102
+ // undefined is returned, indicating the caller should await the promise to serialize writes
103
+ // (no overlapping).
104
+ stream(path, args) {
105
+ let hook = this.call(path, args);
106
+ let pulled = hook.pull();
107
+ let promise;
108
+ if (pulled instanceof Promise) {
109
+ promise = pulled.then((p) => {
110
+ p.dispose();
111
+ });
112
+ } else {
113
+ pulled.dispose();
114
+ promise = Promise.resolve();
115
+ }
116
+ return { promise };
117
+ }
84
118
  };
85
119
  var ErrorStubHook = class extends StubHook {
86
120
  constructor(error) {
@@ -129,7 +163,7 @@ function withCallInterceptor(interceptor, callback) {
129
163
  doCall = oldValue;
130
164
  }
131
165
  }
132
- var RAW_STUB = Symbol("realStub");
166
+ var RAW_STUB = /* @__PURE__ */ Symbol("realStub");
133
167
  var PROXY_HANDLERS = {
134
168
  apply(target, thisArg, argumentsList) {
135
169
  let stub = target.raw;
@@ -305,10 +339,10 @@ async function pullPromise(promise) {
305
339
  }
306
340
  var RpcPayload = class _RpcPayload {
307
341
  // Private constructor; use factory functions above to construct.
308
- constructor(value, source, stubs, promises) {
342
+ constructor(value, source, hooks, promises) {
309
343
  this.value = value;
310
344
  this.source = source;
311
- this.stubs = stubs;
345
+ this.hooks = hooks;
312
346
  this.promises = promises;
313
347
  }
314
348
  // Create a payload from a value passed as params to an RPC from the app.
@@ -333,13 +367,13 @@ var RpcPayload = class _RpcPayload {
333
367
  // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the
334
368
  // inputs should not be. (In case of exception, nothing is disposed, though.)
335
369
  static fromArray(array) {
336
- let stubs = [];
370
+ let hooks = [];
337
371
  let promises = [];
338
372
  let resultArray = [];
339
373
  for (let payload of array) {
340
374
  payload.ensureDeepCopied();
341
- for (let stub of payload.stubs) {
342
- stubs.push(stub);
375
+ for (let hook of payload.hooks) {
376
+ hooks.push(hook);
343
377
  }
344
378
  for (let promise of payload.promises) {
345
379
  if (promise.parent === payload) {
@@ -353,12 +387,12 @@ var RpcPayload = class _RpcPayload {
353
387
  }
354
388
  resultArray.push(payload.value);
355
389
  }
356
- return new _RpcPayload(resultArray, "owned", stubs, promises);
390
+ return new _RpcPayload(resultArray, "owned", hooks, promises);
357
391
  }
358
392
  // Create a payload from a value parsed off the wire using Evaluator.evaluate().
359
393
  //
360
- // A payload is constructed with a null value and the given stubs and promises arrays. The value
361
- // is expected to be filled in by the evaluator, and the stubs and promises arrays are expected
394
+ // A payload is constructed with a null value and the given hooks and promises arrays. The value
395
+ // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected
362
396
  // to be extended with stubs found during parsing. (This weird usage model is necessary so that
363
397
  // if the root value turns out to be a promise, its `parent` in `promises` can be the payload
364
398
  // object itself.)
@@ -366,8 +400,8 @@ var RpcPayload = class _RpcPayload {
366
400
  // When done, the payload takes ownership of the final value and all the stubs within. It may
367
401
  // modify the value in preparation for delivery, and may deliver the value directly to the app
368
402
  // without copying.
369
- static forEvaluate(stubs, promises) {
370
- return new _RpcPayload(null, "owned", stubs, promises);
403
+ static forEvaluate(hooks, promises) {
404
+ return new _RpcPayload(null, "owned", hooks, promises);
371
405
  }
372
406
  // Deep-copy the given value, including dup()ing all stubs.
373
407
  //
@@ -389,14 +423,20 @@ var RpcPayload = class _RpcPayload {
389
423
  return result;
390
424
  }
391
425
  // For `source === "return"` payloads only, this tracks any StubHooks created around RpcTargets
392
- // found in the payload at the time that it is serialized (or deep-copied) for return, so that we
393
- // can make sure they are not disposed before the pipeline ends.
426
+ // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for
427
+ // return, so that we can make sure they are not disposed before the pipeline ends.
394
428
  //
395
429
  // This is initialized on first use.
396
430
  rpcTargets;
397
431
  // Get the StubHook representing the given RpcTarget found inside this payload.
398
432
  getHookForRpcTarget(target, parent, dupStubs = true) {
399
433
  if (this.source === "params") {
434
+ if (dupStubs) {
435
+ let dupable = target;
436
+ if (typeof dupable.dup === "function") {
437
+ target = dupable.dup();
438
+ }
439
+ }
400
440
  return TargetStubHook.create(target, parent);
401
441
  } else if (this.source === "return") {
402
442
  let hook = this.rpcTargets?.get(target);
@@ -423,6 +463,64 @@ var RpcPayload = class _RpcPayload {
423
463
  throw new Error("owned payload shouldn't contain raw RpcTargets");
424
464
  }
425
465
  }
466
+ // Get the StubHook representing the given WritableStream found inside this payload.
467
+ getHookForWritableStream(stream, parent, dupStubs = true) {
468
+ if (this.source === "params") {
469
+ return streamImpl.createWritableStreamHook(stream);
470
+ } else if (this.source === "return") {
471
+ let hook = this.rpcTargets?.get(stream);
472
+ if (hook) {
473
+ if (dupStubs) {
474
+ return hook.dup();
475
+ } else {
476
+ this.rpcTargets?.delete(stream);
477
+ return hook;
478
+ }
479
+ } else {
480
+ hook = streamImpl.createWritableStreamHook(stream);
481
+ if (dupStubs) {
482
+ if (!this.rpcTargets) {
483
+ this.rpcTargets = /* @__PURE__ */ new Map();
484
+ }
485
+ this.rpcTargets.set(stream, hook);
486
+ return hook.dup();
487
+ } else {
488
+ return hook;
489
+ }
490
+ }
491
+ } else {
492
+ throw new Error("owned payload shouldn't contain raw WritableStreams");
493
+ }
494
+ }
495
+ // Get the StubHook representing the given ReadableStream found inside this payload.
496
+ getHookForReadableStream(stream, parent, dupStubs = true) {
497
+ if (this.source === "params") {
498
+ return streamImpl.createReadableStreamHook(stream);
499
+ } else if (this.source === "return") {
500
+ let hook = this.rpcTargets?.get(stream);
501
+ if (hook) {
502
+ if (dupStubs) {
503
+ return hook.dup();
504
+ } else {
505
+ this.rpcTargets?.delete(stream);
506
+ return hook;
507
+ }
508
+ } else {
509
+ hook = streamImpl.createReadableStreamHook(stream);
510
+ if (dupStubs) {
511
+ if (!this.rpcTargets) {
512
+ this.rpcTargets = /* @__PURE__ */ new Map();
513
+ }
514
+ this.rpcTargets.set(stream, hook);
515
+ return hook.dup();
516
+ } else {
517
+ return hook;
518
+ }
519
+ }
520
+ } else {
521
+ throw new Error("owned payload shouldn't contain raw ReadableStreams");
522
+ }
523
+ }
426
524
  deepCopy(value, oldParent, property, parent, dupStubs, owner) {
427
525
  let kind = typeForRpc(value);
428
526
  switch (kind) {
@@ -466,22 +564,21 @@ var RpcPayload = class _RpcPayload {
466
564
  this.promises.push({ parent, property, promise });
467
565
  return promise;
468
566
  } else {
469
- let newStub = new RpcStub(hook);
470
- this.stubs.push(newStub);
471
- return newStub;
567
+ this.hooks.push(hook);
568
+ return new RpcStub(hook);
472
569
  }
473
570
  }
474
571
  case "function":
475
572
  case "rpc-target": {
476
573
  let target = value;
477
- let stub;
574
+ let hook;
478
575
  if (owner) {
479
- stub = new RpcStub(owner.getHookForRpcTarget(target, oldParent, dupStubs));
576
+ hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);
480
577
  } else {
481
- stub = new RpcStub(TargetStubHook.create(target, oldParent));
578
+ hook = TargetStubHook.create(target, oldParent);
482
579
  }
483
- this.stubs.push(stub);
484
- return stub;
580
+ this.hooks.push(hook);
581
+ return new RpcStub(hook);
485
582
  }
486
583
  case "rpc-thenable": {
487
584
  let target = value;
@@ -494,6 +591,28 @@ var RpcPayload = class _RpcPayload {
494
591
  this.promises.push({ parent, property, promise });
495
592
  return promise;
496
593
  }
594
+ case "writable": {
595
+ let stream = value;
596
+ let hook;
597
+ if (owner) {
598
+ hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);
599
+ } else {
600
+ hook = streamImpl.createWritableStreamHook(stream);
601
+ }
602
+ this.hooks.push(hook);
603
+ return stream;
604
+ }
605
+ case "readable": {
606
+ let stream = value;
607
+ let hook;
608
+ if (owner) {
609
+ hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
610
+ } else {
611
+ hook = streamImpl.createReadableStreamHook(stream);
612
+ }
613
+ this.hooks.push(hook);
614
+ return stream;
615
+ }
497
616
  default:
498
617
  throw new Error("unreachable");
499
618
  }
@@ -503,12 +622,12 @@ var RpcPayload = class _RpcPayload {
503
622
  ensureDeepCopied() {
504
623
  if (this.source !== "owned") {
505
624
  let dupStubs = this.source === "params";
506
- this.stubs = [];
625
+ this.hooks = [];
507
626
  this.promises = [];
508
627
  try {
509
628
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
510
629
  } catch (err) {
511
- this.stubs = void 0;
630
+ this.hooks = void 0;
512
631
  this.promises = void 0;
513
632
  throw err;
514
633
  }
@@ -611,7 +730,7 @@ var RpcPayload = class _RpcPayload {
611
730
  }
612
731
  dispose() {
613
732
  if (this.source === "owned") {
614
- this.stubs.forEach((stub) => stub[Symbol.dispose]());
733
+ this.hooks.forEach((hook) => hook.dispose());
615
734
  this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
616
735
  } else if (this.source === "return") {
617
736
  this.disposeImpl(this.value, void 0);
@@ -620,7 +739,7 @@ var RpcPayload = class _RpcPayload {
620
739
  }
621
740
  } else ;
622
741
  this.source = "owned";
623
- this.stubs = [];
742
+ this.hooks = [];
624
743
  this.promises = [];
625
744
  }
626
745
  // Recursive dispose, called only when `source` is "return".
@@ -673,6 +792,28 @@ var RpcPayload = class _RpcPayload {
673
792
  }
674
793
  case "rpc-thenable":
675
794
  return;
795
+ case "writable": {
796
+ let stream = value;
797
+ let hook = this.rpcTargets?.get(stream);
798
+ if (hook) {
799
+ this.rpcTargets.delete(stream);
800
+ } else {
801
+ hook = streamImpl.createWritableStreamHook(stream);
802
+ }
803
+ hook.dispose();
804
+ return;
805
+ }
806
+ case "readable": {
807
+ let stream = value;
808
+ let hook = this.rpcTargets?.get(stream);
809
+ if (hook) {
810
+ this.rpcTargets.delete(stream);
811
+ } else {
812
+ hook = streamImpl.createReadableStreamHook(stream);
813
+ }
814
+ hook.dispose();
815
+ return;
816
+ }
676
817
  default:
677
818
  return;
678
819
  }
@@ -681,9 +822,9 @@ var RpcPayload = class _RpcPayload {
681
822
  // *would* be awaited if this payload were to be delivered. See the similarly-named method of
682
823
  // StubHook for explanation.
683
824
  ignoreUnhandledRejections() {
684
- if (this.stubs) {
685
- this.stubs.forEach((stub) => {
686
- unwrapStubOrParent(stub).ignoreUnhandledRejections();
825
+ if (this.hooks) {
826
+ this.hooks.forEach((hook) => {
827
+ hook.ignoreUnhandledRejections();
687
828
  });
688
829
  this.promises.forEach(
689
830
  (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()
@@ -704,6 +845,8 @@ var RpcPayload = class _RpcPayload {
704
845
  case "undefined":
705
846
  case "function":
706
847
  case "rpc-target":
848
+ case "writable":
849
+ case "readable":
707
850
  return;
708
851
  case "array": {
709
852
  let array = value;
@@ -776,6 +919,12 @@ function followPath(value, parent, path, owner) {
776
919
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
777
920
  return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };
778
921
  }
922
+ case "writable":
923
+ value = void 0;
924
+ break;
925
+ case "readable":
926
+ value = void 0;
927
+ break;
779
928
  case "primitive":
780
929
  case "bigint":
781
930
  case "bytes":
@@ -1015,6 +1164,14 @@ var PromiseStubHook = class _PromiseStubHook extends StubHook {
1015
1164
  args.ensureDeepCopied();
1016
1165
  return new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
1017
1166
  }
1167
+ stream(path, args) {
1168
+ args.ensureDeepCopied();
1169
+ let promise = this.promise.then((hook) => {
1170
+ let result = hook.stream(path, args);
1171
+ return result.promise;
1172
+ });
1173
+ return { promise };
1174
+ }
1018
1175
  map(path, captures, instructions) {
1019
1176
  return new _PromiseStubHook(this.promise.then(
1020
1177
  (hook) => hook.map(path, captures, instructions),
@@ -1087,6 +1244,9 @@ var NullExporter = class {
1087
1244
  }
1088
1245
  unexport(ids) {
1089
1246
  }
1247
+ createPipe(readable) {
1248
+ throw new Error("Cannot create pipes without an RPC session.");
1249
+ }
1090
1250
  onSendError(error) {
1091
1251
  }
1092
1252
  };
@@ -1245,6 +1405,22 @@ var Devaluator = class _Devaluator {
1245
1405
  let hook = this.source.getHookForRpcTarget(value, parent);
1246
1406
  return this.devaluateHook("promise", hook);
1247
1407
  }
1408
+ case "writable": {
1409
+ if (!this.source) {
1410
+ throw new Error("Can't serialize WritableStream in this context.");
1411
+ }
1412
+ let hook = this.source.getHookForWritableStream(value, parent);
1413
+ return this.devaluateHook("writable", hook);
1414
+ }
1415
+ case "readable": {
1416
+ if (!this.source) {
1417
+ throw new Error("Can't serialize ReadableStream in this context.");
1418
+ }
1419
+ let ws = value;
1420
+ let hook = this.source.getHookForReadableStream(ws, parent);
1421
+ let importId = this.exporter.createPipe(ws, hook);
1422
+ return ["readable", importId];
1423
+ }
1248
1424
  default:
1249
1425
  throw new Error("unreachable");
1250
1426
  }
@@ -1269,16 +1445,19 @@ var NullImporter = class {
1269
1445
  getExport(idx) {
1270
1446
  return void 0;
1271
1447
  }
1448
+ getPipeReadable(exportId) {
1449
+ throw new Error("Cannot retrieve pipe readable without an RPC session.");
1450
+ }
1272
1451
  };
1273
1452
  var NULL_IMPORTER = new NullImporter();
1274
1453
  var Evaluator = class _Evaluator {
1275
1454
  constructor(importer) {
1276
1455
  this.importer = importer;
1277
1456
  }
1278
- stubs = [];
1457
+ hooks = [];
1279
1458
  promises = [];
1280
1459
  evaluate(value) {
1281
- let payload = RpcPayload.forEvaluate(this.stubs, this.promises);
1460
+ let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1282
1461
  try {
1283
1462
  payload.value = this.evaluateImpl(value, payload, "value");
1284
1463
  return payload;
@@ -1367,9 +1546,8 @@ var Evaluator = class _Evaluator {
1367
1546
  this.promises.push({ promise, parent, property });
1368
1547
  return promise;
1369
1548
  } else {
1370
- let stub = new RpcPromise(hook2, []);
1371
- this.stubs.push(stub);
1372
- return stub;
1549
+ this.hooks.push(hook2);
1550
+ return new RpcPromise(hook2, []);
1373
1551
  }
1374
1552
  };
1375
1553
  if (value.length == 2) {
@@ -1447,12 +1625,27 @@ var Evaluator = class _Evaluator {
1447
1625
  return promise;
1448
1626
  } else {
1449
1627
  let hook = this.importer.importStub(value[1]);
1450
- let stub = new RpcStub(hook);
1451
- this.stubs.push(stub);
1452
- return stub;
1628
+ this.hooks.push(hook);
1629
+ return new RpcStub(hook);
1453
1630
  }
1454
1631
  }
1455
1632
  break;
1633
+ case "writable":
1634
+ if (typeof value[1] == "number") {
1635
+ let hook = this.importer.importStub(value[1]);
1636
+ let stream = streamImpl.createWritableStreamFromHook(hook);
1637
+ this.hooks.push(hook);
1638
+ return stream;
1639
+ }
1640
+ break;
1641
+ case "readable":
1642
+ if (typeof value[1] == "number") {
1643
+ let stream = this.importer.getPipeReadable(value[1]);
1644
+ let hook = streamImpl.createReadableStreamHook(stream);
1645
+ this.hooks.push(hook);
1646
+ return stream;
1647
+ }
1648
+ break;
1456
1649
  }
1457
1650
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1458
1651
  } else if (value instanceof Object) {
@@ -1592,6 +1785,14 @@ var RpcImportHook = class _RpcImportHook extends StubHook {
1592
1785
  return entry.session.sendCall(entry.importId, path, args);
1593
1786
  }
1594
1787
  }
1788
+ stream(path, args) {
1789
+ let entry = this.getEntry();
1790
+ if (entry.resolution) {
1791
+ return entry.resolution.stream(path, args);
1792
+ } else {
1793
+ return entry.session.sendStream(entry.importId, path, args);
1794
+ }
1795
+ }
1595
1796
  map(path, captures, instructions) {
1596
1797
  let entry;
1597
1798
  try {
@@ -1764,19 +1965,23 @@ var RpcSessionImpl = class {
1764
1965
  return payload;
1765
1966
  }
1766
1967
  };
1968
+ let autoRelease = exp.autoRelease;
1767
1969
  ++this.pullCount;
1768
1970
  exp.pull = resolve().then(
1769
1971
  (payload) => {
1770
1972
  let value = Devaluator.devaluate(payload.value, void 0, this, payload);
1771
1973
  this.send(["resolve", exportId, value]);
1974
+ if (autoRelease) this.releaseExport(exportId, 1);
1772
1975
  },
1773
1976
  (error) => {
1774
1977
  this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);
1978
+ if (autoRelease) this.releaseExport(exportId, 1);
1775
1979
  }
1776
1980
  ).catch(
1777
1981
  (error) => {
1778
1982
  try {
1779
1983
  this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);
1984
+ if (autoRelease) this.releaseExport(exportId, 1);
1780
1985
  } catch (error2) {
1781
1986
  this.abort(error2);
1782
1987
  }
@@ -1828,9 +2033,35 @@ var RpcSessionImpl = class {
1828
2033
  getExport(idx) {
1829
2034
  return this.exports[idx]?.hook;
1830
2035
  }
2036
+ getPipeReadable(exportId) {
2037
+ let entry = this.exports[exportId];
2038
+ if (!entry || !entry.pipeReadable) {
2039
+ throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);
2040
+ }
2041
+ let readable = entry.pipeReadable;
2042
+ entry.pipeReadable = void 0;
2043
+ return readable;
2044
+ }
2045
+ createPipe(readable, readableHook) {
2046
+ if (this.abortReason) throw this.abortReason;
2047
+ this.send(["pipe"]);
2048
+ let importId = this.imports.length;
2049
+ let entry = new ImportTableEntry(this, importId, false);
2050
+ this.imports.push(entry);
2051
+ let hook = new RpcImportHook(
2052
+ /*isPromise=*/
2053
+ false,
2054
+ entry
2055
+ );
2056
+ let writable = streamImpl.createWritableStreamFromHook(hook);
2057
+ readable.pipeTo(writable).catch(() => {
2058
+ }).finally(() => readableHook.dispose());
2059
+ return importId;
2060
+ }
2061
+ // Serializes and sends a message. Returns the byte length of the serialized message.
1831
2062
  send(msg) {
1832
2063
  if (this.abortReason !== void 0) {
1833
- return;
2064
+ return 0;
1834
2065
  }
1835
2066
  let msgText;
1836
2067
  try {
@@ -1843,6 +2074,7 @@ var RpcSessionImpl = class {
1843
2074
  throw err;
1844
2075
  }
1845
2076
  this.transport.send(msgText).catch((err) => this.abort(err, false));
2077
+ return msgText.length;
1846
2078
  }
1847
2079
  sendCall(id, path, args) {
1848
2080
  if (this.abortReason) throw this.abortReason;
@@ -1860,6 +2092,34 @@ var RpcSessionImpl = class {
1860
2092
  entry
1861
2093
  );
1862
2094
  }
2095
+ sendStream(id, path, args) {
2096
+ if (this.abortReason) throw this.abortReason;
2097
+ let value = ["pipeline", id, path];
2098
+ let devalue = Devaluator.devaluate(args.value, void 0, this, args);
2099
+ value.push(devalue[0]);
2100
+ let size = this.send(["stream", value]);
2101
+ let importId = this.imports.length;
2102
+ let entry = new ImportTableEntry(
2103
+ this,
2104
+ importId,
2105
+ /*pulling=*/
2106
+ true
2107
+ );
2108
+ entry.remoteRefcount = 0;
2109
+ entry.localRefcount = 1;
2110
+ this.imports.push(entry);
2111
+ let promise = entry.awaitResolution().then(
2112
+ (p) => {
2113
+ p.dispose();
2114
+ delete this.imports[importId];
2115
+ },
2116
+ (err) => {
2117
+ delete this.imports[importId];
2118
+ throw err;
2119
+ }
2120
+ );
2121
+ return { promise, size };
2122
+ }
1863
2123
  sendMap(id, path, captures, instructions) {
1864
2124
  if (this.abortReason) {
1865
2125
  for (let cap of captures) {
@@ -1947,6 +2207,24 @@ var RpcSessionImpl = class {
1947
2207
  continue;
1948
2208
  }
1949
2209
  break;
2210
+ case "stream": {
2211
+ if (msg.length > 1) {
2212
+ let payload = new Evaluator(this).evaluate(msg[1]);
2213
+ let hook = new PayloadStubHook(payload);
2214
+ hook.ignoreUnhandledRejections();
2215
+ let exportId = this.exports.length;
2216
+ this.exports.push({ hook, refcount: 1, autoRelease: true });
2217
+ this.ensureResolvingExport(exportId);
2218
+ continue;
2219
+ }
2220
+ break;
2221
+ }
2222
+ case "pipe": {
2223
+ let { readable, writable } = new TransformStream();
2224
+ let hook = streamImpl.createWritableStreamHook(writable);
2225
+ this.exports.push({ hook, refcount: 1, pipeReadable: readable });
2226
+ continue;
2227
+ }
1950
2228
  case "pull": {
1951
2229
  let exportId = msg[1];
1952
2230
  if (typeof exportId == "number") {
@@ -2442,6 +2720,9 @@ var MapBuilder = class {
2442
2720
  }
2443
2721
  unexport(ids) {
2444
2722
  }
2723
+ createPipe(readable) {
2724
+ throw new Error("Cannot send ReadableStream inside a mapper function.");
2725
+ }
2445
2726
  onSendError(error) {
2446
2727
  }
2447
2728
  };
@@ -2551,6 +2832,9 @@ var MapApplicator = class {
2551
2832
  return this.variables[idx];
2552
2833
  }
2553
2834
  }
2835
+ getPipeReadable(exportId) {
2836
+ throw new Error("A mapper function cannot use pipe readables.");
2837
+ }
2554
2838
  };
2555
2839
  function applyMapToElement(input, parent, owner, captures, instructions) {
2556
2840
  let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
@@ -2591,6 +2875,333 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2591
2875
  }
2592
2876
  }
2593
2877
  };
2878
+
2879
+ // src/streams.ts
2880
+ var WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {
2881
+ state;
2882
+ // undefined when disposed
2883
+ // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.
2884
+ static create(stream) {
2885
+ let writer = stream.getWriter();
2886
+ return new _WritableStreamStubHook({ refcount: 1, writer, closed: false });
2887
+ }
2888
+ constructor(state, dupFrom) {
2889
+ super();
2890
+ this.state = state;
2891
+ if (dupFrom) {
2892
+ ++state.refcount;
2893
+ }
2894
+ }
2895
+ getState() {
2896
+ if (this.state) {
2897
+ return this.state;
2898
+ } else {
2899
+ throw new Error("Attempted to use a WritableStreamStubHook after it was disposed.");
2900
+ }
2901
+ }
2902
+ call(path, args) {
2903
+ try {
2904
+ let state = this.getState();
2905
+ if (path.length !== 1 || typeof path[0] !== "string") {
2906
+ throw new Error("WritableStream stub only supports direct method calls");
2907
+ }
2908
+ const method = path[0];
2909
+ if (method !== "write" && method !== "close" && method !== "abort") {
2910
+ args.dispose();
2911
+ throw new Error(`Unknown WritableStream method: ${method}`);
2912
+ }
2913
+ if (method === "close" || method === "abort") {
2914
+ state.closed = true;
2915
+ }
2916
+ let func = state.writer[method];
2917
+ let promise = args.deliverCall(func, state.writer);
2918
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2919
+ } catch (err) {
2920
+ return new ErrorStubHook(err);
2921
+ }
2922
+ }
2923
+ map(path, captures, instructions) {
2924
+ for (let cap of captures) {
2925
+ cap.dispose();
2926
+ }
2927
+ return new ErrorStubHook(new Error("Cannot use map() on a WritableStream"));
2928
+ }
2929
+ get(path) {
2930
+ return new ErrorStubHook(new Error("Cannot access properties on a WritableStream stub"));
2931
+ }
2932
+ dup() {
2933
+ let state = this.getState();
2934
+ return new _WritableStreamStubHook(state, this);
2935
+ }
2936
+ pull() {
2937
+ return Promise.reject(new Error("Cannot pull a WritableStream stub"));
2938
+ }
2939
+ ignoreUnhandledRejections() {
2940
+ }
2941
+ dispose() {
2942
+ let state = this.state;
2943
+ this.state = void 0;
2944
+ if (state) {
2945
+ if (--state.refcount === 0) {
2946
+ if (!state.closed) {
2947
+ state.writer.abort(new Error("WritableStream RPC stub was disposed without calling close()")).catch(() => {
2948
+ });
2949
+ }
2950
+ state.writer.releaseLock();
2951
+ }
2952
+ }
2953
+ }
2954
+ onBroken(callback) {
2955
+ }
2956
+ };
2957
+ var INITIAL_WINDOW = 256 * 1024;
2958
+ var MAX_WINDOW = 1024 * 1024 * 1024;
2959
+ var MIN_WINDOW = 64 * 1024;
2960
+ var STARTUP_GROWTH_FACTOR = 2;
2961
+ var STEADY_GROWTH_FACTOR = 1.25;
2962
+ var DECAY_FACTOR = 0.9;
2963
+ var STARTUP_EXIT_ROUNDS = 3;
2964
+ var FlowController = class {
2965
+ constructor(now) {
2966
+ this.now = now;
2967
+ }
2968
+ // The current window size in bytes. The sender blocks when bytesInFlight >= window.
2969
+ window = INITIAL_WINDOW;
2970
+ // Total bytes currently in flight (sent but not yet acked).
2971
+ bytesInFlight = 0;
2972
+ // Whether we're still in the startup phase.
2973
+ inStartupPhase = true;
2974
+ // ----- BDP estimation state (private) -----
2975
+ // Total bytes acked so far.
2976
+ delivered = 0;
2977
+ // Time of most recent ack.
2978
+ deliveredTime = 0;
2979
+ // Time when the very first ack was received.
2980
+ firstAckTime = 0;
2981
+ firstAckDelivered = 0;
2982
+ // Global minimum RTT observed (milliseconds).
2983
+ minRtt = Infinity;
2984
+ // For startup exit: count of consecutive RTT rounds where the window didn't meaningfully grow.
2985
+ roundsWithoutIncrease = 0;
2986
+ // Window size at the start of the current round, for startup exit detection.
2987
+ lastRoundWindow = 0;
2988
+ // Time when the current round started.
2989
+ roundStartTime = 0;
2990
+ // Called when a write of `size` bytes is about to be sent. Returns a token that must be
2991
+ // passed to onAck() when the ack arrives, and whether the sender should block (window full).
2992
+ onSend(size) {
2993
+ this.bytesInFlight += size;
2994
+ let token = {
2995
+ sentTime: this.now(),
2996
+ size,
2997
+ deliveredAtSend: this.delivered,
2998
+ deliveredTimeAtSend: this.deliveredTime,
2999
+ windowAtSend: this.window,
3000
+ windowFullAtSend: this.bytesInFlight >= this.window
3001
+ };
3002
+ return { token, shouldBlock: token.windowFullAtSend };
3003
+ }
3004
+ // Called when a previously-sent write fails. Restores bytesInFlight without updating
3005
+ // any BDP estimates.
3006
+ onError(token) {
3007
+ this.bytesInFlight -= token.size;
3008
+ }
3009
+ // Called when an ack is received for a previously-sent write. Updates BDP estimates and
3010
+ // the window. Returns whether a blocked sender should now unblock.
3011
+ onAck(token) {
3012
+ let ackTime = this.now();
3013
+ this.delivered += token.size;
3014
+ this.deliveredTime = ackTime;
3015
+ this.bytesInFlight -= token.size;
3016
+ let rtt = ackTime - token.sentTime;
3017
+ this.minRtt = Math.min(this.minRtt, rtt);
3018
+ if (this.firstAckTime === 0) {
3019
+ this.firstAckTime = ackTime;
3020
+ this.firstAckDelivered = this.delivered;
3021
+ } else {
3022
+ let baseTime;
3023
+ let baseDelivered;
3024
+ if (token.deliveredTimeAtSend === 0) {
3025
+ baseTime = this.firstAckTime;
3026
+ baseDelivered = this.firstAckDelivered;
3027
+ } else {
3028
+ baseTime = token.deliveredTimeAtSend;
3029
+ baseDelivered = token.deliveredAtSend;
3030
+ }
3031
+ let interval = ackTime - baseTime;
3032
+ let bytes = this.delivered - baseDelivered;
3033
+ let bandwidth = bytes / interval;
3034
+ let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;
3035
+ let newWindow = bandwidth * this.minRtt * growthFactor;
3036
+ newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);
3037
+ if (token.windowFullAtSend) {
3038
+ newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);
3039
+ } else {
3040
+ newWindow = Math.max(newWindow, this.window);
3041
+ }
3042
+ this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);
3043
+ if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {
3044
+ if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) {
3045
+ this.roundsWithoutIncrease = 0;
3046
+ } else {
3047
+ if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) {
3048
+ this.inStartupPhase = false;
3049
+ }
3050
+ }
3051
+ this.roundStartTime = ackTime;
3052
+ this.lastRoundWindow = this.window;
3053
+ }
3054
+ }
3055
+ return this.bytesInFlight < this.window;
3056
+ }
3057
+ };
3058
+ function createWritableStreamFromHook(hook) {
3059
+ let pendingError = void 0;
3060
+ let hookDisposed = false;
3061
+ let fc = new FlowController(() => performance.now());
3062
+ let windowResolve;
3063
+ let windowReject;
3064
+ const disposeHook = () => {
3065
+ if (!hookDisposed) {
3066
+ hookDisposed = true;
3067
+ hook.dispose();
3068
+ }
3069
+ };
3070
+ return new WritableStream({
3071
+ write(chunk, controller) {
3072
+ if (pendingError !== void 0) {
3073
+ throw pendingError;
3074
+ }
3075
+ const payload = RpcPayload.fromAppParams([chunk]);
3076
+ const { promise, size } = hook.stream(["write"], payload);
3077
+ if (size === void 0) {
3078
+ return promise.catch((err) => {
3079
+ if (pendingError === void 0) {
3080
+ pendingError = err;
3081
+ }
3082
+ throw err;
3083
+ });
3084
+ } else {
3085
+ let { token, shouldBlock } = fc.onSend(size);
3086
+ promise.then(() => {
3087
+ let hasCapacity = fc.onAck(token);
3088
+ if (hasCapacity && windowResolve) {
3089
+ windowResolve();
3090
+ windowResolve = void 0;
3091
+ windowReject = void 0;
3092
+ }
3093
+ }, (err) => {
3094
+ fc.onError(token);
3095
+ if (pendingError === void 0) {
3096
+ pendingError = err;
3097
+ controller.error(err);
3098
+ disposeHook();
3099
+ }
3100
+ if (windowReject) {
3101
+ windowReject(err);
3102
+ windowResolve = void 0;
3103
+ windowReject = void 0;
3104
+ }
3105
+ });
3106
+ if (shouldBlock) {
3107
+ return new Promise((resolve, reject) => {
3108
+ windowResolve = resolve;
3109
+ windowReject = reject;
3110
+ });
3111
+ }
3112
+ }
3113
+ },
3114
+ async close() {
3115
+ if (pendingError !== void 0) {
3116
+ disposeHook();
3117
+ throw pendingError;
3118
+ }
3119
+ const { promise } = hook.stream(["close"], RpcPayload.fromAppParams([]));
3120
+ try {
3121
+ await promise;
3122
+ } catch (err) {
3123
+ throw pendingError ?? err;
3124
+ } finally {
3125
+ disposeHook();
3126
+ }
3127
+ },
3128
+ abort(reason) {
3129
+ if (pendingError !== void 0) {
3130
+ return;
3131
+ }
3132
+ pendingError = reason ?? new Error("WritableStream was aborted");
3133
+ if (windowReject) {
3134
+ windowReject(pendingError);
3135
+ windowResolve = void 0;
3136
+ windowReject = void 0;
3137
+ }
3138
+ const { promise } = hook.stream(["abort"], RpcPayload.fromAppParams([reason]));
3139
+ promise.then(() => disposeHook(), () => disposeHook());
3140
+ }
3141
+ });
3142
+ }
3143
+ var ReadableStreamStubHook = class _ReadableStreamStubHook extends StubHook {
3144
+ state;
3145
+ // undefined when disposed
3146
+ // Creates a new ReadableStreamStubHook.
3147
+ static create(stream) {
3148
+ return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: false });
3149
+ }
3150
+ constructor(state, dupFrom) {
3151
+ super();
3152
+ this.state = state;
3153
+ if (dupFrom) {
3154
+ ++state.refcount;
3155
+ }
3156
+ }
3157
+ call(path, args) {
3158
+ args.dispose();
3159
+ return new ErrorStubHook(new Error("Cannot call methods on a ReadableStream stub"));
3160
+ }
3161
+ map(path, captures, instructions) {
3162
+ for (let cap of captures) {
3163
+ cap.dispose();
3164
+ }
3165
+ return new ErrorStubHook(new Error("Cannot use map() on a ReadableStream"));
3166
+ }
3167
+ get(path) {
3168
+ return new ErrorStubHook(new Error("Cannot access properties on a ReadableStream stub"));
3169
+ }
3170
+ dup() {
3171
+ let state = this.state;
3172
+ if (!state) {
3173
+ throw new Error("Attempted to dup a ReadableStreamStubHook after it was disposed.");
3174
+ }
3175
+ return new _ReadableStreamStubHook(state, this);
3176
+ }
3177
+ pull() {
3178
+ return Promise.reject(new Error("Cannot pull a ReadableStream stub"));
3179
+ }
3180
+ ignoreUnhandledRejections() {
3181
+ }
3182
+ dispose() {
3183
+ let state = this.state;
3184
+ this.state = void 0;
3185
+ if (state) {
3186
+ if (--state.refcount === 0) {
3187
+ if (!state.canceled) {
3188
+ state.canceled = true;
3189
+ if (!state.stream.locked) {
3190
+ state.stream.cancel(
3191
+ new Error("ReadableStream RPC stub was disposed without being consumed")
3192
+ ).catch(() => {
3193
+ });
3194
+ }
3195
+ }
3196
+ }
3197
+ }
3198
+ }
3199
+ onBroken(callback) {
3200
+ }
3201
+ };
3202
+ streamImpl.createWritableStreamHook = WritableStreamStubHook.create;
3203
+ streamImpl.createWritableStreamFromHook = createWritableStreamFromHook;
3204
+ streamImpl.createReadableStreamHook = ReadableStreamStubHook.create;
2594
3205
  var RpcStub2 = RpcStub;
2595
3206
  var RpcPromise2 = RpcPromise;
2596
3207
  var RpcSession2 = RpcSession;