@7nohe/openapi-react-query-codegen 3.2.1 → 4.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/AGENTS.md +22 -19
  2. package/README.md +5 -4
  3. package/dist/cli.d.mts +6 -1
  4. package/dist/client/emitSchemas.d.mts +9 -0
  5. package/dist/client/emitSchemas.mjs +130 -0
  6. package/dist/client/emitSdk.d.mts +18 -0
  7. package/dist/client/emitSdk.mjs +253 -0
  8. package/dist/client/emitTransformers.d.mts +19 -0
  9. package/dist/client/emitTransformers.mjs +556 -0
  10. package/dist/client/emitTypes.d.mts +16 -0
  11. package/dist/client/emitTypes.mjs +204 -0
  12. package/dist/client/index.d.mts +44 -0
  13. package/dist/client/index.mjs +126 -0
  14. package/dist/client/naming.d.mts +41 -0
  15. package/dist/client/naming.mjs +175 -0
  16. package/dist/client/operations.d.mts +103 -0
  17. package/dist/client/operations.mjs +352 -0
  18. package/dist/client/runtime/axios.runtime.ts +706 -0
  19. package/dist/client/runtime/fetch.runtime.ts +795 -0
  20. package/dist/client/schema.d.mts +50 -0
  21. package/dist/client/schema.mjs +648 -0
  22. package/dist/client/spec.d.mts +40 -0
  23. package/dist/client/spec.mjs +387 -0
  24. package/dist/client/tsconfig.d.mts +12 -0
  25. package/dist/client/tsconfig.mjs +152 -0
  26. package/dist/common.d.mts +0 -38
  27. package/dist/common.mjs +0 -87
  28. package/dist/constants.d.mts +0 -2
  29. package/dist/constants.mjs +0 -2
  30. package/dist/createSource.d.mts +8 -7
  31. package/dist/createSource.mjs +14 -17
  32. package/dist/format.mjs +0 -1
  33. package/dist/generate.d.mts +9 -9
  34. package/dist/generate.mjs +45 -107
  35. package/dist/runCli.mjs +7 -2
  36. package/dist/tsmorph/buildQueryHooks.mjs +19 -11
  37. package/dist/tsmorph/generateFiles.mjs +105 -161
  38. package/dist/tsmorph/operationNames.d.mts +2 -13
  39. package/dist/tsmorph/operationNames.mjs +4 -24
  40. package/dist/tsmorph/projectFactory.d.mts +7 -2
  41. package/dist/tsmorph/projectFactory.mjs +16 -9
  42. package/dist/types.d.mts +14 -26
  43. package/package.json +7 -8
  44. package/dist/parseOperations.d.mts +0 -10
  45. package/dist/parseOperations.mjs +0 -164
  46. package/dist/service.d.mts +0 -8
  47. package/dist/service.mjs +0 -98
  48. package/dist/util.d.mts +0 -2
  49. package/dist/util.mjs +0 -16
@@ -0,0 +1,204 @@
1
+ import { HEADER } from "./emitSdk.mjs";
2
+ import { propertyKey, toEnumMemberName, uniqueName } from "./naming.mjs";
3
+ import { buildRequestBodyNames, classifyResponses, deref, pickContent, } from "./operations.mjs";
4
+ import { docComment, renderComponentSchema, renderSchema, schemaDescription, } from "./schema.mjs";
5
+ /** First server URL with its variables replaced by their defaults. */
6
+ export function getBaseUrl(doc) {
7
+ const server = Array.isArray(doc.servers) ? doc.servers[0] : undefined;
8
+ if (!server || typeof server.url !== "string")
9
+ return undefined;
10
+ return server.url.replace(/\{([^}]+)\}/g, (match, name) => {
11
+ const value = server.variables?.[name]?.default;
12
+ return value === undefined ? match : String(value);
13
+ });
14
+ }
15
+ function statusKey(status) {
16
+ return /^\d+$/.test(status) || status === "default"
17
+ ? status
18
+ : JSON.stringify(status);
19
+ }
20
+ function renderParamObject(parameters, ctx, indent) {
21
+ const inner = `${indent} `;
22
+ const lines = parameters.map((parameter) => {
23
+ const comment = docComment({
24
+ description: parameter.description,
25
+ deprecated: parameter.deprecated,
26
+ }, inner);
27
+ return `${comment}${inner}${propertyKey(parameter.name)}${parameter.required ? "" : "?"}: ${renderSchema(parameter.schema, ctx, inner)};`;
28
+ });
29
+ return `{\n${lines.join("\n")}\n${indent}}`;
30
+ }
31
+ function renderEntries(responses, ctx) {
32
+ const seen = new Set();
33
+ const types = [];
34
+ const lines = [];
35
+ for (const response of responses) {
36
+ if (seen.has(response.status))
37
+ continue;
38
+ seen.add(response.status);
39
+ const type = response.schema
40
+ ? renderSchema(response.schema, ctx, " ")
41
+ : response.status === "204"
42
+ ? "void"
43
+ : "unknown";
44
+ types.push(type);
45
+ const comment = docComment({ description: response.description }, " ");
46
+ lines.push(`${comment} ${statusKey(response.status)}: ${type};`);
47
+ }
48
+ return { body: lines.join("\n"), types };
49
+ }
50
+ function emitOperationTypes(operation, ctx, writeCtx) {
51
+ const typeNames = [];
52
+ const blocks = [];
53
+ const add = (name, type) => {
54
+ typeNames.push(name);
55
+ blocks.push(`export type ${name} = ${type};`);
56
+ };
57
+ const names = operation.typeNames;
58
+ const byLocation = (location) => operation.parameters.filter((parameter) => parameter.in === location);
59
+ const path = byLocation("path");
60
+ const query = byLocation("query");
61
+ const headers = byLocation("header");
62
+ const fields = [];
63
+ if (operation.body) {
64
+ const comment = docComment({ description: operation.body.description }, " ");
65
+ const type = operation.body.schema
66
+ ? renderSchema(operation.body.schema, writeCtx, " ")
67
+ : "unknown";
68
+ fields.push(`${comment} body${operation.body.required ? "" : "?"}: ${type};`);
69
+ }
70
+ else {
71
+ fields.push(" body?: never;");
72
+ }
73
+ const addGroup = (name, group) => {
74
+ if (group.length === 0) {
75
+ fields.push(` ${name}?: never;`);
76
+ return;
77
+ }
78
+ const required = group.some((parameter) => parameter.required);
79
+ // Parameters are sent, so they are the request-side types too.
80
+ fields.push(` ${name}${required ? "" : "?"}: ${renderParamObject(group, writeCtx, " ")};`);
81
+ };
82
+ addGroup("path", path);
83
+ addGroup("query", query);
84
+ if (headers.length > 0)
85
+ addGroup("headers", headers);
86
+ fields.push(` url: ${JSON.stringify(operation.path)};`);
87
+ add(names.data, `{\n${fields.join("\n")}\n}`);
88
+ const { responses, errors } = classifyResponses(operation);
89
+ const emitGroup = (groupName, aliasName, group) => {
90
+ if (group.length === 0)
91
+ return;
92
+ const { body, types } = renderEntries(group, ctx);
93
+ add(groupName, `{\n${body}\n}`);
94
+ if (types.some((type) => type !== "unknown")) {
95
+ add(aliasName, `${groupName}[keyof ${groupName}]`);
96
+ }
97
+ };
98
+ emitGroup(names.errors, names.error, errors);
99
+ emitGroup(names.responses, names.response, responses);
100
+ return { names: typeNames, blocks };
101
+ }
102
+ function enumKey(name) {
103
+ // `01` would be an octal literal, which TypeScript rejects.
104
+ return /^(0|[1-9]\d*)$/.test(name) ? name : propertyKey(name);
105
+ }
106
+ function emitComponentSchema(schema, key, name, ctx, enumsMode) {
107
+ const comment = docComment({
108
+ description: schemaDescription(schema),
109
+ deprecated: schema?.deprecated,
110
+ });
111
+ const values = Array.isArray(schema?.enum) ? schema.enum : [];
112
+ const isMember = (value) => typeof value === "string" || typeof value === "number";
113
+ // A TypeScript enum can only hold strings and numbers, an object anything.
114
+ const isLiteralEnum = values.some((value) => value !== null) &&
115
+ values.every((value) => isMember(value) ||
116
+ (enumsMode === "javascript" &&
117
+ (value === null || typeof value === "boolean")));
118
+ if (enumsMode && isLiteralEnum) {
119
+ const used = new Set();
120
+ const memberNames = schema["x-enum-varnames"] ?? schema["x-enumNames"];
121
+ const descriptions = schema["x-enum-descriptions"];
122
+ const members = values.map((value, index) => {
123
+ const title = memberNames?.[index];
124
+ return {
125
+ comment: docComment({
126
+ description: schemaDescription({
127
+ title,
128
+ description: descriptions?.[index],
129
+ }),
130
+ }, " "),
131
+ key: enumKey(uniqueName(toEnumMemberName(title ?? value, {
132
+ numericKeys: enumsMode === "javascript",
133
+ }), used)),
134
+ value: JSON.stringify(value),
135
+ };
136
+ });
137
+ if (enumsMode === "typescript") {
138
+ const body = members
139
+ .map((member) => `${member.comment} ${member.key} = ${member.value},`)
140
+ .join("\n");
141
+ return `${comment}export enum ${name} {\n${body}\n}`;
142
+ }
143
+ const body = members
144
+ .map((member) => `${member.comment} ${member.key}: ${member.value},`)
145
+ .join("\n");
146
+ return `${comment}export const ${name} = {\n${body}\n} as const;\n\nexport type ${name} = (typeof ${name})[keyof typeof ${name}];`;
147
+ }
148
+ return `${comment}export type ${name} = ${renderComponentSchema(schema, key, ctx)};`;
149
+ }
150
+ export function emitTypes(doc, operations, ctx, options) {
151
+ const readCtx = { ...ctx, mode: "read" };
152
+ const writeCtx = { ...ctx, mode: "write" };
153
+ const head = [];
154
+ const exported = ["ClientOptions"];
155
+ const baseUrl = getBaseUrl(doc);
156
+ const baseUrlKey = options.clientKind === "axios" ? "baseURL" : "baseUrl";
157
+ head.push(`export type ClientOptions = {\n ${baseUrlKey}: ${baseUrl ? `${JSON.stringify(baseUrl)} | (string & {})` : "string"};\n};`);
158
+ const schemas = (doc.components?.schemas ?? {});
159
+ for (const [key, schema] of Object.entries(schemas)) {
160
+ const name = ctx.names.get(key);
161
+ exported.push(name);
162
+ head.push(emitComponentSchema(schema, key, name, readCtx, options.enums));
163
+ }
164
+ for (const key of Object.keys(schemas)) {
165
+ const name = ctx.writableNames?.get(key);
166
+ if (name === undefined)
167
+ continue;
168
+ head.push(emitComponentSchema(schemas[key], key, name, writeCtx, undefined));
169
+ exported.push(name);
170
+ }
171
+ // A shared request body is a type of its own, as the schemas are.
172
+ const bodyNames = buildRequestBodyNames(doc, [
173
+ ...exported,
174
+ ...operations.flatMap((operation) => [
175
+ operation.functionName,
176
+ ...Object.values(operation.typeNames),
177
+ ]),
178
+ ]);
179
+ for (const [key, name] of bodyNames) {
180
+ let body;
181
+ try {
182
+ body = deref(doc, doc.components.requestBodies[key]);
183
+ }
184
+ catch {
185
+ // Nothing uses it, or `collectOperations` would have thrown already.
186
+ }
187
+ const schema = pickContent(body?.content)?.media?.schema;
188
+ const comment = docComment({ description: body?.description });
189
+ head.push(`${comment}export type ${name} = ${schema ? renderSchema(schema, writeCtx) : "unknown"};`);
190
+ exported.push(name);
191
+ }
192
+ const operationBlocks = [];
193
+ const operationNames = [];
194
+ for (const operation of operations) {
195
+ const { names, blocks } = emitOperationTypes(operation, readCtx, writeCtx);
196
+ operationNames.push(...names);
197
+ operationBlocks.push(...blocks);
198
+ }
199
+ exported.push(...operationNames);
200
+ return {
201
+ content: `${HEADER}\n${[...head, ...operationBlocks].join("\n\n")}\n`,
202
+ exportedNames: exported,
203
+ };
204
+ }
@@ -0,0 +1,44 @@
1
+ import type { GeneratedFile, OperationInfo } from "../types.mjs";
2
+ import { type SchemasMode } from "./emitSchemas.mjs";
3
+ import { type ClientKind } from "./emitSdk.mjs";
4
+ import { type EnumsMode } from "./emitTypes.mjs";
5
+ export type { SchemasMode } from "./emitSchemas.mjs";
6
+ export type { ClientKind } from "./emitSdk.mjs";
7
+ export type { EnumsMode } from "./emitTypes.mjs";
8
+ export { SpecError } from "./spec.mjs";
9
+ export { detectImportExtension, findNearestTsConfigPath } from "./tsconfig.mjs";
10
+ export interface ClientGenOptions {
11
+ /** Path, URL or inline content of the OpenAPI specification. */
12
+ input: string;
13
+ client: ClientKind;
14
+ enums?: EnumsMode;
15
+ /** `.js` for Node16/NodeNext module resolution, otherwise empty. */
16
+ importExtension: "" | ".js";
17
+ /** Name operations after the HTTP method and path instead of operationId. */
18
+ noOperationId?: boolean;
19
+ /** Query parameter used for pagination. */
20
+ pageParam: string;
21
+ /**
22
+ * Generate `schemas.gen.ts` with the component schemas as constants. `form`
23
+ * leaves out descriptions and titles. Off when `false` or not set.
24
+ */
25
+ schemas?: SchemasMode | false;
26
+ /**
27
+ * Type `date` and `date-time` strings as `Date`, and turn them into `Date`
28
+ * objects in successful responses.
29
+ */
30
+ useDateType?: boolean;
31
+ }
32
+ export interface GeneratedClient {
33
+ files: GeneratedFile[];
34
+ operations: OperationInfo[];
35
+ /** Type names exported from `types.gen.ts`. */
36
+ modelNames: string[];
37
+ /** Function names exported from `sdk.gen.ts`. */
38
+ serviceNames: string[];
39
+ /** What the generator could not do as asked, to tell the user. */
40
+ warnings: string[];
41
+ }
42
+ /** Generate the TypeScript client (types, SDK, runtime) for a specification. */
43
+ export declare function generateClient(options: ClientGenOptions): Promise<GeneratedClient>;
44
+ export declare function writeGeneratedFiles(outputDir: string, files: GeneratedFile[]): Promise<void>;
@@ -0,0 +1,126 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { emitSchemas } from "./emitSchemas.mjs";
4
+ import { emitClientFile, emitIndexFile, emitSdk, emitServicesShim, optionsAreOptional, } from "./emitSdk.mjs";
5
+ import { emitTransformers } from "./emitTransformers.mjs";
6
+ import { emitTypes, getBaseUrl } from "./emitTypes.mjs";
7
+ import { capitalizeFirst } from "./naming.mjs";
8
+ import { buildSchemaNames, buildWritableNames, collectOperations, schemaPrimitiveKind, } from "./operations.mjs";
9
+ import { renderSchema } from "./schema.mjs";
10
+ import { bundleExternalRefs, loadSpec } from "./spec.mjs";
11
+ export { SpecError } from "./spec.mjs";
12
+ export { detectImportExtension, findNearestTsConfigPath } from "./tsconfig.mjs";
13
+ const RUNTIME_FILES = {
14
+ fetch: "./runtime/fetch.runtime.ts",
15
+ axios: "./runtime/axios.runtime.ts",
16
+ };
17
+ async function readRuntime(kind) {
18
+ return readFile(new URL(RUNTIME_FILES[kind], import.meta.url), "utf-8");
19
+ }
20
+ function assertSupported(doc) {
21
+ if (doc.swagger) {
22
+ throw new Error(`Swagger/OpenAPI 2.0 specifications are not supported (found swagger: "${doc.swagger}"). Convert the specification to OpenAPI 3.x first.`);
23
+ }
24
+ if (typeof doc.openapi !== "string" || !doc.openapi.startsWith("3.")) {
25
+ throw new Error(`Unsupported or missing "openapi" version: ${JSON.stringify(doc.openapi)}. OpenAPI 3.0 and 3.1 are supported.`);
26
+ }
27
+ }
28
+ function toOperationInfo(operation, ctx, pageParam, emittedTypes) {
29
+ const method = operation.method.toUpperCase();
30
+ const pageParameter = method === "GET"
31
+ ? operation.parameters.find((parameter) => parameter.in === "query" && parameter.name === pageParam)
32
+ : undefined;
33
+ return {
34
+ methodName: operation.functionName,
35
+ capitalizedMethodName: capitalizeFirst(operation.functionName),
36
+ dataTypeName: operation.typeNames.data,
37
+ errorTypeName: emittedTypes.has(operation.typeNames.error)
38
+ ? operation.typeNames.error
39
+ : undefined,
40
+ httpMethod: method,
41
+ jsDoc: operation.jsDoc,
42
+ allParamsOptional: optionsAreOptional(operation),
43
+ isPaginatable: pageParameter !== undefined,
44
+ pageParamType: pageParameter
45
+ ? renderSchema(pageParameter.schema, ctx)
46
+ : undefined,
47
+ pageParamTypeKind: pageParameter
48
+ ? schemaPrimitiveKind(ctx.doc, pageParameter.schema)
49
+ : undefined,
50
+ };
51
+ }
52
+ /** Generate the TypeScript client (types, SDK, runtime) for a specification. */
53
+ export async function generateClient(options) {
54
+ const loaded = await loadSpec(options.input);
55
+ const doc = await bundleExternalRefs(loaded);
56
+ assertSupported(doc);
57
+ const names = buildSchemaNames(doc);
58
+ const writableNames = buildWritableNames(doc, names);
59
+ const ctx = {
60
+ doc,
61
+ names,
62
+ writableNames,
63
+ dates: options.useDateType === true,
64
+ };
65
+ const operations = collectOperations(doc, {
66
+ useOperationId: !options.noOperationId,
67
+ reservedTypeNames: [...names.values(), ...writableNames.values()],
68
+ });
69
+ const ext = options.importExtension;
70
+ const types = emitTypes(doc, operations, ctx, {
71
+ enums: options.enums,
72
+ clientKind: options.client,
73
+ });
74
+ const transformers = options.useDateType
75
+ ? emitTransformers(operations, ctx)
76
+ : undefined;
77
+ const warnings = [];
78
+ if (transformers && transformers.skipped.length > 0) {
79
+ warnings.push(`--useDateType: the dates in these schemas stay strings in responses, because nothing tells the members of the union apart:\n${transformers.skipped
80
+ .map((where) => ` - ${where}`)
81
+ .join("\n")}`);
82
+ }
83
+ const files = [
84
+ { name: "types.gen.ts", content: types.content },
85
+ {
86
+ name: "sdk.gen.ts",
87
+ content: emitSdk(doc, operations, {
88
+ kind: options.client,
89
+ ext,
90
+ transformers: transformers?.byOperation,
91
+ }),
92
+ },
93
+ {
94
+ name: "client.gen.ts",
95
+ content: emitClientFile({
96
+ kind: options.client,
97
+ ext,
98
+ baseUrl: getBaseUrl(doc),
99
+ }),
100
+ },
101
+ { name: "runtime.gen.ts", content: await readRuntime(options.client) },
102
+ { name: "index.ts", content: emitIndexFile(ext) },
103
+ { name: "services.gen.ts", content: emitServicesShim(ext) },
104
+ ];
105
+ if (transformers?.content !== undefined) {
106
+ files.push({ name: "transformers.gen.ts", content: transformers.content });
107
+ }
108
+ const schemas = options.schemas
109
+ ? emitSchemas(ctx, options.schemas)
110
+ : undefined;
111
+ if (schemas !== undefined) {
112
+ files.push({ name: "schemas.gen.ts", content: schemas });
113
+ }
114
+ const emittedTypes = new Set(types.exportedNames);
115
+ return {
116
+ files,
117
+ operations: operations.map((operation) => toOperationInfo(operation, ctx, options.pageParam, emittedTypes)),
118
+ modelNames: types.exportedNames,
119
+ serviceNames: operations.map((operation) => operation.functionName),
120
+ warnings,
121
+ };
122
+ }
123
+ export async function writeGeneratedFiles(outputDir, files) {
124
+ await mkdir(outputDir, { recursive: true });
125
+ await Promise.all(files.map((file) => writeFile(path.join(outputDir, file.name), file.content)));
126
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Identifier helpers shared by the client generator.
3
+ *
4
+ * The rules mirror what the SDK generator the project used before: words are
5
+ * split on non-alphanumerics, a leading digit run is split from the letters
6
+ * that follow it, and an identifier that would start with a digit gets a `_`
7
+ * prefix.
8
+ */
9
+ export declare function isValidIdentifier(name: string): boolean;
10
+ declare function capitalize(word: string): string;
11
+ /**
12
+ * `find pet by id` → `findPetById`; `getHTTPStatus` → `getHttpStatus`;
13
+ * `123numericLead` → `_123NumericLead`. Acronyms are folded like any other word
14
+ * and other characters become `_`, which is what the v3 generator did, so
15
+ * existing imports keep working.
16
+ */
17
+ export declare function toCamelCase(input: string): string;
18
+ /** Name of a function generated for an operation. */
19
+ export declare function toFunctionName(input: string): string;
20
+ /**
21
+ * Name of a type generated from a schema key: the PascalCase form of the same
22
+ * name (`FineTuneDPOHyperparameters` → `FineTuneDpoHyperparameters`,
23
+ * `account_annual_revenue` → `AccountAnnualRevenue`).
24
+ */
25
+ export declare function toTypeName(input: string): string;
26
+ /** Build a camelCase name for an operation that has no operationId. */
27
+ export declare function nameFromPath(method: string, path: string): string;
28
+ /** Object key, quoted only when it is not a valid identifier. */
29
+ export declare function propertyKey(name: string): string;
30
+ /** Make `base` unique inside `used` by appending a counter. */
31
+ export declare function uniqueName(base: string, used: Set<string>): string;
32
+ /**
33
+ * Name for an enum member generated from its value, in UPPER_SNAKE_CASE
34
+ * (`in-progress` → `IN_PROGRESS`). A number gets a `_` prefix, except when
35
+ * `numericKeys` is set (valid as an object key, so `{ 1: 1 }` stays readable).
36
+ * The result can need quoting (`-X`, `2A`).
37
+ */
38
+ export declare function toEnumMemberName(value: unknown, options?: {
39
+ numericKeys?: boolean;
40
+ }): string;
41
+ export { capitalize as capitalizeFirst };
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Identifier helpers shared by the client generator.
3
+ *
4
+ * The rules mirror what the SDK generator the project used before: words are
5
+ * split on non-alphanumerics, a leading digit run is split from the letters
6
+ * that follow it, and an identifier that would start with a digit gets a `_`
7
+ * prefix.
8
+ */
9
+ const IDENTIFIER_RE = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
10
+ const RESERVED_WORDS = new Set([
11
+ "break",
12
+ "case",
13
+ "catch",
14
+ "class",
15
+ "const",
16
+ "continue",
17
+ "debugger",
18
+ "default",
19
+ "delete",
20
+ "do",
21
+ "else",
22
+ "enum",
23
+ "export",
24
+ "extends",
25
+ "false",
26
+ "finally",
27
+ "for",
28
+ "function",
29
+ "if",
30
+ "import",
31
+ "in",
32
+ "instanceof",
33
+ "new",
34
+ "null",
35
+ "return",
36
+ "super",
37
+ "switch",
38
+ "this",
39
+ "throw",
40
+ "true",
41
+ "try",
42
+ "typeof",
43
+ "var",
44
+ "void",
45
+ "while",
46
+ "with",
47
+ "yield",
48
+ "let",
49
+ "static",
50
+ "implements",
51
+ "interface",
52
+ "package",
53
+ "private",
54
+ "protected",
55
+ "public",
56
+ "await",
57
+ "async",
58
+ "arguments",
59
+ "eval",
60
+ ]);
61
+ /**
62
+ * Names generated code already uses wherever it calls an operation: the client
63
+ * instance, the TanStack helpers the hook files import, and the parameters and
64
+ * locals of the generated hooks. A function with one of these names could not
65
+ * be called there.
66
+ */
67
+ const RESERVED_FUNCTION_NAMES = new Set([
68
+ "client",
69
+ "clientOptions",
70
+ "infiniteQueryOptions",
71
+ "mutationKey",
72
+ "options",
73
+ "pageParam",
74
+ "queryClient",
75
+ "queryKey",
76
+ "queryOptions",
77
+ "signal",
78
+ "useInfiniteQuery",
79
+ "useMutation",
80
+ "useQuery",
81
+ "useSuspenseInfiniteQuery",
82
+ "useSuspenseQuery",
83
+ ]);
84
+ export function isValidIdentifier(name) {
85
+ return IDENTIFIER_RE.test(name);
86
+ }
87
+ function capitalize(word) {
88
+ return word.charAt(0).toUpperCase() + word.slice(1);
89
+ }
90
+ const SEPARATORS = "_.$+:\\- `\\\\[\\](){}/";
91
+ const LEADING_SEPARATORS = new RegExp(`^[${SEPARATORS}]+`);
92
+ const SEPARATED = new RegExp(`[${SEPARATORS}]+([\\p{L}\\p{N}_]|$)`, "gu");
93
+ /** The last capital of an acronym, when its `s` starts a word (`APIs2` → `AP-Is2`). */
94
+ const ACRONYM_THEN_S = new RegExp(`(?<=[^-]\\p{Lu})(\\p{Lu})(?=s[${SEPARATORS}]*[^\\p{Lu}${SEPARATORS}])`, "gu");
95
+ /**
96
+ * Mark where the words of a name start: a lowercase letter before a capital,
97
+ * and a capital before a lowercase letter, so `getHTTPStatus` becomes
98
+ * `get-HTTP-Status`. A plural acronym at the end of a word stays whole (`APIs`).
99
+ */
100
+ function markWords(input) {
101
+ return input
102
+ .replace(/(\p{Ll})(?=\p{Lu})/gu, "$1-")
103
+ .replace(/(?<!^)(\p{Lu})(?=(?!s)\p{Ll})/gu, "-$1")
104
+ .replace(ACRONYM_THEN_S, "-$1");
105
+ }
106
+ /**
107
+ * `find pet by id` → `findPetById`; `getHTTPStatus` → `getHttpStatus`;
108
+ * `123numericLead` → `_123NumericLead`. Acronyms are folded like any other word
109
+ * and other characters become `_`, which is what the v3 generator did, so
110
+ * existing imports keep working.
111
+ */
112
+ export function toCamelCase(input) {
113
+ const joined = markWords(input.trim())
114
+ .replace(LEADING_SEPARATORS, "")
115
+ .toLowerCase()
116
+ .replace(/\d+\p{Ll}(?![_\-.])/gu, (match) => match.toUpperCase())
117
+ .replace(SEPARATED, (_match, next) => next.toUpperCase())
118
+ .replace(/[^\p{ID_Continue}]/gu, "_");
119
+ if (!/[\p{L}\p{N}]/u.test(joined))
120
+ return "";
121
+ return /^\d/.test(joined) ? `_${joined}` : joined;
122
+ }
123
+ /** Name of a function generated for an operation. */
124
+ export function toFunctionName(input) {
125
+ const name = toCamelCase(input);
126
+ if (!name)
127
+ return "operation";
128
+ return RESERVED_WORDS.has(name) || RESERVED_FUNCTION_NAMES.has(name)
129
+ ? `${name}_`
130
+ : name;
131
+ }
132
+ /**
133
+ * Name of a type generated from a schema key: the PascalCase form of the same
134
+ * name (`FineTuneDPOHyperparameters` → `FineTuneDpoHyperparameters`,
135
+ * `account_annual_revenue` → `AccountAnnualRevenue`).
136
+ */
137
+ export function toTypeName(input) {
138
+ const name = capitalize(toCamelCase(input)).replace(/(\d)(\p{Lu})$/u, (_match, digit, letter) => digit + letter.toLowerCase());
139
+ return name || "Schema";
140
+ }
141
+ /** Build a camelCase name for an operation that has no operationId. */
142
+ export function nameFromPath(method, path) {
143
+ return toCamelCase(`${method} ${path.replace(/\{([^{}]+)\}/g, " By $1 ")}`);
144
+ }
145
+ /** Object key, quoted only when it is not a valid identifier. */
146
+ export function propertyKey(name) {
147
+ return isValidIdentifier(name) ? name : JSON.stringify(name);
148
+ }
149
+ /** Make `base` unique inside `used` by appending a counter. */
150
+ export function uniqueName(base, used) {
151
+ let name = base;
152
+ let counter = 2;
153
+ while (used.has(name)) {
154
+ name = `${base}${counter}`;
155
+ counter += 1;
156
+ }
157
+ used.add(name);
158
+ return name;
159
+ }
160
+ /**
161
+ * Name for an enum member generated from its value, in UPPER_SNAKE_CASE
162
+ * (`in-progress` → `IN_PROGRESS`). A number gets a `_` prefix, except when
163
+ * `numericKeys` is set (valid as an object key, so `{ 1: 1 }` stays readable).
164
+ * The result can need quoting (`-X`, `2A`).
165
+ */
166
+ export function toEnumMemberName(value, options = {}) {
167
+ if (value === null)
168
+ return "NULL";
169
+ const name = markWords(String(value).trim())
170
+ .toUpperCase()
171
+ .replace(new RegExp(`(?<!^)[${SEPARATORS}]+`, "g"), "_")
172
+ .replace(/_$/, "");
173
+ return /^-?\d+$/.test(name) && !options.numericKeys ? `_${name}` : name;
174
+ }
175
+ export { capitalize as capitalizeFirst };