@jutsustack/api-codegen 0.1.0 → 0.2.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.
Files changed (199) hide show
  1. package/README.md +574 -141
  2. package/dist/cache/manifest.d.ts +0 -1
  3. package/dist/cache/manifest.d.ts.map +1 -1
  4. package/dist/cache/manifest.js +1 -1
  5. package/dist/cache/manifest.js.map +1 -1
  6. package/dist/cjs/cache/manifest.d.ts +34 -0
  7. package/dist/cjs/cache/manifest.js +45 -0
  8. package/dist/cjs/cli.d.ts +8 -0
  9. package/dist/cjs/cli.js +245 -0
  10. package/dist/cjs/codegen/emit-api.d.ts +6 -0
  11. package/dist/cjs/codegen/emit-api.js +108 -0
  12. package/dist/cjs/codegen/emit-bindings.d.ts +8 -0
  13. package/dist/cjs/codegen/emit-bindings.js +115 -0
  14. package/dist/cjs/codegen/emit-types.d.ts +10 -0
  15. package/dist/cjs/codegen/emit-types.js +232 -0
  16. package/dist/cjs/codegen/emit.d.ts +28 -0
  17. package/dist/cjs/codegen/emit.js +180 -0
  18. package/dist/cjs/codegen/files.d.ts +14 -0
  19. package/dist/cjs/codegen/files.js +66 -0
  20. package/dist/cjs/codegen/plan.d.ts +32 -0
  21. package/dist/cjs/codegen/plan.js +84 -0
  22. package/dist/cjs/codegen/print.d.ts +10 -0
  23. package/dist/cjs/codegen/print.js +65 -0
  24. package/dist/cjs/codegen/templates/bindings.d.ts +13 -0
  25. package/dist/cjs/codegen/templates/bindings.js +707 -0
  26. package/dist/cjs/codegen/templates/runtime.d.ts +2 -0
  27. package/dist/cjs/codegen/templates/runtime.js +1401 -0
  28. package/dist/cjs/codegen/templates/transports.d.ts +1 -0
  29. package/dist/cjs/codegen/templates/transports.js +272 -0
  30. package/dist/cjs/codegen/tsType.d.ts +15 -0
  31. package/dist/cjs/codegen/tsType.js +114 -0
  32. package/dist/cjs/collect/collect.d.ts +16 -0
  33. package/dist/cjs/collect/collect.js +472 -0
  34. package/dist/cjs/collect/naming.d.ts +25 -0
  35. package/dist/cjs/collect/naming.js +149 -0
  36. package/dist/cjs/collect/path.d.ts +10 -0
  37. package/dist/cjs/collect/path.js +67 -0
  38. package/dist/cjs/config/init.d.ts +37 -0
  39. package/dist/cjs/config/init.js +143 -0
  40. package/dist/cjs/config/load.d.ts +11 -0
  41. package/dist/cjs/config/load.js +121 -0
  42. package/dist/cjs/config/types.d.ts +88 -0
  43. package/dist/cjs/config/types.js +2 -0
  44. package/dist/cjs/config/validate.d.ts +8 -0
  45. package/dist/cjs/config/validate.js +200 -0
  46. package/dist/cjs/generate.d.ts +55 -0
  47. package/dist/cjs/generate.js +263 -0
  48. package/dist/cjs/index.d.ts +23 -0
  49. package/dist/cjs/index.js +48 -0
  50. package/dist/cjs/model/collection.d.ts +83 -0
  51. package/dist/cjs/model/collection.js +16 -0
  52. package/dist/cjs/model/infer.d.ts +7 -0
  53. package/dist/cjs/model/infer.js +95 -0
  54. package/dist/cjs/model/merge.d.ts +3 -0
  55. package/dist/cjs/model/merge.js +131 -0
  56. package/dist/cjs/model/reserved.d.ts +2 -0
  57. package/dist/cjs/model/reserved.js +128 -0
  58. package/dist/cjs/model/schema.d.ts +54 -0
  59. package/dist/cjs/model/schema.js +2 -0
  60. package/dist/cjs/package.json +1 -0
  61. package/dist/cjs/parsers/openapi-schema.d.ts +30 -0
  62. package/dist/cjs/parsers/openapi-schema.js +241 -0
  63. package/dist/cjs/parsers/openapi.d.ts +8 -0
  64. package/dist/cjs/parsers/openapi.js +435 -0
  65. package/dist/cjs/parsers/postman.d.ts +20 -0
  66. package/dist/cjs/parsers/postman.js +493 -0
  67. package/dist/cjs/parsers/types.d.ts +52 -0
  68. package/dist/cjs/parsers/types.js +2 -0
  69. package/dist/cjs/sources/load.d.ts +25 -0
  70. package/dist/cjs/sources/load.js +296 -0
  71. package/dist/cjs/sources/parse.d.ts +4 -0
  72. package/dist/cjs/sources/parse.js +50 -0
  73. package/dist/cjs/util/errors.d.ts +9 -0
  74. package/dist/cjs/util/errors.js +23 -0
  75. package/dist/cjs/util/fs.d.ts +7 -0
  76. package/dist/cjs/util/fs.js +44 -0
  77. package/dist/cjs/util/hash.d.ts +3 -0
  78. package/dist/cjs/util/hash.js +26 -0
  79. package/dist/cjs/util/json.d.ts +10 -0
  80. package/dist/cjs/util/json.js +31 -0
  81. package/dist/cjs/util/log.d.ts +22 -0
  82. package/dist/cjs/util/log.js +45 -0
  83. package/dist/cjs/version.d.ts +2 -0
  84. package/dist/cjs/version.js +6 -0
  85. package/dist/cli.d.ts +3 -1
  86. package/dist/cli.d.ts.map +1 -1
  87. package/dist/cli.js +42 -12
  88. package/dist/cli.js.map +1 -1
  89. package/dist/codegen/emit-api.d.ts +3 -1
  90. package/dist/codegen/emit-api.d.ts.map +1 -1
  91. package/dist/codegen/emit-api.js +32 -7
  92. package/dist/codegen/emit-api.js.map +1 -1
  93. package/dist/codegen/emit-bindings.d.ts +9 -0
  94. package/dist/codegen/emit-bindings.d.ts.map +1 -0
  95. package/dist/codegen/emit-bindings.js +112 -0
  96. package/dist/codegen/emit-bindings.js.map +1 -0
  97. package/dist/codegen/emit-types.d.ts +8 -1
  98. package/dist/codegen/emit-types.d.ts.map +1 -1
  99. package/dist/codegen/emit-types.js +10 -8
  100. package/dist/codegen/emit-types.js.map +1 -1
  101. package/dist/codegen/emit.d.ts +10 -1
  102. package/dist/codegen/emit.d.ts.map +1 -1
  103. package/dist/codegen/emit.js +142 -37
  104. package/dist/codegen/emit.js.map +1 -1
  105. package/dist/codegen/files.d.ts +3 -12
  106. package/dist/codegen/files.d.ts.map +1 -1
  107. package/dist/codegen/files.js +3 -12
  108. package/dist/codegen/files.js.map +1 -1
  109. package/dist/codegen/print.d.ts +1 -4
  110. package/dist/codegen/print.d.ts.map +1 -1
  111. package/dist/codegen/print.js +1 -4
  112. package/dist/codegen/print.js.map +1 -1
  113. package/dist/codegen/templates/bindings.d.ts +14 -0
  114. package/dist/codegen/templates/bindings.d.ts.map +1 -0
  115. package/dist/codegen/templates/bindings.js +705 -0
  116. package/dist/codegen/templates/bindings.js.map +1 -0
  117. package/dist/codegen/templates/runtime.d.ts +2 -1
  118. package/dist/codegen/templates/runtime.d.ts.map +1 -1
  119. package/dist/codegen/templates/runtime.js +1192 -279
  120. package/dist/codegen/templates/runtime.js.map +1 -1
  121. package/dist/codegen/templates/transports.d.ts +2 -0
  122. package/dist/codegen/templates/transports.d.ts.map +1 -0
  123. package/dist/codegen/templates/transports.js +270 -0
  124. package/dist/codegen/templates/transports.js.map +1 -0
  125. package/dist/collect/collect.d.ts +1 -11
  126. package/dist/collect/collect.d.ts.map +1 -1
  127. package/dist/collect/collect.js +21 -28
  128. package/dist/collect/collect.js.map +1 -1
  129. package/dist/collect/naming.d.ts +1 -4
  130. package/dist/collect/naming.d.ts.map +1 -1
  131. package/dist/collect/naming.js +1 -4
  132. package/dist/collect/naming.js.map +1 -1
  133. package/dist/collect/path.d.ts +2 -9
  134. package/dist/collect/path.d.ts.map +1 -1
  135. package/dist/collect/path.js +2 -9
  136. package/dist/collect/path.js.map +1 -1
  137. package/dist/config/init.d.ts +11 -2
  138. package/dist/config/init.d.ts.map +1 -1
  139. package/dist/config/init.js +55 -7
  140. package/dist/config/init.js.map +1 -1
  141. package/dist/config/load.d.ts.map +1 -1
  142. package/dist/config/load.js +26 -1
  143. package/dist/config/load.js.map +1 -1
  144. package/dist/config/types.d.ts +13 -5
  145. package/dist/config/types.d.ts.map +1 -1
  146. package/dist/config/validate.d.ts +2 -6
  147. package/dist/config/validate.d.ts.map +1 -1
  148. package/dist/config/validate.js +18 -7
  149. package/dist/config/validate.js.map +1 -1
  150. package/dist/generate.d.ts +2 -8
  151. package/dist/generate.d.ts.map +1 -1
  152. package/dist/generate.js +13 -12
  153. package/dist/generate.js.map +1 -1
  154. package/dist/index.d.ts +4 -4
  155. package/dist/index.d.ts.map +1 -1
  156. package/dist/index.js +4 -4
  157. package/dist/index.js.map +1 -1
  158. package/dist/model/infer.d.ts +2 -9
  159. package/dist/model/infer.d.ts.map +1 -1
  160. package/dist/model/infer.js +2 -9
  161. package/dist/model/infer.js.map +1 -1
  162. package/dist/model/merge.d.ts +1 -5
  163. package/dist/model/merge.d.ts.map +1 -1
  164. package/dist/model/merge.js +1 -5
  165. package/dist/model/merge.js.map +1 -1
  166. package/dist/model/reserved.d.ts +1 -4
  167. package/dist/model/reserved.d.ts.map +1 -1
  168. package/dist/model/reserved.js +63 -4
  169. package/dist/model/reserved.js.map +1 -1
  170. package/dist/model/schema.d.ts +1 -4
  171. package/dist/model/schema.d.ts.map +1 -1
  172. package/dist/parsers/openapi-schema.d.ts +1 -5
  173. package/dist/parsers/openapi-schema.d.ts.map +1 -1
  174. package/dist/parsers/openapi-schema.js +2 -5
  175. package/dist/parsers/openapi-schema.js.map +1 -1
  176. package/dist/parsers/postman.d.ts +0 -3
  177. package/dist/parsers/postman.d.ts.map +1 -1
  178. package/dist/parsers/postman.js +2 -5
  179. package/dist/parsers/postman.js.map +1 -1
  180. package/dist/sources/load.d.ts +0 -6
  181. package/dist/sources/load.d.ts.map +1 -1
  182. package/dist/sources/load.js +4 -7
  183. package/dist/sources/load.js.map +1 -1
  184. package/dist/sources/parse.d.ts +0 -2
  185. package/dist/sources/parse.d.ts.map +1 -1
  186. package/dist/sources/parse.js +1 -1
  187. package/dist/sources/parse.js.map +1 -1
  188. package/dist/version.d.ts +1 -1
  189. package/dist/version.js +1 -1
  190. package/package.json +40 -12
  191. package/schema/config.schema.json +58 -12
  192. package/dist/codegen/emit-hooks.d.ts +0 -5
  193. package/dist/codegen/emit-hooks.d.ts.map +0 -1
  194. package/dist/codegen/emit-hooks.js +0 -67
  195. package/dist/codegen/emit-hooks.js.map +0 -1
  196. package/dist/codegen/templates/hooks.d.ts +0 -11
  197. package/dist/codegen/templates/hooks.d.ts.map +0 -1
  198. package/dist/codegen/templates/hooks.js +0 -272
  199. package/dist/codegen/templates/hooks.js.map +0 -1
@@ -0,0 +1,707 @@
1
+ "use strict";
2
+ // Fixed part of the generated framework bindings: each maps the runtime's query and mutation
3
+ // controllers onto one framework's reactivity. Same String.raw rules as runtime.ts.
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ exports.bindingsPrelude = bindingsPrelude;
6
+ const COMMON_IMPORTS = String.raw `import { createApi } from './api__EXT__';
7
+ import type { Api, ApiOptions } from './api__EXT__';
8
+ import { createMutationController, createQueryController__LINK__ } from './runtime__EXT__';
9
+ import type { ApiClient, ApiRequester, MutationOptions, QueryOptions, FallbackReporter, RequestState } from './runtime__EXT__';
10
+ __TYPES__
11
+ /** The api object and the client it calls through. */
12
+ export interface ApiContextValue {
13
+ api: Api;
14
+ client: ApiRequester;
15
+ }
16
+
17
+ let defaultValue: ApiContextValue | undefined;
18
+
19
+ /** The client used when no provider supplies one. Call once at startup. */
20
+ export function configureApi(client: ApiRequester, options?: ApiOptions): Api {
21
+ defaultValue = { api: createApi(client, options), client };
22
+ return defaultValue.api;
23
+ }
24
+
25
+ function pendingOf(client: ApiRequester): { pending: number; subscribe?: ApiClient['subscribe'] } {
26
+ const c = client as Partial<ApiClient>;
27
+ return { pending: c.pending ?? 0, ...(typeof c.subscribe === 'function' ? { subscribe: c.subscribe } : {}) };
28
+ }
29
+
30
+ const MISSING = 'No API client: __MISSING__ or call configureApi(client) once at startup';
31
+ `;
32
+ const REACT = String.raw `import {
33
+ createContext,
34
+ createElement,
35
+ useCallback,
36
+ useContext,
37
+ useEffect,
38
+ useMemo,
39
+ useRef,
40
+ useState,
41
+ useSyncExternalStore,
42
+ } from 'react';
43
+ import type { ReactNode } from 'react';
44
+ import { argsKey } from './runtime__EXT__';
45
+ ${COMMON_IMPORTS}
46
+ const ApiContext = createContext<ApiContextValue | null>(null);
47
+
48
+ export interface ApiProviderProps {
49
+ client: ApiRequester;
50
+ /** keep it stable (module scope or useMemo): a new object recreates the api */
51
+ options?: ApiOptions;
52
+ children?: ReactNode;
53
+ }
54
+
55
+ /** Makes the generated hooks call through client. */
56
+ export function ApiProvider({ client, options, children }: ApiProviderProps) {
57
+ const value = useMemo<ApiContextValue>(() => ({ api: createApi(client, options), client }), [client, options]);
58
+ return createElement(ApiContext.Provider, { value }, children);
59
+ }
60
+
61
+ function useApiContext(): ApiContextValue {
62
+ const value = useContext(ApiContext) ?? defaultValue;
63
+ if (!value) throw new Error(MISSING);
64
+ return value;
65
+ }
66
+
67
+ /** The api object from the nearest ApiProvider (or configureApi). */
68
+ export function useApi(): Api {
69
+ return useApiContext().api;
70
+ }
71
+
72
+ /** Calls in flight on the client, for a global loading indicator. */
73
+ export function usePendingRequests(): number {
74
+ const { client } = useApiContext();
75
+ const subscribe = useCallback(
76
+ (listener: () => void) => {
77
+ const source = pendingOf(client);
78
+ return source.subscribe ? source.subscribe(listener) : () => undefined;
79
+ },
80
+ [client]
81
+ );
82
+ return useSyncExternalStore(subscribe, () => pendingOf(client).pending, () => 0);
83
+ }
84
+
85
+ export type QueryHookOptions<T> = QueryOptions<T>;
86
+
87
+ export interface QueryResult<T> extends RequestState<T> {
88
+ refetch: () => void;
89
+ }
90
+
91
+ /** A request tied to the component: refetches when args change, aborts on unmount. */
92
+ export function useApiQuery<A, T>(
93
+ fn: (api: Api, args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
94
+ args: A,
95
+ options: QueryHookOptions<T> = {}
96
+ ): QueryResult<T> {
97
+ const api = useApi();
98
+ const latest = useRef({ fn, api, args, options });
99
+ latest.current = { fn, api, args, options };
100
+ const [controller] = useState(() =>
101
+ createQueryController<A, T>(
102
+ (a, signal, report) => latest.current.fn(latest.current.api, a, signal, report),
103
+ () => latest.current.options
104
+ )
105
+ );
106
+ const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
107
+ const key = argsKey(args);
108
+ const enabled = options.enabled !== false;
109
+ useEffect(() => {
110
+ controller.update(latest.current.args, enabled);
111
+ }, [controller, key, enabled]);
112
+ const firstApi = useRef(api);
113
+ useEffect(() => {
114
+ if (firstApi.current === api) return;
115
+ firstApi.current = api;
116
+ controller.refetch();
117
+ }, [controller, api]);
118
+ useEffect(() => () => controller.cancel(), [controller]);
119
+ return useMemo(() => ({ ...state, refetch: controller.refetch }), [state, controller]);
120
+ }
121
+
122
+ export type MutationHookOptions<T, V> = MutationOptions<T, V>;
123
+
124
+ export interface MutationResult<T, V> extends RequestState<T> {
125
+ /** never rejects (errors land in error / onError); resolves the data or undefined */
126
+ run: (vars: V) => Promise<T | undefined>;
127
+ /** like run() but rejects with the error */
128
+ runAsync: (vars: V) => Promise<T>;
129
+ reset: () => void;
130
+ }
131
+
132
+ /** A write tied to the component: tracks status of the latest call. */
133
+ export function useApiMutation<V, T>(
134
+ fn: (api: Api, vars: V, report: FallbackReporter) => Promise<T>,
135
+ options: MutationHookOptions<T, V> = {}
136
+ ): MutationResult<T, V> {
137
+ const api = useApi();
138
+ const latest = useRef({ fn, api, options });
139
+ latest.current = { fn, api, options };
140
+ const [controller] = useState(() =>
141
+ createMutationController<V, T>(
142
+ (vars, report) => latest.current.fn(latest.current.api, vars, report),
143
+ () => latest.current.options
144
+ )
145
+ );
146
+ const state = useSyncExternalStore(controller.subscribe, controller.getState, controller.getState);
147
+ return useMemo(
148
+ () => ({ ...state, run: controller.run, runAsync: controller.runAsync, reset: controller.reset }),
149
+ [state, controller]
150
+ );
151
+ }
152
+ `;
153
+ const VUE = String.raw `import {
154
+ computed,
155
+ getCurrentScope,
156
+ hasInjectionContext,
157
+ inject,
158
+ onScopeDispose,
159
+ provide,
160
+ shallowRef,
161
+ toValue,
162
+ watch,
163
+ } from 'vue';
164
+ import type { App, ComputedRef, InjectionKey, MaybeRefOrGetter, ShallowRef } from 'vue';
165
+ import { argsKey } from './runtime__EXT__';
166
+ ${COMMON_IMPORTS}
167
+ const API_KEY: InjectionKey<ApiContextValue> = Symbol('@jutsustack/api-codegen');
168
+
169
+ /** app.use(createApiPlugin(client)): every component can use the composables. */
170
+ export function createApiPlugin(client: ApiRequester, options?: ApiOptions) {
171
+ return {
172
+ install(app: App) {
173
+ app.provide(API_KEY, { api: createApi(client, options), client });
174
+ },
175
+ };
176
+ }
177
+
178
+ /** Provide a client to this component's subtree (call in setup). */
179
+ export function provideApi(client: ApiRequester, options?: ApiOptions): Api {
180
+ const value: ApiContextValue = { api: createApi(client, options), client };
181
+ provide(API_KEY, value);
182
+ return value.api;
183
+ }
184
+
185
+ function context(): ApiContextValue {
186
+ const value = (hasInjectionContext() ? inject(API_KEY, null) : null) ?? defaultValue;
187
+ if (!value) throw new Error(MISSING);
188
+ return value;
189
+ }
190
+
191
+ /** The api object from createApiPlugin / provideApi (or configureApi). */
192
+ export function useApi(): Api {
193
+ return context().api;
194
+ }
195
+
196
+ function bind<T>(store: { getState(): RequestState<T>; subscribe(listener: () => void): () => void }, dispose: () => void) {
197
+ const state = shallowRef(store.getState());
198
+ const off = store.subscribe(() => {
199
+ state.value = store.getState();
200
+ });
201
+ if (getCurrentScope()) {
202
+ onScopeDispose(() => {
203
+ off();
204
+ dispose();
205
+ });
206
+ }
207
+ return {
208
+ state: state as Readonly<ShallowRef<RequestState<T>>>,
209
+ data: computed(() => state.value.data),
210
+ error: computed(() => state.value.error),
211
+ status: computed(() => state.value.status),
212
+ isLoading: computed(() => state.value.isLoading),
213
+ isSuccess: computed(() => state.value.isSuccess),
214
+ isError: computed(() => state.value.isError),
215
+ fromFallback: computed(() => state.value.fromFallback),
216
+ };
217
+ }
218
+
219
+ export interface RequestRefs<T> {
220
+ state: Readonly<ShallowRef<RequestState<T>>>;
221
+ data: ComputedRef<T | undefined>;
222
+ error: ComputedRef<Error | undefined>;
223
+ status: ComputedRef<RequestState<T>['status']>;
224
+ isLoading: ComputedRef<boolean>;
225
+ isSuccess: ComputedRef<boolean>;
226
+ isError: ComputedRef<boolean>;
227
+ /** the data came from a fallback: show it as stale / offline */
228
+ fromFallback: ComputedRef<boolean>;
229
+ }
230
+
231
+ /** Calls in flight on the client, for a global loading indicator. */
232
+ export function usePendingRequests(): Readonly<ShallowRef<number>> {
233
+ const source = pendingOf(context().client);
234
+ const pending = shallowRef(source.pending);
235
+ if (source.subscribe) {
236
+ const off = source.subscribe((n) => {
237
+ pending.value = n;
238
+ });
239
+ if (getCurrentScope()) onScopeDispose(off);
240
+ }
241
+ return pending;
242
+ }
243
+
244
+ export interface QueryComposableOptions<T> extends Omit<QueryOptions<T>, 'enabled'> {
245
+ enabled?: MaybeRefOrGetter<boolean>;
246
+ }
247
+
248
+ export interface QueryRefs<T> extends RequestRefs<T> {
249
+ refetch: () => void;
250
+ }
251
+
252
+ /** Refetches when args (a ref, getter or value) change by value; aborts on scope dispose. */
253
+ export function useApiQuery<A, T>(
254
+ fn: (api: Api, args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
255
+ args: MaybeRefOrGetter<A>,
256
+ options: QueryComposableOptions<T> = {}
257
+ ): QueryRefs<T> {
258
+ const { api } = context();
259
+ const isEnabled = () => toValue(options.enabled) !== false;
260
+ const controller = createQueryController<A, T>(
261
+ (a, signal, report) => fn(api, a, signal, report),
262
+ () => ({ ...options, enabled: isEnabled() })
263
+ );
264
+ const refs = bind(controller, controller.cancel);
265
+ watch(
266
+ () => [argsKey(toValue(args)), isEnabled()] as const,
267
+ ([, enabled]) => controller.update(toValue(args), enabled),
268
+ { immediate: true }
269
+ );
270
+ return { ...refs, refetch: controller.refetch };
271
+ }
272
+
273
+ export type MutationComposableOptions<T, V> = MutationOptions<T, V>;
274
+
275
+ export interface MutationRefs<T, V> extends RequestRefs<T> {
276
+ run: (vars: V) => Promise<T | undefined>;
277
+ runAsync: (vars: V) => Promise<T>;
278
+ reset: () => void;
279
+ }
280
+
281
+ export function useApiMutation<V, T>(
282
+ fn: (api: Api, vars: V, report: FallbackReporter) => Promise<T>,
283
+ options: MutationComposableOptions<T, V> = {}
284
+ ): MutationRefs<T, V> {
285
+ const { api } = context();
286
+ const controller = createMutationController<V, T>((vars, report) => fn(api, vars, report), () => options);
287
+ const refs = bind(controller, () => undefined);
288
+ return { ...refs, run: controller.run, runAsync: controller.runAsync, reset: controller.reset };
289
+ }
290
+ `;
291
+ const ANGULAR = String.raw `import { DestroyRef, InjectionToken, computed, effect, inject, signal } from '@angular/core';
292
+ import type { Provider, Signal } from '@angular/core';
293
+ ${COMMON_IMPORTS}
294
+ export const API_CONTEXT = new InjectionToken<ApiContextValue>('@jutsustack/api-codegen');
295
+
296
+ /** providers: [provideApi(() => createClient({ http: inject(HttpClient) }))] */
297
+ export function provideApi(factory: () => ApiRequester, options?: ApiOptions): Provider {
298
+ return {
299
+ provide: API_CONTEXT,
300
+ useFactory: (): ApiContextValue => {
301
+ const client = factory();
302
+ return { api: createApi(client, options), client };
303
+ },
304
+ };
305
+ }
306
+
307
+ function context(): ApiContextValue {
308
+ const value = inject(API_CONTEXT, { optional: true }) ?? defaultValue;
309
+ if (!value) throw new Error(MISSING);
310
+ return value;
311
+ }
312
+
313
+ /** The api object from provideApi (or configureApi). Call in an injection context. */
314
+ export function injectApi(): Api {
315
+ return context().api;
316
+ }
317
+
318
+ /** Calls in flight on the client, for a global loading indicator. */
319
+ export function injectPendingRequests(): Signal<number> {
320
+ const source = pendingOf(context().client);
321
+ const pending = signal(source.pending);
322
+ if (source.subscribe) inject(DestroyRef).onDestroy(source.subscribe((n) => pending.set(n)));
323
+ return pending.asReadonly();
324
+ }
325
+
326
+ /** A value or a getter (signals are getters, so a signal re-runs the query when it changes). */
327
+ export type Input<V> = V | (() => V);
328
+
329
+ function read<V>(input: Input<V>): V {
330
+ return typeof input === 'function' ? (input as () => V)() : input;
331
+ }
332
+
333
+ export interface RequestSignals<T> {
334
+ state: Signal<RequestState<T>>;
335
+ data: Signal<T | undefined>;
336
+ error: Signal<Error | undefined>;
337
+ status: Signal<RequestState<T>['status']>;
338
+ isLoading: Signal<boolean>;
339
+ isSuccess: Signal<boolean>;
340
+ isError: Signal<boolean>;
341
+ /** the data came from a fallback: show it as stale / offline */
342
+ fromFallback: Signal<boolean>;
343
+ }
344
+
345
+ function bind<T>(store: { getState(): RequestState<T>; subscribe(listener: () => void): () => void }) {
346
+ const state = signal(store.getState());
347
+ const off = store.subscribe(() => state.set(store.getState()));
348
+ const view: RequestSignals<T> = {
349
+ state: state.asReadonly(),
350
+ data: computed(() => state().data),
351
+ error: computed(() => state().error),
352
+ status: computed(() => state().status),
353
+ isLoading: computed(() => state().isLoading),
354
+ isSuccess: computed(() => state().isSuccess),
355
+ isError: computed(() => state().isError),
356
+ fromFallback: computed(() => state().fromFallback),
357
+ };
358
+ return { view, off };
359
+ }
360
+
361
+ export interface QuerySignalOptions<T> extends Omit<QueryOptions<T>, 'enabled'> {
362
+ enabled?: Input<boolean>;
363
+ }
364
+
365
+ export interface QuerySignals<T> extends RequestSignals<T> {
366
+ refetch: () => void;
367
+ }
368
+
369
+ /** Call in an injection context (field initializer / constructor). Args may read signals. */
370
+ export function injectApiQuery<A, T>(
371
+ fn: (api: Api, args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
372
+ args: Input<A>,
373
+ options: QuerySignalOptions<T> = {}
374
+ ): QuerySignals<T> {
375
+ const { api } = context();
376
+ const isEnabled = () => read(options.enabled ?? true) !== false;
377
+ const controller = createQueryController<A, T>(
378
+ (a, abort, report) => fn(api, a, abort, report),
379
+ () => ({ ...options, enabled: isEnabled() })
380
+ );
381
+ const { view, off } = bind(controller);
382
+ let destroyed = false;
383
+ const watcher = effect(() => {
384
+ const a = read(args);
385
+ const enabled = isEnabled();
386
+ // state is written outside the effect (signal writes in effects need Angular 19+)
387
+ queueMicrotask(() => {
388
+ if (!destroyed) controller.update(a, enabled);
389
+ });
390
+ });
391
+ inject(DestroyRef).onDestroy(() => {
392
+ destroyed = true;
393
+ off();
394
+ controller.cancel();
395
+ watcher.destroy();
396
+ });
397
+ return { ...view, refetch: controller.refetch };
398
+ }
399
+
400
+ export type MutationSignalOptions<T, V> = MutationOptions<T, V>;
401
+
402
+ export interface MutationSignals<T, V> extends RequestSignals<T> {
403
+ run: (vars: V) => Promise<T | undefined>;
404
+ runAsync: (vars: V) => Promise<T>;
405
+ reset: () => void;
406
+ }
407
+
408
+ /** Call in an injection context. */
409
+ export function injectApiMutation<V, T>(
410
+ fn: (api: Api, vars: V, report: FallbackReporter) => Promise<T>,
411
+ options: MutationSignalOptions<T, V> = {}
412
+ ): MutationSignals<T, V> {
413
+ const { api } = context();
414
+ const controller = createMutationController<V, T>((vars, report) => fn(api, vars, report), () => options);
415
+ const { view, off } = bind(controller);
416
+ inject(DestroyRef).onDestroy(off);
417
+ return { ...view, run: controller.run, runAsync: controller.runAsync, reset: controller.reset };
418
+ }
419
+ `;
420
+ const SVELTE = String.raw `import { getContext, setContext } from 'svelte';
421
+ import { readable } from 'svelte/store';
422
+ import type { Readable } from 'svelte/store';
423
+ ${COMMON_IMPORTS}
424
+ const KEY = Symbol.for('@jutsustack/api-codegen');
425
+
426
+ /** Provide a client to this component's subtree (call during component init). */
427
+ export function setApiContext(client: ApiRequester, options?: ApiOptions): Api {
428
+ const value: ApiContextValue = { api: createApi(client, options), client };
429
+ setContext(KEY, value);
430
+ return value.api;
431
+ }
432
+
433
+ function context(): ApiContextValue {
434
+ let value: ApiContextValue | undefined;
435
+ try {
436
+ value = getContext<ApiContextValue | undefined>(KEY);
437
+ } catch {
438
+ // outside component initialisation
439
+ value = undefined;
440
+ }
441
+ value = value ?? defaultValue;
442
+ if (!value) throw new Error(MISSING);
443
+ return value;
444
+ }
445
+
446
+ /** The api object from setApiContext (or configureApi). */
447
+ export function getApi(): Api {
448
+ return context().api;
449
+ }
450
+
451
+ /** Calls in flight on the client, for a global loading indicator. */
452
+ export function pendingRequests(): Readable<number> {
453
+ const { client } = context();
454
+ return readable(pendingOf(client).pending, (set) => {
455
+ const source = pendingOf(client);
456
+ set(source.pending);
457
+ return source.subscribe ? source.subscribe(set) : undefined;
458
+ });
459
+ }
460
+
461
+ /** A value or a store of values. */
462
+ export type StoreInput<V> = V | Readable<V>;
463
+
464
+ function isReadable<V>(input: unknown): input is Readable<V> {
465
+ return typeof input === 'object' && input !== null && typeof (input as { subscribe?: unknown }).subscribe === 'function';
466
+ }
467
+
468
+ function toStore<T>(source: { getState(): RequestState<T>; subscribe(listener: () => void): () => void }, start: () => () => void) {
469
+ return readable(source.getState(), (set) => {
470
+ set(source.getState());
471
+ const off = source.subscribe(() => set(source.getState()));
472
+ const stop = start();
473
+ return () => {
474
+ off();
475
+ stop();
476
+ };
477
+ });
478
+ }
479
+
480
+ export interface QueryStoreOptions<T> extends Omit<QueryOptions<T>, 'enabled'> {
481
+ enabled?: StoreInput<boolean>;
482
+ }
483
+
484
+ export interface QueryStore<T> extends Readable<RequestState<T>> {
485
+ refetch: () => void;
486
+ }
487
+
488
+ /** A store that runs the query while subscribed; args may be a store (refetches on change). */
489
+ export function createApiQuery<A, T>(
490
+ fn: (api: Api, args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
491
+ args: StoreInput<A>,
492
+ options: QueryStoreOptions<T> = {}
493
+ ): QueryStore<T> {
494
+ const { api } = context();
495
+ let enabled = !isReadable(options.enabled) ? options.enabled !== false : true;
496
+ const controller = createQueryController<A, T>(
497
+ (a, signal, report) => fn(api, a, signal, report),
498
+ () => ({ ...options, enabled })
499
+ );
500
+ const store = toStore(controller, () => {
501
+ let current: A | undefined;
502
+ let ready = false;
503
+ const sync = () => {
504
+ if (ready) controller.update(current as A, enabled);
505
+ };
506
+ // enabled first, so the first args never start a disabled query
507
+ const offEnabled = isReadable<boolean>(options.enabled)
508
+ ? options.enabled.subscribe((value) => {
509
+ enabled = value !== false;
510
+ sync();
511
+ })
512
+ : undefined;
513
+ const offArgs = isReadable<A>(args)
514
+ ? args.subscribe((value) => {
515
+ current = value;
516
+ ready = true;
517
+ sync();
518
+ })
519
+ : undefined;
520
+ if (!isReadable(args)) {
521
+ current = args;
522
+ ready = true;
523
+ sync();
524
+ }
525
+ return () => {
526
+ offEnabled?.();
527
+ offArgs?.();
528
+ controller.cancel();
529
+ };
530
+ });
531
+ return { subscribe: store.subscribe, refetch: controller.refetch };
532
+ }
533
+
534
+ export type MutationStoreOptions<T, V> = MutationOptions<T, V>;
535
+
536
+ export interface MutationStore<T, V> extends Readable<RequestState<T>> {
537
+ run: (vars: V) => Promise<T | undefined>;
538
+ runAsync: (vars: V) => Promise<T>;
539
+ reset: () => void;
540
+ }
541
+
542
+ export function createApiMutation<V, T>(
543
+ fn: (api: Api, vars: V, report: FallbackReporter) => Promise<T>,
544
+ options: MutationStoreOptions<T, V> = {}
545
+ ): MutationStore<T, V> {
546
+ const { api } = context();
547
+ const controller = createMutationController<V, T>((vars, report) => fn(api, vars, report), () => options);
548
+ const store = toStore(controller, () => () => undefined);
549
+ return { subscribe: store.subscribe, run: controller.run, runAsync: controller.runAsync, reset: controller.reset };
550
+ }
551
+ `;
552
+ const SOLID = String.raw `import { createContext, createMemo, createSignal, onCleanup, useContext } from 'solid-js';
553
+ import type { Accessor } from 'solid-js';
554
+ ${COMMON_IMPORTS}
555
+ /** Solid 1: <ApiContext.Provider value={...}>; Solid 2: <ApiContext value={...}> */
556
+ export const ApiContext = createContext<ApiContextValue>();
557
+
558
+ /** The value to give ApiContext. */
559
+ export function apiContextValue(client: ApiRequester, options?: ApiOptions): ApiContextValue {
560
+ return { api: createApi(client, options), client };
561
+ }
562
+
563
+ function context(): ApiContextValue {
564
+ let value: ApiContextValue | undefined;
565
+ try {
566
+ value = useContext(ApiContext);
567
+ } catch {
568
+ // Solid 2 throws when no provider is mounted
569
+ value = undefined;
570
+ }
571
+ value = value ?? defaultValue;
572
+ if (!value) throw new Error(MISSING);
573
+ return value;
574
+ }
575
+
576
+ /** The api object from ApiContext (or configureApi). */
577
+ export function useApi(): Api {
578
+ return context().api;
579
+ }
580
+
581
+ /** Calls in flight on the client, for a global loading indicator. */
582
+ export function createPendingRequests(): Accessor<number> {
583
+ const source = pendingOf(context().client);
584
+ const [pending, setPending] = createSignal(source.pending);
585
+ if (source.subscribe) onCleanup(source.subscribe((n) => setPending(() => n)));
586
+ return pending;
587
+ }
588
+
589
+ /** A value or an accessor (re-runs the query when what it reads changes). */
590
+ export type Input<V> = V | Accessor<V>;
591
+
592
+ function read<V>(input: Input<V>): V {
593
+ return typeof input === 'function' ? (input as Accessor<V>)() : input;
594
+ }
595
+
596
+ export interface RequestAccessors<T> {
597
+ state: Accessor<RequestState<T>>;
598
+ data: Accessor<T | undefined>;
599
+ error: Accessor<Error | undefined>;
600
+ status: Accessor<RequestState<T>['status']>;
601
+ isLoading: Accessor<boolean>;
602
+ isSuccess: Accessor<boolean>;
603
+ isError: Accessor<boolean>;
604
+ /** the data came from a fallback: show it as stale / offline */
605
+ fromFallback: Accessor<boolean>;
606
+ }
607
+
608
+ function bind<T>(store: { getState(): RequestState<T>; subscribe(listener: () => void): () => void }) {
609
+ const [state, setState] = createSignal<RequestState<T>>(store.getState(), { equals: false });
610
+ const off = store.subscribe(() => setState(() => store.getState()));
611
+ const view: RequestAccessors<T> = {
612
+ state,
613
+ data: () => state().data,
614
+ error: () => state().error,
615
+ status: () => state().status,
616
+ isLoading: () => state().isLoading,
617
+ isSuccess: () => state().isSuccess,
618
+ isError: () => state().isError,
619
+ fromFallback: () => state().fromFallback,
620
+ };
621
+ return { view, off };
622
+ }
623
+
624
+ export interface QueryPrimitiveOptions<T> extends Omit<QueryOptions<T>, 'enabled'> {
625
+ enabled?: Input<boolean>;
626
+ }
627
+
628
+ export interface QueryAccessors<T> extends RequestAccessors<T> {
629
+ refetch: () => void;
630
+ }
631
+
632
+ /** Re-runs when the args accessor changes (by value); aborts on cleanup. Solid 1.8+ and 2.x. */
633
+ export function createApiQuery<A, T>(
634
+ fn: (api: Api, args: A, signal: AbortSignal, report: FallbackReporter) => Promise<T>,
635
+ args: Input<A>,
636
+ options: QueryPrimitiveOptions<T> = {}
637
+ ): QueryAccessors<T> {
638
+ const { api } = context();
639
+ const isEnabled = () => read(options.enabled ?? true) !== false;
640
+ const controller = createQueryController<A, T>(
641
+ (a, signal, report) => fn(api, a, signal, report),
642
+ () => ({ ...options, enabled: isEnabled() })
643
+ );
644
+ const { view, off } = bind(controller);
645
+ let disposed = false;
646
+ // a memo tracks args in Solid 1 and 2 alike
647
+ createMemo(() => {
648
+ const a = read(args);
649
+ const enabled = isEnabled();
650
+ queueMicrotask(() => {
651
+ if (!disposed) controller.update(a, enabled);
652
+ });
653
+ return undefined;
654
+ });
655
+ onCleanup(() => {
656
+ disposed = true;
657
+ off();
658
+ controller.cancel();
659
+ });
660
+ return { ...view, refetch: controller.refetch };
661
+ }
662
+
663
+ export type MutationPrimitiveOptions<T, V> = MutationOptions<T, V>;
664
+
665
+ export interface MutationAccessors<T, V> extends RequestAccessors<T> {
666
+ run: (vars: V) => Promise<T | undefined>;
667
+ runAsync: (vars: V) => Promise<T>;
668
+ reset: () => void;
669
+ }
670
+
671
+ export function createApiMutation<V, T>(
672
+ fn: (api: Api, vars: V, report: FallbackReporter) => Promise<T>,
673
+ options: MutationPrimitiveOptions<T, V> = {}
674
+ ): MutationAccessors<T, V> {
675
+ const { api } = context();
676
+ const controller = createMutationController<V, T>((vars, report) => fn(api, vars, report), () => options);
677
+ const { view, off } = bind(controller);
678
+ onCleanup(off);
679
+ return { ...view, run: controller.run, runAsync: controller.runAsync, reset: controller.reset };
680
+ }
681
+ `;
682
+ const PRELUDES = {
683
+ react: {
684
+ source: REACT,
685
+ missing: 'wrap the tree in <ApiProvider client={client}>',
686
+ },
687
+ vue: { source: VUE, missing: 'app.use(createApiPlugin(client))' },
688
+ angular: {
689
+ source: ANGULAR,
690
+ missing: 'add provideApi(() => client) to your providers',
691
+ },
692
+ svelte: {
693
+ source: SVELTE,
694
+ missing: 'call setApiContext(client) in a parent component',
695
+ },
696
+ solid: { source: SOLID, missing: 'wrap the tree in an ApiContext provider' },
697
+ };
698
+ function bindingsPrelude(o) {
699
+ const { source, missing } = PRELUDES[o.framework];
700
+ const body = source
701
+ .replace('__LINK__', o.hasQueries ? ', linkSignals' : '')
702
+ .replace('__TYPES__', o.hasEndpoints ? "import type * as T from './types__EXT__';\n" : '')
703
+ .replace('__MISSING__', missing)
704
+ .split('__EXT__')
705
+ .join(o.ext);
706
+ return (o.useClient ? "'use client';\n\n" : '') + body;
707
+ }
@@ -0,0 +1,2 @@
1
+ export declare const RUNTIME: string;
2
+ export declare function runtimeSource(): string;