@checkstack/frontend-api 0.1.0 → 0.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,80 @@
1
1
  # @checkstack/frontend-api
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 4eed42d: Fix "No QueryClient set" error in containerized builds
8
+
9
+ **Problem**: The containerized application was throwing "No QueryClient set, use QueryClientProvider to set one" errors during plugin registration. This didn't happen in dev mode.
10
+
11
+ **Root Cause**: The `@tanstack/react-query` package was being bundled separately in different workspace packages, causing multiple React Query contexts. The `QueryClientProvider` from the main app wasn't visible to plugin code due to this module duplication.
12
+
13
+ **Changes**:
14
+
15
+ - `@checkstack/frontend-api`: Export `useQueryClient` from the centralized React Query import, ensuring all packages use the same context
16
+ - `@checkstack/dashboard-frontend`: Import `useQueryClient` from `@checkstack/frontend-api` instead of directly from `@tanstack/react-query`, and remove the direct dependency
17
+ - `@checkstack/frontend`: Add `@tanstack/react-query` to Vite's `resolve.dedupe` as a safety net
18
+
19
+ ## 0.2.0
20
+
21
+ ### Minor Changes
22
+
23
+ - 7a23261: ## TanStack Query Integration
24
+
25
+ Migrated all frontend components to use `usePluginClient` hook with TanStack Query integration, replacing the legacy `forPlugin()` pattern.
26
+
27
+ ### New Features
28
+
29
+ - **`usePluginClient` hook**: Provides type-safe access to plugin APIs with `.useQuery()` and `.useMutation()` methods
30
+ - **Automatic request deduplication**: Multiple components requesting the same data share a single network request
31
+ - **Built-in caching**: Configurable stale time and cache duration per query
32
+ - **Loading/error states**: TanStack Query provides `isLoading`, `error`, `isRefetching` states automatically
33
+ - **Background refetching**: Stale data is automatically refreshed when components mount
34
+
35
+ ### Contract Changes
36
+
37
+ All RPC contracts now require `operationType: "query"` or `operationType: "mutation"` metadata:
38
+
39
+ ```typescript
40
+ const getItems = proc()
41
+ .meta({ operationType: "query", access: [access.read] })
42
+ .output(z.array(itemSchema))
43
+ .query();
44
+
45
+ const createItem = proc()
46
+ .meta({ operationType: "mutation", access: [access.manage] })
47
+ .input(createItemSchema)
48
+ .output(itemSchema)
49
+ .mutation();
50
+ ```
51
+
52
+ ### Migration
53
+
54
+ ```typescript
55
+ // Before (forPlugin pattern)
56
+ const api = useApi(myPluginApiRef);
57
+ const [items, setItems] = useState<Item[]>([]);
58
+ useEffect(() => {
59
+ api.getItems().then(setItems);
60
+ }, [api]);
61
+
62
+ // After (usePluginClient pattern)
63
+ const client = usePluginClient(MyPluginApi);
64
+ const { data: items, isLoading } = client.getItems.useQuery({});
65
+ ```
66
+
67
+ ### Bug Fixes
68
+
69
+ - Fixed `rpc.test.ts` test setup for middleware type inference
70
+ - Fixed `SearchDialog` to use `setQuery` instead of deprecated `search` method
71
+ - Fixed null→undefined warnings in notification and queue frontends
72
+
73
+ ### Patch Changes
74
+
75
+ - Updated dependencies [7a23261]
76
+ - @checkstack/common@0.3.0
77
+
3
78
  ## 0.1.0
4
79
 
5
80
  ### Minor Changes
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@checkstack/frontend-api",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "scripts": {
@@ -13,7 +13,10 @@
13
13
  },
14
14
  "dependencies": {
15
15
  "@checkstack/common": "workspace:*",
16
- "@orpc/client": "^1.13.2"
16
+ "@orpc/client": "^1.13.2",
17
+ "@orpc/react-query": "1.13.4",
18
+ "@orpc/tanstack-query": "^1.13.2",
19
+ "@tanstack/react-query": "^5.64.0"
17
20
  },
18
21
  "devDependencies": {
19
22
  "@types/bun": "^1.3.5",
package/src/index.ts CHANGED
@@ -8,3 +8,4 @@ export * from "./utils";
8
8
  export * from "./slots";
9
9
  export * from "./use-plugin-route";
10
10
  export * from "./runtime-config";
11
+ export * from "./orpc-query";
@@ -0,0 +1,345 @@
1
+ import { createContext, useContext, useMemo, type ReactNode } from "react";
2
+ import {
3
+ createRouterUtils,
4
+ type RouterUtils,
5
+ type ProcedureUtils,
6
+ } from "@orpc/react-query";
7
+ import type { NestedClient, ClientContext } from "@orpc/client";
8
+ import {
9
+ useQuery,
10
+ useMutation,
11
+ type UseQueryResult,
12
+ type UseMutationResult,
13
+ type UseQueryOptions,
14
+ type UseMutationOptions,
15
+ } from "@tanstack/react-query";
16
+
17
+ // Re-export useQueryClient for cache invalidation in consuming packages
18
+ // This ensures all packages use the same React Query instance
19
+ export { useQueryClient } from "@tanstack/react-query";
20
+ import { useApi } from "./api-context";
21
+ import { rpcApiRef } from "./core-apis";
22
+ import type { ClientDefinition, InferClient } from "@checkstack/common";
23
+ import type { ContractProcedure, AnyContractRouter } from "@orpc/contract";
24
+
25
+ // =============================================================================
26
+ // TYPES
27
+ // =============================================================================
28
+
29
+ type OrpcUtils = RouterUtils<NestedClient<ClientContext>>;
30
+
31
+ // =============================================================================
32
+ // CONTEXT
33
+ // =============================================================================
34
+
35
+ const OrpcQueryContext = createContext<OrpcUtils | undefined>(undefined);
36
+
37
+ // =============================================================================
38
+ // PROVIDER
39
+ // =============================================================================
40
+
41
+ interface OrpcQueryProviderProps {
42
+ children: ReactNode;
43
+ }
44
+
45
+ /**
46
+ * Provides oRPC React Query utilities to the application.
47
+ * Must be inside ApiProvider and QueryClientProvider.
48
+ */
49
+ export const OrpcQueryProvider: React.FC<OrpcQueryProviderProps> = ({
50
+ children,
51
+ }) => {
52
+ const rpcApi = useApi(rpcApiRef);
53
+
54
+ const orpcUtils = useMemo(() => {
55
+ return createRouterUtils(rpcApi.client as NestedClient<ClientContext>);
56
+ }, [rpcApi.client]);
57
+
58
+ return (
59
+ <OrpcQueryContext.Provider value={orpcUtils}>
60
+ {children}
61
+ </OrpcQueryContext.Provider>
62
+ );
63
+ };
64
+
65
+ // =============================================================================
66
+ // INTERNAL
67
+ // =============================================================================
68
+
69
+ function useOrpcUtils(): OrpcUtils {
70
+ const context = useContext(OrpcQueryContext);
71
+ if (!context) {
72
+ throw new Error(
73
+ "usePluginClient must be used within OrpcQueryProvider. " +
74
+ "Wrap your app with <OrpcQueryProvider>."
75
+ );
76
+ }
77
+ return context;
78
+ }
79
+
80
+ // =============================================================================
81
+ // TYPE HELPERS FOR STRICT operationType INFERENCE
82
+ // =============================================================================
83
+
84
+ /**
85
+ * Query procedure hook interface - only exposes useQuery.
86
+ * Input is optional when the procedure has no input schema.
87
+ */
88
+ interface QueryProcedure<TInput, TOutput> {
89
+ useQuery: (
90
+ input?: TInput,
91
+ options?: Omit<UseQueryOptions<TOutput, Error>, "queryKey" | "queryFn">
92
+ ) => UseQueryResult<TOutput, Error>;
93
+ }
94
+
95
+ /**
96
+ * Mutation procedure hook interface - only exposes useMutation.
97
+ * Mutations don't take input directly - it's passed to mutate/mutateAsync.
98
+ */
99
+ interface MutationProcedure<TInput, TOutput> {
100
+ useMutation: (
101
+ options?: Omit<
102
+ UseMutationOptions<TOutput, Error, TInput>,
103
+ "mutationFn" | "mutationKey"
104
+ >
105
+ ) => UseMutationResult<TOutput, Error, TInput>;
106
+ }
107
+
108
+ /**
109
+ * Maps a contract procedure to the appropriate hook type based on operationType.
110
+ * Extracts input/output types from ContractProcedure's schema types.
111
+ */
112
+ type WrappedProcedure<TContractProcedure, _TClientProcedure> =
113
+ TContractProcedure extends ContractProcedure<
114
+ infer TInputSchema,
115
+ infer TOutputSchema,
116
+ infer _TErrors,
117
+ infer TMeta
118
+ >
119
+ ? TMeta extends { operationType: "mutation" }
120
+ ? MutationProcedure<
121
+ InferSchemaInputType<TInputSchema>,
122
+ InferSchemaOutputType<TOutputSchema>
123
+ >
124
+ : QueryProcedure<
125
+ InferSchemaInputType<TInputSchema>,
126
+ InferSchemaOutputType<TOutputSchema>
127
+ >
128
+ : never;
129
+
130
+ /**
131
+ * Extract input type from Zod schema.
132
+ * Zod schemas have { _input: T } for input inference.
133
+ * Returns empty object when no input schema is defined (unknown input),
134
+ * allowing useQuery({}) calls for parameterless procedures.
135
+ */
136
+ type InferSchemaInputType<T> = T extends { _input: infer I }
137
+ ? unknown extends I
138
+ ? Record<string, never>
139
+ : I
140
+ : Record<string, never>;
141
+
142
+ /**
143
+ * Extract output type from Zod schema.
144
+ * Zod schemas have { _output: T } for output inference.
145
+ */
146
+ type InferSchemaOutputType<T> = T extends { _output: infer O } ? O : unknown;
147
+
148
+ /**
149
+ * Check if a contract type is a procedure (not a nested router).
150
+ */
151
+ type IsContractProcedure<T> = T extends ContractProcedure<
152
+ infer _TInput,
153
+ infer _TOutput,
154
+ infer _TErrors,
155
+ infer _TMeta
156
+ >
157
+ ? true
158
+ : false;
159
+
160
+ /**
161
+ * Maps a contract router to wrapped procedures based on operationType.
162
+ * Recursively handles nested routers.
163
+ */
164
+ type WrappedClient<TContract extends AnyContractRouter, TClient> = {
165
+ [K in keyof TClient & keyof TContract]: IsContractProcedure<
166
+ TContract[K]
167
+ > extends true
168
+ ? WrappedProcedure<TContract[K], TClient[K]>
169
+ : TClient[K] extends object
170
+ ? TContract[K] extends AnyContractRouter
171
+ ? WrappedClient<TContract[K], TClient[K]>
172
+ : never
173
+ : never;
174
+ };
175
+
176
+ // =============================================================================
177
+ // HOOK: usePluginClient
178
+ // =============================================================================
179
+
180
+ /**
181
+ * Access a plugin's RPC client with TanStack Query integration.
182
+ *
183
+ * Each procedure exposes only the appropriate hook based on its operationType:
184
+ * - `operationType: "query"` → `.useQuery(input, options)`
185
+ * - `operationType: "mutation"` → `.useMutation(options)`
186
+ *
187
+ * @example
188
+ * ```tsx
189
+ * const catalog = usePluginClient(CatalogApi);
190
+ *
191
+ * // Queries (only useQuery available)
192
+ * const { data, isLoading } = catalog.getEntities.useQuery({});
193
+ *
194
+ * // Mutations (only useMutation available)
195
+ * const deleteMutation = catalog.deleteSystem.useMutation({
196
+ * onSuccess: () => toast.success("Deleted!"),
197
+ * });
198
+ *
199
+ * const handleDelete = () => {
200
+ * deleteMutation.mutate({ systemId });
201
+ * };
202
+ * ```
203
+ */
204
+ export function usePluginClient<T extends ClientDefinition>(
205
+ definition: T
206
+ ): WrappedClient<NonNullable<T["__contractType"]>, InferClient<T>> {
207
+ const orpcUtils = useOrpcUtils();
208
+
209
+ const pluginUtils = (orpcUtils as Record<string, unknown>)[
210
+ definition.pluginId
211
+ ] as Record<string, unknown> | undefined;
212
+
213
+ if (!pluginUtils) {
214
+ throw new Error(
215
+ `Plugin "${definition.pluginId}" not found. ` +
216
+ `Ensure the plugin is registered and the backend is running.`
217
+ );
218
+ }
219
+
220
+ // Get contract for operationType checking
221
+ const contract = definition.contract as Record<string, unknown>;
222
+
223
+ return useMemo(() => {
224
+ return wrapPluginUtils(pluginUtils, contract);
225
+ }, [pluginUtils, contract]) as WrappedClient<
226
+ NonNullable<T["__contractType"]>,
227
+ InferClient<T>
228
+ >;
229
+ }
230
+
231
+ // =============================================================================
232
+ // WRAPPER IMPLEMENTATION
233
+ // =============================================================================
234
+
235
+ function wrapPluginUtils(
236
+ utils: Record<string, unknown>,
237
+ contract: Record<string, unknown>
238
+ ): Record<string, unknown> {
239
+ const wrapped: Record<string, unknown> = {};
240
+
241
+ // Iterate over CONTRACT keys (procedure names like "getTheme", "getSystems")
242
+ // not the internal oRPC utility methods ("key", "call", "queryOptions" etc.)
243
+ for (const key of Object.keys(contract)) {
244
+ // Skip oRPC internal metadata keys
245
+ if (key.startsWith("~")) continue;
246
+
247
+ const procedureUtils = utils[key] as
248
+ | ProcedureUtils<ClientContext, unknown, unknown, Error>
249
+ | Record<string, unknown>
250
+ | undefined;
251
+
252
+ const contractProcedure = contract[key] as
253
+ | Record<string, unknown>
254
+ | undefined;
255
+
256
+ if (!procedureUtils || typeof procedureUtils !== "object") {
257
+ // Procedure might not be available in utils
258
+ continue;
259
+ }
260
+
261
+ // Check if this is a procedure (has queryOptions or mutationOptions method)
262
+ if (
263
+ typeof (
264
+ procedureUtils as ProcedureUtils<ClientContext, unknown, unknown, Error>
265
+ ).queryOptions === "function" ||
266
+ typeof (
267
+ procedureUtils as ProcedureUtils<ClientContext, unknown, unknown, Error>
268
+ ).mutationOptions === "function"
269
+ ) {
270
+ // Get operationType from contract metadata
271
+ const operationType = getOperationType(contractProcedure, key);
272
+ wrapped[key] = createProcedureHook(
273
+ procedureUtils as ProcedureUtils<
274
+ ClientContext,
275
+ unknown,
276
+ unknown,
277
+ Error
278
+ >,
279
+ operationType
280
+ );
281
+ } else {
282
+ // Nested namespace - recurse
283
+ wrapped[key] = wrapPluginUtils(
284
+ procedureUtils as Record<string, unknown>,
285
+ (contractProcedure || {}) as Record<string, unknown>
286
+ );
287
+ }
288
+ }
289
+
290
+ return wrapped;
291
+ }
292
+
293
+ /**
294
+ * Extract operationType from contract procedure metadata.
295
+ * Throws if operationType is not defined (required in all contracts).
296
+ */
297
+ function getOperationType(
298
+ contractProcedure: Record<string, unknown> | undefined,
299
+ procedureName?: string
300
+ ): "query" | "mutation" {
301
+ const orpcMeta = contractProcedure?.["~orpc"] as
302
+ | { meta?: { operationType?: "query" | "mutation" } }
303
+ | undefined;
304
+
305
+ const operationType = orpcMeta?.meta?.operationType;
306
+
307
+ if (!operationType) {
308
+ throw new Error(
309
+ `Procedure ${
310
+ procedureName ? `"${procedureName}" ` : ""
311
+ }is missing required "operationType" in contract metadata. ` +
312
+ `Add operationType: "query" or operationType: "mutation" to the procedure's .meta() call.`
313
+ );
314
+ }
315
+
316
+ return operationType;
317
+ }
318
+
319
+ /**
320
+ * Creates the appropriate hook wrapper based on operationType.
321
+ */
322
+ function createProcedureHook<TInput, TOutput>(
323
+ proc: ProcedureUtils<ClientContext, TInput, TOutput, Error>,
324
+ operationType: "query" | "mutation"
325
+ ): QueryProcedure<TInput, TOutput> | MutationProcedure<TInput, TOutput> {
326
+ if (operationType === "mutation") {
327
+ return {
328
+ useMutation: (options) => {
329
+ const mutationOpts = proc.mutationOptions(options);
330
+ return useMutation(mutationOpts);
331
+ },
332
+ };
333
+ }
334
+
335
+ return {
336
+ useQuery: (input, options) => {
337
+ // Get base query options from oRPC
338
+ const queryOpts = proc.queryOptions({
339
+ input: input as TInput,
340
+ });
341
+ // Spread caller options AFTER to ensure they take precedence (e.g., enabled: false)
342
+ return useQuery({ ...queryOpts, ...options });
343
+ },
344
+ };
345
+ }
@@ -15,6 +15,18 @@ interface RuntimeConfigContextValue {
15
15
  error: Error | undefined;
16
16
  }
17
17
 
18
+ // Module-level cache for synchronous access from non-React code
19
+ let cachedConfig: RuntimeConfig | undefined;
20
+
21
+ /**
22
+ * Get the cached runtime config synchronously.
23
+ * Returns undefined if config hasn't been loaded yet.
24
+ * Use this for class-based APIs that can't use hooks.
25
+ */
26
+ export function getCachedRuntimeConfig(): RuntimeConfig | undefined {
27
+ return cachedConfig;
28
+ }
29
+
18
30
  const RuntimeConfigContext = createContext<RuntimeConfigContextValue>({
19
31
  config: undefined,
20
32
  isLoading: true,
@@ -50,11 +62,14 @@ export const RuntimeConfigProvider: React.FC<RuntimeConfigProviderProps> = ({
50
62
  throw new Error(`Failed to fetch config: ${response.status}`);
51
63
  }
52
64
  const data = (await response.json()) as RuntimeConfig;
65
+ cachedConfig = data; // Populate module-level cache
53
66
  setConfig(data);
54
67
  } catch (error_) {
55
68
  console.error("RuntimeConfigProvider: Failed to load config", error_);
56
69
  // Fallback to localhost for development
57
- setConfig({ baseUrl: "http://localhost:3000" });
70
+ const fallback = { baseUrl: "http://localhost:3000" };
71
+ cachedConfig = fallback; // Populate cache even on error
72
+ setConfig(fallback);
58
73
  setError(error_ instanceof Error ? error_ : new Error(String(error_)));
59
74
  } finally {
60
75
  setIsLoading(false);