capnweb 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -42,8 +43,14 @@ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | I
42
43
  type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
43
44
  | WritableStream<any> // Chunk type can be any RPC-compatible type
44
45
  | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
45
52
  // prettier-ignore
46
- type Stubify<T> = T extends Stubable ? Stub<T> : T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
53
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
47
54
  : T extends {
48
55
  [key: string | number]: any;
49
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -76,6 +83,24 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type b
76
83
  // same type arguments, the checker short-circuits on identity instead of recursing through the
77
84
  // full structural comparison of these mutually-recursive types.
78
85
  type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
95
+ // transformation so constructing from a promised stub matches the method-return type.
96
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
97
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
98
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
99
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
100
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
101
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
102
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
103
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
79
104
  // Type for method return or property on an RPC interface.
80
105
  // - Stubable types are replaced by stubs.
81
106
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -84,14 +109,20 @@ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & Stu
84
109
  // Technically, we use custom thenables here, but they quack like `Promise`s.
85
110
  // Intersecting with `(Maybe)Provider` allows pipelining.
86
111
  // prettier-ignore
87
- type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? RpcPromise$1<R> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
88
- type IsAny<T> = 0 extends (1 & T) ? true : false;
89
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
112
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
113
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
114
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
115
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
116
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
117
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
118
+ // types.
119
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
120
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
90
121
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
91
122
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
92
123
  // For properties, rewrite types to be `Result`s.
93
124
  // In each case, unwrap `Promise`s.
94
- type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
125
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
95
126
  // This is intersected with methods/properties.
96
127
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
97
128
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -109,6 +140,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
109
140
  };
110
141
  type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
111
142
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
143
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
144
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
145
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
112
146
  type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
113
147
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
114
148
  });
@@ -327,9 +361,21 @@ declare const RpcStub: {
327
361
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
328
362
  * if you only intend to use the promise for pipelining and you never await it, then there's no
329
363
  * need to transmit the resolution!
364
+ *
365
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
366
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
367
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
368
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
369
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
370
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
371
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
372
+ * with a `dup()` if you also intend to keep the stub.
330
373
  */
331
374
  type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
332
- declare const RpcPromise: {};
375
+ declare const RpcPromise: {
376
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
377
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
378
+ };
333
379
  /**
334
380
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
335
381
  *
@@ -20,7 +20,8 @@ interface RpcTargetBranded {
20
20
  // `never[]` preserves compatibility with strongly-typed function signatures without introducing
21
21
  // `any` into inference.
22
22
  type Stubable = RpcTargetBranded | ((...args: never[]) => unknown);
23
- type IsUnknown<T> = unknown extends T ? ([T] extends [unknown] ? true : false) : false; // Types that can be passed over RPC
23
+ // Note: also true for `any` (call sites that care check `IsAny` first).
24
+ type IsUnknown<T> = unknown extends T ? true : false; // Types that can be passed over RPC
24
25
  // The reason for using a generic type here is to build the serializable subset of RPC-compatible
25
26
  // composite types. This allows types defined with the "interface" keyword to pass the
26
27
  // serializable check as well. Otherwise, only types defined with the "type" keyword would pass.
@@ -42,8 +43,14 @@ type TypedArray = Uint8Array | Uint8ClampedArray | Uint16Array | Uint32Array | I
42
43
  type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | Blob | ReadableStream<any> // Chunk type can be any RPC-compatible type
43
44
  | WritableStream<any> // Chunk type can be any RPC-compatible type
44
45
  | URL | Request | Response | Headers; // Recursively rewrite all `Stubable` types with `Stub`s, and resolve promises.
46
+ // Arm ordering matters here:
47
+ // - `Promise` must come before `StubBase`: `RpcPromise<T>` matches both, and must resolve
48
+ // through the Promise arm rather than pass through as-is.
49
+ // - `StubBase` must come before `Stubable`: `Stub<T>` of a callable `T` is itself callable, so
50
+ // it matches `Stubable`. Checking `StubBase` first keeps existing stubs as-is instead of
51
+ // double-wrapping them as `Stub<Stub<T>>`.
45
52
  // prettier-ignore
46
- type Stubify<T> = T extends Stubable ? Stub<T> : T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
53
+ type Stubify<T> = T extends Promise<infer U> ? Stubify<U> : T extends StubBase<any> ? T : T extends Stubable ? Stub<T> : T extends Map<infer K, infer V> ? Map<Stubify<K>, Stubify<V>> : T extends Set<infer V> ? Set<Stubify<V>> : T extends [] ? [] : T extends [infer Head, ...infer Tail] ? [Stubify<Head>, ...Stubify<Tail>] : T extends readonly [] ? readonly [] : T extends readonly [infer Head, ...infer Tail] ? readonly [Stubify<Head>, ...Stubify<Tail>] : T extends Array<infer V> ? Array<Stubify<V>> : T extends ReadonlyArray<infer V> ? ReadonlyArray<Stubify<V>> : T extends BaseType ? T // When using "unknown" instead of "any", interfaces are not stubified.
47
54
  : T extends {
48
55
  [key: string | number]: any;
49
56
  } ? { [K in keyof T as K extends string | number ? K : never]: Stubify<T[K]> } : T;
@@ -76,6 +83,24 @@ type MaybeDisposable<T> = T extends object ? Disposable : unknown; // The type b
76
83
  // same type arguments, the checker short-circuits on identity instead of recursing through the
77
84
  // full structural comparison of these mutually-recursive types.
78
85
  type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & StubBase<T> : Promise<Stubify<T> & MaybeDisposable<T>> & Provider<T> & StubBase<T>;
86
+ // The elision `Result` applies to a bare stub type: unwrap `Stub<T>` back to `T` when the
87
+ // payload is `Stubable`. Such stubs await back to a stub either way, so eliding keeps a
88
+ // declared `Promise<RpcStub<T>>` return interchangeable with a `Promise<T>` return.
89
+ // Plain-interface stubs are NOT elided: `RpcPromise<U>` only awaits to `Stub<U>` when
90
+ // `U extends Stubable`, so eliding those would change the awaited type from a stub to a
91
+ // stubified record. The payload check is deliberately non-distributive (`[U] extends [...]`).
92
+ // `Stub<any>` is not elided either: `[any] extends [Stubable]` is true, so without the `IsAny`
93
+ // guard an `any`-payload stub would lose its stub surface.
94
+ // Also used by the `RpcPromise` constructor signature (index.ts), which applies exactly this
95
+ // transformation so constructing from a promised stub matches the method-return type.
96
+ type ElideStub<T> = T extends StubBase<infer U> ? (IsAny<U> extends true ? T : [U] extends [Stubable] ? U : T) : T;
97
+ // What the promise given to `new RpcPromise<T>(...)` may resolve to: the payload itself, or —
98
+ // for stubable payloads — a stub of it. `NoInfer` keeps the stub arm out of inference, so an
99
+ // inferred `T` is always the promise's own resolution type; the arm only matters when `T` is
100
+ // explicitly annotated (`new RpcPromise<Counter>(promiseOfStub)`). Stubs of non-stubable
101
+ // payloads are deliberately rejected: `ElideStub` wouldn't elide those, so accepting one would
102
+ // claim the promise awaits to a stubified record while the runtime resolves to a stub.
103
+ type PayloadOrStub<T> = T | NoInfer<Stub<Extract<T, Stubable>>>;
79
104
  // Type for method return or property on an RPC interface.
80
105
  // - Stubable types are replaced by stubs.
81
106
  // - RpcCompatible types are passed by value, with stubable types replaced by stubs
@@ -84,14 +109,20 @@ type RpcPromise$1<T> = T extends Stubable ? Promise<Stub<T>> & Provider<T> & Stu
84
109
  // Technically, we use custom thenables here, but they quack like `Promise`s.
85
110
  // Intersecting with `(Maybe)Provider` allows pipelining.
86
111
  // prettier-ignore
87
- type Result<R> = IsAny<R> extends true ? UnknownResult : IsUnknown<R> extends true ? UnknownResult : R extends Stubable ? RpcPromise$1<R> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
88
- type IsAny<T> = 0 extends (1 & T) ? true : false;
89
- type UnknownResult = Promise<unknown> & Provider<unknown> & StubBase<unknown>; // Type for method or property on an RPC interface.
112
+ type Result<R> = IsAny<R> extends true ? RpcPromise$1<unknown> // `RpcPromise<U>`: always safe to normalize — `Result` is idempotent — so a declared
113
+ // `RpcPromise<U>` return produces the same type as a `Promise<U>` return.
114
+ : R extends PromiseLike<unknown> & StubBase<infer U> ? Result<U> // Bare stubs: elide per `ElideStub` above. Note there is no `RpcCompatible<R>` re-check
115
+ // here: anything matching our `StubBase` was produced by machinery that already enforced
116
+ // the constraint, and re-evaluating `RpcCompatible<R>` in this arm recurses through its
117
+ // `Stub<Stubable>` member back into `Result`, tripping TS2615 circularity errors in mapped
118
+ // types.
119
+ : R extends StubBase<any> ? RpcPromise$1<ElideStub<R>> : R extends RpcCompatible<R> ? RpcPromise$1<R> : never;
120
+ type IsAny<T> = 0 extends (1 & T) ? true : false; // Type for method or property on an RPC interface.
90
121
  // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s.
91
122
  // Unwrapping `Stub`s allows calling with `Stubable` arguments.
92
123
  // For properties, rewrite types to be `Result`s.
93
124
  // In each case, unwrap `Promise`s.
94
- type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => IsAny<R> extends true ? UnknownResult : Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
125
+ type MethodOrProperty<V> = V extends ((...args: infer P) => infer R) ? (...args: UnstubifyAll<P>) => Result<Awaited<R>> : Result<Awaited<V>>; // Type for the callable part of an `Provider` if `T` is callable.
95
126
  // This is intersected with methods/properties.
96
127
  type MaybeCallableProvider<T> = T extends ((...args: any[]) => any) ? MethodOrProperty<T> : unknown;
97
128
  type TupleIndexKeys<T extends ReadonlyArray<unknown>> = Extract<keyof T, `${number}`>;
@@ -109,6 +140,9 @@ type ArrayProvider<E> = { [K in number]: MethodOrProperty<E> } & {
109
140
  };
110
141
  type TupleProvider<T extends ReadonlyArray<unknown>> = { [K in TupleIndexKeys<T>]: MethodOrProperty<T[K]> } & ArrayProvider<T[number]>; // Base type for all other types providing RPC-like interfaces.
111
142
  // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types.
143
+ // `__RPC_TARGET_BRAND` deliberately flows through the key mapping (as a `never` property) so
144
+ // stubs of branded targets stay assignable to workers-types' `Stubable`. Such stubs match our
145
+ // `Stubable` too — harmless, since all machinery checks `StubBase` before `Stubable`.
112
146
  type Provider<T> = MaybeCallableProvider<T> & (T extends ReadonlyArray<unknown> ? number extends T["length"] ? ArrayProvider<T[number]> : TupleProvider<T> : { [K in Exclude<keyof T, symbol | keyof StubBase<never>>]: MethodOrProperty<T[K]> } & {
113
147
  map<V>(callback: (value: MapCallbackValue<NonNullable<T>>) => MapCallbackReturn<V>): Result<Array<V>>;
114
148
  });
@@ -327,9 +361,21 @@ declare const RpcStub: {
327
361
  * until you actually `await` the promise (or call `then()`, etc. on it). This is an optimization:
328
362
  * if you only intend to use the promise for pipelining and you never await it, then there's no
329
363
  * need to transmit the resolution!
364
+ *
365
+ * You may also construct an `RpcPromise` yourself from a regular `Promise`, using
366
+ * `new RpcPromise(promise)`, allowing you to perform promise pipelining on a local promise. This
367
+ * is semantically identical to creating a local-loopback RPC that returns the promise, and then
368
+ * invoking it: pipelined calls wait until the promise resolves, then are delivered, in order, to
369
+ * the resolution. This is useful when you plan to obtain some stub in the future, but want to
370
+ * allow code to start queuing calls on it immediately. Note that the `RpcPromise` takes
371
+ * ownership of the resolution: disposing it disposes the resolution, so resolve the promise
372
+ * with a `dup()` if you also intend to keep the stub.
330
373
  */
331
374
  type RpcPromise<T extends RpcCompatible<T>> = RpcPromise$1<T>;
332
- declare const RpcPromise: {};
375
+ declare const RpcPromise: {
376
+ new <T extends RpcCompatible<T>>(value: Promise<T>): RpcPromise$1<ElideStub<T>>;
377
+ new <T extends RpcCompatible<T>>(value: Promise<PayloadOrStub<T>>): RpcPromise$1<ElideStub<T>>;
378
+ };
333
379
  /**
334
380
  * Use to construct an `RpcSession` on top of a custom `RpcTransport`.
335
381
  *
@@ -96,7 +96,14 @@ let streamImpl = {
96
96
  };
97
97
  var StubHook = class {
98
98
  stream(path, args) {
99
- let pulled = this.call(path, args).pull();
99
+ let hook = this.call(path, args);
100
+ let pulled;
101
+ try {
102
+ pulled = hook.pull();
103
+ } catch (err) {
104
+ hook.dispose();
105
+ throw err;
106
+ }
100
107
  let promise;
101
108
  if (pulled instanceof Promise) promise = pulled.then((p) => {
102
109
  p.dispose();
@@ -115,9 +122,11 @@ var ErrorStubHook = class extends StubHook {
115
122
  this.error = error;
116
123
  }
117
124
  call(path, args) {
125
+ args.dispose();
118
126
  return this;
119
127
  }
120
128
  map(path, captures, instructions) {
129
+ for (let cap of captures) cap.dispose();
121
130
  return this;
122
131
  }
123
132
  get(path) {
@@ -241,7 +250,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
241
250
  };
242
251
  var RpcPromise$1 = class extends RpcStub$1 {
243
252
  constructor(hook, pathIfPromise) {
244
- super(hook, pathIfPromise);
253
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
254
+ else {
255
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
256
+ let kind = typeForRpc(hook);
257
+ if (kind === "rpc-promise") {
258
+ let raw = unwrapStubAndPath(hook);
259
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
260
+ else {
261
+ let adopted = raw.hook;
262
+ raw.hook = DISPOSED_HOOK;
263
+ super(adopted, []);
264
+ }
265
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
266
+ else {
267
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
268
+ promiseHook.ignoreUnhandledRejections();
269
+ super(promiseHook, []);
270
+ }
271
+ }
245
272
  }
246
273
  then(onfulfilled, onrejected) {
247
274
  return pullPromise(this).then(...arguments);
@@ -781,17 +808,22 @@ function followPath(value, parent, path, owner) {
781
808
  }
782
809
  var ValueStubHook = class extends StubHook {
783
810
  call(path, args) {
811
+ let followResult;
784
812
  try {
785
813
  let { value, owner } = this.getValue();
786
- let followResult = followPath(value, void 0, path, owner);
787
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
788
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
789
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
790
- return new PayloadStubHook(payload);
791
- }));
814
+ followResult = followPath(value, void 0, path, owner);
792
815
  } catch (err) {
816
+ args.dispose();
793
817
  return new ErrorStubHook(err);
794
818
  }
819
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
820
+ if (typeof followResult.value != "function") {
821
+ args.dispose();
822
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
823
+ }
824
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
825
+ return new PayloadStubHook(payload);
826
+ }));
795
827
  }
796
828
  map(path, captures, instructions) {
797
829
  try {
@@ -812,7 +844,10 @@ var ValueStubHook = class extends StubHook {
812
844
  get(path) {
813
845
  try {
814
846
  let { value, owner } = this.getValue();
815
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
847
+ if (path.length === 0 && owner === null) {
848
+ if (value instanceof Object && "then" in value) return this.dup();
849
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
850
+ }
816
851
  let followResult = followPath(value, void 0, path, owner);
817
852
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
818
853
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -915,7 +950,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
915
950
  this.target = void 0;
916
951
  }
917
952
  }
918
- onBroken(callback) {}
953
+ onBroken(callback) {
954
+ let target = this.target;
955
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
956
+ }
919
957
  };
920
958
  var PromiseStubHook = class PromiseStubHook extends StubHook {
921
959
  promise;
@@ -929,12 +967,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
929
967
  }
930
968
  call(path, args) {
931
969
  args.ensureDeepCopied();
932
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
970
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
971
+ args.dispose();
972
+ throw err;
973
+ }));
933
974
  }
934
975
  stream(path, args) {
935
976
  args.ensureDeepCopied();
936
- return { promise: this.promise.then((hook) => {
937
- return hook.stream(path, args).promise;
977
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
978
+ args.dispose();
979
+ throw err;
938
980
  }) };
939
981
  }
940
982
  map(path, captures, instructions) {
@@ -961,10 +1003,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
961
1003
  }, (err) => {});
962
1004
  }
963
1005
  dispose() {
964
- if (this.resolution) this.resolution.dispose();
965
- else this.promise.then((hook) => {
966
- hook.dispose();
967
- }, (err) => {});
1006
+ this.promise.then((hook) => hook.dispose(), () => {});
968
1007
  }
969
1008
  onBroken(callback) {
970
1009
  if (this.resolution) this.resolution.onBroken(callback);
@@ -1793,24 +1832,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1793
1832
  if (this.entry) return this.entry;
1794
1833
  else throw new Error("This RpcImportHook was already disposed.");
1795
1834
  }
1835
+ getEntryTakingOwnership(disposeOwned) {
1836
+ try {
1837
+ return this.getEntry();
1838
+ } catch (err) {
1839
+ disposeOwned();
1840
+ throw err;
1841
+ }
1842
+ }
1796
1843
  call(path, args) {
1797
- let entry = this.getEntry();
1844
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1798
1845
  if (entry.resolution) return entry.resolution.call(path, args);
1799
1846
  else return entry.session.sendCall(entry.importId, path, args);
1800
1847
  }
1801
1848
  stream(path, args) {
1802
- let entry = this.getEntry();
1849
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1803
1850
  if (entry.resolution) return entry.resolution.stream(path, args);
1804
1851
  else return entry.session.sendStream(entry.importId, path, args);
1805
1852
  }
1806
1853
  map(path, captures, instructions) {
1807
- let entry;
1808
- try {
1809
- entry = this.getEntry();
1810
- } catch (err) {
1854
+ let entry = this.getEntryTakingOwnership(() => {
1811
1855
  for (let cap of captures) cap.dispose();
1812
- throw err;
1813
- }
1856
+ });
1814
1857
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1815
1858
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1816
1859
  }
@@ -2071,14 +2114,23 @@ var RpcSessionImpl = class {
2071
2114
  }
2072
2115
  }
2073
2116
  sendCall(id, path, args) {
2074
- if (this.abortReason) throw this.abortReason;
2117
+ if (this.abortReason) {
2118
+ args?.dispose();
2119
+ throw this.abortReason;
2120
+ }
2075
2121
  let value = [
2076
2122
  "pipeline",
2077
2123
  id,
2078
2124
  path
2079
2125
  ];
2080
2126
  if (args) {
2081
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2127
+ let devalue;
2128
+ try {
2129
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2130
+ } catch (err) {
2131
+ args.dispose();
2132
+ throw err;
2133
+ }
2082
2134
  value.push(devalue[0]);
2083
2135
  }
2084
2136
  this.send(["push", value]);
@@ -2087,13 +2139,22 @@ var RpcSessionImpl = class {
2087
2139
  return new RpcImportHook(true, entry);
2088
2140
  }
2089
2141
  sendStream(id, path, args) {
2090
- if (this.abortReason) throw this.abortReason;
2142
+ if (this.abortReason) {
2143
+ args.dispose();
2144
+ throw this.abortReason;
2145
+ }
2091
2146
  let value = [
2092
2147
  "pipeline",
2093
2148
  id,
2094
2149
  path
2095
2150
  ];
2096
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2151
+ let devalue;
2152
+ try {
2153
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2154
+ } catch (err) {
2155
+ args.dispose();
2156
+ throw err;
2157
+ }
2097
2158
  value.push(devalue[0]);
2098
2159
  let msg = ["stream", value];
2099
2160
  let size = this.send(msg);
@@ -2724,9 +2785,11 @@ var MapVariableHook = class extends StubHook {
2724
2785
  else throwMapperBuilderUseError();
2725
2786
  }
2726
2787
  call(path, args) {
2788
+ args.dispose();
2727
2789
  throwMapperBuilderUseError();
2728
2790
  }
2729
2791
  map(path, captures, instructions) {
2792
+ for (let cap of captures) cap.dispose();
2730
2793
  throwMapperBuilderUseError();
2731
2794
  }
2732
2795
  pull() {
@@ -2837,13 +2900,11 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2837
2900
  let state = this.getState();
2838
2901
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2839
2902
  const method = path[0];
2840
- if (method !== "write" && method !== "close" && method !== "abort") {
2841
- args.dispose();
2842
- throw new Error(`Unknown WritableStream method: ${method}`);
2843
- }
2903
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2844
2904
  if (method === "close" || method === "abort") state.closed = true;
2845
2905
  return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2846
2906
  } catch (err) {
2907
+ args.dispose();
2847
2908
  return new ErrorStubHook(err);
2848
2909
  }
2849
2910
  }