@voltro/client 0.80.0 → 0.82.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.
package/dist/runtime.d.ts CHANGED
@@ -6,6 +6,10 @@ import { Rpc } from '@effect/rpc';
6
6
  import { RpcClient } from '@effect/rpc';
7
7
  import { RpcClientError } from '@effect/rpc';
8
8
  import { RpcGroup } from '@effect/rpc';
9
+ import { ServiceApi } from '@voltro/protocol';
10
+ import { ServiceCallOptions } from '@voltro/protocol';
11
+ import { ServiceSubscribeHandlers } from '@voltro/protocol';
12
+ import { ServiceSubscription } from '@voltro/protocol';
9
13
  import * as Socket from '@effect/platform/Socket';
10
14
  import { Stream } from 'effect';
11
15
  import { SubscriptionEvent } from '@voltro/protocol';
@@ -155,6 +159,14 @@ export declare interface BuildApiRuntimeOptions {
155
159
  */
156
160
  readonly errorBus?: RpcErrorBus;
157
161
  readonly recovery?: RecoveryCoordinator;
162
+ /**
163
+ * Which of the server's published surfaces this group should match: the
164
+ * browser's client `surface` (default), or the `serviceSurface` another app
165
+ * of the project calls. A service client compared against the client
166
+ * surface would report every framework built-in as missing — true, and not
167
+ * its concern.
168
+ */
169
+ readonly surfaceAudience?: 'client' | 'service';
158
170
  }
159
171
 
160
172
  export declare type BuildClient = (api: MountedApi, generation: number, onSocketOpen: () => void, onSocketIssue: (kind: SocketIssueKind) => void,
@@ -266,7 +278,10 @@ export declare interface CacheSnapshot<T> {
266
278
  readonly revision: number;
267
279
  /** Wall-clock ms when the most recent server delta was emitted; undefined for snapshots. */
268
280
  readonly emittedAt: number | undefined;
269
- /** Error from the underlying stream (if no snapshot has ever arrived). */
281
+ /** Why the stream failed, if no snapshot has ever arrived — the value the
282
+ * api's error bus carries in `RpcError.error` for the same failure: the
283
+ * declared error itself (match on `_tag`), an `RpcClientError` for a
284
+ * transport failure, or the defect. Never an Effect `Cause`. */
270
285
  readonly error: unknown | undefined;
271
286
  /** Number of live optimistic patches currently applied. */
272
287
  readonly pendingPatches: number;
@@ -388,6 +403,9 @@ declare class ConnectionScope {
388
403
  begin(): ConnectionAttempt;
389
404
  }
390
405
 
406
+ /** Default deadline for one service call. */
407
+ export declare const DEFAULT_SERVICE_CALL_TIMEOUT_MS = 10000;
408
+
391
409
  declare interface EntryState<T> {
392
410
  /** Last server-delivered data (base for patches). */
393
411
  base: T | undefined;
@@ -474,6 +492,8 @@ export declare class LoadingSubscriptionCache extends SubscriptionCache {
474
492
  };
475
493
  }
476
494
 
495
+ export declare const makeServiceClient: (options: ServiceClientOptions) => ServiceClient;
496
+
477
497
  /**
478
498
  * One api the client is mounted against: its name, its typed rpc surface, its
479
499
  * descriptor map and where to connect.
@@ -773,6 +793,71 @@ options?: {
773
793
  readonly signal?: AbortSignal | undefined;
774
794
  }) => Promise<A>;
775
795
 
796
+ /**
797
+ * Wrap an untyped client in the nested, typed facade. The tag is assembled
798
+ * from the property path; the procedure's KIND comes from the callee's
799
+ * descriptors, so a query path resolves to a snapshot and a mutation path to
800
+ * its result.
801
+ */
802
+ export declare const serviceApi: <P>(client: ServiceClient) => ServiceApi<P>;
803
+
804
+ /** One observed call, for the caller's metrics. */
805
+ export declare interface ServiceCallEvent {
806
+ readonly api: string;
807
+ readonly tag: string;
808
+ readonly durationMs: number;
809
+ readonly outcome: 'ok' | 'error' | 'unavailable';
810
+ }
811
+
812
+ /** The untyped client every typed facade sits on. */
813
+ export declare interface ServiceClient {
814
+ readonly name: string;
815
+ /** Call one procedure. A query resolves to its FIRST snapshot. */
816
+ readonly call: (tag: string, input: unknown, options?: ServiceCallOptions) => Promise<unknown>;
817
+ /** The same call as an Effect — failures on the error channel, typed. */
818
+ readonly callEffect: (tag: string, input: unknown, options?: ServiceCallOptions) => Effect.Effect<unknown, unknown>;
819
+ /** Hold a live query open; values arrive materialized (snapshot + deltas applied). */
820
+ readonly subscribe: (tag: string, input: unknown, handlers: ServiceSubscribeHandlers<unknown>) => ServiceSubscription;
821
+ /** Is a transport currently built? (Not proof the socket is open — see `buildApiRuntime`.) */
822
+ readonly connected: () => boolean;
823
+ /** Tear the connection down. Later calls fail with `ApiUnavailable('closed')`. */
824
+ readonly close: () => Promise<void>;
825
+ }
826
+
827
+ export declare interface ServiceClientOptions {
828
+ /** The binding name on the caller — `apis.<name>`. */
829
+ readonly name: string;
830
+ /** The callee's WebSocket endpoint. A function so a late-resolved URL (dev
831
+ * port discovery) is read at connect time, not at construction. */
832
+ readonly wsUrl: string | (() => string);
833
+ /** The service credential, read at each (re)connect. */
834
+ readonly token: () => string;
835
+ /** The callee's `serviceGroup` (erased — see `BuildApiRuntimeOptions.group`). */
836
+ readonly group: RpcGroup.Any;
837
+ /** The callee's `serviceDescriptors` — the kind of every tag. */
838
+ readonly descriptors: Readonly<Record<string, {
839
+ readonly kind: string;
840
+ }>>;
841
+ /** How to open a socket. Defaults to the platform's global `WebSocket`
842
+ * (Node 22+ has one). */
843
+ readonly webSocketConstructor?: (url: string, protocols?: string | ReadonlyArray<string>) => globalThis.WebSocket;
844
+ /** Default deadline for every call. */
845
+ readonly defaultTimeoutMs?: number;
846
+ /**
847
+ * The key a WRITE carries when the call site gave none — derived by the
848
+ * server from where the call is made (a workflow step's execution and name),
849
+ * so a re-sent step replays instead of writing twice. `undefined` → a fresh
850
+ * key per logical call.
851
+ */
852
+ readonly ambientIdempotencyKey?: (tag: string, input: unknown) => Effect.Effect<string | undefined>;
853
+ /** Extra per-call headers (trace propagation). */
854
+ readonly callHeaders?: () => Readonly<Record<string, string>>;
855
+ /** Observe every finished call — metrics, never control flow. */
856
+ readonly onCall?: (event: ServiceCallEvent) => void;
857
+ }
858
+
859
+ export declare type ServiceProcedureKind = 'query' | 'mutation' | 'action';
860
+
776
861
  export declare type SocketIssueKind = 'close' | 'error' | 'connect-timeout';
777
862
 
778
863
  /**
@@ -1063,9 +1148,9 @@ export declare interface SubscriptionCacheOptions {
1063
1148
  * CRDT cell merger for the downstream lane (plan 18): folds a
1064
1149
  * `mergeCells` delta op's incremental update into the held cell. The one
1065
1150
  * real implementation is `crdtMergeCell` from `@voltro/local-first` (this
1066
- * package stays CRDT-library-free). Absent → a mergeCells op replaces the
1067
- * cell (the producer only emits them when the app declares CRDT tables,
1068
- * so an app without the binding never sees one).
1151
+ * package stays CRDT-library-free). Absent → the merger registered with
1152
+ * `registerCellMerger` (`@voltro/local-first` registers `crdtMergeCell` on
1153
+ * import); with none at all, a mergeCells op replaces the cell.
1069
1154
  */
1070
1155
  readonly mergeCell?: (column: string, prevValue: unknown, update: unknown) => unknown;
1071
1156
  /** Milliseconds to keep an entry alive after the last subscriber leaves.
package/dist/runtime.js CHANGED
@@ -1,2 +1,128 @@
1
- import { A as e, D as t, E as n, O as r, S as i, T as a, _ as o, a as s, b as c, d as l, f as u, g as d, h as f, i as p, k as m, l as h, m as g, n as _, o as v, p as y, r as b, s as x, t as S, u as C, v as w, x as T, y as E } from "./authRefresh-Ds_lYhKr.js";
2
- export { h as INITIAL_RECOVERY_SNAPSHOT, o as LoadingSubscriptionCache, C as RecoveryCoordinator, y as RpcErrorBus, w as SubscriptionCache, v as buildApiRuntime, T as clearClientDiagnostics, i as clientDiagnosticsSnapshot, S as isUnauthenticated, g as publishClientError, m as publishClientTrace, a as recordClientDiagnostic, l as recoveryCoordinatorFor, t as rememberRpcErrorKind, f as reportClientError, p as resolveByTag, u as resolveRecoveryOptions, r as rpcErrorKind, b as runRpcPromise, E as stableKey, s as startApiSupervisor, n as subscribeClientDiagnostics, d as subscribeClientErrors, e as subscribeClientTraces, c as supersedesConfirmedPatches, _ as wireAuthRefresh, x as withProtocolOpenRecovery };
1
+ import { A as e, C as t, D as n, M as r, N as i, O as a, S as o, _ as s, a as c, b as l, c as u, d, f, g as p, h as m, i as h, j as g, k as _, l as v, m as y, n as b, o as x, p as S, r as C, s as w, t as T, v as E, w as D, x as O, y as k } from "./authRefresh-Cu2A-H5R.js";
2
+ import { Duration as A, Effect as j, Exit as M, Option as N, Schedule as P, Stream as F } from "effect";
3
+ import * as I from "@effect/platform/Headers";
4
+ import { RpcClient as L } from "@effect/rpc";
5
+ import { ApiUnavailable as R, MUTATION_IN_FLIGHT_RETRY_AFTER_MS as z } from "@voltro/protocol";
6
+ //#region src/serviceClient.ts
7
+ var B = (e) => e?._tag === "MutationInFlight", V = 1e4, H = (e, t) => {
8
+ let n = e.descriptors[t]?.kind;
9
+ return n === "query" || n === "mutation" || n === "action" ? n : void 0;
10
+ }, U = (e) => {
11
+ let t = e.defaultTimeoutMs ?? 1e4, n, r, a = !1, o = () => {
12
+ if (a) return Promise.reject(new R({
13
+ api: e.name,
14
+ tag: "",
15
+ reason: "closed",
16
+ message: "client closed"
17
+ }));
18
+ if (n !== void 0) return n;
19
+ let t = typeof e.wsUrl == "function" ? e.wsUrl() : e.wsUrl, i = e.webSocketConstructor ?? ((e, t) => new globalThis.WebSocket(e, t));
20
+ return n = u({
21
+ name: `service:${e.name}`,
22
+ wsUrl: t,
23
+ group: e.group,
24
+ headers: async () => ({ authorization: `Bearer ${e.token()}` }),
25
+ webSocketConstructor: i,
26
+ surfaceAudience: "service"
27
+ }).then((e) => (r = e, e), (e) => {
28
+ throw n = void 0, e;
29
+ }), n;
30
+ }, s = (t, n, r) => new R({
31
+ api: e.name,
32
+ tag: t,
33
+ reason: n,
34
+ message: r
35
+ }), c = (t) => {
36
+ let n = e.callHeaders?.() ?? {};
37
+ return t.pipe(j.locallyWith(L.currentHeaders, (t) => {
38
+ let r = I.set(t, "authorization", `Bearer ${e.token()}`);
39
+ for (let [e, t] of Object.entries(n)) r = I.set(r, e, t);
40
+ return r;
41
+ }));
42
+ }, l = (e) => e.pipe(F.filter((e) => e._tag === "snapshot" || e._tag === "error"), F.runHead, j.flatMap((e) => {
43
+ if (N.isNone(e)) return j.fail(/* @__PURE__ */ Error("the query stream ended before its first snapshot"));
44
+ let t = e.value;
45
+ return t._tag === "error" ? j.fail(t.error) : j.succeed(t.data);
46
+ })), d = (n, r, i) => {
47
+ let u = H(e, n), d = i?.timeoutMs ?? t, f = Date.now(), p = (t) => {
48
+ e.onCall?.({
49
+ api: e.name,
50
+ tag: n,
51
+ durationMs: Date.now() - f,
52
+ outcome: t
53
+ });
54
+ };
55
+ if (u === void 0) return j.die(/* @__PURE__ */ Error(`apis.${e.name}: '${n}' is not a service procedure of this api — is the caller built against an older contract?`));
56
+ let m = j.gen(function* () {
57
+ let t = yield* j.tryPromise({
58
+ try: () => o(),
59
+ catch: (e) => s(n, a ? "closed" : "transport", `could not build the connection: ${String(e)}`)
60
+ }), d = x(t.client, n);
61
+ if (u === "query") {
62
+ let e = d(r);
63
+ return yield* c(l(e));
64
+ }
65
+ let f = i?.idempotencyKey === void 0 && e.ambientIdempotencyKey !== void 0 ? yield* e.ambientIdempotencyKey(n, r) : void 0, p = i?.idempotencyKey ?? f ?? C();
66
+ return yield* c(h(d(r), p)).pipe(j.tapError((e) => j.sync(() => {
67
+ B(e) && (g = !0);
68
+ })), j.retry({
69
+ while: B,
70
+ schedule: P.spaced(A.millis(z))
71
+ }));
72
+ }), g = !1;
73
+ return m.pipe(j.timeoutFail({
74
+ duration: A.millis(d),
75
+ onTimeout: () => s(n, "timeout", g ? `no answer within ${d} ms — an earlier send with this idempotency key is still in flight on the callee` : `no answer within ${d} ms`)
76
+ }), j.mapError((e) => e?._tag === "RpcClientError" ? s(n, "transport", String(e.message ?? e)) : e), j.tapBoth({
77
+ onFailure: (e) => j.sync(() => p(e?._tag === "ApiUnavailable" ? "unavailable" : "error")),
78
+ onSuccess: () => j.sync(() => p("ok"))
79
+ }));
80
+ };
81
+ return {
82
+ name: e.name,
83
+ call: async (e, t, n) => {
84
+ let r = await j.runPromiseExit(d(e, t, n), n?.signal === void 0 ? void 0 : { signal: n.signal });
85
+ if (M.isSuccess(r)) return r.value;
86
+ throw i(r.cause);
87
+ },
88
+ callEffect: d,
89
+ subscribe: (t, n, r) => {
90
+ if (H(e, t) !== "query") throw Error(`apis.${e.name}: '${t}' is not a query — only a query can be subscribed to`);
91
+ let i, a = !1, c = -2, l;
92
+ return o().then((e) => {
93
+ if (a) return;
94
+ let o = [t, n], s = e.cache.subscribe(o, () => x(e.client, t)(n), e.runtime, () => {
95
+ let e = s.getSnapshot();
96
+ e.error !== void 0 && e.error !== l && (l = e.error, r.onError?.(e.error)), e.revision >= 0 && e.revision !== c && e.data !== void 0 && (c = e.revision, r.onValue(e.data));
97
+ });
98
+ i = s.unsubscribe;
99
+ }, (e) => {
100
+ r.onError?.(s(t, "transport", `could not build the connection: ${String(e)}`));
101
+ }), { unsubscribe: () => {
102
+ a = !0, i?.();
103
+ } };
104
+ },
105
+ connected: () => r !== void 0,
106
+ close: async () => {
107
+ a = !0;
108
+ let e = r;
109
+ r = void 0, n = void 0, e !== void 0 && (e.cache.destroy(e.runtime), await e.runtime.dispose());
110
+ }
111
+ };
112
+ }, W = (e) => {
113
+ let t = (n) => {
114
+ let r = n.join("."), i = Object.assign((t, n) => e.call(r, t, n), {
115
+ effect: (t, n) => e.callEffect(r, t, n),
116
+ subscribe: (t, n) => e.subscribe(r, t, n)
117
+ });
118
+ return new Proxy(i, { get: (e, r) => {
119
+ if (typeof r == "string") {
120
+ if (r === "effect" || r === "subscribe") return e[r];
121
+ if (r !== "then") return t([...n, r]);
122
+ }
123
+ } });
124
+ };
125
+ return new Proxy({}, { get: (e, n) => typeof n == "string" && n !== "then" ? t([n]) : void 0 });
126
+ };
127
+ //#endregion
128
+ export { V as DEFAULT_SERVICE_CALL_TIMEOUT_MS, d as INITIAL_RECOVERY_SNAPSHOT, k as LoadingSubscriptionCache, f as RecoveryCoordinator, m as RpcErrorBus, l as SubscriptionCache, u as buildApiRuntime, t as clearClientDiagnostics, D as clientDiagnosticsSnapshot, T as isUnauthenticated, U as makeServiceClient, p as publishClientError, g as publishClientTrace, n as recordClientDiagnostic, S as recoveryCoordinatorFor, _ as rememberRpcErrorKind, s as reportClientError, x as resolveByTag, y as resolveRecoveryOptions, e as rpcErrorKind, c as runRpcPromise, W as serviceApi, O as stableKey, w as startApiSupervisor, a as subscribeClientDiagnostics, E as subscribeClientErrors, r as subscribeClientTraces, o as supersedesConfirmedPatches, b as wireAuthRefresh, v as withProtocolOpenRecovery };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/client",
3
- "version": "0.80.0",
3
+ "version": "0.82.0",
4
4
  "description": "Framework-agnostic client bindings — the typed RpcClient, subscription cache, and reactive data layer the web hooks build on.",
5
5
  "keywords": [
6
6
  "voltro",
@@ -45,7 +45,7 @@
45
45
  "dependencies": {
46
46
  "@tanstack/form-core": "^1.33.5",
47
47
  "@tanstack/react-store": "^0.11.1",
48
- "@voltro/protocol": "0.80.0"
48
+ "@voltro/protocol": "0.82.0"
49
49
  },
50
50
  "peerDependencies": {
51
51
  "@effect/platform": "^0.97.2",