cushin-monorepo 3.0.1
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/.changeset/README.md +8 -0
- package/.changeset/config.json +14 -0
- package/.claude/settings.local.json +44 -0
- package/CHANGELOG.md +93 -0
- package/LICENSE +0 -0
- package/README.md +482 -0
- package/biome.json +34 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +1552 -0
- package/dist/cli.js.map +1 -0
- package/dist/config/index.d.ts +84 -0
- package/dist/config/index.js +69 -0
- package/dist/config/index.js.map +1 -0
- package/dist/config/schema.d.ts +43 -0
- package/dist/config/schema.js +14 -0
- package/dist/config/schema.js.map +1 -0
- package/dist/index.d.ts +27 -0
- package/dist/index.js +1666 -0
- package/dist/index.js.map +1 -0
- package/dist/runtime/client.d.ts +40 -0
- package/dist/runtime/client.js +260 -0
- package/dist/runtime/client.js.map +1 -0
- package/package.json +41 -0
- package/packages/api-codegen/CHANGELOG.md +86 -0
- package/packages/api-codegen/biome.json +34 -0
- package/packages/api-codegen/dist/cli.js +1038 -0
- package/packages/api-codegen/dist/cli.js.map +1 -0
- package/packages/api-codegen/dist/index.d.ts +103 -0
- package/packages/api-codegen/dist/index.js +1026 -0
- package/packages/api-codegen/dist/index.js.map +1 -0
- package/packages/api-codegen/node_modules/.bin/acorn +21 -0
- package/packages/api-codegen/node_modules/.bin/conventional-changelog +21 -0
- package/packages/api-codegen/node_modules/.bin/conventional-commits-parser +21 -0
- package/packages/api-codegen/node_modules/.bin/esbuild +21 -0
- package/packages/api-codegen/node_modules/.bin/eslint +21 -0
- package/packages/api-codegen/node_modules/.bin/jiti +21 -0
- package/packages/api-codegen/node_modules/.bin/next +21 -0
- package/packages/api-codegen/node_modules/.bin/tsc +21 -0
- package/packages/api-codegen/node_modules/.bin/tsserver +21 -0
- package/packages/api-codegen/node_modules/.bin/tsup +21 -0
- package/packages/api-codegen/node_modules/.bin/tsup-node +21 -0
- package/packages/api-codegen/node_modules/.bin/vitest +21 -0
- package/packages/api-codegen/package.json +88 -0
- package/packages/api-runtime/CHANGELOG.md +46 -0
- package/packages/api-runtime/README.md +95 -0
- package/packages/api-runtime/dist/chunk-3FFXWCVP.js +17 -0
- package/packages/api-runtime/dist/chunk-3FFXWCVP.js.map +1 -0
- package/packages/api-runtime/dist/chunk-EZ5P7OPH.js +267 -0
- package/packages/api-runtime/dist/chunk-EZ5P7OPH.js.map +1 -0
- package/packages/api-runtime/dist/client.d.ts +40 -0
- package/packages/api-runtime/dist/client.js +13 -0
- package/packages/api-runtime/dist/client.js.map +1 -0
- package/packages/api-runtime/dist/index.d.ts +3 -0
- package/packages/api-runtime/dist/index.js +21 -0
- package/packages/api-runtime/dist/index.js.map +1 -0
- package/packages/api-runtime/dist/schema.d.ts +45 -0
- package/packages/api-runtime/dist/schema.js +11 -0
- package/packages/api-runtime/dist/schema.js.map +1 -0
- package/packages/api-runtime/node_modules/.bin/esbuild +21 -0
- package/packages/api-runtime/node_modules/.bin/jiti +21 -0
- package/packages/api-runtime/node_modules/.bin/tsc +21 -0
- package/packages/api-runtime/node_modules/.bin/tsserver +21 -0
- package/packages/api-runtime/node_modules/.bin/tsup +21 -0
- package/packages/api-runtime/node_modules/.bin/tsup-node +21 -0
- package/packages/api-runtime/package.json +54 -0
- package/packages/cli/CHANGELOG.md +34 -0
- package/packages/cli/biome.json +34 -0
- package/packages/cli/dist/index.d.ts +27 -0
- package/packages/cli/dist/index.js +183 -0
- package/packages/cli/dist/index.js.map +1 -0
- package/packages/cli/node_modules/.bin/esbuild +21 -0
- package/packages/cli/node_modules/.bin/jiti +21 -0
- package/packages/cli/node_modules/.bin/tsc +21 -0
- package/packages/cli/node_modules/.bin/tsserver +21 -0
- package/packages/cli/node_modules/.bin/tsup +21 -0
- package/packages/cli/node_modules/.bin/tsup-node +21 -0
- package/packages/cli/package.json +47 -0
- package/pnpm-workspace.yaml +2 -0
- package/test-config.js +9 -0
- package/test-content-type-handling.mjs +100 -0
- package/test-endpoints-config.mjs +144 -0
- package/test-formdata-content-type-protection.mjs +127 -0
- package/test-formdata-runtime.mjs +127 -0
- package/test-full-integration.mjs +90 -0
- package/test-headers-formdata.mjs +97 -0
- package/test-headers-runtime.mjs +106 -0
- package/test-headers.mjs +79 -0
- package/test-internal-calls.mjs +57 -0
- package/test-ky-formdata.mjs +81 -0
- package/test-output/actions.ts +134 -0
- package/test-output/client.ts +81 -0
- package/test-output/hooks.ts +182 -0
- package/test-output/index.ts +9 -0
- package/test-output/prefetchs.ts +25 -0
- package/test-output/queries.ts +78 -0
- package/test-output/query-keys.ts +16 -0
- package/test-output/query-options.ts +38 -0
- package/test-output/server-client.ts +32 -0
- package/test-output/types.ts +61 -0
- package/test-real-endpoints.mjs +132 -0
- package/test-runtime-params.mjs +160 -0
- package/test-simple-config.mjs +71 -0
- package/tsconfig.base.json +29 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,1666 @@
|
|
|
1
|
+
import { cosmiconfig } from 'cosmiconfig';
|
|
2
|
+
import path6 from 'path';
|
|
3
|
+
import ky, { HTTPError } from 'ky';
|
|
4
|
+
import { createJiti } from 'jiti';
|
|
5
|
+
import fs5 from 'fs/promises';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
7
|
+
|
|
8
|
+
// src/config/schema.ts
|
|
9
|
+
function defineConfig(config) {
|
|
10
|
+
return config;
|
|
11
|
+
}
|
|
12
|
+
function defineEndpoint(config) {
|
|
13
|
+
return config;
|
|
14
|
+
}
|
|
15
|
+
function defineEndpoints(endpoints) {
|
|
16
|
+
return endpoints;
|
|
17
|
+
}
|
|
18
|
+
var explorer = cosmiconfig("api-codegen", {
|
|
19
|
+
searchPlaces: [
|
|
20
|
+
"api-codegen.config.js",
|
|
21
|
+
"api-codegen.config.mjs",
|
|
22
|
+
"api-codegen.config.ts",
|
|
23
|
+
"api-codegen.config.json",
|
|
24
|
+
".api-codegenrc",
|
|
25
|
+
".api-codegenrc.json",
|
|
26
|
+
".api-codegenrc.js"
|
|
27
|
+
]
|
|
28
|
+
});
|
|
29
|
+
async function loadConfig(configPath) {
|
|
30
|
+
try {
|
|
31
|
+
const result = configPath ? await explorer.load(configPath) : await explorer.search();
|
|
32
|
+
if (!result || !result.config) {
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
const userConfig = result.config;
|
|
36
|
+
const rootDir = path6.dirname(result.filepath);
|
|
37
|
+
const endpointsPath = path6.resolve(rootDir, userConfig.endpoints);
|
|
38
|
+
const outputDir = path6.resolve(rootDir, userConfig.output);
|
|
39
|
+
const generateHooks = userConfig.generateHooks ?? true;
|
|
40
|
+
const generateServerActions = userConfig.generateServerActions ?? userConfig.provider === "nextjs";
|
|
41
|
+
const generateServerQueries = userConfig.generateServerQueries ?? userConfig.provider === "nextjs";
|
|
42
|
+
const generateClient = userConfig.generateClient ?? true;
|
|
43
|
+
const generatePrefetch = userConfig.generatePrefetch ?? true;
|
|
44
|
+
return {
|
|
45
|
+
...userConfig,
|
|
46
|
+
rootDir,
|
|
47
|
+
endpointsPath,
|
|
48
|
+
outputDir,
|
|
49
|
+
generateHooks,
|
|
50
|
+
generateServerActions,
|
|
51
|
+
generateServerQueries,
|
|
52
|
+
generateClient,
|
|
53
|
+
generatePrefetch
|
|
54
|
+
};
|
|
55
|
+
} catch (error) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Failed to load config: ${error instanceof Error ? error.message : String(error)}`
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function validateConfig(config) {
|
|
62
|
+
if (!config.endpoints) {
|
|
63
|
+
throw new Error('Config error: "endpoints" path is required');
|
|
64
|
+
}
|
|
65
|
+
if (!config.provider) {
|
|
66
|
+
throw new Error(
|
|
67
|
+
'Config error: "provider" must be specified (vite or nextjs)'
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
if (!["vite", "nextjs"].includes(config.provider)) {
|
|
71
|
+
throw new Error(
|
|
72
|
+
'Config error: "provider" must be either "vite" or "nextjs"'
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
if (!config.output) {
|
|
76
|
+
throw new Error('Config error: "output" directory is required');
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
var APIError = class extends Error {
|
|
80
|
+
constructor(message, status, response) {
|
|
81
|
+
super(message);
|
|
82
|
+
this.status = status;
|
|
83
|
+
this.response = response;
|
|
84
|
+
this.name = "APIError";
|
|
85
|
+
}
|
|
86
|
+
};
|
|
87
|
+
var AuthError = class extends APIError {
|
|
88
|
+
constructor(message = "Authentication failed") {
|
|
89
|
+
super(message, 401);
|
|
90
|
+
this.name = "AuthError";
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
var APIClient = class {
|
|
94
|
+
constructor(config, authCallbacks) {
|
|
95
|
+
this.config = config;
|
|
96
|
+
this.authCallbacks = authCallbacks;
|
|
97
|
+
this.hooks = {
|
|
98
|
+
beforeRequest: [
|
|
99
|
+
async (request) => {
|
|
100
|
+
const tokens = await this.authCallbacks?.getTokens();
|
|
101
|
+
if (tokens?.accessToken) {
|
|
102
|
+
request.headers.set(
|
|
103
|
+
"Authorization",
|
|
104
|
+
`Bearer ${tokens.accessToken}`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
],
|
|
109
|
+
beforeRetry: [
|
|
110
|
+
async ({ request, error, retryCount }) => {
|
|
111
|
+
if (error instanceof HTTPError && error.response.status === 401) {
|
|
112
|
+
if (retryCount === 1 && this.authCallbacks) {
|
|
113
|
+
try {
|
|
114
|
+
await this.refreshTokens();
|
|
115
|
+
const tokens = await this.authCallbacks.getTokens();
|
|
116
|
+
if (tokens?.accessToken) {
|
|
117
|
+
request.headers.set(
|
|
118
|
+
"Authorization",
|
|
119
|
+
`Bearer ${tokens.accessToken}`
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
} catch (refreshError) {
|
|
123
|
+
this.authCallbacks.onAuthError?.();
|
|
124
|
+
throw new AuthError();
|
|
125
|
+
}
|
|
126
|
+
} else {
|
|
127
|
+
this.authCallbacks?.onAuthError?.();
|
|
128
|
+
throw new AuthError();
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
],
|
|
133
|
+
beforeError: [
|
|
134
|
+
async (error) => {
|
|
135
|
+
const { response } = error;
|
|
136
|
+
if (response?.body) {
|
|
137
|
+
try {
|
|
138
|
+
const body = await response.json();
|
|
139
|
+
error.message = body.message || `HTTP ${response.status}`;
|
|
140
|
+
} catch {
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return error;
|
|
144
|
+
}
|
|
145
|
+
]
|
|
146
|
+
};
|
|
147
|
+
this.client = ky.create({
|
|
148
|
+
prefixUrl: this.config.baseUrl,
|
|
149
|
+
headers: {
|
|
150
|
+
"Content-Type": "application/json"
|
|
151
|
+
},
|
|
152
|
+
retry: {
|
|
153
|
+
limit: 2,
|
|
154
|
+
methods: ["get", "post", "put", "delete", "patch"],
|
|
155
|
+
statusCodes: [401]
|
|
156
|
+
},
|
|
157
|
+
hooks: this.hooks
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
client;
|
|
161
|
+
isRefreshing = false;
|
|
162
|
+
refreshPromise = null;
|
|
163
|
+
hooks;
|
|
164
|
+
async refreshTokens() {
|
|
165
|
+
if (!this.authCallbacks) {
|
|
166
|
+
throw new AuthError("No auth callbacks provided");
|
|
167
|
+
}
|
|
168
|
+
if (this.isRefreshing && this.refreshPromise) {
|
|
169
|
+
return this.refreshPromise;
|
|
170
|
+
}
|
|
171
|
+
this.isRefreshing = true;
|
|
172
|
+
this.refreshPromise = (async () => {
|
|
173
|
+
try {
|
|
174
|
+
if (this.authCallbacks?.onRefreshToken) {
|
|
175
|
+
await this.authCallbacks.onRefreshToken();
|
|
176
|
+
} else {
|
|
177
|
+
throw new AuthError("No refresh token handler provided");
|
|
178
|
+
}
|
|
179
|
+
} catch (error) {
|
|
180
|
+
throw error;
|
|
181
|
+
} finally {
|
|
182
|
+
this.isRefreshing = false;
|
|
183
|
+
this.refreshPromise = null;
|
|
184
|
+
}
|
|
185
|
+
})();
|
|
186
|
+
return this.refreshPromise;
|
|
187
|
+
}
|
|
188
|
+
buildPath(path12, params) {
|
|
189
|
+
if (!params) return path12;
|
|
190
|
+
let finalPath = path12;
|
|
191
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
192
|
+
finalPath = finalPath.replace(
|
|
193
|
+
`:${key}`,
|
|
194
|
+
encodeURIComponent(String(value))
|
|
195
|
+
);
|
|
196
|
+
});
|
|
197
|
+
return finalPath;
|
|
198
|
+
}
|
|
199
|
+
getEndpointBaseUrl(endpoint) {
|
|
200
|
+
return endpoint.baseUrl || this.config.baseUrl;
|
|
201
|
+
}
|
|
202
|
+
getClientForEndpoint(endpoint) {
|
|
203
|
+
const endpointBaseUrl = this.getEndpointBaseUrl(endpoint);
|
|
204
|
+
if (endpointBaseUrl === this.config.baseUrl) {
|
|
205
|
+
return this.client;
|
|
206
|
+
}
|
|
207
|
+
return ky.create({
|
|
208
|
+
prefixUrl: endpointBaseUrl,
|
|
209
|
+
headers: {
|
|
210
|
+
"Content-Type": "application/json"
|
|
211
|
+
},
|
|
212
|
+
retry: {
|
|
213
|
+
limit: 2,
|
|
214
|
+
methods: ["get", "post", "put", "delete", "patch"],
|
|
215
|
+
statusCodes: [401]
|
|
216
|
+
},
|
|
217
|
+
hooks: this.hooks
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
async request(endpoint, params, query, body) {
|
|
221
|
+
try {
|
|
222
|
+
const path12 = this.buildPath(endpoint.path, params);
|
|
223
|
+
const client = this.getClientForEndpoint(endpoint);
|
|
224
|
+
const options = {
|
|
225
|
+
method: endpoint.method
|
|
226
|
+
};
|
|
227
|
+
if (query && Object.keys(query).length > 0) {
|
|
228
|
+
const searchParams = new URLSearchParams();
|
|
229
|
+
Object.entries(query).forEach(([key, value]) => {
|
|
230
|
+
if (value !== void 0 && value !== null) {
|
|
231
|
+
searchParams.append(key, String(value));
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
if (searchParams.toString()) {
|
|
235
|
+
options.searchParams = searchParams;
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
if (body && endpoint.method !== "GET") {
|
|
239
|
+
if (endpoint.body) {
|
|
240
|
+
const validatedBody = endpoint.body.parse(body);
|
|
241
|
+
options.json = validatedBody;
|
|
242
|
+
} else {
|
|
243
|
+
options.json = body;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
const response = await client(path12, options);
|
|
247
|
+
const data = await response.json();
|
|
248
|
+
if (endpoint.response) {
|
|
249
|
+
return endpoint.response.parse(data);
|
|
250
|
+
}
|
|
251
|
+
return data;
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error instanceof HTTPError) {
|
|
254
|
+
const errorData = await error.response.json().catch(() => ({}));
|
|
255
|
+
throw new APIError(
|
|
256
|
+
errorData.message || error.message,
|
|
257
|
+
error.response.status,
|
|
258
|
+
errorData
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
if (error instanceof AuthError) {
|
|
262
|
+
throw error;
|
|
263
|
+
}
|
|
264
|
+
throw new APIError(
|
|
265
|
+
error instanceof Error ? error.message : "Network error",
|
|
266
|
+
0
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
updateAuthCallbacks(authCallbacks) {
|
|
271
|
+
this.authCallbacks = authCallbacks;
|
|
272
|
+
}
|
|
273
|
+
async refreshAuth() {
|
|
274
|
+
if (!this.authCallbacks) {
|
|
275
|
+
throw new AuthError("No auth callbacks provided");
|
|
276
|
+
}
|
|
277
|
+
await this.refreshTokens();
|
|
278
|
+
}
|
|
279
|
+
generateMethods() {
|
|
280
|
+
const methods = {};
|
|
281
|
+
Object.entries(this.config.endpoints).forEach(([name, endpoint]) => {
|
|
282
|
+
if (endpoint.method === "GET") {
|
|
283
|
+
if (endpoint.params && endpoint.query) {
|
|
284
|
+
methods[name] = (params, query) => {
|
|
285
|
+
return this.request(endpoint, params, query);
|
|
286
|
+
};
|
|
287
|
+
} else if (endpoint.params) {
|
|
288
|
+
methods[name] = (params) => {
|
|
289
|
+
return this.request(endpoint, params);
|
|
290
|
+
};
|
|
291
|
+
} else if (endpoint.query) {
|
|
292
|
+
methods[name] = (query) => {
|
|
293
|
+
return this.request(endpoint, void 0, query);
|
|
294
|
+
};
|
|
295
|
+
} else {
|
|
296
|
+
methods[name] = () => {
|
|
297
|
+
return this.request(endpoint);
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
} else {
|
|
301
|
+
if (endpoint.params && endpoint.body) {
|
|
302
|
+
methods[name] = (params, body) => {
|
|
303
|
+
return this.request(endpoint, params, void 0, body);
|
|
304
|
+
};
|
|
305
|
+
} else if (endpoint.params) {
|
|
306
|
+
methods[name] = (params) => {
|
|
307
|
+
return this.request(endpoint, params);
|
|
308
|
+
};
|
|
309
|
+
} else if (endpoint.body) {
|
|
310
|
+
methods[name] = (body) => {
|
|
311
|
+
return this.request(endpoint, void 0, void 0, body);
|
|
312
|
+
};
|
|
313
|
+
} else {
|
|
314
|
+
methods[name] = () => {
|
|
315
|
+
return this.request(endpoint);
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
return methods;
|
|
321
|
+
}
|
|
322
|
+
};
|
|
323
|
+
function createAPIClient(config, authCallbacks) {
|
|
324
|
+
const instance = new APIClient(config, authCallbacks);
|
|
325
|
+
const methods = instance.generateMethods();
|
|
326
|
+
return {
|
|
327
|
+
...methods,
|
|
328
|
+
refreshAuth: () => instance.refreshAuth(),
|
|
329
|
+
updateAuthCallbacks: (newCallbacks) => instance.updateAuthCallbacks(newCallbacks)
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/generators/base.ts
|
|
334
|
+
var BaseGenerator = class {
|
|
335
|
+
constructor(context) {
|
|
336
|
+
this.context = context;
|
|
337
|
+
}
|
|
338
|
+
isQueryEndpoint(endpoint) {
|
|
339
|
+
return endpoint.method === "GET";
|
|
340
|
+
}
|
|
341
|
+
isMutationEndpoint(endpoint) {
|
|
342
|
+
return !this.isQueryEndpoint(endpoint);
|
|
343
|
+
}
|
|
344
|
+
capitalize(str) {
|
|
345
|
+
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
346
|
+
}
|
|
347
|
+
getQueryTags(endpoint) {
|
|
348
|
+
return endpoint.tags || [];
|
|
349
|
+
}
|
|
350
|
+
getInvalidationTags(endpoint) {
|
|
351
|
+
const tags = endpoint.tags || [];
|
|
352
|
+
return tags.filter((tag) => tag !== "query" && tag !== "mutation");
|
|
353
|
+
}
|
|
354
|
+
hasParams(endpoint) {
|
|
355
|
+
return !!endpoint.params;
|
|
356
|
+
}
|
|
357
|
+
hasQuery(endpoint) {
|
|
358
|
+
return !!endpoint.query;
|
|
359
|
+
}
|
|
360
|
+
hasBody(endpoint) {
|
|
361
|
+
return !!endpoint.body;
|
|
362
|
+
}
|
|
363
|
+
getEndpointSignature(name, endpoint) {
|
|
364
|
+
const hasParams = this.hasParams(endpoint);
|
|
365
|
+
const hasQuery = this.hasQuery(endpoint);
|
|
366
|
+
const hasBody = this.hasBody(endpoint);
|
|
367
|
+
return {
|
|
368
|
+
hasParams,
|
|
369
|
+
hasQuery,
|
|
370
|
+
hasBody,
|
|
371
|
+
paramType: hasParams ? `ExtractParams<APIEndpoints['${name}']>` : "never",
|
|
372
|
+
queryType: hasQuery ? `ExtractQuery<APIEndpoints['${name}']>` : "never",
|
|
373
|
+
bodyType: hasBody ? `ExtractBody<APIEndpoints['${name}']>` : "never",
|
|
374
|
+
responseType: `ExtractResponse<APIEndpoints['${name}']>`
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
generateMutationCall(name, hasParams, hasBody) {
|
|
378
|
+
if (hasParams && hasBody) {
|
|
379
|
+
return `return apiClient.${name}(input.params, input.body);`;
|
|
380
|
+
} else if (hasParams) {
|
|
381
|
+
return `return apiClient.${name}(input);`;
|
|
382
|
+
} else if (hasBody) {
|
|
383
|
+
return `return apiClient.${name}(input);`;
|
|
384
|
+
} else {
|
|
385
|
+
return `return apiClient.${name}();`;
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
inferNonNull(expr) {
|
|
389
|
+
return `z.infer<NonNullable<${expr}>>`;
|
|
390
|
+
}
|
|
391
|
+
toCamelCase(str) {
|
|
392
|
+
return str.toLowerCase().replace(/[-_\s]+(.)?/g, (_, c) => c ? c.toUpperCase() : "").replace(/^./, (c) => c.toLowerCase());
|
|
393
|
+
}
|
|
394
|
+
getResourceFromEndpoint(_name, endpoint) {
|
|
395
|
+
const tag = endpoint.tags?.find((t) => t !== "query" && t !== "mutation");
|
|
396
|
+
if (tag) return this.toCamelCase(tag);
|
|
397
|
+
const match = endpoint.path.match(/^\/([^/]+)/);
|
|
398
|
+
return match ? this.toCamelCase(match[1]) : "general";
|
|
399
|
+
}
|
|
400
|
+
groupEndpointsByResource() {
|
|
401
|
+
const groups = {};
|
|
402
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
403
|
+
([name, endpoint]) => {
|
|
404
|
+
const res = this.getResourceFromEndpoint(name, endpoint);
|
|
405
|
+
if (!groups[res]) groups[res] = [];
|
|
406
|
+
groups[res].push({ name, endpoint });
|
|
407
|
+
}
|
|
408
|
+
);
|
|
409
|
+
return groups;
|
|
410
|
+
}
|
|
411
|
+
resourceHasQueryEndpoints(resource) {
|
|
412
|
+
return this.groupEndpointsByResource()[resource]?.some(
|
|
413
|
+
({ endpoint }) => endpoint.method === "GET"
|
|
414
|
+
) ?? false;
|
|
415
|
+
}
|
|
416
|
+
getEndpointKeyName(name) {
|
|
417
|
+
return name.startsWith("get") ? name[3].toLowerCase() + name.slice(4) : name;
|
|
418
|
+
}
|
|
419
|
+
generateQueryKeyCall(resource, name, endpoint) {
|
|
420
|
+
const key = this.getEndpointKeyName(name);
|
|
421
|
+
const args = [];
|
|
422
|
+
if (endpoint.params) args.push("params");
|
|
423
|
+
if (endpoint.query) args.push("filters");
|
|
424
|
+
return args.length ? `queryKeys.${resource}.${key}(${args.join(", ")})` : `queryKeys.${resource}.${key}()`;
|
|
425
|
+
}
|
|
426
|
+
hasQueryOptions() {
|
|
427
|
+
return Object.values(this.context.apiConfig.endpoints).some(
|
|
428
|
+
(e) => e.method === "GET"
|
|
429
|
+
);
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
|
|
433
|
+
// src/generators/hooks.ts
|
|
434
|
+
var HooksGenerator = class extends BaseGenerator {
|
|
435
|
+
async generate() {
|
|
436
|
+
const content = this.generateContent();
|
|
437
|
+
const outputPath = path6.join(this.context.config.outputDir, "hooks.ts");
|
|
438
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
439
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
440
|
+
}
|
|
441
|
+
generateContent() {
|
|
442
|
+
const useClientDirective = this.context.config.options?.useClientDirective ?? true;
|
|
443
|
+
const outputPath = path6.join(this.context.config.outputDir, "types.ts");
|
|
444
|
+
const endpointsPath = path6.join(this.context.config.endpointsPath);
|
|
445
|
+
const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
|
|
446
|
+
const content = `${useClientDirective ? "'use client';\n" : ""}
|
|
447
|
+
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
|
448
|
+
import { apiClient } from "./client";
|
|
449
|
+
import { queryKeys } from "./query-keys";
|
|
450
|
+
import { apiQueryOptions } from "./query-options";
|
|
451
|
+
import { z } from "zod";
|
|
452
|
+
import { apiConfig } from "${relativePath}";
|
|
453
|
+
|
|
454
|
+
${this.generateQueryHooks()}
|
|
455
|
+
${this.generateMutationHooks()}
|
|
456
|
+
`;
|
|
457
|
+
return content;
|
|
458
|
+
}
|
|
459
|
+
generateQueryHooks() {
|
|
460
|
+
const hooks = [];
|
|
461
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
462
|
+
([name, endpoint]) => {
|
|
463
|
+
if (endpoint.method === "GET")
|
|
464
|
+
hooks.push(this.generateQueryHook(name, endpoint));
|
|
465
|
+
}
|
|
466
|
+
);
|
|
467
|
+
return hooks.join("\n\n");
|
|
468
|
+
}
|
|
469
|
+
generateQueryHook(name, endpoint) {
|
|
470
|
+
const hookName = `use${this.capitalize(name)}`;
|
|
471
|
+
const resource = this.getResourceFromEndpoint(name, endpoint);
|
|
472
|
+
const optionName = this.getEndpointKeyName(name);
|
|
473
|
+
const inferParams = this.inferNonNull(
|
|
474
|
+
`typeof apiConfig.endpoints.${name}.params`
|
|
475
|
+
);
|
|
476
|
+
const inferQuery = this.inferNonNull(
|
|
477
|
+
`typeof apiConfig.endpoints.${name}.query`
|
|
478
|
+
);
|
|
479
|
+
const inferResponse = this.inferNonNull(
|
|
480
|
+
`typeof apiConfig.endpoints.${name}.response`
|
|
481
|
+
);
|
|
482
|
+
const params = [];
|
|
483
|
+
const optionParams = [];
|
|
484
|
+
const queryTags = this.getQueryTags(endpoint);
|
|
485
|
+
if (endpoint.params) {
|
|
486
|
+
params.push(`params: ${inferParams}`);
|
|
487
|
+
optionParams.push("params");
|
|
488
|
+
}
|
|
489
|
+
if (endpoint.query) {
|
|
490
|
+
params.push(`filters?: ${inferQuery}`);
|
|
491
|
+
optionParams.push("filters");
|
|
492
|
+
}
|
|
493
|
+
params.push(`options?: {
|
|
494
|
+
enabled?: boolean;
|
|
495
|
+
select?: <TData = ${inferResponse}>(data: ${inferResponse}) => TData;
|
|
496
|
+
}`);
|
|
497
|
+
return `/**
|
|
498
|
+
* ${endpoint.description || `Query hook for ${name}`}
|
|
499
|
+
* @tags ${queryTags.join(", ") || "none"}
|
|
500
|
+
*/
|
|
501
|
+
export function ${hookName}(${params.join(",\n ")}) {
|
|
502
|
+
return useQuery({
|
|
503
|
+
...apiQueryOptions.${resource}.${optionName}(${optionParams.join(", ")}),
|
|
504
|
+
...options,
|
|
505
|
+
});
|
|
506
|
+
}`;
|
|
507
|
+
}
|
|
508
|
+
generateMutationHooks() {
|
|
509
|
+
const hooks = [];
|
|
510
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
511
|
+
([name, endpoint]) => {
|
|
512
|
+
if (endpoint.method !== "GET")
|
|
513
|
+
hooks.push(this.generateMutationHook(name, endpoint));
|
|
514
|
+
}
|
|
515
|
+
);
|
|
516
|
+
return hooks.join("\n\n");
|
|
517
|
+
}
|
|
518
|
+
generateMutationHook(name, endpoint) {
|
|
519
|
+
const hookName = `use${this.capitalize(name)}`;
|
|
520
|
+
const resource = this.getResourceFromEndpoint(name, endpoint);
|
|
521
|
+
const inferParams = this.inferNonNull(
|
|
522
|
+
`typeof apiConfig.endpoints.${name}.params`
|
|
523
|
+
);
|
|
524
|
+
const inferBody = this.inferNonNull(
|
|
525
|
+
`typeof apiConfig.endpoints.${name}.body`
|
|
526
|
+
);
|
|
527
|
+
const inferResponse = this.inferNonNull(
|
|
528
|
+
`typeof apiConfig.endpoints.${name}.response`
|
|
529
|
+
);
|
|
530
|
+
const resourceHasQueries = this.resourceHasQueryEndpoints(resource);
|
|
531
|
+
let inputType;
|
|
532
|
+
let fnBody;
|
|
533
|
+
if (endpoint.params && endpoint.body) {
|
|
534
|
+
inputType = `{ params: ${inferParams}; body: ${inferBody}; }`;
|
|
535
|
+
fnBody = `({ params, body }: ${inputType}) => apiClient.${name}(params, body)`;
|
|
536
|
+
} else if (endpoint.params) {
|
|
537
|
+
inputType = `${inferParams}`;
|
|
538
|
+
fnBody = `(params: ${inputType}) => apiClient.${name}(params)`;
|
|
539
|
+
} else if (endpoint.body) {
|
|
540
|
+
inputType = `${inferBody}`;
|
|
541
|
+
fnBody = `(body: ${inputType}) => apiClient.${name}(body)`;
|
|
542
|
+
} else {
|
|
543
|
+
inputType = "void";
|
|
544
|
+
fnBody = `() => apiClient.${name}()`;
|
|
545
|
+
}
|
|
546
|
+
const invalidate = resourceHasQueries ? `queryClient.invalidateQueries({ queryKey: queryKeys.${resource}.all });` : "";
|
|
547
|
+
return `/**
|
|
548
|
+
* ${endpoint.description || `Mutation hook for ${name}`}
|
|
549
|
+
* @tags ${endpoint.tags?.join(", ") || "none"}
|
|
550
|
+
*/
|
|
551
|
+
export function ${hookName}(options?: {
|
|
552
|
+
onSuccess?: (data: ${inferResponse}, variables: ${inputType}, context: unknown) => void;
|
|
553
|
+
onError?: (error: Error, variables: ${inputType}, context: unknown) => void;
|
|
554
|
+
onSettled?: (data: ${inferResponse} | undefined, error: Error | null, variables: ${inputType}, context: unknown) => void;
|
|
555
|
+
onMutate?: (variables: ${inputType}) => Promise<unknown> | unknown;
|
|
556
|
+
}) {
|
|
557
|
+
${invalidate ? "const queryClient = useQueryClient();" : ""}
|
|
558
|
+
return useMutation({
|
|
559
|
+
mutationFn: ${fnBody},
|
|
560
|
+
onSuccess: (data, variables, context) => {
|
|
561
|
+
${invalidate}
|
|
562
|
+
options?.onSuccess?.(data, variables, context);
|
|
563
|
+
},
|
|
564
|
+
onError: options?.onError,
|
|
565
|
+
onSettled: options?.onSettled,
|
|
566
|
+
onMutate: options?.onMutate,
|
|
567
|
+
});
|
|
568
|
+
}`;
|
|
569
|
+
}
|
|
570
|
+
};
|
|
571
|
+
var ServerActionsGenerator = class extends BaseGenerator {
|
|
572
|
+
async generate() {
|
|
573
|
+
const content = this.generateContent();
|
|
574
|
+
const outputPath = path6.join(this.context.config.outputDir, "actions.ts");
|
|
575
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
576
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
577
|
+
}
|
|
578
|
+
generateContent() {
|
|
579
|
+
const imports = `'use server';
|
|
580
|
+
|
|
581
|
+
import { revalidateTag, revalidatePath } from 'next/cache';
|
|
582
|
+
import { serverClient } from './server-client';
|
|
583
|
+
import type {
|
|
584
|
+
APIEndpoints,
|
|
585
|
+
ExtractBody,
|
|
586
|
+
ExtractParams,
|
|
587
|
+
ExtractResponse
|
|
588
|
+
} from './types';
|
|
589
|
+
|
|
590
|
+
export type ActionResult<T> =
|
|
591
|
+
| { success: true; data: T }
|
|
592
|
+
| { success: false; error: string };
|
|
593
|
+
`;
|
|
594
|
+
const actions = [];
|
|
595
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(([name, endpoint]) => {
|
|
596
|
+
if (this.isMutationEndpoint(endpoint)) {
|
|
597
|
+
actions.push(this.generateServerAction(name, endpoint));
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
return imports + "\n" + actions.join("\n\n");
|
|
601
|
+
}
|
|
602
|
+
generateServerAction(name, endpoint) {
|
|
603
|
+
const actionSuffix = this.context.config.options?.actionSuffix || "Action";
|
|
604
|
+
const actionName = `${name}${actionSuffix}`;
|
|
605
|
+
const signature = this.getEndpointSignature(name, endpoint);
|
|
606
|
+
const invalidationTags = this.getInvalidationTags(endpoint);
|
|
607
|
+
let inputType = "";
|
|
608
|
+
let inputParam = "";
|
|
609
|
+
if (signature.hasParams && signature.hasBody) {
|
|
610
|
+
inputType = `input: { params: ${signature.paramType}; body: ${signature.bodyType} }`;
|
|
611
|
+
inputParam = "input";
|
|
612
|
+
} else if (signature.hasParams) {
|
|
613
|
+
inputType = `params: ${signature.paramType}`;
|
|
614
|
+
inputParam = "params";
|
|
615
|
+
} else if (signature.hasBody) {
|
|
616
|
+
inputType = `body: ${signature.bodyType}`;
|
|
617
|
+
inputParam = "body";
|
|
618
|
+
}
|
|
619
|
+
const revalidateStatements = invalidationTags.length > 0 ? invalidationTags.map((tag) => ` revalidateTag('${tag}');`).join("\n") : " // No automatic revalidations";
|
|
620
|
+
return `/**
|
|
621
|
+
* ${endpoint.description || `Server action for ${name}`}
|
|
622
|
+
* @tags ${endpoint.tags?.join(", ") || "none"}
|
|
623
|
+
*/
|
|
624
|
+
export async function ${actionName}(
|
|
625
|
+
${inputType}
|
|
626
|
+
): Promise<ActionResult<${signature.responseType}>> {
|
|
627
|
+
try {
|
|
628
|
+
const result = await serverClient.${name}(${inputParam ? inputParam : ""});
|
|
629
|
+
|
|
630
|
+
// Revalidate related data
|
|
631
|
+
${revalidateStatements}
|
|
632
|
+
|
|
633
|
+
return { success: true, data: result };
|
|
634
|
+
} catch (error) {
|
|
635
|
+
console.error('[Server Action Error]:', error);
|
|
636
|
+
return {
|
|
637
|
+
success: false,
|
|
638
|
+
error: error instanceof Error ? error.message : 'Unknown error'
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
}`;
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
var ServerQueriesGenerator = class extends BaseGenerator {
|
|
645
|
+
async generate() {
|
|
646
|
+
const content = this.generateContent();
|
|
647
|
+
const outputPath = path6.join(this.context.config.outputDir, "queries.ts");
|
|
648
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
649
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
650
|
+
}
|
|
651
|
+
generateContent() {
|
|
652
|
+
const imports = `import { cache } from 'react';
|
|
653
|
+
import { unstable_cache } from 'next/cache';
|
|
654
|
+
import { serverClient } from './server-client';
|
|
655
|
+
import type {
|
|
656
|
+
APIEndpoints,
|
|
657
|
+
ExtractParams,
|
|
658
|
+
ExtractQuery,
|
|
659
|
+
ExtractResponse
|
|
660
|
+
} from './types';
|
|
661
|
+
`;
|
|
662
|
+
const queries = [];
|
|
663
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
664
|
+
([name, endpoint]) => {
|
|
665
|
+
if (this.isQueryEndpoint(endpoint)) {
|
|
666
|
+
queries.push(this.generateServerQuery(name, endpoint));
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
);
|
|
670
|
+
return imports + "\n" + queries.join("\n\n");
|
|
671
|
+
}
|
|
672
|
+
generateServerQuery(name, endpoint) {
|
|
673
|
+
const queryName = `${name}Query`;
|
|
674
|
+
const signature = this.getEndpointSignature(name, endpoint);
|
|
675
|
+
const queryTags = this.getQueryTags(endpoint);
|
|
676
|
+
const paramDef = signature.hasParams ? `params: ${signature.paramType}` : "";
|
|
677
|
+
const queryDef = signature.hasQuery ? `query?: ${signature.queryType}` : "";
|
|
678
|
+
const paramsList = [paramDef, queryDef].filter(Boolean).join(",\n ");
|
|
679
|
+
const clientCallArgs = [];
|
|
680
|
+
if (signature.hasParams) clientCallArgs.push("params");
|
|
681
|
+
if (signature.hasQuery) clientCallArgs.push("query");
|
|
682
|
+
const cacheKeyParts = [`'${name}'`];
|
|
683
|
+
if (signature.hasParams) cacheKeyParts.push("JSON.stringify(params)");
|
|
684
|
+
if (signature.hasQuery) cacheKeyParts.push("JSON.stringify(query)");
|
|
685
|
+
return `/**
|
|
686
|
+
* ${endpoint.description || `Server query for ${name}`}
|
|
687
|
+
* @tags ${queryTags.join(", ") || "none"}
|
|
688
|
+
*/
|
|
689
|
+
export const ${queryName} = cache(async (
|
|
690
|
+
${paramsList}
|
|
691
|
+
): Promise<${signature.responseType}> => {
|
|
692
|
+
return unstable_cache(
|
|
693
|
+
async () => serverClient.${name}(${clientCallArgs.join(", ")}),
|
|
694
|
+
[${cacheKeyParts.join(", ")}],
|
|
695
|
+
{
|
|
696
|
+
tags: [${queryTags.map((tag) => `'${tag}'`).join(", ")}],
|
|
697
|
+
revalidate: 3600, // 1 hour default, can be overridden
|
|
698
|
+
}
|
|
699
|
+
)();
|
|
700
|
+
});`;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
var TypesGenerator = class extends BaseGenerator {
|
|
704
|
+
async generate() {
|
|
705
|
+
const content = this.generateContent();
|
|
706
|
+
const outputPath = path6.join(this.context.config.outputDir, "types.ts");
|
|
707
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
708
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
709
|
+
}
|
|
710
|
+
generateContent() {
|
|
711
|
+
const outputPath = path6.join(this.context.config.outputDir, "types.ts");
|
|
712
|
+
const endpointsPath = path6.join(this.context.config.endpointsPath);
|
|
713
|
+
const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
|
|
714
|
+
return `// Auto-generated type definitions
|
|
715
|
+
// Do not edit this file manually
|
|
716
|
+
|
|
717
|
+
import type { z } from 'zod';
|
|
718
|
+
import { apiConfig } from '${relativePath}';
|
|
719
|
+
|
|
720
|
+
|
|
721
|
+
// Re-export endpoint configuration types
|
|
722
|
+
export type { APIConfig, APIEndpoint, HTTPMethod } from './schema';
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* Type helper to extract params schema from an endpoint
|
|
726
|
+
*/
|
|
727
|
+
export type ExtractParams<T> = T extends { params: infer P extends z.ZodType }
|
|
728
|
+
? z.infer<P>
|
|
729
|
+
: never;
|
|
730
|
+
|
|
731
|
+
/**
|
|
732
|
+
* Type helper to extract query schema from an endpoint
|
|
733
|
+
*/
|
|
734
|
+
export type ExtractQuery<T> = T extends { query: infer Q extends z.ZodType }
|
|
735
|
+
? z.infer<Q>
|
|
736
|
+
: never;
|
|
737
|
+
|
|
738
|
+
/**
|
|
739
|
+
* Type helper to extract body schema from an endpoint
|
|
740
|
+
*/
|
|
741
|
+
export type ExtractBody<T> = T extends { body: infer B extends z.ZodType }
|
|
742
|
+
? z.infer<B>
|
|
743
|
+
: never;
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* Type helper to extract response schema from an endpoint
|
|
747
|
+
*/
|
|
748
|
+
export type ExtractResponse<T> = T extends { response: infer R extends z.ZodType }
|
|
749
|
+
? z.infer<R>
|
|
750
|
+
: never;
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* Import your API config to get typed endpoints
|
|
754
|
+
*
|
|
755
|
+
*/
|
|
756
|
+
export type APIEndpoints = typeof apiConfig.endpoints;
|
|
757
|
+
|
|
758
|
+
${this.generateEndpointTypes()}
|
|
759
|
+
`;
|
|
760
|
+
}
|
|
761
|
+
generateEndpointTypes() {
|
|
762
|
+
const types = [];
|
|
763
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
764
|
+
([name, endpoint]) => {
|
|
765
|
+
const cap = this.capitalize(name);
|
|
766
|
+
if (endpoint.response)
|
|
767
|
+
types.push(
|
|
768
|
+
`export type ${cap}Response = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.response`)};`
|
|
769
|
+
);
|
|
770
|
+
if (endpoint.body)
|
|
771
|
+
types.push(
|
|
772
|
+
`export type ${cap}Input = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.body`)};`
|
|
773
|
+
);
|
|
774
|
+
if (endpoint.query)
|
|
775
|
+
types.push(
|
|
776
|
+
`export type ${cap}Query = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.query`)};`
|
|
777
|
+
);
|
|
778
|
+
if (endpoint.params)
|
|
779
|
+
types.push(
|
|
780
|
+
`export type ${cap}Params = ${this.inferNonNull(`typeof apiConfig.endpoints.${name}.params`)};`
|
|
781
|
+
);
|
|
782
|
+
}
|
|
783
|
+
);
|
|
784
|
+
return types.join("\n");
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
var ClientGenerator = class extends BaseGenerator {
|
|
788
|
+
async generate() {
|
|
789
|
+
await this.generateClientFile();
|
|
790
|
+
if (this.context.config.provider === "nextjs") {
|
|
791
|
+
await this.generateServerClientFile();
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
async generateClientFile() {
|
|
795
|
+
const content = this.generateClientContent();
|
|
796
|
+
const outputPath = path6.join(this.context.config.outputDir, "client.ts");
|
|
797
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
798
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
799
|
+
}
|
|
800
|
+
async generateServerClientFile() {
|
|
801
|
+
const content = this.generateServerClientContent();
|
|
802
|
+
const outputPath = path6.join(
|
|
803
|
+
this.context.config.outputDir,
|
|
804
|
+
"server-client.ts"
|
|
805
|
+
);
|
|
806
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
807
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
808
|
+
}
|
|
809
|
+
generateClientContent() {
|
|
810
|
+
const useClientDirective = this.context.config.options?.useClientDirective ?? true;
|
|
811
|
+
const outputPath = path6.join(this.context.config.outputDir, "types.ts");
|
|
812
|
+
const endpointsPath = path6.join(this.context.config.endpointsPath);
|
|
813
|
+
const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
|
|
814
|
+
return `${useClientDirective ? "'use client';\n" : ""}
|
|
815
|
+
import { createAPIClient } from './core';
|
|
816
|
+
import type { AuthCallbacks } from './core';
|
|
817
|
+
import { apiConfig } from '${relativePath}';
|
|
818
|
+
import { z } from 'zod';
|
|
819
|
+
|
|
820
|
+
// Type the methods based on endpoints
|
|
821
|
+
type APIClientMethods = {
|
|
822
|
+
[K in keyof typeof apiConfig.endpoints]: (typeof apiConfig.endpoints)[K] extends {
|
|
823
|
+
method: infer M;
|
|
824
|
+
params?: infer P;
|
|
825
|
+
query?: infer Q;
|
|
826
|
+
body?: infer B;
|
|
827
|
+
response: infer R;
|
|
828
|
+
}
|
|
829
|
+
? M extends "GET"
|
|
830
|
+
? P extends z.ZodJSONSchema
|
|
831
|
+
? Q extends z.ZodJSONSchema
|
|
832
|
+
? (params: z.infer<P>, query?: z.infer<Q>) => Promise<z.infer<R>>
|
|
833
|
+
: (params: z.infer<P>) => Promise<z.infer<R>>
|
|
834
|
+
: Q extends z.ZodJSONSchema
|
|
835
|
+
? (query?: z.infer<Q>) => Promise<z.infer<R>>
|
|
836
|
+
: () => Promise<z.infer<R>>
|
|
837
|
+
: P extends z.ZodJSONSchema
|
|
838
|
+
? B extends z.ZodJSONSchema
|
|
839
|
+
? (params: z.infer<P>, body: z.infer<B>) => Promise<z.infer<R>>
|
|
840
|
+
: (params: z.infer<P>) => Promise<z.infer<R>>
|
|
841
|
+
: B extends z.ZodJSONSchema
|
|
842
|
+
? (body: z.infer<B>) => Promise<z.infer<R>>
|
|
843
|
+
: () => Promise<z.infer<R>>
|
|
844
|
+
: never;
|
|
845
|
+
};
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
// Export singleton instance (will be initialized later)
|
|
849
|
+
export let baseClient: APIClientMethods & {
|
|
850
|
+
refreshAuth: () => Promise<void>;
|
|
851
|
+
updateAuthCallbacks: (callbacks: AuthCallbacks) => void;
|
|
852
|
+
};
|
|
853
|
+
|
|
854
|
+
export const apiClient = {
|
|
855
|
+
${this.generateApiClientMethods()}
|
|
856
|
+
};
|
|
857
|
+
|
|
858
|
+
/**
|
|
859
|
+
* Initialize API client with auth callbacks
|
|
860
|
+
* Call this function in your auth provider setup
|
|
861
|
+
*
|
|
862
|
+
* @example
|
|
863
|
+
* const authCallbacks = {
|
|
864
|
+
* getTokens: () => getStoredTokens(),
|
|
865
|
+
* onAuthError: () => router.push('/login'),
|
|
866
|
+
* onRefreshToken: async () => {
|
|
867
|
+
* await refreshAccessToken();
|
|
868
|
+
* },
|
|
869
|
+
* };
|
|
870
|
+
*
|
|
871
|
+
* initializeAPIClient(authCallbacks);
|
|
872
|
+
*/
|
|
873
|
+
export const initializeAPIClient = (authCallbacks: AuthCallbacks) => {
|
|
874
|
+
baseClient = createAPIClient(apiConfig, authCallbacks) as any;
|
|
875
|
+
return baseClient;
|
|
876
|
+
};
|
|
877
|
+
|
|
878
|
+
// Export for custom usage
|
|
879
|
+
export { createAPIClient };
|
|
880
|
+
export type { AuthCallbacks };
|
|
881
|
+
`;
|
|
882
|
+
}
|
|
883
|
+
generateServerClientContent() {
|
|
884
|
+
return `import { createAPIClient } from './core';
|
|
885
|
+
import { apiConfig } from '../config/endpoints';
|
|
886
|
+
import type { APIEndpoints } from './types';
|
|
887
|
+
|
|
888
|
+
// Type-safe API client methods for server-side
|
|
889
|
+
type APIClientMethods = {
|
|
890
|
+
[K in keyof APIEndpoints]: APIEndpoints[K] extends {
|
|
891
|
+
method: infer M;
|
|
892
|
+
params?: infer P;
|
|
893
|
+
query?: infer Q;
|
|
894
|
+
body?: infer B;
|
|
895
|
+
response: infer R;
|
|
896
|
+
}
|
|
897
|
+
? M extends 'GET'
|
|
898
|
+
? P extends { _type: any }
|
|
899
|
+
? Q extends { _type: any }
|
|
900
|
+
? (params: P['_type'], query?: Q['_type']) => Promise<R['_type']>
|
|
901
|
+
: (params: P['_type']) => Promise<R['_type']>
|
|
902
|
+
: Q extends { _type: any }
|
|
903
|
+
? (query?: Q['_type']) => Promise<R['_type']>
|
|
904
|
+
: () => Promise<R['_type']>
|
|
905
|
+
: P extends { _type: any }
|
|
906
|
+
? B extends { _type: any }
|
|
907
|
+
? (params: P['_type'], body: B['_type']) => Promise<R['_type']>
|
|
908
|
+
: (params: P['_type']) => Promise<R['_type']>
|
|
909
|
+
: B extends { _type: any }
|
|
910
|
+
? (body: B['_type']) => Promise<R['_type']>
|
|
911
|
+
: () => Promise<R['_type']>
|
|
912
|
+
: never;
|
|
913
|
+
};
|
|
914
|
+
|
|
915
|
+
/**
|
|
916
|
+
* Server-side API client (no auth, direct API calls)
|
|
917
|
+
* Use this in Server Components, Server Actions, and Route Handlers
|
|
918
|
+
*/
|
|
919
|
+
export const serverClient = createAPIClient(apiConfig) as APIClientMethods;
|
|
920
|
+
`;
|
|
921
|
+
}
|
|
922
|
+
generateApiClientMethods() {
|
|
923
|
+
const methods = [];
|
|
924
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
925
|
+
([name, endpoint]) => {
|
|
926
|
+
const inferParams = this.inferNonNull(
|
|
927
|
+
`typeof apiConfig.endpoints.${name}.params`
|
|
928
|
+
);
|
|
929
|
+
const inferQuery = this.inferNonNull(
|
|
930
|
+
`typeof apiConfig.endpoints.${name}.query`
|
|
931
|
+
);
|
|
932
|
+
const inferBody = this.inferNonNull(
|
|
933
|
+
`typeof apiConfig.endpoints.${name}.body`
|
|
934
|
+
);
|
|
935
|
+
const inferResponse = this.inferNonNull(
|
|
936
|
+
`typeof apiConfig.endpoints.${name}.response`
|
|
937
|
+
);
|
|
938
|
+
if (endpoint.method === "GET") {
|
|
939
|
+
if (endpoint.params && endpoint.query) {
|
|
940
|
+
methods.push(` ${name}: (params: ${inferParams}, query?: ${inferQuery}): Promise<${inferResponse}> =>
|
|
941
|
+
(baseClient as any).${name}(params, query),`);
|
|
942
|
+
} else if (endpoint.params) {
|
|
943
|
+
methods.push(` ${name}: (params: ${inferParams}): Promise<${inferResponse}> =>
|
|
944
|
+
(baseClient as any).${name}(params),`);
|
|
945
|
+
} else if (endpoint.query) {
|
|
946
|
+
methods.push(` ${name}: (query?: ${inferQuery}): Promise<${inferResponse}> =>
|
|
947
|
+
(baseClient as any).${name}(query),`);
|
|
948
|
+
} else {
|
|
949
|
+
methods.push(` ${name}: (): Promise<${inferResponse}> =>
|
|
950
|
+
(baseClient as any).${name}(),`);
|
|
951
|
+
}
|
|
952
|
+
} else {
|
|
953
|
+
if (endpoint.params && endpoint.body) {
|
|
954
|
+
methods.push(` ${name}: (params: ${inferParams}, body: ${inferBody}): Promise<${inferResponse}> =>
|
|
955
|
+
(baseClient as any).${name}(params, body),`);
|
|
956
|
+
} else if (endpoint.params) {
|
|
957
|
+
methods.push(` ${name}: (params: ${inferParams}): Promise<${inferResponse}> =>
|
|
958
|
+
(baseClient as any).${name}(params),`);
|
|
959
|
+
} else if (endpoint.body) {
|
|
960
|
+
methods.push(` ${name}: (body: ${inferBody}): Promise<${inferResponse}> =>
|
|
961
|
+
(baseClient as any).${name}(body),`);
|
|
962
|
+
} else {
|
|
963
|
+
methods.push(` ${name}: (): Promise<${inferResponse}> =>
|
|
964
|
+
(baseClient as any).${name}(),`);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
);
|
|
969
|
+
return methods.join("\n");
|
|
970
|
+
}
|
|
971
|
+
};
|
|
972
|
+
var QueryKeysGenerator = class extends BaseGenerator {
|
|
973
|
+
async generate() {
|
|
974
|
+
const content = this.generateContent();
|
|
975
|
+
const outputPath = path6.join(
|
|
976
|
+
this.context.config.outputDir,
|
|
977
|
+
"query-keys.ts"
|
|
978
|
+
);
|
|
979
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
980
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
981
|
+
}
|
|
982
|
+
generateContent() {
|
|
983
|
+
const outputPath = path6.join(this.context.config.outputDir, "types.ts");
|
|
984
|
+
const endpointsPath = path6.join(this.context.config.endpointsPath);
|
|
985
|
+
const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
|
|
986
|
+
const content = `// Auto-generated query keys
|
|
987
|
+
import { z } from 'zod';
|
|
988
|
+
import { apiConfig } from '${relativePath}';
|
|
989
|
+
|
|
990
|
+
export const queryKeys = {
|
|
991
|
+
${this.generateQueryKeysContent()}
|
|
992
|
+
} as const;
|
|
993
|
+
`;
|
|
994
|
+
return content;
|
|
995
|
+
}
|
|
996
|
+
generateQueryKeysContent() {
|
|
997
|
+
const resourceGroups = this.groupEndpointsByResource();
|
|
998
|
+
const keys = [];
|
|
999
|
+
Object.entries(resourceGroups).forEach(([resource, endpoints]) => {
|
|
1000
|
+
const queryEndpoints = endpoints.filter(
|
|
1001
|
+
({ endpoint }) => endpoint.method === "GET"
|
|
1002
|
+
);
|
|
1003
|
+
if (queryEndpoints.length === 0) return;
|
|
1004
|
+
const resourceKeys = [` all: ['${resource}'] as const,`];
|
|
1005
|
+
const added = /* @__PURE__ */ new Set();
|
|
1006
|
+
queryEndpoints.forEach(({ name, endpoint }) => {
|
|
1007
|
+
const keyName = this.getEndpointKeyName(name);
|
|
1008
|
+
if (added.has(keyName)) return;
|
|
1009
|
+
const inferParams = this.inferNonNull(
|
|
1010
|
+
`typeof apiConfig.endpoints.${name}.params`
|
|
1011
|
+
);
|
|
1012
|
+
const inferQuery = this.inferNonNull(
|
|
1013
|
+
`typeof apiConfig.endpoints.${name}.query`
|
|
1014
|
+
);
|
|
1015
|
+
if (endpoint.params || endpoint.query) {
|
|
1016
|
+
const params = [];
|
|
1017
|
+
if (endpoint.params) params.push(`params?: ${inferParams}`);
|
|
1018
|
+
if (endpoint.query) params.push(`query?: ${inferQuery}`);
|
|
1019
|
+
resourceKeys.push(` ${keyName}: (${params.join(", ")}) =>
|
|
1020
|
+
['${resource}', '${keyName}', ${endpoint.params ? "params" : "undefined"}, ${endpoint.query ? "query" : "undefined"}] as const,`);
|
|
1021
|
+
} else {
|
|
1022
|
+
resourceKeys.push(
|
|
1023
|
+
` ${keyName}: () => ['${resource}', '${keyName}'] as const,`
|
|
1024
|
+
);
|
|
1025
|
+
}
|
|
1026
|
+
added.add(keyName);
|
|
1027
|
+
});
|
|
1028
|
+
keys.push(` ${resource}: {
|
|
1029
|
+
${resourceKeys.join("\n")}
|
|
1030
|
+
},`);
|
|
1031
|
+
});
|
|
1032
|
+
return keys.join("\n");
|
|
1033
|
+
}
|
|
1034
|
+
};
|
|
1035
|
+
var QueryOptionsGenerator = class extends BaseGenerator {
|
|
1036
|
+
async generate() {
|
|
1037
|
+
const content = this.generateContent();
|
|
1038
|
+
const outputPath = path6.join(
|
|
1039
|
+
this.context.config.outputDir,
|
|
1040
|
+
"query-options.ts"
|
|
1041
|
+
);
|
|
1042
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
1043
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
1044
|
+
}
|
|
1045
|
+
generateContent() {
|
|
1046
|
+
const outputPath = path6.join(this.context.config.outputDir, "types.ts");
|
|
1047
|
+
const endpointsPath = path6.join(this.context.config.endpointsPath);
|
|
1048
|
+
const relativePath = path6.relative(path6.dirname(outputPath), endpointsPath).replace(/\\/g, "/");
|
|
1049
|
+
const content = `// Auto-generated query options
|
|
1050
|
+
import { queryOptions } from '@tanstack/react-query';
|
|
1051
|
+
import { apiClient } from './client';
|
|
1052
|
+
import { queryKeys } from './query-keys';
|
|
1053
|
+
import { z } from 'zod';
|
|
1054
|
+
import { apiConfig } from '${relativePath}';
|
|
1055
|
+
|
|
1056
|
+
${this.generateQueryOptionsContent()}
|
|
1057
|
+
|
|
1058
|
+
export const apiQueryOptions = {
|
|
1059
|
+
${this.generateQueryOptionsExports()}
|
|
1060
|
+
} as const;
|
|
1061
|
+
`;
|
|
1062
|
+
return content;
|
|
1063
|
+
}
|
|
1064
|
+
generateQueryOptionsContent() {
|
|
1065
|
+
const groups = this.groupEndpointsByResource();
|
|
1066
|
+
const options = [];
|
|
1067
|
+
Object.entries(groups).forEach(([resource, endpoints]) => {
|
|
1068
|
+
const queries = endpoints.filter(
|
|
1069
|
+
({ endpoint }) => endpoint.method === "GET"
|
|
1070
|
+
);
|
|
1071
|
+
if (queries.length === 0) return;
|
|
1072
|
+
const resourceOptions = [];
|
|
1073
|
+
queries.forEach(({ name, endpoint }) => {
|
|
1074
|
+
const optionName = this.getEndpointKeyName(name);
|
|
1075
|
+
const inferParams = this.inferNonNull(
|
|
1076
|
+
`typeof apiConfig.endpoints.${name}.params`
|
|
1077
|
+
);
|
|
1078
|
+
const inferQuery = this.inferNonNull(
|
|
1079
|
+
`typeof apiConfig.endpoints.${name}.query`
|
|
1080
|
+
);
|
|
1081
|
+
const inferResponse = this.inferNonNull(
|
|
1082
|
+
`typeof apiConfig.endpoints.${name}.response`
|
|
1083
|
+
);
|
|
1084
|
+
const params = [];
|
|
1085
|
+
let apiCall = "";
|
|
1086
|
+
if (endpoint.params && endpoint.query) {
|
|
1087
|
+
params.push(`params: ${inferParams}`, `filters?: ${inferQuery}`);
|
|
1088
|
+
apiCall = `apiClient.${name}(params, filters)`;
|
|
1089
|
+
} else if (endpoint.params) {
|
|
1090
|
+
params.push(`params: ${inferParams}`);
|
|
1091
|
+
apiCall = `apiClient.${name}(params)`;
|
|
1092
|
+
} else if (endpoint.query) {
|
|
1093
|
+
params.push(`filters?: ${inferQuery}`);
|
|
1094
|
+
apiCall = `apiClient.${name}(filters)`;
|
|
1095
|
+
} else {
|
|
1096
|
+
apiCall = `apiClient.${name}()`;
|
|
1097
|
+
}
|
|
1098
|
+
const keyCall = this.generateQueryKeyCall(resource, name, endpoint);
|
|
1099
|
+
resourceOptions.push(` ${optionName}: (${params.join(", ")}) =>
|
|
1100
|
+
queryOptions({
|
|
1101
|
+
queryKey: ${keyCall},
|
|
1102
|
+
queryFn: (): Promise<${inferResponse}> => ${apiCall},
|
|
1103
|
+
staleTime: 1000 * 60 * 5,
|
|
1104
|
+
}),`);
|
|
1105
|
+
});
|
|
1106
|
+
options.push(
|
|
1107
|
+
`const ${resource}QueryOptions = {
|
|
1108
|
+
${resourceOptions.join("\n")}
|
|
1109
|
+
};
|
|
1110
|
+
`
|
|
1111
|
+
);
|
|
1112
|
+
});
|
|
1113
|
+
return options.join("\n");
|
|
1114
|
+
}
|
|
1115
|
+
generateQueryOptionsExports() {
|
|
1116
|
+
const groups = this.groupEndpointsByResource();
|
|
1117
|
+
const exports$1 = [];
|
|
1118
|
+
Object.keys(groups).forEach((resource) => {
|
|
1119
|
+
const hasQueries = groups[resource].some(
|
|
1120
|
+
({ endpoint }) => endpoint.method === "GET"
|
|
1121
|
+
);
|
|
1122
|
+
if (hasQueries) exports$1.push(` ${resource}: ${resource}QueryOptions,`);
|
|
1123
|
+
});
|
|
1124
|
+
return exports$1.join("\n");
|
|
1125
|
+
}
|
|
1126
|
+
};
|
|
1127
|
+
var PrefetchGenerator = class extends BaseGenerator {
|
|
1128
|
+
async generate() {
|
|
1129
|
+
const content = this.generateContent();
|
|
1130
|
+
const outputPath = path6.join(this.context.config.outputDir, "prefetchs.ts");
|
|
1131
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
1132
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
1133
|
+
}
|
|
1134
|
+
generateContent() {
|
|
1135
|
+
const content = `// Auto-generated prefetch utilities
|
|
1136
|
+
import { type QueryClient } from '@tanstack/react-query';
|
|
1137
|
+
${this.hasQueryOptions() ? "import { apiQueryOptions } from './query-options';" : ""}
|
|
1138
|
+
import { z } from 'zod';
|
|
1139
|
+
import { apiConfig } from '../config/endpoints';
|
|
1140
|
+
|
|
1141
|
+
${this.generatePrefetchFunctions()}
|
|
1142
|
+
`;
|
|
1143
|
+
return content;
|
|
1144
|
+
}
|
|
1145
|
+
generatePrefetchFunctions() {
|
|
1146
|
+
const funcs = [];
|
|
1147
|
+
Object.entries(this.context.apiConfig.endpoints).forEach(
|
|
1148
|
+
([name, endpoint]) => {
|
|
1149
|
+
if (endpoint.method === "GET")
|
|
1150
|
+
funcs.push(this.generatePrefetchFunction(name, endpoint));
|
|
1151
|
+
}
|
|
1152
|
+
);
|
|
1153
|
+
return funcs.join("\n\n");
|
|
1154
|
+
}
|
|
1155
|
+
generatePrefetchFunction(name, endpoint) {
|
|
1156
|
+
const prefetchName = `prefetch${this.capitalize(name)}`;
|
|
1157
|
+
const resource = this.getResourceFromEndpoint(name, endpoint);
|
|
1158
|
+
const optionName = this.getEndpointKeyName(name);
|
|
1159
|
+
const inferParams = this.inferNonNull(
|
|
1160
|
+
`typeof apiConfig.endpoints.${name}.params`
|
|
1161
|
+
);
|
|
1162
|
+
const inferQuery = this.inferNonNull(
|
|
1163
|
+
`typeof apiConfig.endpoints.${name}.query`
|
|
1164
|
+
);
|
|
1165
|
+
const params = ["queryClient: QueryClient"];
|
|
1166
|
+
const optionParams = [];
|
|
1167
|
+
if (endpoint.params) {
|
|
1168
|
+
params.push(`params: ${inferParams}`);
|
|
1169
|
+
optionParams.push("params");
|
|
1170
|
+
}
|
|
1171
|
+
if (endpoint.query) {
|
|
1172
|
+
params.push(`filters?: ${inferQuery}`);
|
|
1173
|
+
optionParams.push("filters");
|
|
1174
|
+
}
|
|
1175
|
+
return `export const ${prefetchName} = async (${params.join(",\n ")}) => {
|
|
1176
|
+
return await queryClient.ensureQueryData(apiQueryOptions.${resource}.${optionName}(${optionParams.join(", ")}));
|
|
1177
|
+
};`;
|
|
1178
|
+
}
|
|
1179
|
+
};
|
|
1180
|
+
var SchemaGenerator = class extends BaseGenerator {
|
|
1181
|
+
async generate() {
|
|
1182
|
+
const content = this.generateContent();
|
|
1183
|
+
const outputPath = path6.join(this.context.config.outputDir, "schema.ts");
|
|
1184
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
1185
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
1186
|
+
}
|
|
1187
|
+
generateContent() {
|
|
1188
|
+
const content = `// Auto-generated schema definitions
|
|
1189
|
+
|
|
1190
|
+
import type { z } from 'zod';
|
|
1191
|
+
|
|
1192
|
+
export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
1193
|
+
|
|
1194
|
+
export interface APIEndpoint {
|
|
1195
|
+
path: string;
|
|
1196
|
+
method: HTTPMethod;
|
|
1197
|
+
baseUrl?: string;
|
|
1198
|
+
params?: z.ZodType<any>;
|
|
1199
|
+
query?: z.ZodType<any>;
|
|
1200
|
+
body?: z.ZodType<any>;
|
|
1201
|
+
response: z.ZodType<any>;
|
|
1202
|
+
tags?: string[];
|
|
1203
|
+
description?: string;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
export interface APIConfig {
|
|
1207
|
+
baseUrl?: string;
|
|
1208
|
+
endpoints: Record<string, APIEndpoint>;
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
export type EndpointConfig<
|
|
1212
|
+
TPath extends string = string,
|
|
1213
|
+
TMethod extends HTTPMethod = HTTPMethod,
|
|
1214
|
+
TParams = undefined,
|
|
1215
|
+
TQuery = undefined,
|
|
1216
|
+
TBody = undefined,
|
|
1217
|
+
TResponse = any,
|
|
1218
|
+
> = {
|
|
1219
|
+
path: TPath;
|
|
1220
|
+
method: TMethod;
|
|
1221
|
+
baseUrl?: string;
|
|
1222
|
+
params?: z.ZodType<TParams>;
|
|
1223
|
+
query?: z.ZodType<TQuery>;
|
|
1224
|
+
body?: z.ZodType<TBody>;
|
|
1225
|
+
response: z.ZodType<TResponse>;
|
|
1226
|
+
tags?: string[];
|
|
1227
|
+
description?: string;
|
|
1228
|
+
};
|
|
1229
|
+
|
|
1230
|
+
/**
|
|
1231
|
+
* Helper function to define API configuration with type safety
|
|
1232
|
+
*/
|
|
1233
|
+
export function defineConfig<T extends APIConfig>(config: T): T {
|
|
1234
|
+
return config;
|
|
1235
|
+
}
|
|
1236
|
+
|
|
1237
|
+
/**
|
|
1238
|
+
* Helper function to define a single endpoint with type inference
|
|
1239
|
+
*/
|
|
1240
|
+
export function defineEndpoint<
|
|
1241
|
+
TPath extends string,
|
|
1242
|
+
TMethod extends HTTPMethod,
|
|
1243
|
+
TParams = undefined,
|
|
1244
|
+
TQuery = undefined,
|
|
1245
|
+
TBody = undefined,
|
|
1246
|
+
TResponse = any,
|
|
1247
|
+
>(
|
|
1248
|
+
config: EndpointConfig<TPath, TMethod, TParams, TQuery, TBody, TResponse>,
|
|
1249
|
+
): EndpointConfig<TPath, TMethod, TParams, TQuery, TBody, TResponse> {
|
|
1250
|
+
return config;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
/**
|
|
1254
|
+
* Helper to define multiple endpoints
|
|
1255
|
+
*/
|
|
1256
|
+
export function defineEndpoints<
|
|
1257
|
+
T extends Record<string, APIEndpoint>,
|
|
1258
|
+
>(endpoints: T): T {
|
|
1259
|
+
return endpoints;
|
|
1260
|
+
}
|
|
1261
|
+
}
|
|
1262
|
+
`;
|
|
1263
|
+
return content;
|
|
1264
|
+
}
|
|
1265
|
+
};
|
|
1266
|
+
var CoreGenerator = class extends BaseGenerator {
|
|
1267
|
+
async generate() {
|
|
1268
|
+
const content = this.generateContent();
|
|
1269
|
+
const outputPath = path6.join(this.context.config.outputDir, "core.ts");
|
|
1270
|
+
await fs5.mkdir(path6.dirname(outputPath), { recursive: true });
|
|
1271
|
+
await fs5.writeFile(outputPath, content, "utf-8");
|
|
1272
|
+
}
|
|
1273
|
+
generateContent() {
|
|
1274
|
+
const content = `// Auto-generated schema definitions
|
|
1275
|
+
|
|
1276
|
+
import ky, { HTTPError } from "ky";
|
|
1277
|
+
import type { APIConfig, APIEndpoint } from "../config/schema.js";
|
|
1278
|
+
|
|
1279
|
+
export interface AuthTokens {
|
|
1280
|
+
accessToken: string;
|
|
1281
|
+
refreshToken?: string;
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
export interface AuthCallbacks {
|
|
1285
|
+
getTokens: () => Promise<AuthTokens | null>;
|
|
1286
|
+
onAuthError?: () => void;
|
|
1287
|
+
onRefreshToken?: () => Promise<void>;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
export class APIError extends Error {
|
|
1291
|
+
constructor(
|
|
1292
|
+
message: string,
|
|
1293
|
+
public status: number,
|
|
1294
|
+
public response?: any,
|
|
1295
|
+
) {
|
|
1296
|
+
super(message);
|
|
1297
|
+
this.name = "APIError";
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
export class AuthError extends APIError {
|
|
1302
|
+
constructor(message: string = "Authentication failed") {
|
|
1303
|
+
super(message, 401);
|
|
1304
|
+
this.name = "AuthError";
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
export class APIClient {
|
|
1309
|
+
private client: typeof ky;
|
|
1310
|
+
private isRefreshing = false;
|
|
1311
|
+
private refreshPromise: Promise<void> | null = null;
|
|
1312
|
+
private hooks: any;
|
|
1313
|
+
|
|
1314
|
+
constructor(
|
|
1315
|
+
private config: APIConfig,
|
|
1316
|
+
private authCallbacks?: AuthCallbacks,
|
|
1317
|
+
) {
|
|
1318
|
+
this.hooks = {
|
|
1319
|
+
beforeRequest: [
|
|
1320
|
+
async (request: Request) => {
|
|
1321
|
+
const tokens = await this.authCallbacks?.getTokens();
|
|
1322
|
+
if (tokens?.accessToken) {
|
|
1323
|
+
request.headers.set(
|
|
1324
|
+
"Authorization",
|
|
1325
|
+
\`Bearer \${tokens.accessToken}\`,
|
|
1326
|
+
);
|
|
1327
|
+
}
|
|
1328
|
+
},
|
|
1329
|
+
],
|
|
1330
|
+
beforeRetry: [
|
|
1331
|
+
async ({ request, error, retryCount }: any) => {
|
|
1332
|
+
if (error instanceof HTTPError && error.response.status === 401) {
|
|
1333
|
+
if (retryCount === 1 && this.authCallbacks) {
|
|
1334
|
+
try {
|
|
1335
|
+
await this.refreshTokens();
|
|
1336
|
+
const tokens = await this.authCallbacks.getTokens();
|
|
1337
|
+
if (tokens?.accessToken) {
|
|
1338
|
+
request.headers.set(
|
|
1339
|
+
"Authorization",
|
|
1340
|
+
\`Bearer \${tokens.accessToken}\`,
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
} catch (refreshError) {
|
|
1344
|
+
this.authCallbacks.onAuthError?.();
|
|
1345
|
+
throw new AuthError();
|
|
1346
|
+
}
|
|
1347
|
+
} else {
|
|
1348
|
+
this.authCallbacks?.onAuthError?.();
|
|
1349
|
+
throw new AuthError();
|
|
1350
|
+
}
|
|
1351
|
+
}
|
|
1352
|
+
},
|
|
1353
|
+
],
|
|
1354
|
+
beforeError: [
|
|
1355
|
+
async (error: any) => {
|
|
1356
|
+
const { response } = error;
|
|
1357
|
+
if (response?.body) {
|
|
1358
|
+
try {
|
|
1359
|
+
const body = await response.json();
|
|
1360
|
+
error.message =
|
|
1361
|
+
(body as Error).message || \`HTTP \${response.status}\`;
|
|
1362
|
+
} catch {
|
|
1363
|
+
// Keep original message
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
return error;
|
|
1367
|
+
},
|
|
1368
|
+
],
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
this.client = ky.create({
|
|
1372
|
+
prefixUrl: this.config.baseUrl,
|
|
1373
|
+
headers: {
|
|
1374
|
+
"Content-Type": "application/json",
|
|
1375
|
+
},
|
|
1376
|
+
retry: {
|
|
1377
|
+
limit: 2,
|
|
1378
|
+
methods: ["get", "post", "put", "delete", "patch"],
|
|
1379
|
+
statusCodes: [401],
|
|
1380
|
+
},
|
|
1381
|
+
hooks: this.hooks,
|
|
1382
|
+
});
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
private async refreshTokens(): Promise<void> {
|
|
1386
|
+
if (!this.authCallbacks) {
|
|
1387
|
+
throw new AuthError("No auth callbacks provided");
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
if (this.isRefreshing && this.refreshPromise) {
|
|
1391
|
+
return this.refreshPromise;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
this.isRefreshing = true;
|
|
1395
|
+
|
|
1396
|
+
this.refreshPromise = (async () => {
|
|
1397
|
+
try {
|
|
1398
|
+
if (this.authCallbacks?.onRefreshToken) {
|
|
1399
|
+
await this.authCallbacks.onRefreshToken();
|
|
1400
|
+
} else {
|
|
1401
|
+
throw new AuthError("No refresh token handler provided");
|
|
1402
|
+
}
|
|
1403
|
+
} catch (error) {
|
|
1404
|
+
throw error;
|
|
1405
|
+
} finally {
|
|
1406
|
+
this.isRefreshing = false;
|
|
1407
|
+
this.refreshPromise = null;
|
|
1408
|
+
}
|
|
1409
|
+
})();
|
|
1410
|
+
|
|
1411
|
+
return this.refreshPromise;
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
private buildPath(path: string, params?: Record<string, any>): string {
|
|
1415
|
+
if (!params) return path;
|
|
1416
|
+
|
|
1417
|
+
let finalPath = path;
|
|
1418
|
+
Object.entries(params).forEach(([key, value]) => {
|
|
1419
|
+
finalPath = finalPath.replace(
|
|
1420
|
+
\`:\${key}\`,
|
|
1421
|
+
encodeURIComponent(String(value)),
|
|
1422
|
+
);
|
|
1423
|
+
});
|
|
1424
|
+
|
|
1425
|
+
return finalPath;
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
private getEndpointBaseUrl(endpoint: APIEndpoint): string {
|
|
1429
|
+
return endpoint.baseUrl || this.config.baseUrl!;
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
private getClientForEndpoint(endpoint: APIEndpoint): typeof ky {
|
|
1433
|
+
const endpointBaseUrl = this.getEndpointBaseUrl(endpoint);
|
|
1434
|
+
|
|
1435
|
+
if (endpointBaseUrl === this.config.baseUrl) {
|
|
1436
|
+
return this.client;
|
|
1437
|
+
}
|
|
1438
|
+
|
|
1439
|
+
return ky.create({
|
|
1440
|
+
prefixUrl: endpointBaseUrl,
|
|
1441
|
+
headers: {
|
|
1442
|
+
"Content-Type": "application/json",
|
|
1443
|
+
},
|
|
1444
|
+
retry: {
|
|
1445
|
+
limit: 2,
|
|
1446
|
+
methods: ["get", "post", "put", "delete", "patch"],
|
|
1447
|
+
statusCodes: [401],
|
|
1448
|
+
},
|
|
1449
|
+
hooks: this.hooks,
|
|
1450
|
+
});
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
async request<T>(
|
|
1454
|
+
endpoint: APIEndpoint,
|
|
1455
|
+
params?: Record<string, any>,
|
|
1456
|
+
query?: Record<string, any>,
|
|
1457
|
+
body?: any,
|
|
1458
|
+
): Promise<T> {
|
|
1459
|
+
try {
|
|
1460
|
+
const path = this.buildPath(endpoint.path, params);
|
|
1461
|
+
const client = this.getClientForEndpoint(endpoint);
|
|
1462
|
+
|
|
1463
|
+
const options: Record<string, any> = {
|
|
1464
|
+
method: endpoint.method,
|
|
1465
|
+
};
|
|
1466
|
+
|
|
1467
|
+
if (query && Object.keys(query).length > 0) {
|
|
1468
|
+
const searchParams = new URLSearchParams();
|
|
1469
|
+
Object.entries(query).forEach(([key, value]) => {
|
|
1470
|
+
if (value !== undefined && value !== null) {
|
|
1471
|
+
searchParams.append(key, String(value));
|
|
1472
|
+
}
|
|
1473
|
+
});
|
|
1474
|
+
if (searchParams.toString()) {
|
|
1475
|
+
options.searchParams = searchParams;
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
if (body && endpoint.method !== "GET") {
|
|
1480
|
+
if (endpoint.body) {
|
|
1481
|
+
const validatedBody = endpoint.body.parse(body);
|
|
1482
|
+
options.json = validatedBody;
|
|
1483
|
+
} else {
|
|
1484
|
+
options.json = body;
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
const response = await client(path, options);
|
|
1489
|
+
const data = await response.json();
|
|
1490
|
+
|
|
1491
|
+
if (endpoint.response) {
|
|
1492
|
+
return endpoint.response.parse(data);
|
|
1493
|
+
}
|
|
1494
|
+
|
|
1495
|
+
return data as T;
|
|
1496
|
+
} catch (error) {
|
|
1497
|
+
if (error instanceof HTTPError) {
|
|
1498
|
+
const errorData = await error.response.json().catch(() => ({}));
|
|
1499
|
+
throw new APIError(
|
|
1500
|
+
errorData.message || error.message,
|
|
1501
|
+
error.response.status,
|
|
1502
|
+
errorData,
|
|
1503
|
+
);
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
if (error instanceof AuthError) {
|
|
1507
|
+
throw error;
|
|
1508
|
+
}
|
|
1509
|
+
|
|
1510
|
+
throw new APIError(
|
|
1511
|
+
error instanceof Error ? error.message : "Network error",
|
|
1512
|
+
0,
|
|
1513
|
+
);
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
updateAuthCallbacks(authCallbacks: AuthCallbacks) {
|
|
1518
|
+
this.authCallbacks = authCallbacks;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
async refreshAuth(): Promise<void> {
|
|
1522
|
+
if (!this.authCallbacks) {
|
|
1523
|
+
throw new AuthError("No auth callbacks provided");
|
|
1524
|
+
}
|
|
1525
|
+
await this.refreshTokens();
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
generateMethods() {
|
|
1529
|
+
const methods: any = {};
|
|
1530
|
+
|
|
1531
|
+
Object.entries(this.config.endpoints).forEach(([name, endpoint]) => {
|
|
1532
|
+
if (endpoint.method === "GET") {
|
|
1533
|
+
if (endpoint.params && endpoint.query) {
|
|
1534
|
+
methods[name] = (params: any, query?: any): Promise<any> => {
|
|
1535
|
+
return this.request(endpoint, params, query);
|
|
1536
|
+
};
|
|
1537
|
+
} else if (endpoint.params) {
|
|
1538
|
+
methods[name] = (params: any): Promise<any> => {
|
|
1539
|
+
return this.request(endpoint, params);
|
|
1540
|
+
};
|
|
1541
|
+
} else if (endpoint.query) {
|
|
1542
|
+
methods[name] = (query?: any): Promise<any> => {
|
|
1543
|
+
return this.request(endpoint, undefined, query);
|
|
1544
|
+
};
|
|
1545
|
+
} else {
|
|
1546
|
+
methods[name] = (): Promise<any> => {
|
|
1547
|
+
return this.request(endpoint);
|
|
1548
|
+
};
|
|
1549
|
+
}
|
|
1550
|
+
} else {
|
|
1551
|
+
if (endpoint.params && endpoint.body) {
|
|
1552
|
+
methods[name] = (params: any, body: any): Promise<any> => {
|
|
1553
|
+
return this.request(endpoint, params, undefined, body);
|
|
1554
|
+
};
|
|
1555
|
+
} else if (endpoint.params) {
|
|
1556
|
+
methods[name] = (params: any): Promise<any> => {
|
|
1557
|
+
return this.request(endpoint, params);
|
|
1558
|
+
};
|
|
1559
|
+
} else if (endpoint.body) {
|
|
1560
|
+
methods[name] = (body: any): Promise<any> => {
|
|
1561
|
+
return this.request(endpoint, undefined, undefined, body);
|
|
1562
|
+
};
|
|
1563
|
+
} else {
|
|
1564
|
+
methods[name] = (): Promise<any> => {
|
|
1565
|
+
return this.request(endpoint);
|
|
1566
|
+
};
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
});
|
|
1570
|
+
|
|
1571
|
+
return methods;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
export function createAPIClient(
|
|
1576
|
+
config: APIConfig,
|
|
1577
|
+
authCallbacks?: AuthCallbacks,
|
|
1578
|
+
) {
|
|
1579
|
+
const instance = new APIClient(config, authCallbacks);
|
|
1580
|
+
const methods = instance.generateMethods();
|
|
1581
|
+
|
|
1582
|
+
return {
|
|
1583
|
+
...methods,
|
|
1584
|
+
refreshAuth: () => instance.refreshAuth(),
|
|
1585
|
+
updateAuthCallbacks: (newCallbacks: AuthCallbacks) =>
|
|
1586
|
+
instance.updateAuthCallbacks(newCallbacks),
|
|
1587
|
+
};
|
|
1588
|
+
}
|
|
1589
|
+
`;
|
|
1590
|
+
return content;
|
|
1591
|
+
}
|
|
1592
|
+
};
|
|
1593
|
+
|
|
1594
|
+
// src/generators/index.ts
|
|
1595
|
+
var CodeGenerator = class {
|
|
1596
|
+
constructor(context) {
|
|
1597
|
+
this.context = context;
|
|
1598
|
+
}
|
|
1599
|
+
async generate() {
|
|
1600
|
+
const generators = this.getGenerators();
|
|
1601
|
+
for (const generator of generators) {
|
|
1602
|
+
await generator.generate();
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
getGenerators() {
|
|
1606
|
+
const generators = [];
|
|
1607
|
+
generators.push(new TypesGenerator(this.context));
|
|
1608
|
+
generators.push(new SchemaGenerator(this.context));
|
|
1609
|
+
generators.push(new CoreGenerator(this.context));
|
|
1610
|
+
if (this.context.config.generateClient) {
|
|
1611
|
+
generators.push(new ClientGenerator(this.context));
|
|
1612
|
+
}
|
|
1613
|
+
if (this.context.config.generateHooks) {
|
|
1614
|
+
generators.push(new QueryKeysGenerator(this.context));
|
|
1615
|
+
generators.push(new QueryOptionsGenerator(this.context));
|
|
1616
|
+
generators.push(new HooksGenerator(this.context));
|
|
1617
|
+
}
|
|
1618
|
+
if (this.context.config.generatePrefetch) {
|
|
1619
|
+
generators.push(new PrefetchGenerator(this.context));
|
|
1620
|
+
}
|
|
1621
|
+
if (this.context.config.generateServerActions && this.context.config.provider === "nextjs") {
|
|
1622
|
+
generators.push(new ServerActionsGenerator(this.context));
|
|
1623
|
+
}
|
|
1624
|
+
if (this.context.config.generateServerQueries && this.context.config.provider === "nextjs") {
|
|
1625
|
+
generators.push(new ServerQueriesGenerator(this.context));
|
|
1626
|
+
}
|
|
1627
|
+
return generators;
|
|
1628
|
+
}
|
|
1629
|
+
};
|
|
1630
|
+
var CodegenCore = class {
|
|
1631
|
+
constructor(config) {
|
|
1632
|
+
this.config = config;
|
|
1633
|
+
}
|
|
1634
|
+
async execute() {
|
|
1635
|
+
const apiConfig = await this.loadAPIConfig();
|
|
1636
|
+
this.config.apiConfig = apiConfig;
|
|
1637
|
+
const generator = new CodeGenerator({
|
|
1638
|
+
config: this.config,
|
|
1639
|
+
apiConfig
|
|
1640
|
+
});
|
|
1641
|
+
await generator.generate();
|
|
1642
|
+
}
|
|
1643
|
+
async loadAPIConfig() {
|
|
1644
|
+
try {
|
|
1645
|
+
const jiti = createJiti(fileURLToPath(import.meta.url), {
|
|
1646
|
+
interopDefault: true
|
|
1647
|
+
});
|
|
1648
|
+
const module = await jiti.import(this.config.endpointsPath);
|
|
1649
|
+
const apiConfig = module.apiConfig || module.default?.apiConfig || module.default || module;
|
|
1650
|
+
if (!apiConfig || !apiConfig.endpoints) {
|
|
1651
|
+
throw new Error(
|
|
1652
|
+
'Invalid API config: must export an object with "endpoints" property'
|
|
1653
|
+
);
|
|
1654
|
+
}
|
|
1655
|
+
return apiConfig;
|
|
1656
|
+
} catch (error) {
|
|
1657
|
+
throw new Error(
|
|
1658
|
+
`Failed to load endpoints from "${this.config.endpointsPath}": ${error instanceof Error ? error.message : String(error)}`
|
|
1659
|
+
);
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
};
|
|
1663
|
+
|
|
1664
|
+
export { APIError, AuthError, CodeGenerator, CodegenCore, createAPIClient, defineConfig, defineEndpoint, defineEndpoints, loadConfig, validateConfig };
|
|
1665
|
+
//# sourceMappingURL=index.js.map
|
|
1666
|
+
//# sourceMappingURL=index.js.map
|