@reliantlabs/forge-web-runtime 0.10.2 → 0.11.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.
@@ -1,5 +1,5 @@
1
1
  import { type DescMessage, type MessageInitShape } from "@bufbuild/protobuf";
2
- import { type InfiniteData, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult } from "@tanstack/react-query";
2
+ import { type DataTag, type InfiniteData, type UseInfiniteQueryOptions, type UseInfiniteQueryResult, type UseMutationOptions, type UseMutationResult, type UseQueryOptions, type UseQueryResult } from "@tanstack/react-query";
3
3
  import type { ConnectClientError } from "./errors.js";
4
4
  /**
5
5
  * A generated query key. The tuple is [service, entity?, method,
@@ -82,26 +82,76 @@ export declare function serviceKeys(service: string): ServiceKeyBuilders;
82
82
  */
83
83
  export type ServiceCall<Schema extends DescMessage, Response> = (req: MessageInitShape<Schema>, signal?: AbortSignal) => Promise<Response>;
84
84
  /**
85
- * A generated query hook: `useGetOrder(req, options?)`.
85
+ * The options a generated read takes — its hook (`useGetOrder(req,
86
+ * options?)`) and its query-options builder
87
+ * (`orderServiceQueries.getOrder(req, options?)`) alike: React Query's own,
88
+ * minus the two the read owns, the key and the fetch. Everything else
89
+ * (`select`, `enabled`, `staleTime`, `placeholderData`, …) passes through.
86
90
  *
87
- * TData is what the hook's `data` is, exactly as in React Query's own
88
- * useQuery: the response by default, or whatever `select` returns. A call
89
- * site mapping the proto response to a view model passes
90
- * `select: (r) => toView(r)` and gets `data: View` — no useMemo over `data`,
91
- * and React Query re-runs the mapping only when the response changes (or
92
- * when `select` itself does, so hoist it or wrap it in useCallback when it
93
- * is expensive). TData is inferred from `select` and is a parameter of the
94
- * HOOK, not of the factory, so every call site picks its own.
95
- */
96
- export type ServiceQueryHook<Schema extends DescMessage, Response> = <TData = Response>(req: MessageInitShape<Schema>, options?: Partial<UseQueryOptions<Response, ConnectClientError, TData>>) => UseQueryResult<TData, ConnectClientError>;
97
- /**
98
- * The options a generated infinite hook takes: React Query's own, minus the
99
- * four the hook owns — the key, the fetch, and the page-token plumbing.
91
+ * TData is what `data` is, exactly as in React Query's own useQuery: the
92
+ * response by default, or whatever `select` returns. A call site mapping the
93
+ * proto response to a view model passes `select: (r) => toView(r)` and gets
94
+ * `data: View` — no useMemo over `data`, and React Query re-runs the mapping
95
+ * only when the response changes (or when `select` itself does, so hoist it
96
+ * or wrap it in useCallback when it is expensive).
97
+ */
98
+ export type ServiceQueryInput<Response, TData = Response> = Partial<Omit<UseQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey>, "queryKey" | "queryFn">>;
99
+ /**
100
+ * What a query-options builder returns: TanStack's `queryOptions(...)`
101
+ * result, so it goes anywhere React Query takes one —
102
+ * `queryClient.fetchQuery`, `ensureQueryData`, `prefetchQuery`,
103
+ * `useQueries({ queries })`, `useQuery`, `useSuspenseQuery`. Its `queryKey`
104
+ * is data-tagged, so `queryClient.getQueryData(opts.queryKey)` and
105
+ * `setQueryData` are typed as the response with no annotation.
106
+ *
107
+ * fetchQuery / ensureQueryData resolve to the RESPONSE, not to `select`'s
108
+ * TData: they return what the cache holds, and `select` is an observer
109
+ * option that only a hook or useQueries applies.
110
+ */
111
+ export type ServiceQueryOptions<Response, TData = Response> = UseQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey> & {
112
+ queryKey: DataTag<ServiceQueryKey, Response, ConnectClientError>;
113
+ };
114
+ /**
115
+ * A generated query-options builder: `orderServiceQueries.getOrder(req,
116
+ * options?)`. It is the read's single definition — the generated hook
117
+ * `useGetOrder` is `useQuery` over exactly this — so code outside React (an
118
+ * imperative action, a stream handler, a router loader, a prefetch) shares
119
+ * the hook's cache entry and fetch by construction rather than by copying
120
+ * its key and its client call.
121
+ */
122
+ export type ServiceQueryOptionsBuilder<Schema extends DescMessage, Response> = <TData = Response>(req: MessageInitShape<Schema>, options?: ServiceQueryInput<Response, TData>) => ServiceQueryOptions<Response, TData>;
123
+ /**
124
+ * A generated query hook: `useGetOrder(req, options?)` — `useQuery` over the
125
+ * service's query-options builder for the same rpc. TData is inferred from
126
+ * `select` and is a parameter of the HOOK, not of the factory, so every call
127
+ * site picks its own.
128
+ */
129
+ export type ServiceQueryHook<Schema extends DescMessage, Response> = <TData = Response>(req: MessageInitShape<Schema>, options?: ServiceQueryInput<Response, TData>) => UseQueryResult<TData, ConnectClientError>;
130
+ /**
131
+ * The options a generated infinite read takes: React Query's own, minus the
132
+ * three the read owns — the key, the fetch, and the first page param.
100
133
  * `getNextPageParam` defaults to the response's `nextPageToken` (empty means
101
134
  * last page) and may be overridden; everything else (`select`,
102
135
  * `placeholderData`, `staleTime`, `enabled`, `maxPages`, …) passes through.
103
136
  */
104
- export type ServiceInfiniteQueryOptions<Response, TData> = Partial<Omit<UseInfiniteQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey, string>, "queryKey" | "queryFn" | "initialPageParam">>;
137
+ export type ServiceInfiniteQueryInput<Response, TData> = Partial<Omit<UseInfiniteQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey, string>, "queryKey" | "queryFn" | "initialPageParam">>;
138
+ /**
139
+ * What an infinite query-options builder returns: TanStack's
140
+ * `infiniteQueryOptions(...)` result, for `queryClient.fetchInfiniteQuery`,
141
+ * `prefetchInfiniteQuery`, `ensureInfiniteQueryData` and
142
+ * `useInfiniteQuery`. Its key is data-tagged as `InfiniteData<Response,
143
+ * string>`, the `{ pages, pageParams }` the cache holds.
144
+ */
145
+ export type ServiceInfiniteQueryOptions<Response, TData = InfiniteData<Response, string>> = UseInfiniteQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey, string> & {
146
+ queryKey: DataTag<ServiceQueryKey, InfiniteData<Response, string>, ConnectClientError>;
147
+ };
148
+ /**
149
+ * A generated infinite query-options builder:
150
+ * `orderServiceQueries.listOrdersInfinite(req, options?)`, for a read that
151
+ * follows forge's list-pagination shape. `useListOrdersInfinite` is
152
+ * `useInfiniteQuery` over exactly this.
153
+ */
154
+ export type ServiceInfiniteQueryOptionsBuilder<Schema extends DescMessage, Response extends PagedResponse> = <TData = InfiniteData<Response, string>>(req: PageRequest<Schema>, options?: ServiceInfiniteQueryInput<Response, TData>) => ServiceInfiniteQueryOptions<Response, TData>;
105
155
  /**
106
156
  * A generated infinite-query hook: `useListOrdersInfinite(req, options?)`,
107
157
  * for a read that follows forge's list-pagination shape (`string page_token`
@@ -112,7 +162,7 @@ export type ServiceInfiniteQueryOptions<Response, TData> = Partial<Omit<UseInfin
112
162
  * flattening the pages into one list is
113
163
  * `select: (d) => d.pages.flatMap((p) => p.orders)`.
114
164
  */
115
- export type ServiceInfiniteQueryHook<Schema extends DescMessage, Response extends PagedResponse> = <TData = InfiniteData<Response, string>>(req: PageRequest<Schema>, options?: ServiceInfiniteQueryOptions<Response, TData>) => UseInfiniteQueryResult<TData, ConnectClientError>;
165
+ export type ServiceInfiniteQueryHook<Schema extends DescMessage, Response extends PagedResponse> = <TData = InfiniteData<Response, string>>(req: PageRequest<Schema>, options?: ServiceInfiniteQueryInput<Response, TData>) => UseInfiniteQueryResult<TData, ConnectClientError>;
116
166
  /**
117
167
  * A generated mutation hook: `useCreateOrder(options?)`.
118
168
  *
@@ -127,34 +177,51 @@ export type ServiceInfiniteQueryHook<Schema extends DescMessage, Response extend
127
177
  */
128
178
  export type ServiceMutationHook<Schema extends DescMessage, Response> = <TContext = unknown>(options?: Partial<UseMutationOptions<Response, ConnectClientError, MessageInitShape<Schema>, TContext>>) => UseMutationResult<Response, ConnectClientError, MessageInitShape<Schema>, TContext>;
129
179
  /**
130
- * createQueryHook builds one useQuery wrapper.
180
+ * createQueryOptions builds one read's query-options builder — the single
181
+ * definition of its cache key and its fetch that the generated hook, and
182
+ * every caller outside React, share.
131
183
  *
132
- * The signature it returns is the one call sites already use — `(req,
133
- * options?)`, with the error typed as ConnectClientError rather than React
134
- * Query's default `Error`. That type is declared on the OPTIONS parameter
135
- * because React Query takes the result's error type from the same TError it
136
- * reads there, so `query.error` is a ConnectClientError at every call site
137
- * with nothing to pass. Typing it as `Error` hid `.reason`, `.codeName`, `.status`
138
- * and `.retryable`, and left `err.message.includes(...)` as the only
139
- * expression that compiled — the one thing the error contract forbids.
184
+ * The error is typed as ConnectClientError rather than React Query's default
185
+ * `Error`, on the options themselves, because React Query takes a result's
186
+ * error type from the TError it reads there: `query.error` is a
187
+ * ConnectClientError at every call site with nothing to pass. Typing it as
188
+ * `Error` hid `.reason`, `.codeName`, `.status` and `.retryable`, and left
189
+ * `err.message.includes(...)` as the only expression that compiled — the one
190
+ * thing the error contract forbids.
191
+ *
192
+ * The caller's options are spread BEFORE the key and the fetch: a caller may
193
+ * set anything else, never the two that make this read this read.
140
194
  */
141
- export declare function createQueryHook<Schema extends DescMessage, Response>(keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey, call: ServiceCall<Schema, Response>): ServiceQueryHook<Schema, Response>;
195
+ export declare function createQueryOptions<Schema extends DescMessage, Response>(keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey, call: ServiceCall<Schema, Response>): ServiceQueryOptionsBuilder<Schema, Response>;
142
196
  /**
143
- * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged
144
- * read.
197
+ * createQueryHook builds one useQuery wrapper over a read's query-options
198
+ * builder. It adds nothing to the options: a hook and a `fetchQuery` of the
199
+ * same request therefore read and write one cache entry with one fetch.
200
+ */
201
+ export declare function createQueryHook<Schema extends DescMessage, Response>(optionsFor: ServiceQueryOptionsBuilder<Schema, Response>): ServiceQueryHook<Schema, Response>;
202
+ /**
203
+ * createInfiniteQueryOptions builds one paged read's infinite query-options
204
+ * builder.
145
205
  *
146
- * The page token is the hook's: the first page is fetched with the caller's
147
- * request as given (no token, so an `optional string page_token` stays
148
- * unset), each later one with the previous response's `nextPageToken`, and
149
- * an empty token ends the listing. The key is `keys.infinite(...)`, which
150
- * strips the token and sits under the service and entity scopes, so the
151
- * mutations that invalidate a plain list refetch this one too.
206
+ * The page token is the builder's: the first page is fetched with the
207
+ * caller's request as given (no token, so an `optional string page_token`
208
+ * stays unset), each later one with the previous response's
209
+ * `nextPageToken`, and an empty token ends the listing. The key is
210
+ * `keys.infinite(...)`, which strips the token and sits under the service and
211
+ * entity scopes, so the mutations that invalidate a plain list refetch this
212
+ * one too.
152
213
  *
153
214
  * The caller's options are spread BETWEEN the default getNextPageParam and
154
- * the four fields the hook owns: a caller may replace the default, never the
155
- * key or the fetch.
215
+ * the three fields the read owns: a caller may replace the default, never the
216
+ * key, the fetch or the first page.
217
+ */
218
+ export declare function createInfiniteQueryOptions<Schema extends DescMessage, Response extends PagedResponse>(keyFor: (req: PageRequest<Schema>) => ServiceQueryKey, call: ServiceCall<Schema, Response>): ServiceInfiniteQueryOptionsBuilder<Schema, Response>;
219
+ /**
220
+ * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged
221
+ * read's infinite query-options builder, adding nothing to it — so a hook
222
+ * and a `fetchInfiniteQuery` of the same request share one cache entry.
156
223
  */
157
- export declare function createInfiniteQueryHook<Schema extends DescMessage, Response extends PagedResponse>(keyFor: (req: PageRequest<Schema>) => ServiceQueryKey, call: ServiceCall<Schema, Response>): ServiceInfiniteQueryHook<Schema, Response>;
224
+ export declare function createInfiniteQueryHook<Schema extends DescMessage, Response extends PagedResponse>(optionsFor: ServiceInfiniteQueryOptionsBuilder<Schema, Response>): ServiceInfiniteQueryHook<Schema, Response>;
158
225
  /**
159
226
  * createMutationHook builds one useMutation wrapper with scoped invalidation.
160
227
  *
@@ -36,7 +36,7 @@
36
36
  // either: "CreateOrder succeeded" leaks RPC names into the UI, so the toast /
37
37
  // redirect / inline confirmation stays the call site's via options.onSuccess.
38
38
  import { create, toJson, } from "@bufbuild/protobuf";
39
- import { useInfiniteQuery, useMutation, useQuery, useQueryClient, } from "@tanstack/react-query";
39
+ import { infiniteQueryOptions, queryOptions, useInfiniteQuery, useMutation, useQuery, useQueryClient, } from "@tanstack/react-query";
40
40
  /**
41
41
  * requestKey projects a request init into protojson for use inside a query
42
42
  * key. Two reasons this is not the raw request object:
@@ -101,41 +101,54 @@ export function serviceKeys(service) {
101
101
  };
102
102
  }
103
103
  /**
104
- * createQueryHook builds one useQuery wrapper.
104
+ * createQueryOptions builds one read's query-options builder — the single
105
+ * definition of its cache key and its fetch that the generated hook, and
106
+ * every caller outside React, share.
105
107
  *
106
- * The signature it returns is the one call sites already use — `(req,
107
- * options?)`, with the error typed as ConnectClientError rather than React
108
- * Query's default `Error`. That type is declared on the OPTIONS parameter
109
- * because React Query takes the result's error type from the same TError it
110
- * reads there, so `query.error` is a ConnectClientError at every call site
111
- * with nothing to pass. Typing it as `Error` hid `.reason`, `.codeName`, `.status`
112
- * and `.retryable`, and left `err.message.includes(...)` as the only
113
- * expression that compiled — the one thing the error contract forbids.
108
+ * The error is typed as ConnectClientError rather than React Query's default
109
+ * `Error`, on the options themselves, because React Query takes a result's
110
+ * error type from the TError it reads there: `query.error` is a
111
+ * ConnectClientError at every call site with nothing to pass. Typing it as
112
+ * `Error` hid `.reason`, `.codeName`, `.status` and `.retryable`, and left
113
+ * `err.message.includes(...)` as the only expression that compiled — the one
114
+ * thing the error contract forbids.
115
+ *
116
+ * The caller's options are spread BEFORE the key and the fetch: a caller may
117
+ * set anything else, never the two that make this read this read.
114
118
  */
115
- export function createQueryHook(keyFor, call) {
116
- return (req, options) => useQuery({
119
+ export function createQueryOptions(keyFor, call) {
120
+ return (req, options) => queryOptions({
121
+ ...options,
117
122
  queryKey: keyFor(req),
118
123
  queryFn: ({ signal }) => call(req, signal),
119
- ...options,
120
124
  });
121
125
  }
122
126
  /**
123
- * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged
124
- * read.
127
+ * createQueryHook builds one useQuery wrapper over a read's query-options
128
+ * builder. It adds nothing to the options: a hook and a `fetchQuery` of the
129
+ * same request therefore read and write one cache entry with one fetch.
130
+ */
131
+ export function createQueryHook(optionsFor) {
132
+ return (req, options) => useQuery(optionsFor(req, options));
133
+ }
134
+ /**
135
+ * createInfiniteQueryOptions builds one paged read's infinite query-options
136
+ * builder.
125
137
  *
126
- * The page token is the hook's: the first page is fetched with the caller's
127
- * request as given (no token, so an `optional string page_token` stays
128
- * unset), each later one with the previous response's `nextPageToken`, and
129
- * an empty token ends the listing. The key is `keys.infinite(...)`, which
130
- * strips the token and sits under the service and entity scopes, so the
131
- * mutations that invalidate a plain list refetch this one too.
138
+ * The page token is the builder's: the first page is fetched with the
139
+ * caller's request as given (no token, so an `optional string page_token`
140
+ * stays unset), each later one with the previous response's
141
+ * `nextPageToken`, and an empty token ends the listing. The key is
142
+ * `keys.infinite(...)`, which strips the token and sits under the service and
143
+ * entity scopes, so the mutations that invalidate a plain list refetch this
144
+ * one too.
132
145
  *
133
146
  * The caller's options are spread BETWEEN the default getNextPageParam and
134
- * the four fields the hook owns: a caller may replace the default, never the
135
- * key or the fetch.
147
+ * the three fields the read owns: a caller may replace the default, never the
148
+ * key, the fetch or the first page.
136
149
  */
137
- export function createInfiniteQueryHook(keyFor, call) {
138
- return (req, options) => useInfiniteQuery({
150
+ export function createInfiniteQueryOptions(keyFor, call) {
151
+ return (req, options) => infiniteQueryOptions({
139
152
  getNextPageParam: (last) => last.nextPageToken || undefined,
140
153
  ...options,
141
154
  queryKey: keyFor(req),
@@ -148,6 +161,14 @@ export function createInfiniteQueryHook(keyFor, call) {
148
161
  initialPageParam: "",
149
162
  });
150
163
  }
164
+ /**
165
+ * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged
166
+ * read's infinite query-options builder, adding nothing to it — so a hook
167
+ * and a `fetchInfiniteQuery` of the same request share one cache entry.
168
+ */
169
+ export function createInfiniteQueryHook(optionsFor) {
170
+ return (req, options) => useInfiniteQuery(optionsFor(req, options));
171
+ }
151
172
  /**
152
173
  * createMutationHook builds one useMutation wrapper with scoped invalidation.
153
174
  *
@@ -1 +1 @@
1
- {"version":3,"file":"service-hooks.js","sourceRoot":"","sources":["../src/service-hooks.ts"],"names":[],"mappings":"AA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cG;AACH,MAAM,UAAU,uBAAuB,CAIrC,MAAqD,EACrD,IAAmC;IAEnC,OAAO,CACL,GAAwB,EACxB,OAAsD,EACtD,EAAE,CACF,gBAAgB,CAMd;QACA,gBAAgB,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,aAAa,IAAI,SAAS;QAC3D,GAAG,OAAO;QACV,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC;QACrB,OAAO,EAAE,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,EAAE,CACjC,IAAI,CACF,CAAC,SAAS,KAAK,EAAE;YACf,CAAC,CAAC,GAAG;YACL,CAAC,CAAC;gBACE,GAAG,GAAG;gBACN,SAAS,EAAE,SAAS;aACrB,CAAwC,EAC7C,MAAM,CACP;QACH,gBAAgB,EAAE,EAAE;KACrB,CAAC,CAAC;AACP,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,aAA8B,EAC9B,IAA0D;IAE1D,OAAO,CACL,OAOC,EACD,EAAE;QACF,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7C,OAAO,WAAW,CAKhB;YACA,UAAU,EAAE,CAAC,GAA6B,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE;gBACrB,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC,CAAC;gBAC3D,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,GAAG,IAAI;SACR,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Every export below is a React hook or builds one, so this module belongs in\n// the CLIENT graph. Without the directive the Next.js App Router compiles it\n// into the SERVER graph, where it binds a SECOND @tanstack/react-query\n// instance and every generated hook throws \"No QueryClient set\" at runtime —\n// invisible to tsc, eslint AND `next build`. published-surface.test.ts asserts\n// the directive survives into dist/. It is NOT applied package-wide: the\n// ./interceptors subpath exists to be importable without React.\n//\n// The React Query wrapper machinery behind forge's generated per-service hook\n// files (`src/hooks/<svc>-service-hooks_gen.ts`).\n//\n// WHAT WAS HERE BEFORE. Each generated file re-emitted the same three things\n// per RPC: a query-key entry, a useQuery or useMutation wrapper, and — for\n// mutations — the entity-scoped invalidateQueries plus the onSuccess\n// composition, with the reasoning for each re-inlined as comments. A\n// five-service project rendered five copies of machinery that differed only in\n// RPC names and message types. This module IS that machinery, written once.\n// The generated file keeps exactly what varies per RPC: the name, the request\n// schema, the response type, query-vs-mutation, and the entity scope.\n//\n// WHY A SUBPATH AND NOT THE BARREL. This module imports @tanstack/react-query.\n// Every browser frontend forge scaffolds depends on it — but the barrel is\n// also what a consumer imports for interceptors and errors alone, and\n// anchoring React Query there would make a non-React consumer resolve a\n// package it never installed. Same reasoning as ./mock-transport and ./otel:\n// an engine with its own dependency footprint gets its own entry point, and\n// React Query is an OPTIONAL peer.\n//\n// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — the\n// app-wide MutationCache in src/lib/query-client.ts is the single error-toast\n// chokepoint, and pages that render errors inline pass\n// `meta: { silenceErrorToast: true }`. It never defaults success-side UX\n// either: \"CreateOrder succeeded\" leaks RPC names into the UI, so the toast /\n// redirect / inline confirmation stays the call site's via options.onSuccess.\nimport {\n create,\n toJson,\n type DescMessage,\n type MessageInitShape,\n} from \"@bufbuild/protobuf\";\nimport {\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type InfiniteData,\n type UseInfiniteQueryOptions,\n type UseInfiniteQueryResult,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\nimport type { ConnectClientError } from \"./errors.js\";\n\n/**\n * A generated query key. The tuple is [service, entity?, method,\n * protojson(req)] for a method key and [service] / [service, entity] for the\n * broader scopes.\n */\nexport type ServiceQueryKey = readonly unknown[];\n\n/**\n * requestKey projects a request init into protojson for use inside a query\n * key. Two reasons this is not the raw request object:\n *\n * - React Query's default hasher is JSON.stringify, which THROWS on bigint\n * fields (any proto int64) — the raw message crashes the cache.\n * - protojson normalizes representations, so { id: 1 } and { id: \"1\" } land\n * in ONE cache entry instead of silently splitting the cache.\n *\n * Exported because a hand-written hook that wants to share a generated hook's\n * cache entry has to hash its request the identical way.\n */\nexport function requestKey<Schema extends DescMessage>(\n schema: Schema,\n req: MessageInitShape<Schema>,\n): unknown {\n return toJson(schema, create(schema, req));\n}\n\n/** The three key-scope builders a generated key factory is assembled from. */\nexport interface ServiceKeyBuilders {\n /** Every query on this service: [service]. */\n readonly all: readonly [string];\n /** Every query for one CRUD entity: [service, entity]. Mutations invalidate this. */\n entity(name: string): readonly [string, string];\n /**\n * One query: [service, entity?, method, protojson(req)]. Returns the\n * per-request key FUNCTION, which is what both the query hook and any\n * call-site prefetch/setQueryData use.\n */\n query<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: MessageInitShape<Schema>) => ServiceQueryKey;\n /**\n * One paged read: [service, entity?, method, protojson(req), \"infinite\"],\n * where req is the request WITHOUT its page token — the hook owns the\n * token, so every page of one listing shares one cache entry.\n *\n * It nests under the same scopes as `query`, so an entity or service-wide\n * invalidation refetches it. The \"infinite\" suffix keeps it OFF the plain\n * query's entry for the same request: an infinite query caches\n * `{ pages, pageParams }`, not one response, and a plain hook reading that\n * entry would get the wrong shape.\n */\n infinite<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: PageRequest<Schema>) => ServiceQueryKey;\n}\n\n/**\n * Omit distributed over a union. MessageInitShape is `Message | init\n * object`, and a plain Omit over a union keeps only the keys both members\n * share — which would silently drop every field from the init side.\n */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * The request a generated infinite hook takes: the rpc's request without\n * `pageToken`, which the hook supplies page by page.\n */\nexport type PageRequest<Schema extends DescMessage> = DistributiveOmit<\n MessageInitShape<Schema>,\n \"pageToken\"\n>;\n\n/**\n * The response shape forge's list-pagination convention (AIP-158) gives a\n * paged read: `string next_page_token`, empty on the last page. Optional so\n * an `optional string next_page_token` response satisfies it too.\n */\nexport interface PagedResponse {\n nextPageToken?: string;\n}\n\n/**\n * pageRequestKey is requestKey with the page token dropped, so every page of\n * one listing hashes to one key even when a caller (JS, or a cast) passes a\n * token anyway. It is dropped from the protojson rather than from the init\n * object: a spread Message keeps its $typeName, and create() would hand that\n * token-less copy back as if it were a complete message.\n */\nfunction pageRequestKey<Schema extends DescMessage>(\n schema: Schema,\n req: PageRequest<Schema>,\n): unknown {\n const json = requestKey(schema, req as unknown as MessageInitShape<Schema>);\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n return json;\n }\n const { pageToken: _pageToken, ...rest } = json as Record<string, unknown>;\n return rest;\n}\n\n/**\n * serviceKeys returns the builders for one service's query-key factory.\n *\n * Cache-key semantics are a compatibility contract, not an implementation\n * detail: an existing app's\n * `invalidateQueries({ queryKey: orderServiceKeys.order })` has to keep\n * matching the keys its queries were registered under across a version bump.\n * So the tuple order and contents produced here are fixed, and identical to\n * what forge previously inlined into every generated hook file.\n */\nexport function serviceKeys(service: string): ServiceKeyBuilders {\n return {\n all: [service] as const,\n entity: (name: string) => [service, name] as const,\n query:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: MessageInitShape<Schema>): ServiceQueryKey =>\n entityScope === undefined\n ? ([service, method, requestKey(schema, req)] as const)\n : ([service, entityScope, method, requestKey(schema, req)] as const),\n infinite:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: PageRequest<Schema>): ServiceQueryKey =>\n entityScope === undefined\n ? ([\n service,\n method,\n pageRequestKey(schema, req),\n \"infinite\",\n ] as const)\n : ([\n service,\n entityScope,\n method,\n pageRequestKey(schema, req),\n \"infinite\",\n ] as const),\n };\n}\n\n/**\n * How a generated file calls one rpc. `signal` is React Query's: a query\n * that is unmounted or superseded (a new key while typing) aborts its\n * request instead of letting it land on a cache entry nobody reads.\n */\nexport type ServiceCall<Schema extends DescMessage, Response> = (\n req: MessageInitShape<Schema>,\n signal?: AbortSignal,\n) => Promise<Response>;\n\n/**\n * A generated query hook: `useGetOrder(req, options?)`.\n *\n * TData is what the hook's `data` is, exactly as in React Query's own\n * useQuery: the response by default, or whatever `select` returns. A call\n * site mapping the proto response to a view model passes\n * `select: (r) => toView(r)` and gets `data: View` — no useMemo over `data`,\n * and React Query re-runs the mapping only when the response changes (or\n * when `select` itself does, so hoist it or wrap it in useCallback when it\n * is expensive). TData is inferred from `select` and is a parameter of the\n * HOOK, not of the factory, so every call site picks its own.\n */\nexport type ServiceQueryHook<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: Partial<UseQueryOptions<Response, ConnectClientError, TData>>,\n) => UseQueryResult<TData, ConnectClientError>;\n\n/**\n * The options a generated infinite hook takes: React Query's own, minus the\n * four the hook owns — the key, the fetch, and the page-token plumbing.\n * `getNextPageParam` defaults to the response's `nextPageToken` (empty means\n * last page) and may be overridden; everything else (`select`,\n * `placeholderData`, `staleTime`, `enabled`, `maxPages`, …) passes through.\n */\nexport type ServiceInfiniteQueryOptions<Response, TData> = Partial<\n Omit<\n UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >,\n \"queryKey\" | \"queryFn\" | \"initialPageParam\"\n >\n>;\n\n/**\n * A generated infinite-query hook: `useListOrdersInfinite(req, options?)`,\n * for a read that follows forge's list-pagination shape (`string page_token`\n * on the request, `string next_page_token` on the response).\n *\n * `req` is the first page's request without its token. `data` is React\n * Query's `{ pages, pageParams }` by default; `select` reshapes it, so\n * flattening the pages into one list is\n * `select: (d) => d.pages.flatMap((p) => p.orders)`.\n */\nexport type ServiceInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryOptions<Response, TData>,\n) => UseInfiniteQueryResult<TData, ConnectClientError>;\n\n/**\n * A generated mutation hook: `useCreateOrder(options?)`.\n *\n * TContext is React Query's fourth type parameter — what `onMutate` returns\n * and `onError` / `onSettled` receive back. It is a parameter of the HOOK,\n * not of the factory, so each call site gets its own: TypeScript infers it\n * from the `onMutate` the caller passes, and an optimistic update reads its\n * rollback off `context` with no cast. Fixing it at the factory (or leaving\n * it out, which pinned it to `unknown`) forced every such call site to\n * narrow `unknown` by hand. It defaults to `unknown`, so a call without\n * `onMutate` types exactly as before.\n */\nexport type ServiceMutationHook<Schema extends DescMessage, Response> = <\n TContext = unknown,\n>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n) => UseMutationResult<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n>;\n\n/**\n * createQueryHook builds one useQuery wrapper.\n *\n * The signature it returns is the one call sites already use — `(req,\n * options?)`, with the error typed as ConnectClientError rather than React\n * Query's default `Error`. That type is declared on the OPTIONS parameter\n * because React Query takes the result's error type from the same TError it\n * reads there, so `query.error` is a ConnectClientError at every call site\n * with nothing to pass. Typing it as `Error` hid `.reason`, `.codeName`, `.status`\n * and `.retryable`, and left `err.message.includes(...)` as the only\n * expression that compiled — the one thing the error contract forbids.\n */\nexport function createQueryHook<Schema extends DescMessage, Response>(\n keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceQueryHook<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: Partial<UseQueryOptions<Response, ConnectClientError, TData>>,\n ) =>\n useQuery<Response, ConnectClientError, TData>({\n queryKey: keyFor(req),\n queryFn: ({ signal }) => call(req, signal),\n ...options,\n });\n}\n\n/**\n * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged\n * read.\n *\n * The page token is the hook's: the first page is fetched with the caller's\n * request as given (no token, so an `optional string page_token` stays\n * unset), each later one with the previous response's `nextPageToken`, and\n * an empty token ends the listing. The key is `keys.infinite(...)`, which\n * strips the token and sits under the service and entity scopes, so the\n * mutations that invalidate a plain list refetch this one too.\n *\n * The caller's options are spread BETWEEN the default getNextPageParam and\n * the four fields the hook owns: a caller may replace the default, never the\n * key or the fetch.\n */\nexport function createInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n keyFor: (req: PageRequest<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceInfiniteQueryHook<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryOptions<Response, TData>,\n ) =>\n useInfiniteQuery<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >({\n getNextPageParam: (last) => last.nextPageToken || undefined,\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ pageParam, signal }) =>\n call(\n (pageParam === \"\"\n ? req\n : {\n ...req,\n pageToken: pageParam,\n }) as unknown as MessageInitShape<Schema>,\n signal,\n ),\n initialPageParam: \"\",\n });\n}\n\n/**\n * createMutationHook builds one useMutation wrapper with scoped invalidation.\n *\n * invalidateKey is the entity scope when the RPC maps to a CRUD entity, and\n * the whole-service scope otherwise — a bespoke mutation may touch anything,\n * so over-invalidating is the safe default there.\n *\n * The invalidation is composed BEFORE the caller's onSuccess and is never\n * replaced by it: onSuccess is destructured out and re-invoked after the\n * invalidate, while the rest of the options object is spread separately. A\n * caller passing onSuccess therefore ADDS behaviour, rather than silently\n * disabling the cache refresh — which is exactly what a plain `...options`\n * spread over a default onSuccess would do.\n */\nexport function createMutationHook<Schema extends DescMessage, Response>(\n invalidateKey: ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceMutationHook<Schema, Response> {\n return <TContext = unknown>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n ) => {\n const queryClient = useQueryClient();\n const { onSuccess, ...rest } = options ?? {};\n return useMutation<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >({\n mutationFn: (req: MessageInitShape<Schema>) => call(req),\n onSuccess: (...args) => {\n queryClient.invalidateQueries({ queryKey: invalidateKey });\n onSuccess?.(...args);\n },\n ...rest,\n });\n };\n}\n"]}
1
+ {"version":3,"file":"service-hooks.js","sourceRoot":"","sources":["../src/service-hooks.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,sEAAsE;AACtE,EAAE;AACF,8EAA8E;AAC9E,6EAA6E;AAC7E,uEAAuE;AACvE,6EAA6E;AAC7E,+EAA+E;AAC/E,yEAAyE;AACzE,gEAAgE;AAChE,EAAE;AACF,8EAA8E;AAC9E,kDAAkD;AAClD,EAAE;AACF,6EAA6E;AAC7E,2EAA2E;AAC3E,qEAAqE;AACrE,qEAAqE;AACrE,+EAA+E;AAC/E,4EAA4E;AAC5E,8EAA8E;AAC9E,sEAAsE;AACtE,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,sEAAsE;AACtE,wEAAwE;AACxE,6EAA6E;AAC7E,4EAA4E;AAC5E,mCAAmC;AACnC,EAAE;AACF,wEAAwE;AACxE,8EAA8E;AAC9E,uDAAuD;AACvD,yEAAyE;AACzE,8EAA8E;AAC9E,8EAA8E;AAC9E,OAAO,EACL,MAAM,EACN,MAAM,GAGP,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EACL,oBAAoB,EACpB,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,QAAQ,EACR,cAAc,GASf,MAAM,uBAAuB,CAAC;AAW/B;;;;;;;;;;;GAWG;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,CAAiD,CAAC;AACvD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,uBAAuB,CAIrC,UAAgE;IAEhE,OAAO,CACL,GAAwB,EACxB,OAAoD,EACpD,EAAE,CAAC,gBAAgB,CAAC,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC,CAAC;AAClD,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,aAA8B,EAC9B,IAA0D;IAE1D,OAAO,CACL,OAOC,EACD,EAAE;QACF,MAAM,WAAW,GAAG,cAAc,EAAE,CAAC;QACrC,MAAM,EAAE,SAAS,EAAE,GAAG,IAAI,EAAE,GAAG,OAAO,IAAI,EAAE,CAAC;QAC7C,OAAO,WAAW,CAKhB;YACA,UAAU,EAAE,CAAC,GAA6B,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC;YACxD,SAAS,EAAE,CAAC,GAAG,IAAI,EAAE,EAAE;gBACrB,WAAW,CAAC,iBAAiB,CAAC,EAAE,QAAQ,EAAE,aAAa,EAAE,CAAC,CAAC;gBAC3D,SAAS,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;YACvB,CAAC;YACD,GAAG,IAAI;SACR,CAAC,CAAC;IACL,CAAC,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\n// Part of @reliantlabs/forge-web-runtime — the web twin of forge/pkg.\n//\n// Every export below is a React hook or builds one, so this module belongs in\n// the CLIENT graph. Without the directive the Next.js App Router compiles it\n// into the SERVER graph, where it binds a SECOND @tanstack/react-query\n// instance and every generated hook throws \"No QueryClient set\" at runtime —\n// invisible to tsc, eslint AND `next build`. published-surface.test.ts asserts\n// the directive survives into dist/. It is NOT applied package-wide: the\n// ./interceptors subpath exists to be importable without React.\n//\n// The React Query wrapper machinery behind forge's generated per-service hook\n// files (`src/hooks/<svc>-service-hooks_gen.ts`).\n//\n// WHAT WAS HERE BEFORE. Each generated file re-emitted the same three things\n// per RPC: a query-key entry, a useQuery or useMutation wrapper, and — for\n// mutations — the entity-scoped invalidateQueries plus the onSuccess\n// composition, with the reasoning for each re-inlined as comments. A\n// five-service project rendered five copies of machinery that differed only in\n// RPC names and message types. This module IS that machinery, written once.\n// The generated file keeps exactly what varies per RPC: the name, the request\n// schema, the response type, query-vs-mutation, and the entity scope.\n//\n// WHY A SUBPATH AND NOT THE BARREL. This module imports @tanstack/react-query.\n// Every browser frontend forge scaffolds depends on it — but the barrel is\n// also what a consumer imports for interceptors and errors alone, and\n// anchoring React Query there would make a non-React consumer resolve a\n// package it never installed. Same reasoning as ./mock-transport and ./otel:\n// an engine with its own dependency footprint gets its own entry point, and\n// React Query is an OPTIONAL peer.\n//\n// WHAT IT DELIBERATELY DOES NOT DO. It does not emit error toasts — the\n// app-wide MutationCache in src/lib/query-client.ts is the single error-toast\n// chokepoint, and pages that render errors inline pass\n// `meta: { silenceErrorToast: true }`. It never defaults success-side UX\n// either: \"CreateOrder succeeded\" leaks RPC names into the UI, so the toast /\n// redirect / inline confirmation stays the call site's via options.onSuccess.\nimport {\n create,\n toJson,\n type DescMessage,\n type MessageInitShape,\n} from \"@bufbuild/protobuf\";\nimport {\n infiniteQueryOptions,\n queryOptions,\n useInfiniteQuery,\n useMutation,\n useQuery,\n useQueryClient,\n type DataTag,\n type InfiniteData,\n type UseInfiniteQueryOptions,\n type UseInfiniteQueryResult,\n type UseMutationOptions,\n type UseMutationResult,\n type UseQueryOptions,\n type UseQueryResult,\n} from \"@tanstack/react-query\";\n\nimport type { ConnectClientError } from \"./errors.js\";\n\n/**\n * A generated query key. The tuple is [service, entity?, method,\n * protojson(req)] for a method key and [service] / [service, entity] for the\n * broader scopes.\n */\nexport type ServiceQueryKey = readonly unknown[];\n\n/**\n * requestKey projects a request init into protojson for use inside a query\n * key. Two reasons this is not the raw request object:\n *\n * - React Query's default hasher is JSON.stringify, which THROWS on bigint\n * fields (any proto int64) — the raw message crashes the cache.\n * - protojson normalizes representations, so { id: 1 } and { id: \"1\" } land\n * in ONE cache entry instead of silently splitting the cache.\n *\n * Exported because a hand-written hook that wants to share a generated hook's\n * cache entry has to hash its request the identical way.\n */\nexport function requestKey<Schema extends DescMessage>(\n schema: Schema,\n req: MessageInitShape<Schema>,\n): unknown {\n return toJson(schema, create(schema, req));\n}\n\n/** The three key-scope builders a generated key factory is assembled from. */\nexport interface ServiceKeyBuilders {\n /** Every query on this service: [service]. */\n readonly all: readonly [string];\n /** Every query for one CRUD entity: [service, entity]. Mutations invalidate this. */\n entity(name: string): readonly [string, string];\n /**\n * One query: [service, entity?, method, protojson(req)]. Returns the\n * per-request key FUNCTION, which is what both the query hook and any\n * call-site prefetch/setQueryData use.\n */\n query<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: MessageInitShape<Schema>) => ServiceQueryKey;\n /**\n * One paged read: [service, entity?, method, protojson(req), \"infinite\"],\n * where req is the request WITHOUT its page token — the hook owns the\n * token, so every page of one listing shares one cache entry.\n *\n * It nests under the same scopes as `query`, so an entity or service-wide\n * invalidation refetches it. The \"infinite\" suffix keeps it OFF the plain\n * query's entry for the same request: an infinite query caches\n * `{ pages, pageParams }`, not one response, and a plain hook reading that\n * entry would get the wrong shape.\n */\n infinite<Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ): (req: PageRequest<Schema>) => ServiceQueryKey;\n}\n\n/**\n * Omit distributed over a union. MessageInitShape is `Message | init\n * object`, and a plain Omit over a union keeps only the keys both members\n * share — which would silently drop every field from the init side.\n */\ntype DistributiveOmit<T, K extends PropertyKey> = T extends unknown\n ? Omit<T, K>\n : never;\n\n/**\n * The request a generated infinite hook takes: the rpc's request without\n * `pageToken`, which the hook supplies page by page.\n */\nexport type PageRequest<Schema extends DescMessage> = DistributiveOmit<\n MessageInitShape<Schema>,\n \"pageToken\"\n>;\n\n/**\n * The response shape forge's list-pagination convention (AIP-158) gives a\n * paged read: `string next_page_token`, empty on the last page. Optional so\n * an `optional string next_page_token` response satisfies it too.\n */\nexport interface PagedResponse {\n nextPageToken?: string;\n}\n\n/**\n * pageRequestKey is requestKey with the page token dropped, so every page of\n * one listing hashes to one key even when a caller (JS, or a cast) passes a\n * token anyway. It is dropped from the protojson rather than from the init\n * object: a spread Message keeps its $typeName, and create() would hand that\n * token-less copy back as if it were a complete message.\n */\nfunction pageRequestKey<Schema extends DescMessage>(\n schema: Schema,\n req: PageRequest<Schema>,\n): unknown {\n const json = requestKey(schema, req as unknown as MessageInitShape<Schema>);\n if (json === null || typeof json !== \"object\" || Array.isArray(json)) {\n return json;\n }\n const { pageToken: _pageToken, ...rest } = json as Record<string, unknown>;\n return rest;\n}\n\n/**\n * serviceKeys returns the builders for one service's query-key factory.\n *\n * Cache-key semantics are a compatibility contract, not an implementation\n * detail: an existing app's\n * `invalidateQueries({ queryKey: orderServiceKeys.order })` has to keep\n * matching the keys its queries were registered under across a version bump.\n * So the tuple order and contents produced here are fixed, and identical to\n * what forge previously inlined into every generated hook file.\n */\nexport function serviceKeys(service: string): ServiceKeyBuilders {\n return {\n all: [service] as const,\n entity: (name: string) => [service, name] as const,\n query:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: MessageInitShape<Schema>): ServiceQueryKey =>\n entityScope === undefined\n ? ([service, method, requestKey(schema, req)] as const)\n : ([service, entityScope, method, requestKey(schema, req)] as const),\n infinite:\n <Schema extends DescMessage>(\n method: string,\n schema: Schema,\n entityScope?: string,\n ) =>\n (req: PageRequest<Schema>): ServiceQueryKey =>\n entityScope === undefined\n ? ([\n service,\n method,\n pageRequestKey(schema, req),\n \"infinite\",\n ] as const)\n : ([\n service,\n entityScope,\n method,\n pageRequestKey(schema, req),\n \"infinite\",\n ] as const),\n };\n}\n\n/**\n * How a generated file calls one rpc. `signal` is React Query's: a query\n * that is unmounted or superseded (a new key while typing) aborts its\n * request instead of letting it land on a cache entry nobody reads.\n */\nexport type ServiceCall<Schema extends DescMessage, Response> = (\n req: MessageInitShape<Schema>,\n signal?: AbortSignal,\n) => Promise<Response>;\n\n/**\n * The options a generated read takes — its hook (`useGetOrder(req,\n * options?)`) and its query-options builder\n * (`orderServiceQueries.getOrder(req, options?)`) alike: React Query's own,\n * minus the two the read owns, the key and the fetch. Everything else\n * (`select`, `enabled`, `staleTime`, `placeholderData`, …) passes through.\n *\n * TData is what `data` is, exactly as in React Query's own useQuery: the\n * response by default, or whatever `select` returns. A call site mapping the\n * proto response to a view model passes `select: (r) => toView(r)` and gets\n * `data: View` — no useMemo over `data`, and React Query re-runs the mapping\n * only when the response changes (or when `select` itself does, so hoist it\n * or wrap it in useCallback when it is expensive).\n */\nexport type ServiceQueryInput<Response, TData = Response> = Partial<\n Omit<\n UseQueryOptions<Response, ConnectClientError, TData, ServiceQueryKey>,\n \"queryKey\" | \"queryFn\"\n >\n>;\n\n/**\n * What a query-options builder returns: TanStack's `queryOptions(...)`\n * result, so it goes anywhere React Query takes one —\n * `queryClient.fetchQuery`, `ensureQueryData`, `prefetchQuery`,\n * `useQueries({ queries })`, `useQuery`, `useSuspenseQuery`. Its `queryKey`\n * is data-tagged, so `queryClient.getQueryData(opts.queryKey)` and\n * `setQueryData` are typed as the response with no annotation.\n *\n * fetchQuery / ensureQueryData resolve to the RESPONSE, not to `select`'s\n * TData: they return what the cache holds, and `select` is an observer\n * option that only a hook or useQueries applies.\n */\nexport type ServiceQueryOptions<Response, TData = Response> = UseQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey\n> & {\n queryKey: DataTag<ServiceQueryKey, Response, ConnectClientError>;\n};\n\n/**\n * A generated query-options builder: `orderServiceQueries.getOrder(req,\n * options?)`. It is the read's single definition — the generated hook\n * `useGetOrder` is `useQuery` over exactly this — so code outside React (an\n * imperative action, a stream handler, a router loader, a prefetch) shares\n * the hook's cache entry and fetch by construction rather than by copying\n * its key and its client call.\n */\nexport type ServiceQueryOptionsBuilder<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n) => ServiceQueryOptions<Response, TData>;\n\n/**\n * A generated query hook: `useGetOrder(req, options?)` — `useQuery` over the\n * service's query-options builder for the same rpc. TData is inferred from\n * `select` and is a parameter of the HOOK, not of the factory, so every call\n * site picks its own.\n */\nexport type ServiceQueryHook<Schema extends DescMessage, Response> = <\n TData = Response,\n>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n) => UseQueryResult<TData, ConnectClientError>;\n\n/**\n * The options a generated infinite read takes: React Query's own, minus the\n * three the read owns — the key, the fetch, and the first page param.\n * `getNextPageParam` defaults to the response's `nextPageToken` (empty means\n * last page) and may be overridden; everything else (`select`,\n * `placeholderData`, `staleTime`, `enabled`, `maxPages`, …) passes through.\n */\nexport type ServiceInfiniteQueryInput<Response, TData> = Partial<\n Omit<\n UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >,\n \"queryKey\" | \"queryFn\" | \"initialPageParam\"\n >\n>;\n\n/**\n * What an infinite query-options builder returns: TanStack's\n * `infiniteQueryOptions(...)` result, for `queryClient.fetchInfiniteQuery`,\n * `prefetchInfiniteQuery`, `ensureInfiniteQueryData` and\n * `useInfiniteQuery`. Its key is data-tagged as `InfiniteData<Response,\n * string>`, the `{ pages, pageParams }` the cache holds.\n */\nexport type ServiceInfiniteQueryOptions<\n Response,\n TData = InfiniteData<Response, string>,\n> = UseInfiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n> & {\n queryKey: DataTag<\n ServiceQueryKey,\n InfiniteData<Response, string>,\n ConnectClientError\n >;\n};\n\n/**\n * A generated infinite query-options builder:\n * `orderServiceQueries.listOrdersInfinite(req, options?)`, for a read that\n * follows forge's list-pagination shape. `useListOrdersInfinite` is\n * `useInfiniteQuery` over exactly this.\n */\nexport type ServiceInfiniteQueryOptionsBuilder<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n) => ServiceInfiniteQueryOptions<Response, TData>;\n\n/**\n * A generated infinite-query hook: `useListOrdersInfinite(req, options?)`,\n * for a read that follows forge's list-pagination shape (`string page_token`\n * on the request, `string next_page_token` on the response).\n *\n * `req` is the first page's request without its token. `data` is React\n * Query's `{ pages, pageParams }` by default; `select` reshapes it, so\n * flattening the pages into one list is\n * `select: (d) => d.pages.flatMap((p) => p.orders)`.\n */\nexport type ServiceInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n> = <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n) => UseInfiniteQueryResult<TData, ConnectClientError>;\n\n/**\n * A generated mutation hook: `useCreateOrder(options?)`.\n *\n * TContext is React Query's fourth type parameter — what `onMutate` returns\n * and `onError` / `onSettled` receive back. It is a parameter of the HOOK,\n * not of the factory, so each call site gets its own: TypeScript infers it\n * from the `onMutate` the caller passes, and an optimistic update reads its\n * rollback off `context` with no cast. Fixing it at the factory (or leaving\n * it out, which pinned it to `unknown`) forced every such call site to\n * narrow `unknown` by hand. It defaults to `unknown`, so a call without\n * `onMutate` types exactly as before.\n */\nexport type ServiceMutationHook<Schema extends DescMessage, Response> = <\n TContext = unknown,\n>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n) => UseMutationResult<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n>;\n\n/**\n * createQueryOptions builds one read's query-options builder — the single\n * definition of its cache key and its fetch that the generated hook, and\n * every caller outside React, share.\n *\n * The error is typed as ConnectClientError rather than React Query's default\n * `Error`, on the options themselves, because React Query takes a result's\n * error type from the TError it reads there: `query.error` is a\n * ConnectClientError at every call site with nothing to pass. Typing it as\n * `Error` hid `.reason`, `.codeName`, `.status` and `.retryable`, and left\n * `err.message.includes(...)` as the only expression that compiled — the one\n * thing the error contract forbids.\n *\n * The caller's options are spread BEFORE the key and the fetch: a caller may\n * set anything else, never the two that make this read this read.\n */\nexport function createQueryOptions<Schema extends DescMessage, Response>(\n keyFor: (req: MessageInitShape<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceQueryOptionsBuilder<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n ): ServiceQueryOptions<Response, TData> =>\n queryOptions<Response, ConnectClientError, TData, ServiceQueryKey>({\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ signal }) => call(req, signal),\n }) as ServiceQueryOptions<Response, TData>;\n}\n\n/**\n * createQueryHook builds one useQuery wrapper over a read's query-options\n * builder. It adds nothing to the options: a hook and a `fetchQuery` of the\n * same request therefore read and write one cache entry with one fetch.\n */\nexport function createQueryHook<Schema extends DescMessage, Response>(\n optionsFor: ServiceQueryOptionsBuilder<Schema, Response>,\n): ServiceQueryHook<Schema, Response> {\n return <TData = Response>(\n req: MessageInitShape<Schema>,\n options?: ServiceQueryInput<Response, TData>,\n ) => useQuery(optionsFor(req, options));\n}\n\n/**\n * createInfiniteQueryOptions builds one paged read's infinite query-options\n * builder.\n *\n * The page token is the builder's: the first page is fetched with the\n * caller's request as given (no token, so an `optional string page_token`\n * stays unset), each later one with the previous response's\n * `nextPageToken`, and an empty token ends the listing. The key is\n * `keys.infinite(...)`, which strips the token and sits under the service and\n * entity scopes, so the mutations that invalidate a plain list refetch this\n * one too.\n *\n * The caller's options are spread BETWEEN the default getNextPageParam and\n * the three fields the read owns: a caller may replace the default, never the\n * key, the fetch or the first page.\n */\nexport function createInfiniteQueryOptions<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n keyFor: (req: PageRequest<Schema>) => ServiceQueryKey,\n call: ServiceCall<Schema, Response>,\n): ServiceInfiniteQueryOptionsBuilder<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n ): ServiceInfiniteQueryOptions<Response, TData> =>\n infiniteQueryOptions<\n Response,\n ConnectClientError,\n TData,\n ServiceQueryKey,\n string\n >({\n getNextPageParam: (last) => last.nextPageToken || undefined,\n ...options,\n queryKey: keyFor(req),\n queryFn: ({ pageParam, signal }) =>\n call(\n (pageParam === \"\"\n ? req\n : {\n ...req,\n pageToken: pageParam,\n }) as unknown as MessageInitShape<Schema>,\n signal,\n ),\n initialPageParam: \"\",\n }) as ServiceInfiniteQueryOptions<Response, TData>;\n}\n\n/**\n * createInfiniteQueryHook builds one useInfiniteQuery wrapper over a paged\n * read's infinite query-options builder, adding nothing to it — so a hook\n * and a `fetchInfiniteQuery` of the same request share one cache entry.\n */\nexport function createInfiniteQueryHook<\n Schema extends DescMessage,\n Response extends PagedResponse,\n>(\n optionsFor: ServiceInfiniteQueryOptionsBuilder<Schema, Response>,\n): ServiceInfiniteQueryHook<Schema, Response> {\n return <TData = InfiniteData<Response, string>>(\n req: PageRequest<Schema>,\n options?: ServiceInfiniteQueryInput<Response, TData>,\n ) => useInfiniteQuery(optionsFor(req, options));\n}\n\n/**\n * createMutationHook builds one useMutation wrapper with scoped invalidation.\n *\n * invalidateKey is the entity scope when the RPC maps to a CRUD entity, and\n * the whole-service scope otherwise — a bespoke mutation may touch anything,\n * so over-invalidating is the safe default there.\n *\n * The invalidation is composed BEFORE the caller's onSuccess and is never\n * replaced by it: onSuccess is destructured out and re-invoked after the\n * invalidate, while the rest of the options object is spread separately. A\n * caller passing onSuccess therefore ADDS behaviour, rather than silently\n * disabling the cache refresh — which is exactly what a plain `...options`\n * spread over a default onSuccess would do.\n */\nexport function createMutationHook<Schema extends DescMessage, Response>(\n invalidateKey: ServiceQueryKey,\n call: (req: MessageInitShape<Schema>) => Promise<Response>,\n): ServiceMutationHook<Schema, Response> {\n return <TContext = unknown>(\n options?: Partial<\n UseMutationOptions<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >\n >,\n ) => {\n const queryClient = useQueryClient();\n const { onSuccess, ...rest } = options ?? {};\n return useMutation<\n Response,\n ConnectClientError,\n MessageInitShape<Schema>,\n TContext\n >({\n mutationFn: (req: MessageInitShape<Schema>) => call(req),\n onSuccess: (...args) => {\n queryClient.invalidateQueries({ queryKey: invalidateKey });\n onSuccess?.(...args);\n },\n ...rest,\n });\n };\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reliantlabs/forge-web-runtime",
3
- "version": "0.10.2",
3
+ "version": "0.11.0",
4
4
  "description": "The forge frontend runtime: Connect interceptor stack, session, error boundary, toast queue, <Resource> container, W3C trace propagation and the HyperDX browser SDK wiring (errors, console, network, traces; replay off by default). The web twin of forge/pkg.",
5
5
  "license": "Apache-2.0",
6
6
  "//repository note": "REQUIRED for `npm publish --provenance`, not decoration. npm cross-checks this against the repository in the signed provenance statement and rejects the publish with a 422 if they disagree — an absent field reads as \"\" and fails that comparison. `directory` names the subdirectory this package lives in, so the provenance points at the real source. Omitting this is what made the first 0.3.1 publish fail AFTER the tarball had been signed and written to the sigstore transparency log.",
@@ -78,7 +78,7 @@
78
78
  "@connectrpc/connect": "^2.0.0",
79
79
  "@hyperdx/browser": "0.26.0",
80
80
  "@opentelemetry/api": "^1.9.0",
81
- "@tanstack/react-query": "^5.59.0",
81
+ "@tanstack/react-query": "^5.62.0",
82
82
  "react": "^18.3.0 || ^19.0.0"
83
83
  },
84
84
  "peerDependenciesMeta": {
@@ -103,7 +103,7 @@
103
103
  "@connectrpc/connect": "^2.0.0",
104
104
  "@hyperdx/browser": "0.26.0",
105
105
  "@opentelemetry/api": "^1.9.0",
106
- "@tanstack/react-query": "^5.59.0",
106
+ "@tanstack/react-query": "^5.62.0",
107
107
  "@types/node": "^22.14.0",
108
108
  "@types/react": "^19.1.0",
109
109
  "@types/react-18": "npm:@types/react@~18.3.0",