@yigityalim/next-router-client 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,647 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ generateClient: () => generateClient,
34
+ generateFetchers: () => generateFetchers,
35
+ generateHooks: () => generateHooks,
36
+ generateKeys: () => generateKeys,
37
+ generateTypes: () => generateTypes
38
+ });
39
+ module.exports = __toCommonJS(index_exports);
40
+
41
+ // src/generate-client.ts
42
+ var import_node_fs5 = __toESM(require("fs"));
43
+ var import_node_path5 = __toESM(require("path"));
44
+
45
+ // src/generators/fetchers.ts
46
+ var import_node_fs = __toESM(require("fs"));
47
+ var import_node_path = __toESM(require("path"));
48
+ async function generateFetchers(options) {
49
+ const { openApiPath, outputDir, baseUrl } = options;
50
+ const spec = JSON.parse(import_node_fs.default.readFileSync(openApiPath, "utf-8"));
51
+ const routes = parseRoutes(spec);
52
+ const code = generateFetcherCode(routes, baseUrl);
53
+ const fetchersPath = import_node_path.default.join(outputDir, "fetchers.ts");
54
+ import_node_fs.default.writeFileSync(fetchersPath, code);
55
+ }
56
+ function parseRoutes(spec) {
57
+ const routes = [];
58
+ for (const [path6, pathItem] of Object.entries(spec.paths || {})) {
59
+ for (const [method, operation] of Object.entries(pathItem)) {
60
+ if (!["get", "post", "put", "delete", "patch"].includes(method)) continue;
61
+ routes.push({
62
+ path: path6,
63
+ method: method.toUpperCase(),
64
+ operationId: operation.operationId || `${method}${path6.replace(/\//g, "_")}`,
65
+ parameters: operation.parameters || [],
66
+ requestBody: operation.requestBody,
67
+ responses: operation.responses || {}
68
+ });
69
+ }
70
+ }
71
+ return routes;
72
+ }
73
+ function generateFetcherCode(routes, baseUrl) {
74
+ let code = `/**
75
+ * This file was auto-generated by route-handler client generator.
76
+ * Do not make direct changes to this file.
77
+ */
78
+
79
+ export interface FetcherOptions {
80
+ baseUrl?: string;
81
+ headers?: Record<string, string>;
82
+ }
83
+
84
+ const defaultOptions: FetcherOptions = {
85
+ baseUrl: "${baseUrl}",
86
+ };
87
+
88
+ function buildQueryString(params: Record<string, unknown>): string {
89
+ const searchParams = new URLSearchParams();
90
+ for (const [key, value] of Object.entries(params)) {
91
+ if (value !== undefined && value !== null) {
92
+ searchParams.append(key, String(value));
93
+ }
94
+ }
95
+ return searchParams.toString();
96
+ }
97
+
98
+ async function fetcher<TData = unknown>(
99
+ path: string,
100
+ init?: RequestInit,
101
+ options?: FetcherOptions,
102
+ ): Promise<TData> {
103
+ const { baseUrl, headers } = { ...defaultOptions, ...options };
104
+ const url = \`\${baseUrl}\${path}\`;
105
+
106
+ const response = await fetch(url, {
107
+ ...init,
108
+ headers: {
109
+ "Content-Type": "application/json",
110
+ ...headers,
111
+ ...init?.headers,
112
+ },
113
+ });
114
+
115
+ if (!response.ok) {
116
+ throw new Error(\`HTTP error! status: \${response.status}\`);
117
+ }
118
+
119
+ return response.json();
120
+ }
121
+
122
+ `;
123
+ const resourceMap = /* @__PURE__ */ new Map();
124
+ for (const route of routes) {
125
+ const resource = extractResource(route.path);
126
+ if (!resourceMap.has(resource)) {
127
+ resourceMap.set(resource, []);
128
+ }
129
+ resourceMap.get(resource).push(route);
130
+ }
131
+ for (const [resource, resourceRoutes] of resourceMap) {
132
+ code += `export const ${resource}Fetchers = {
133
+ `;
134
+ for (const route of resourceRoutes) {
135
+ code += generateFetcherFunction(route);
136
+ }
137
+ code += `};
138
+
139
+ `;
140
+ }
141
+ return code;
142
+ }
143
+ function extractResource(path6) {
144
+ const parts = path6.split("/").filter(Boolean);
145
+ const resourcePart = parts.find((p) => !p.startsWith("{") && p !== "v1");
146
+ return resourcePart || "api";
147
+ }
148
+ function generateFetcherFunction(route) {
149
+ const { method, path: path6, operationId } = route;
150
+ const hasPathParams = path6.includes("{");
151
+ const hasQueryParams = route.parameters?.some((p) => p.in === "query");
152
+ const hasBody = method !== "GET" && method !== "DELETE";
153
+ const funcName = operationId.replace(
154
+ /[A-Z]/g,
155
+ (m, offset) => offset > 0 ? m : m.toLowerCase()
156
+ );
157
+ let params = "";
158
+ let pathReplacement = path6;
159
+ let fetchOptions = "";
160
+ if (hasPathParams) {
161
+ const pathParams = route.parameters?.filter((p) => p.in === "path") || [];
162
+ params += pathParams.map((p) => `${p.name}: string`).join(", ");
163
+ for (const param of pathParams) {
164
+ pathReplacement = pathReplacement.replace(
165
+ `{${param.name}}`,
166
+ `\${${param.name}}`
167
+ );
168
+ }
169
+ }
170
+ if (hasQueryParams) {
171
+ if (params) params += ", ";
172
+ params += "params?: Record<string, unknown>";
173
+ }
174
+ if (hasBody) {
175
+ if (params) params += ", ";
176
+ params += "body?: unknown";
177
+ fetchOptions = `, { method: "${method}", body: JSON.stringify(body) }`;
178
+ } else if (method !== "GET") {
179
+ fetchOptions = `, { method: "${method}" }`;
180
+ }
181
+ let url = `\`${pathReplacement}\``;
182
+ if (hasQueryParams) {
183
+ url += ` + (params ? \`?\${buildQueryString(params)}\` : "")`;
184
+ }
185
+ return ` ${funcName}: async (${params}) => fetcher(${url}${fetchOptions}),
186
+ `;
187
+ }
188
+
189
+ // src/generators/hooks.ts
190
+ var import_node_fs2 = __toESM(require("fs"));
191
+ var import_node_path2 = __toESM(require("path"));
192
+ async function generateHooks(options) {
193
+ const { openApiPath, outputDir, library } = options;
194
+ const spec = JSON.parse(import_node_fs2.default.readFileSync(openApiPath, "utf-8"));
195
+ const routes = parseRoutes2(spec);
196
+ const code = library === "react-query" ? generateReactQueryHooks(routes) : generateSWRHooks(routes);
197
+ const hooksPath = import_node_path2.default.join(outputDir, "hooks.ts");
198
+ import_node_fs2.default.writeFileSync(hooksPath, code);
199
+ }
200
+ function parseRoutes2(spec) {
201
+ const routes = [];
202
+ for (const [path6, pathItem] of Object.entries(spec.paths || {})) {
203
+ for (const [method, operation] of Object.entries(pathItem)) {
204
+ if (!["get", "post", "put", "delete", "patch"].includes(method)) continue;
205
+ routes.push({
206
+ path: path6,
207
+ method: method.toUpperCase(),
208
+ operationId: operation.operationId || `${method}${path6.replace(/\//g, "_")}`,
209
+ parameters: operation.parameters || [],
210
+ requestBody: operation.requestBody,
211
+ responses: operation.responses || {}
212
+ });
213
+ }
214
+ }
215
+ return routes;
216
+ }
217
+ function generateReactQueryHooks(routes) {
218
+ let code = `/**
219
+ * This file was auto-generated by route-handler client generator.
220
+ * Do not make direct changes to this file.
221
+ */
222
+
223
+ import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
224
+ import type { UseQueryOptions, UseMutationOptions } from "@tanstack/react-query";
225
+ import * as fetchers from "./fetchers";
226
+ import * as keys from "./keys";
227
+
228
+ `;
229
+ const resourceMap = /* @__PURE__ */ new Map();
230
+ for (const route of routes) {
231
+ const resource = extractResource2(route.path);
232
+ if (!resourceMap.has(resource)) {
233
+ resourceMap.set(resource, []);
234
+ }
235
+ resourceMap.get(resource).push(route);
236
+ }
237
+ for (const [resource, resourceRoutes] of resourceMap) {
238
+ for (const route of resourceRoutes.filter((r) => r.method === "GET")) {
239
+ code += generateReactQueryHook(resource, route);
240
+ }
241
+ for (const route of resourceRoutes.filter((r) => r.method !== "GET")) {
242
+ code += generateReactMutationHook(resource, route);
243
+ }
244
+ }
245
+ return code;
246
+ }
247
+ function generateReactQueryHook(resource, route) {
248
+ const isList = !route.path.includes("{");
249
+ const hookName = isList ? `use${capitalize(resource)}` : `use${capitalize(resource.endsWith("s") ? resource.slice(0, -1) : resource)}`;
250
+ const keyFactory = isList ? `keys.${resource}Keys.list` : `keys.${resource}Keys.detail`;
251
+ const fetcherName = route.operationId;
252
+ const hasQueryParams = route.parameters?.some((p) => p.in === "query");
253
+ let params = "";
254
+ let fetcherArgs = "";
255
+ let keyArgs = "";
256
+ if (isList && hasQueryParams) {
257
+ params = "params?: Record<string, unknown>, ";
258
+ fetcherArgs = "params";
259
+ keyArgs = "params";
260
+ } else if (isList) {
261
+ keyArgs = "undefined";
262
+ } else if (!isList) {
263
+ params = "id: string, ";
264
+ fetcherArgs = "id";
265
+ keyArgs = "id";
266
+ }
267
+ return `export function ${hookName}(${params}options?: Omit<UseQueryOptions, "queryKey" | "queryFn">) {
268
+ return useQuery({
269
+ queryKey: ${keyFactory}(${keyArgs}),
270
+ queryFn: () => fetchers.${resource}Fetchers.${fetcherName}(${fetcherArgs}),
271
+ ...options,
272
+ });
273
+ }
274
+
275
+ `;
276
+ }
277
+ function generateReactMutationHook(resource, route) {
278
+ const hookName = generateHookName(resource, route);
279
+ const fetcherName = route.operationId;
280
+ const pathParams = route.parameters?.filter((p) => p.in === "path") || [];
281
+ const hasBody = route.method !== "DELETE" && route.method !== "GET";
282
+ let paramsInterface = "{ ";
283
+ for (const param of pathParams) {
284
+ paramsInterface += `${param.name}: string; `;
285
+ }
286
+ if (hasBody) {
287
+ paramsInterface += "body?: unknown; ";
288
+ }
289
+ paramsInterface += "}";
290
+ let destructure = "{ ";
291
+ let fetcherArgs = "";
292
+ for (const param of pathParams) {
293
+ destructure += `${param.name}, `;
294
+ fetcherArgs += `${param.name}, `;
295
+ }
296
+ if (hasBody) {
297
+ destructure += "body ";
298
+ fetcherArgs += "body";
299
+ } else {
300
+ destructure = destructure.slice(0, -2);
301
+ fetcherArgs = fetcherArgs.slice(0, -2);
302
+ }
303
+ destructure += "}";
304
+ return `export function ${hookName}(options?: UseMutationOptions<unknown, Error, ${paramsInterface}>) {
305
+ const queryClient = useQueryClient();
306
+
307
+ return useMutation({
308
+ mutationFn: (${destructure}) => fetchers.${resource}Fetchers.${fetcherName}(${fetcherArgs}),
309
+ onSuccess: () => {
310
+ queryClient.invalidateQueries({ queryKey: keys.${resource}Keys.all });
311
+ },
312
+ ...options,
313
+ });
314
+ }
315
+
316
+ `;
317
+ }
318
+ function generateHookName(resource, route) {
319
+ const singular = resource.endsWith("s") ? resource.slice(0, -1) : resource;
320
+ switch (route.method) {
321
+ case "POST":
322
+ return `useCreate${capitalize(singular)}`;
323
+ case "PUT":
324
+ case "PATCH":
325
+ if (route.path.includes("/public")) {
326
+ return `useToggle${capitalize(singular)}Visibility`;
327
+ }
328
+ return `useUpdate${capitalize(singular)}`;
329
+ case "DELETE":
330
+ return `useDelete${capitalize(singular)}`;
331
+ default:
332
+ return `use${capitalize(route.operationId)}`;
333
+ }
334
+ }
335
+ function generateSWRHooks(routes) {
336
+ let code = `/**
337
+ * This file was auto-generated by route-handler client generator.
338
+ * Do not make direct changes to this file.
339
+ */
340
+
341
+ import useSWR from "swr";
342
+ import useSWRMutation from "swr/mutation";
343
+ import type { SWRConfiguration } from "swr";
344
+ import * as fetchers from "./fetchers";
345
+ import * as keys from "./keys";
346
+
347
+ `;
348
+ const resourceMap = /* @__PURE__ */ new Map();
349
+ for (const route of routes) {
350
+ const resource = extractResource2(route.path);
351
+ if (!resourceMap.has(resource)) {
352
+ resourceMap.set(resource, []);
353
+ }
354
+ resourceMap.get(resource).push(route);
355
+ }
356
+ for (const [resource, resourceRoutes] of resourceMap) {
357
+ for (const route of resourceRoutes.filter((r) => r.method === "GET")) {
358
+ code += generateSWRHook(resource, route);
359
+ }
360
+ for (const route of resourceRoutes.filter((r) => r.method !== "GET")) {
361
+ code += generateSWRMutationHook(resource, route);
362
+ }
363
+ }
364
+ return code;
365
+ }
366
+ function generateSWRHook(resource, route) {
367
+ const isList = !route.path.includes("{");
368
+ const hookName = isList ? `use${capitalize(resource)}` : `use${capitalize(resource.endsWith("s") ? resource.slice(0, -1) : resource)}`;
369
+ const keyFactory = isList ? `keys.${resource}Keys.list` : `keys.${resource}Keys.detail`;
370
+ const fetcherName = route.operationId;
371
+ const hasQueryParams = route.parameters?.some((p) => p.in === "query");
372
+ let params = "";
373
+ let fetcherArgs = "";
374
+ let keyArgs = "";
375
+ if (isList && hasQueryParams) {
376
+ params = "params?: Record<string, unknown>, ";
377
+ fetcherArgs = "params";
378
+ keyArgs = "params";
379
+ } else if (isList) {
380
+ keyArgs = "undefined";
381
+ } else if (!isList) {
382
+ params = "id: string, ";
383
+ fetcherArgs = "id";
384
+ keyArgs = "id";
385
+ }
386
+ return `export function ${hookName}(${params}config?: SWRConfiguration) {
387
+ return useSWR(
388
+ ${keyFactory}(${keyArgs}),
389
+ () => fetchers.${resource}Fetchers.${fetcherName}(${fetcherArgs}),
390
+ config
391
+ );
392
+ }
393
+
394
+ `;
395
+ }
396
+ function generateSWRMutationHook(resource, route) {
397
+ const hookName = generateHookName(resource, route);
398
+ const fetcherName = route.operationId;
399
+ const pathParams = route.parameters?.filter((p) => p.in === "path") || [];
400
+ const hasBody = route.method !== "DELETE" && route.method !== "GET";
401
+ let argType = "{ ";
402
+ for (const param of pathParams) {
403
+ argType += `${param.name}: string; `;
404
+ }
405
+ if (hasBody) {
406
+ argType += "body?: unknown; ";
407
+ }
408
+ argType += "}";
409
+ let fetcherArgs = "";
410
+ for (const param of pathParams) {
411
+ fetcherArgs += `arg.${param.name}, `;
412
+ }
413
+ if (hasBody) {
414
+ fetcherArgs += "arg.body";
415
+ } else {
416
+ fetcherArgs = fetcherArgs.slice(0, -2);
417
+ }
418
+ return `export function ${hookName}() {
419
+ return useSWRMutation(
420
+ keys.${resource}Keys.all,
421
+ async (_key, { arg }: { arg: ${argType} }) =>
422
+ fetchers.${resource}Fetchers.${fetcherName}(${fetcherArgs})
423
+ );
424
+ }
425
+
426
+ `;
427
+ }
428
+ function extractResource2(path6) {
429
+ const parts = path6.split("/").filter(Boolean);
430
+ const resourcePart = parts.find((p) => !p.startsWith("{") && p !== "v1");
431
+ return resourcePart || "api";
432
+ }
433
+ function capitalize(str) {
434
+ return str.charAt(0).toUpperCase() + str.slice(1);
435
+ }
436
+
437
+ // src/generators/keys.ts
438
+ var import_node_fs3 = __toESM(require("fs"));
439
+ var import_node_path3 = __toESM(require("path"));
440
+ async function generateKeys(options) {
441
+ const { openApiPath, outputDir } = options;
442
+ const spec = JSON.parse(import_node_fs3.default.readFileSync(openApiPath, "utf-8"));
443
+ const routes = parseRoutes3(spec);
444
+ const code = generateKeysCode(routes);
445
+ const keysPath = import_node_path3.default.join(outputDir, "keys.ts");
446
+ import_node_fs3.default.writeFileSync(keysPath, code);
447
+ }
448
+ function parseRoutes3(spec) {
449
+ const routes = [];
450
+ for (const [path6, pathItem] of Object.entries(spec.paths || {})) {
451
+ for (const [method, operation] of Object.entries(pathItem)) {
452
+ if (!["get", "post", "put", "delete", "patch"].includes(method)) continue;
453
+ routes.push({
454
+ path: path6,
455
+ method: method.toUpperCase(),
456
+ operationId: operation.operationId || `${method}${path6.replace(/\//g, "_")}`,
457
+ parameters: operation.parameters || [],
458
+ requestBody: operation.requestBody,
459
+ responses: operation.responses || {}
460
+ });
461
+ }
462
+ }
463
+ return routes;
464
+ }
465
+ function generateKeysCode(routes) {
466
+ let code = `/**
467
+ * This file was auto-generated by route-handler client generator.
468
+ * Do not make direct changes to this file.
469
+ *
470
+ * Query key factories following TanStack Query best practices.
471
+ * @see https://tkdodo.eu/blog/effective-react-query-keys
472
+ */
473
+
474
+ `;
475
+ const resourceMap = /* @__PURE__ */ new Map();
476
+ for (const route of routes) {
477
+ const resource = extractResource3(route.path);
478
+ if (!resourceMap.has(resource)) {
479
+ resourceMap.set(resource, []);
480
+ }
481
+ resourceMap.get(resource).push(route);
482
+ }
483
+ for (const [resource, resourceRoutes] of resourceMap) {
484
+ code += `export const ${resource}Keys = {
485
+ `;
486
+ code += ` all: ["${resource}"] as const,
487
+ `;
488
+ const listRoutes = resourceRoutes.filter(
489
+ (r) => !r.path.includes("{") && r.method === "GET"
490
+ );
491
+ if (listRoutes.length > 0) {
492
+ code += ` lists: () => [...${resource}Keys.all, "list"] as const,
493
+ `;
494
+ code += ` list: (filters?: Record<string, unknown>) => [...${resource}Keys.lists(), filters] as const,
495
+ `;
496
+ }
497
+ const detailRoutes = resourceRoutes.filter(
498
+ (r) => r.path.includes("{") && r.method === "GET"
499
+ );
500
+ if (detailRoutes.length > 0) {
501
+ code += ` details: () => [...${resource}Keys.all, "detail"] as const,
502
+ `;
503
+ code += ` detail: (id: string) => [...${resource}Keys.details(), id] as const,
504
+ `;
505
+ }
506
+ code += `};
507
+
508
+ `;
509
+ }
510
+ return code;
511
+ }
512
+ function extractResource3(path6) {
513
+ const parts = path6.split("/").filter(Boolean);
514
+ const resourcePart = parts.find((p) => !p.startsWith("{") && p !== "v1");
515
+ return resourcePart || "api";
516
+ }
517
+
518
+ // src/generators/types.ts
519
+ var import_node_fs4 = __toESM(require("fs"));
520
+ var import_node_path4 = __toESM(require("path"));
521
+ var import_openapi_typescript = __toESM(require("openapi-typescript"));
522
+ async function generateTypes(options) {
523
+ const { openApiPath, outputDir } = options;
524
+ const ast = await (0, import_openapi_typescript.default)(new URL(`file://${import_node_path4.default.resolve(openApiPath)}`));
525
+ const output = (0, import_openapi_typescript.astToString)(ast);
526
+ const header = `/**
527
+ * This file was auto-generated by route-handler client generator.
528
+ * Do not make direct changes to this file.
529
+ */
530
+
531
+ `;
532
+ const typesPath = import_node_path4.default.join(outputDir, "types.ts");
533
+ import_node_fs4.default.writeFileSync(typesPath, header + output);
534
+ }
535
+
536
+ // src/generate-client.ts
537
+ async function generateClient(options) {
538
+ const {
539
+ openApiPath,
540
+ outputDir = ".next-router/generated",
541
+ library = "vanilla",
542
+ baseUrl = "/api/v1"
543
+ } = options;
544
+ const resolvedOutputDir = import_node_path5.default.resolve(process.cwd(), outputDir);
545
+ if (import_node_fs5.default.existsSync(resolvedOutputDir)) {
546
+ import_node_fs5.default.rmSync(resolvedOutputDir, { recursive: true, force: true });
547
+ }
548
+ import_node_fs5.default.mkdirSync(resolvedOutputDir, { recursive: true });
549
+ console.log(`
550
+ \u{1F4C1} Output directory: ${outputDir}`);
551
+ console.log(`\u{1F4DA} Client library: ${library}`);
552
+ console.log(`\u{1F310} Base URL: ${baseUrl}
553
+ `);
554
+ console.log("\u2699\uFE0F Generating types...");
555
+ await generateTypes({ openApiPath, outputDir: resolvedOutputDir });
556
+ console.log("\u2699\uFE0F Generating fetchers...");
557
+ await generateFetchers({
558
+ openApiPath,
559
+ outputDir: resolvedOutputDir,
560
+ baseUrl
561
+ });
562
+ console.log("\u2699\uFE0F Generating query keys...");
563
+ await generateKeys({ openApiPath, outputDir: resolvedOutputDir });
564
+ if (library !== "vanilla") {
565
+ console.log(`\u2699\uFE0F Generating ${library} hooks...`);
566
+ await generateHooks({ openApiPath, outputDir: resolvedOutputDir, library });
567
+ }
568
+ const indexContent = generateIndexFile(library);
569
+ import_node_fs5.default.writeFileSync(import_node_path5.default.join(resolvedOutputDir, "index.ts"), indexContent);
570
+ updateTsConfig(resolvedOutputDir);
571
+ console.log("\n\u2705 Client generation complete!");
572
+ console.log(`
573
+ Import from: import { ... } from "next-router/generated"
574
+ `);
575
+ }
576
+ function generateIndexFile(library) {
577
+ let exports2 = `export * from "./types";
578
+ export * from "./fetchers";
579
+ export * from "./keys";
580
+ `;
581
+ if (library !== "vanilla") {
582
+ exports2 += `export * from "./hooks";
583
+ `;
584
+ }
585
+ return exports2;
586
+ }
587
+ function updateTsConfig(resolvedOutputDir) {
588
+ let searchDir = resolvedOutputDir;
589
+ let tsconfigPath = null;
590
+ for (let i = 0; i < 5; i++) {
591
+ searchDir = import_node_path5.default.dirname(searchDir);
592
+ const candidatePath = import_node_path5.default.join(searchDir, "tsconfig.json");
593
+ if (import_node_fs5.default.existsSync(candidatePath)) {
594
+ tsconfigPath = candidatePath;
595
+ break;
596
+ }
597
+ }
598
+ if (!tsconfigPath) {
599
+ console.log("\n\u26A0\uFE0F tsconfig.json not found - skipping path alias setup");
600
+ console.log(` Add this to your tsconfig.json manually:`);
601
+ console.log(` "paths": { "next-router/generated/*": [".next-router/generated/*"] }
602
+ `);
603
+ return;
604
+ }
605
+ const tsconfigDir = import_node_path5.default.dirname(tsconfigPath);
606
+ const relativeOutputDir = import_node_path5.default.relative(tsconfigDir, resolvedOutputDir).replace(/\\/g, "/");
607
+ try {
608
+ const tsconfigContent = import_node_fs5.default.readFileSync(tsconfigPath, "utf-8");
609
+ const tsconfig = JSON.parse(tsconfigContent);
610
+ if (!tsconfig.compilerOptions) {
611
+ tsconfig.compilerOptions = {};
612
+ }
613
+ if (!tsconfig.compilerOptions.paths) {
614
+ tsconfig.compilerOptions.paths = {};
615
+ }
616
+ const pathKey = `next-router/generated/*`;
617
+ const pathValue = [`${relativeOutputDir}/*`];
618
+ const existingPath = tsconfig.compilerOptions.paths[pathKey];
619
+ if (JSON.stringify(existingPath) !== JSON.stringify(pathValue)) {
620
+ tsconfig.compilerOptions.paths[pathKey] = pathValue;
621
+ import_node_fs5.default.writeFileSync(tsconfigPath, JSON.stringify(tsconfig, null, 2) + "\n");
622
+ console.log(`
623
+ \u2705 Updated ${import_node_path5.default.basename(import_node_path5.default.dirname(tsconfigPath))}/${import_node_path5.default.basename(tsconfigPath)} with path alias:`);
624
+ console.log(` "${pathKey}": ["${pathValue[0]}"]`);
625
+ } else {
626
+ console.log(`
627
+ \u2713 Path alias already configured in ${import_node_path5.default.basename(import_node_path5.default.dirname(tsconfigPath))}/${import_node_path5.default.basename(tsconfigPath)}`);
628
+ }
629
+ } catch (error) {
630
+ console.log(`
631
+ \u26A0\uFE0F Could not update tsconfig.json automatically`);
632
+ console.log(` Add this to your tsconfig.json manually:`);
633
+ console.log(
634
+ ` "paths": { "next-router/generated/*": ["${relativeOutputDir}/*"] }
635
+ `
636
+ );
637
+ }
638
+ }
639
+ // Annotate the CommonJS export names for ESM import in node:
640
+ 0 && (module.exports = {
641
+ generateClient,
642
+ generateFetchers,
643
+ generateHooks,
644
+ generateKeys,
645
+ generateTypes
646
+ });
647
+ //# sourceMappingURL=index.js.map