@7nohe/openapi-react-query-codegen 3.1.0 → 4.0.0-beta.2
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/AGENTS.md +207 -0
- package/README.md +7 -3
- package/dist/check.d.mts +59 -0
- package/dist/check.mjs +162 -0
- package/dist/cli.d.mts +6 -1
- package/dist/cli.mjs +4 -31
- package/dist/client/emitSchemas.d.mts +9 -0
- package/dist/client/emitSchemas.mjs +130 -0
- package/dist/client/emitSdk.d.mts +18 -0
- package/dist/client/emitSdk.mjs +253 -0
- package/dist/client/emitTransformers.d.mts +19 -0
- package/dist/client/emitTransformers.mjs +556 -0
- package/dist/client/emitTypes.d.mts +16 -0
- package/dist/client/emitTypes.mjs +204 -0
- package/dist/client/index.d.mts +44 -0
- package/dist/client/index.mjs +126 -0
- package/dist/client/naming.d.mts +41 -0
- package/dist/client/naming.mjs +175 -0
- package/dist/client/operations.d.mts +103 -0
- package/dist/client/operations.mjs +352 -0
- package/dist/client/runtime/axios.runtime.ts +706 -0
- package/dist/client/runtime/fetch.runtime.ts +795 -0
- package/dist/client/schema.d.mts +50 -0
- package/dist/client/schema.mjs +648 -0
- package/dist/client/spec.d.mts +40 -0
- package/dist/client/spec.mjs +387 -0
- package/dist/client/tsconfig.d.mts +13 -0
- package/dist/client/tsconfig.mjs +56 -0
- package/dist/common.d.mts +0 -38
- package/dist/common.mjs +0 -87
- package/dist/constants.d.mts +0 -2
- package/dist/constants.mjs +0 -2
- package/dist/createSource.d.mts +8 -7
- package/dist/createSource.mjs +14 -17
- package/dist/errors.d.mts +43 -0
- package/dist/errors.mjs +61 -0
- package/dist/format.mjs +0 -1
- package/dist/generate.d.mts +25 -3
- package/dist/generate.mjs +83 -83
- package/dist/runCli.d.mts +20 -0
- package/dist/runCli.mjs +105 -0
- package/dist/tsmorph/buildQueryHooks.mjs +19 -11
- package/dist/tsmorph/generateFiles.mjs +105 -161
- package/dist/tsmorph/operationNames.d.mts +2 -13
- package/dist/tsmorph/operationNames.mjs +4 -24
- package/dist/tsmorph/projectFactory.d.mts +7 -2
- package/dist/tsmorph/projectFactory.mjs +16 -9
- package/dist/types.d.mts +14 -26
- package/package.json +8 -8
- package/dist/parseOperations.d.mts +0 -10
- package/dist/parseOperations.mjs +0 -164
- package/dist/service.d.mts +0 -8
- package/dist/service.mjs +0 -98
- package/dist/util.d.mts +0 -2
- package/dist/util.mjs +0 -16
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export type Json = any;
|
|
2
|
+
export type Doc = Record<string, Json>;
|
|
3
|
+
/**
|
|
4
|
+
* A specification that could not be loaded: because it, or a document it
|
|
5
|
+
* refers to, could not be read (`not-found`), or because what was read is not
|
|
6
|
+
* a JSON or YAML object (`parse`).
|
|
7
|
+
*/
|
|
8
|
+
export declare class SpecError extends Error {
|
|
9
|
+
readonly reason: "not-found" | "parse";
|
|
10
|
+
constructor(reason: "not-found" | "parse", message: string, options?: {
|
|
11
|
+
cause?: unknown;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
export type LoadedSpec = {
|
|
15
|
+
doc: Doc;
|
|
16
|
+
/** Path or URL the document came from; undefined for inline content. */
|
|
17
|
+
location: string | undefined;
|
|
18
|
+
};
|
|
19
|
+
/** Load a specification from a file path, a URL or inline JSON/YAML content. */
|
|
20
|
+
export declare function loadSpec(input: string): Promise<LoadedSpec>;
|
|
21
|
+
/** Resolve a JSON pointer such as `#/components/schemas/Pet`. */
|
|
22
|
+
export declare function getByPointer(root: Json, pointer: string): Json;
|
|
23
|
+
/**
|
|
24
|
+
* The part of a schema that sits next to its `$ref` and changes the type, as a
|
|
25
|
+
* schema of its own. OpenAPI 3.1 applies such keywords together with the
|
|
26
|
+
* reference, while 3.0 says they are ignored.
|
|
27
|
+
*/
|
|
28
|
+
export declare function refSiblingSchema(doc: Doc, node: Json): Json | undefined;
|
|
29
|
+
/** Follow a chain of `$ref`s. The result is undefined if one dangles. */
|
|
30
|
+
export declare function resolveRef(doc: Doc, node: Json, depth?: number): Json;
|
|
31
|
+
/**
|
|
32
|
+
* Bundle every external `$ref` (relative files and URLs) into the root
|
|
33
|
+
* document. Internal `$ref`s of the root document stay untouched.
|
|
34
|
+
*
|
|
35
|
+
* An external schema becomes a named entry of `components.schemas` and the
|
|
36
|
+
* reference an internal one, so that it is one type however often it is used,
|
|
37
|
+
* a recursive one included. Everything else (parameters, responses, path
|
|
38
|
+
* items) is inlined.
|
|
39
|
+
*/
|
|
40
|
+
export declare function bundleExternalRefs(loaded: LoadedSpec): Promise<Doc>;
|
|
@@ -0,0 +1,387 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { readFile } from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { parse as parseYaml } from "yaml";
|
|
6
|
+
import { uniqueName } from "./naming.mjs";
|
|
7
|
+
const URL_RE = /^https?:\/\//i;
|
|
8
|
+
/**
|
|
9
|
+
* A specification that could not be loaded: because it, or a document it
|
|
10
|
+
* refers to, could not be read (`not-found`), or because what was read is not
|
|
11
|
+
* a JSON or YAML object (`parse`).
|
|
12
|
+
*/
|
|
13
|
+
export class SpecError extends Error {
|
|
14
|
+
reason;
|
|
15
|
+
constructor(reason, message, options) {
|
|
16
|
+
super(message, options);
|
|
17
|
+
this.name = "SpecError";
|
|
18
|
+
this.reason = reason;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/** JSON when it is, which is much faster to parse than YAML. */
|
|
22
|
+
function parseJsonOrYaml(text) {
|
|
23
|
+
if (text.startsWith("{")) {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(text);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
// A document in YAML's flow style starts the same way.
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return parseYaml(text, { maxAliasCount: -1 });
|
|
32
|
+
}
|
|
33
|
+
function parseText(text, source) {
|
|
34
|
+
const trimmed = text.trim();
|
|
35
|
+
let parsed;
|
|
36
|
+
try {
|
|
37
|
+
parsed = parseJsonOrYaml(trimmed);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
throw new SpecError("parse", `Failed to parse the OpenAPI specification (${source}): ${error.message}`, { cause: error });
|
|
41
|
+
}
|
|
42
|
+
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
43
|
+
throw new SpecError("parse", `The OpenAPI specification (${source}) must be a JSON/YAML object.`);
|
|
44
|
+
}
|
|
45
|
+
return parsed;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Read a document. `location` in the result is where it really came from, which
|
|
49
|
+
* after a redirect is not the URL asked for and is what its relative `$ref`s
|
|
50
|
+
* resolve against.
|
|
51
|
+
*/
|
|
52
|
+
async function readLocation(location) {
|
|
53
|
+
const unreadable = (verb, cause) => new SpecError("not-found", `Failed to ${verb} ${location}: ${cause.message}`, { cause });
|
|
54
|
+
if (URL_RE.test(location)) {
|
|
55
|
+
const response = await fetch(location).catch((cause) => {
|
|
56
|
+
throw unreadable("fetch", cause);
|
|
57
|
+
});
|
|
58
|
+
if (!response.ok) {
|
|
59
|
+
throw new SpecError("not-found", `Failed to fetch ${location}: ${response.status} ${response.statusText}`);
|
|
60
|
+
}
|
|
61
|
+
return { text: await response.text(), location: response.url || location };
|
|
62
|
+
}
|
|
63
|
+
const text = await readFile(location, "utf-8").catch((cause) => {
|
|
64
|
+
throw unreadable("read", cause);
|
|
65
|
+
});
|
|
66
|
+
return { text, location };
|
|
67
|
+
}
|
|
68
|
+
async function loadDocument(location) {
|
|
69
|
+
const read = await readLocation(location);
|
|
70
|
+
return { doc: parseText(read.text, location), location: read.location };
|
|
71
|
+
}
|
|
72
|
+
/** Load a specification from a file path, a URL or inline JSON/YAML content. */
|
|
73
|
+
export async function loadSpec(input) {
|
|
74
|
+
if (URL_RE.test(input))
|
|
75
|
+
return loadDocument(input);
|
|
76
|
+
if (input.startsWith("file:")) {
|
|
77
|
+
return loadDocument(path.resolve(fileURLToPath(input)));
|
|
78
|
+
}
|
|
79
|
+
const looksInline = input.includes("\n") || input.trimStart().startsWith("{");
|
|
80
|
+
if (!looksInline && existsSync(input)) {
|
|
81
|
+
return loadDocument(path.resolve(input));
|
|
82
|
+
}
|
|
83
|
+
if (!looksInline) {
|
|
84
|
+
throw new SpecError("not-found", `OpenAPI specification not found: ${input}`);
|
|
85
|
+
}
|
|
86
|
+
return { doc: parseText(input, "inline content"), location: undefined };
|
|
87
|
+
}
|
|
88
|
+
/** Resolve a JSON pointer such as `#/components/schemas/Pet`. */
|
|
89
|
+
export function getByPointer(root, pointer) {
|
|
90
|
+
const clean = pointer.startsWith("#") ? pointer.slice(1) : pointer;
|
|
91
|
+
if (clean === "" || clean === "/")
|
|
92
|
+
return root;
|
|
93
|
+
let current = root;
|
|
94
|
+
for (const rawSegment of clean.replace(/^\//, "").split("/")) {
|
|
95
|
+
const segment = decodeURIComponent(rawSegment)
|
|
96
|
+
.replaceAll("~1", "/")
|
|
97
|
+
.replaceAll("~0", "~");
|
|
98
|
+
if (current === null || typeof current !== "object")
|
|
99
|
+
return undefined;
|
|
100
|
+
current = current[segment];
|
|
101
|
+
}
|
|
102
|
+
return current;
|
|
103
|
+
}
|
|
104
|
+
const REF_SIBLING_KEYWORDS = [
|
|
105
|
+
"additionalProperties",
|
|
106
|
+
"allOf",
|
|
107
|
+
"anyOf",
|
|
108
|
+
"const",
|
|
109
|
+
"enum",
|
|
110
|
+
"items",
|
|
111
|
+
"oneOf",
|
|
112
|
+
"prefixItems",
|
|
113
|
+
"properties",
|
|
114
|
+
"required",
|
|
115
|
+
];
|
|
116
|
+
/**
|
|
117
|
+
* The part of a schema that sits next to its `$ref` and changes the type, as a
|
|
118
|
+
* schema of its own. OpenAPI 3.1 applies such keywords together with the
|
|
119
|
+
* reference, while 3.0 says they are ignored.
|
|
120
|
+
*/
|
|
121
|
+
export function refSiblingSchema(doc, node) {
|
|
122
|
+
if (typeof doc.openapi !== "string" || doc.openapi.startsWith("3.0")) {
|
|
123
|
+
return undefined;
|
|
124
|
+
}
|
|
125
|
+
if (!REF_SIBLING_KEYWORDS.some((key) => node[key] !== undefined)) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const { $ref: _ref, ...siblings } = node;
|
|
129
|
+
return siblings;
|
|
130
|
+
}
|
|
131
|
+
/** Follow a chain of `$ref`s. The result is undefined if one dangles. */
|
|
132
|
+
export function resolveRef(doc, node, depth = 0) {
|
|
133
|
+
return typeof node?.$ref === "string" && depth < 32
|
|
134
|
+
? resolveRef(doc, getByPointer(doc, node.$ref), depth + 1)
|
|
135
|
+
: node;
|
|
136
|
+
}
|
|
137
|
+
/** Keywords holding data, where a `$ref` key is not a reference. */
|
|
138
|
+
const DATA_KEYWORDS = new Set([
|
|
139
|
+
"const",
|
|
140
|
+
"default",
|
|
141
|
+
"enum",
|
|
142
|
+
"example",
|
|
143
|
+
"examples",
|
|
144
|
+
]);
|
|
145
|
+
/**
|
|
146
|
+
* Keywords whose keys are names the author chose, so that a property called
|
|
147
|
+
* `example` or a `default` response is not mistaken for a data keyword.
|
|
148
|
+
*/
|
|
149
|
+
const NAME_MAP_KEYWORDS = new Set([
|
|
150
|
+
"$defs",
|
|
151
|
+
"callbacks",
|
|
152
|
+
"definitions",
|
|
153
|
+
"dependentSchemas",
|
|
154
|
+
"encoding",
|
|
155
|
+
"headers",
|
|
156
|
+
"links",
|
|
157
|
+
"parameters",
|
|
158
|
+
"pathItems",
|
|
159
|
+
"paths",
|
|
160
|
+
"patternProperties",
|
|
161
|
+
"properties",
|
|
162
|
+
"requestBodies",
|
|
163
|
+
"responses",
|
|
164
|
+
"schemas",
|
|
165
|
+
"securitySchemes",
|
|
166
|
+
"webhooks",
|
|
167
|
+
]);
|
|
168
|
+
/** The name maps among them whose values are schemas. */
|
|
169
|
+
const SCHEMA_MAP_KEYWORDS = new Set([
|
|
170
|
+
"$defs",
|
|
171
|
+
"definitions",
|
|
172
|
+
"dependentSchemas",
|
|
173
|
+
"patternProperties",
|
|
174
|
+
"properties",
|
|
175
|
+
"schemas",
|
|
176
|
+
]);
|
|
177
|
+
function childPosition(position, key) {
|
|
178
|
+
if (position === "schemaMap")
|
|
179
|
+
return "schema";
|
|
180
|
+
if (position === "nameMap")
|
|
181
|
+
return "other";
|
|
182
|
+
if (SCHEMA_MAP_KEYWORDS.has(key))
|
|
183
|
+
return "schemaMap";
|
|
184
|
+
if (position === "schema")
|
|
185
|
+
return "schema";
|
|
186
|
+
if (key === "schema")
|
|
187
|
+
return "schema";
|
|
188
|
+
return NAME_MAP_KEYWORDS.has(key) ? "nameMap" : "other";
|
|
189
|
+
}
|
|
190
|
+
function resolveLocation(base, target) {
|
|
191
|
+
if (URL_RE.test(target))
|
|
192
|
+
return target;
|
|
193
|
+
if (target.startsWith("file:"))
|
|
194
|
+
return fileURLToPath(target);
|
|
195
|
+
if (!base) {
|
|
196
|
+
throw new Error(`Cannot resolve the external $ref "${target}" because the specification was passed as inline content.`);
|
|
197
|
+
}
|
|
198
|
+
if (URL_RE.test(base))
|
|
199
|
+
return new URL(target, base).toString();
|
|
200
|
+
return path.resolve(path.dirname(base), decodeReference(target));
|
|
201
|
+
}
|
|
202
|
+
/** A `$ref` is a URI reference, so a file name in it can be percent-encoded. */
|
|
203
|
+
function decodeReference(reference) {
|
|
204
|
+
try {
|
|
205
|
+
return decodeURIComponent(reference);
|
|
206
|
+
}
|
|
207
|
+
catch {
|
|
208
|
+
return reference;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
/** The file a `$ref` points into and the pointer inside it. */
|
|
212
|
+
function locateRef(ref, nodeLocation) {
|
|
213
|
+
const hashIndex = ref.indexOf("#");
|
|
214
|
+
const filePart = hashIndex === -1 ? ref : ref.slice(0, hashIndex);
|
|
215
|
+
const pointer = hashIndex === -1 ? "" : ref.slice(hashIndex);
|
|
216
|
+
const location = filePart
|
|
217
|
+
? resolveLocation(nodeLocation, filePart)
|
|
218
|
+
: nodeLocation;
|
|
219
|
+
return { location, pointer, key: `${location}${pointer}` };
|
|
220
|
+
}
|
|
221
|
+
/** What an external schema is called: its key, or else the name of its file. */
|
|
222
|
+
function externalSchemaName(location, pointer) {
|
|
223
|
+
const last = pointer.slice(pointer.lastIndexOf("/") + 1);
|
|
224
|
+
if (pointer.includes("/") && last) {
|
|
225
|
+
return decodeReference(last).replaceAll("~1", "/").replaceAll("~0", "~");
|
|
226
|
+
}
|
|
227
|
+
const file = path.basename(location.replace(/[?#].*$/, ""));
|
|
228
|
+
return file.replace(/\.[^.]+$/, "") || "Schema";
|
|
229
|
+
}
|
|
230
|
+
function componentSchemaRef(name) {
|
|
231
|
+
const segment = name.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
232
|
+
return `#/components/schemas/${encodeURIComponent(segment)}`;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Bundle every external `$ref` (relative files and URLs) into the root
|
|
236
|
+
* document. Internal `$ref`s of the root document stay untouched.
|
|
237
|
+
*
|
|
238
|
+
* An external schema becomes a named entry of `components.schemas` and the
|
|
239
|
+
* reference an internal one, so that it is one type however often it is used,
|
|
240
|
+
* a recursive one included. Everything else (parameters, responses, path
|
|
241
|
+
* items) is inlined.
|
|
242
|
+
*/
|
|
243
|
+
export async function bundleExternalRefs(loaded) {
|
|
244
|
+
const { doc, location: rootLocation } = loaded;
|
|
245
|
+
const cache = new Map();
|
|
246
|
+
if (rootLocation) {
|
|
247
|
+
cache.set(rootLocation, Promise.resolve({ doc, location: rootLocation }));
|
|
248
|
+
}
|
|
249
|
+
/** The name in `components.schemas` of each external schema. */
|
|
250
|
+
const hoisted = new Map();
|
|
251
|
+
const hoistedSchemas = new Map();
|
|
252
|
+
/** Discriminator mappings, whose targets are rewritten once all are named. */
|
|
253
|
+
const mappings = [];
|
|
254
|
+
const rootSchemas = doc.components?.schemas ?? {};
|
|
255
|
+
const usedNames = new Set(Object.keys(rootSchemas));
|
|
256
|
+
// A root schema that is nothing but an external reference names its target,
|
|
257
|
+
// rather than being an alias of a second type with a made-up name.
|
|
258
|
+
for (const [name, schema] of Object.entries(rootSchemas)) {
|
|
259
|
+
const ref = schema?.$ref;
|
|
260
|
+
if (typeof ref !== "string" || ref.startsWith("#"))
|
|
261
|
+
continue;
|
|
262
|
+
if (Object.keys(schema).length > 1)
|
|
263
|
+
continue;
|
|
264
|
+
const target = locateRef(ref, rootLocation);
|
|
265
|
+
if (target.location !== rootLocation && !hoisted.has(target.key)) {
|
|
266
|
+
hoisted.set(target.key, name);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
function loadFile(location) {
|
|
270
|
+
let file = cache.get(location);
|
|
271
|
+
if (!file) {
|
|
272
|
+
file = loadDocument(location);
|
|
273
|
+
cache.set(location, file);
|
|
274
|
+
}
|
|
275
|
+
return file;
|
|
276
|
+
}
|
|
277
|
+
async function loadTarget(target, ref) {
|
|
278
|
+
const file = await loadFile(target.location);
|
|
279
|
+
const node = getByPointer(file.doc, target.pointer);
|
|
280
|
+
if (node === undefined) {
|
|
281
|
+
throw new Error(`Unresolvable $ref: ${ref}`);
|
|
282
|
+
}
|
|
283
|
+
return { node, location: file.location };
|
|
284
|
+
}
|
|
285
|
+
/** Make the target a named schema of the root, once, and refer to it. */
|
|
286
|
+
async function hoist(target, ref, stack) {
|
|
287
|
+
let name = hoisted.get(target.key);
|
|
288
|
+
if (name === undefined) {
|
|
289
|
+
name = uniqueName(externalSchemaName(target.location, target.pointer), usedNames);
|
|
290
|
+
hoisted.set(target.key, name);
|
|
291
|
+
}
|
|
292
|
+
if (!hoistedSchemas.has(name)) {
|
|
293
|
+
// Taken before the target is read, so that the schemas come out in the
|
|
294
|
+
// order they are first used and a recursive one refers to itself.
|
|
295
|
+
hoistedSchemas.set(name, {});
|
|
296
|
+
const { node, location } = await loadTarget(target, ref);
|
|
297
|
+
hoistedSchemas.set(name, await walk(node, location, new Set(stack).add(target.key), "schema"));
|
|
298
|
+
}
|
|
299
|
+
return componentSchemaRef(name);
|
|
300
|
+
}
|
|
301
|
+
// One node after the other, so that the names given to hoisted schemas do
|
|
302
|
+
// not depend on which file happens to be read first.
|
|
303
|
+
async function walk(node, nodeLocation, stack, position) {
|
|
304
|
+
if (Array.isArray(node)) {
|
|
305
|
+
const itemPosition = childPosition(position, "");
|
|
306
|
+
const items = [];
|
|
307
|
+
for (const item of node) {
|
|
308
|
+
items.push(await walk(item, nodeLocation, stack, itemPosition));
|
|
309
|
+
}
|
|
310
|
+
return items;
|
|
311
|
+
}
|
|
312
|
+
if (node === null || typeof node !== "object")
|
|
313
|
+
return node;
|
|
314
|
+
const ref = node.$ref;
|
|
315
|
+
const isExternalFile = nodeLocation !== rootLocation;
|
|
316
|
+
if (typeof ref === "string" && (!ref.startsWith("#") || isExternalFile)) {
|
|
317
|
+
const target = locateRef(ref, nodeLocation);
|
|
318
|
+
const isBackReference = target.location === rootLocation && target.pointer !== "";
|
|
319
|
+
// A file pointing back into the root keeps the root's named type, and an
|
|
320
|
+
// external schema gets one. What sits next to the reference stays there,
|
|
321
|
+
// as it does next to an internal one.
|
|
322
|
+
if (isBackReference || position === "schema" || stack.has(target.key)) {
|
|
323
|
+
const { $ref: _ref, ...rest } = node;
|
|
324
|
+
const siblings = Object.keys(rest).length > 0
|
|
325
|
+
? await walk(rest, nodeLocation, stack, position)
|
|
326
|
+
: undefined;
|
|
327
|
+
return {
|
|
328
|
+
...siblings,
|
|
329
|
+
$ref: isBackReference
|
|
330
|
+
? target.pointer
|
|
331
|
+
: await hoist(target, ref, stack),
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
const loadedTarget = await loadTarget(target, ref);
|
|
335
|
+
return walk(loadedTarget.node, loadedTarget.location, new Set(stack).add(target.key), position);
|
|
336
|
+
}
|
|
337
|
+
const isNameMap = position === "schemaMap" || position === "nameMap";
|
|
338
|
+
const result = {};
|
|
339
|
+
for (const [key, value] of Object.entries(node)) {
|
|
340
|
+
const isData = !isNameMap && (DATA_KEYWORDS.has(key) || key.startsWith("x-"));
|
|
341
|
+
result[key] = isData
|
|
342
|
+
? value
|
|
343
|
+
: await walk(value, nodeLocation, stack, childPosition(position, key));
|
|
344
|
+
}
|
|
345
|
+
const mapping = result.discriminator?.mapping;
|
|
346
|
+
if (!isNameMap && mapping !== null && typeof mapping === "object") {
|
|
347
|
+
mappings.push({ mapping, location: nodeLocation });
|
|
348
|
+
}
|
|
349
|
+
return result;
|
|
350
|
+
}
|
|
351
|
+
const bundled = (await walk(doc, rootLocation, new Set(), "other"));
|
|
352
|
+
// A mapping names its targets the way a `$ref` does, or by schema name.
|
|
353
|
+
for (const { mapping, location } of mappings) {
|
|
354
|
+
for (const [value, target] of Object.entries(mapping)) {
|
|
355
|
+
if (typeof target !== "string")
|
|
356
|
+
continue;
|
|
357
|
+
if (target.startsWith("#") && location === rootLocation)
|
|
358
|
+
continue;
|
|
359
|
+
let name;
|
|
360
|
+
try {
|
|
361
|
+
const located = locateRef(target, location);
|
|
362
|
+
if (located.location === rootLocation && located.pointer !== "") {
|
|
363
|
+
mapping[value] = located.pointer;
|
|
364
|
+
continue;
|
|
365
|
+
}
|
|
366
|
+
name =
|
|
367
|
+
hoisted.get(located.key) ??
|
|
368
|
+
hoisted.get(`${location}${componentSchemaRef(target)}`) ??
|
|
369
|
+
hoisted.get(`${location}#/components/schemas/${target}`);
|
|
370
|
+
}
|
|
371
|
+
catch {
|
|
372
|
+
// Not a reference that can be resolved, so a schema name.
|
|
373
|
+
}
|
|
374
|
+
if (name !== undefined && hoistedSchemas.has(name)) {
|
|
375
|
+
mapping[value] = componentSchemaRef(name);
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (hoistedSchemas.size > 0) {
|
|
380
|
+
bundled.components ??= {};
|
|
381
|
+
bundled.components.schemas = {
|
|
382
|
+
...bundled.components.schemas,
|
|
383
|
+
...Object.fromEntries(hoistedSchemas),
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
return bundled;
|
|
387
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import ts from "typescript";
|
|
2
|
+
/**
|
|
3
|
+
* Find the tsconfig that applies to the generated output by walking up from
|
|
4
|
+
* `startDir`. Anchoring the search at the caller's directory finds the
|
|
5
|
+
* tsconfig the caller's own `tsc` will use.
|
|
6
|
+
*/
|
|
7
|
+
export declare function findNearestTsConfigPath(startDir: string): string | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Relative imports must spell out `.js` under Node16/NodeNext module
|
|
10
|
+
* resolution and must not under bundler-style resolution. Read the caller's
|
|
11
|
+
* tsconfig to pick the matching convention.
|
|
12
|
+
*/
|
|
13
|
+
export declare function detectImportExtension(startDir: string, host?: ts.System | null): "" | ".js";
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { readdirSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
/**
|
|
5
|
+
* Find the tsconfig that applies to the generated output by walking up from
|
|
6
|
+
* `startDir`. Anchoring the search at the caller's directory finds the
|
|
7
|
+
* tsconfig the caller's own `tsc` will use.
|
|
8
|
+
*/
|
|
9
|
+
export function findNearestTsConfigPath(startDir) {
|
|
10
|
+
let dir = startDir;
|
|
11
|
+
while (true) {
|
|
12
|
+
const candidates = readdirSync(dir).filter((file) => file.startsWith("tsconfig") && file.endsWith(".json"));
|
|
13
|
+
if (candidates.length > 0) {
|
|
14
|
+
candidates.sort((a) => (a === "tsconfig.json" ? -1 : 1));
|
|
15
|
+
return path.join(dir, candidates[0]);
|
|
16
|
+
}
|
|
17
|
+
const parent = path.dirname(dir);
|
|
18
|
+
if (parent === dir)
|
|
19
|
+
return undefined;
|
|
20
|
+
dir = parent;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Relative imports must spell out `.js` under Node16/NodeNext module
|
|
25
|
+
* resolution and must not under bundler-style resolution. Read the caller's
|
|
26
|
+
* tsconfig to pick the matching convention.
|
|
27
|
+
*/
|
|
28
|
+
export function detectImportExtension(startDir, host = ts.sys) {
|
|
29
|
+
const configPath = findNearestTsConfigPath(startDir);
|
|
30
|
+
if (!configPath)
|
|
31
|
+
return "";
|
|
32
|
+
try {
|
|
33
|
+
const read = ts.readConfigFile(configPath, host.readFile);
|
|
34
|
+
if (read.error || !read.config)
|
|
35
|
+
return "";
|
|
36
|
+
const parsed = ts.parseJsonConfigFileContent(read.config, host, path.dirname(configPath));
|
|
37
|
+
const { moduleResolution, module } = parsed.options;
|
|
38
|
+
if (moduleResolution !== undefined) {
|
|
39
|
+
return moduleResolution === ts.ModuleResolutionKind.Node16 ||
|
|
40
|
+
moduleResolution === ts.ModuleResolutionKind.NodeNext
|
|
41
|
+
? ".js"
|
|
42
|
+
: "";
|
|
43
|
+
}
|
|
44
|
+
// A range, so that `node18`, `node20` and later ones count as well.
|
|
45
|
+
return module !== undefined &&
|
|
46
|
+
module >= ts.ModuleKind.Node16 &&
|
|
47
|
+
module <= ts.ModuleKind.NodeNext
|
|
48
|
+
? ".js"
|
|
49
|
+
: "";
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// An unusual TypeScript build without the compiler host API: fall back
|
|
53
|
+
// to the bundler convention rather than failing the whole run.
|
|
54
|
+
return "";
|
|
55
|
+
}
|
|
56
|
+
}
|
package/dist/common.d.mts
CHANGED
|
@@ -1,24 +1,6 @@
|
|
|
1
1
|
import type { PathLike } from "node:fs";
|
|
2
|
-
import { type ClassDeclaration, type ParameterDeclaration, type SourceFile, type VariableDeclaration } from "ts-morph";
|
|
3
|
-
import ts from "typescript";
|
|
4
2
|
import type { LimitedUserConfig } from "./cli.mjs";
|
|
5
|
-
export declare const capitalizeFirstLetter: (str: string) => string;
|
|
6
|
-
export declare const lowercaseFirstLetter: (str: string) => string;
|
|
7
|
-
export declare const getVariableArrowFunctionParameters: (variable: VariableDeclaration) => ParameterDeclaration[];
|
|
8
|
-
export declare const getNameFromVariable: (variable: VariableDeclaration) => string;
|
|
9
|
-
export type FunctionDescription = {
|
|
10
|
-
node: SourceFile;
|
|
11
|
-
method: VariableDeclaration;
|
|
12
|
-
methodBlock?: ts.Block;
|
|
13
|
-
httpMethodName: string;
|
|
14
|
-
jsDoc: string;
|
|
15
|
-
isDeprecated: boolean;
|
|
16
|
-
};
|
|
17
3
|
export declare function exists(f: PathLike): Promise<boolean>;
|
|
18
|
-
/**
|
|
19
|
-
* Build a common type name by prepending the Common namespace.
|
|
20
|
-
*/
|
|
21
|
-
export declare function BuildCommonTypeName(name: string | ts.Identifier): ts.Identifier;
|
|
22
4
|
/**
|
|
23
5
|
* Safely parse a value into a number. Checks for NaN and Infinity.
|
|
24
6
|
* Returns NaN if the string is not a valid number.
|
|
@@ -26,26 +8,6 @@ export declare function BuildCommonTypeName(name: string | ts.Identifier): ts.Id
|
|
|
26
8
|
* @returns The parsed number or NaN if the value is not a valid number.
|
|
27
9
|
*/
|
|
28
10
|
export declare function safeParseNumber(value: unknown): number;
|
|
29
|
-
export declare function extractPropertiesFromObjectParam(param: ParameterDeclaration): {
|
|
30
|
-
name: string;
|
|
31
|
-
optional: boolean;
|
|
32
|
-
type: import("ts-morph").Type<import("ts-morph").ts.Type> | undefined;
|
|
33
|
-
}[];
|
|
34
|
-
/**
|
|
35
|
-
* Replace the import("...") surrounding the type if there is one.
|
|
36
|
-
* This can happen when the type is imported from another file, but
|
|
37
|
-
* we are already importing all the types from that file.
|
|
38
|
-
*
|
|
39
|
-
* https://regex101.com/r/3DyHaQ/1
|
|
40
|
-
*
|
|
41
|
-
* TODO: Replace with a more robust solution.
|
|
42
|
-
*/
|
|
43
|
-
export declare function getShortType(type: string): string;
|
|
44
|
-
export declare function getClassesFromService(node: SourceFile): {
|
|
45
|
-
className: string;
|
|
46
|
-
klass: ClassDeclaration;
|
|
47
|
-
}[];
|
|
48
|
-
export declare function getClassNameFromClassNode(klass: ClassDeclaration): string;
|
|
49
11
|
export declare function formatOptions(options: LimitedUserConfig): LimitedUserConfig;
|
|
50
12
|
export declare function buildRequestsOutputPath(outputPath: string): string;
|
|
51
13
|
export declare function buildQueriesOutputPath(outputPath: string): string;
|
package/dist/common.mjs
CHANGED
|
@@ -1,31 +1,6 @@
|
|
|
1
1
|
import { stat } from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
-
import { ArrowFunction, } from "ts-morph";
|
|
4
|
-
import ts from "typescript";
|
|
5
3
|
import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
|
|
6
|
-
export const capitalizeFirstLetter = (str) => {
|
|
7
|
-
return str.charAt(0).toUpperCase() + str.slice(1);
|
|
8
|
-
};
|
|
9
|
-
export const lowercaseFirstLetter = (str) => {
|
|
10
|
-
return str.charAt(0).toLowerCase() + str.slice(1);
|
|
11
|
-
};
|
|
12
|
-
export const getVariableArrowFunctionParameters = (variable) => {
|
|
13
|
-
const initializer = variable.getInitializer();
|
|
14
|
-
if (!initializer) {
|
|
15
|
-
throw new Error("Initializer not found");
|
|
16
|
-
}
|
|
17
|
-
if (!ArrowFunction.isArrowFunction(initializer)) {
|
|
18
|
-
throw new Error("Initializer is not an arrow function");
|
|
19
|
-
}
|
|
20
|
-
return initializer.getParameters();
|
|
21
|
-
};
|
|
22
|
-
export const getNameFromVariable = (variable) => {
|
|
23
|
-
const variableName = variable.getName();
|
|
24
|
-
if (!variableName) {
|
|
25
|
-
throw new Error("Variable name not found");
|
|
26
|
-
}
|
|
27
|
-
return variableName;
|
|
28
|
-
};
|
|
29
4
|
export async function exists(f) {
|
|
30
5
|
try {
|
|
31
6
|
await stat(f);
|
|
@@ -35,16 +10,6 @@ export async function exists(f) {
|
|
|
35
10
|
return false;
|
|
36
11
|
}
|
|
37
12
|
}
|
|
38
|
-
const Common = "Common";
|
|
39
|
-
/**
|
|
40
|
-
* Build a common type name by prepending the Common namespace.
|
|
41
|
-
*/
|
|
42
|
-
export function BuildCommonTypeName(name) {
|
|
43
|
-
if (typeof name === "string") {
|
|
44
|
-
return ts.factory.createIdentifier(`${Common}.${name}`);
|
|
45
|
-
}
|
|
46
|
-
return ts.factory.createIdentifier(`${Common}.${name.text}`);
|
|
47
|
-
}
|
|
48
13
|
/**
|
|
49
14
|
* Safely parse a value into a number. Checks for NaN and Infinity.
|
|
50
15
|
* Returns NaN if the string is not a valid number.
|
|
@@ -64,58 +29,6 @@ export function safeParseNumber(value) {
|
|
|
64
29
|
}
|
|
65
30
|
return Number.NaN;
|
|
66
31
|
}
|
|
67
|
-
export function extractPropertiesFromObjectParam(param) {
|
|
68
|
-
const referenced = param.findReferences()[0];
|
|
69
|
-
const def = referenced.getDefinition();
|
|
70
|
-
const paramNodes = def
|
|
71
|
-
.getNode()
|
|
72
|
-
.getType()
|
|
73
|
-
.getProperties()
|
|
74
|
-
.filter((prop) => prop.getValueDeclaration()?.getType())
|
|
75
|
-
.map((prop) => {
|
|
76
|
-
return {
|
|
77
|
-
name: prop.getName(),
|
|
78
|
-
optional: prop.isOptional(),
|
|
79
|
-
type: prop.getValueDeclaration()?.getType(),
|
|
80
|
-
};
|
|
81
|
-
});
|
|
82
|
-
return paramNodes;
|
|
83
|
-
}
|
|
84
|
-
/**
|
|
85
|
-
* Replace the import("...") surrounding the type if there is one.
|
|
86
|
-
* This can happen when the type is imported from another file, but
|
|
87
|
-
* we are already importing all the types from that file.
|
|
88
|
-
*
|
|
89
|
-
* https://regex101.com/r/3DyHaQ/1
|
|
90
|
-
*
|
|
91
|
-
* TODO: Replace with a more robust solution.
|
|
92
|
-
*/
|
|
93
|
-
export function getShortType(type) {
|
|
94
|
-
return type.replaceAll(/import\(".*?"\)\./g, "");
|
|
95
|
-
}
|
|
96
|
-
export function getClassesFromService(node) {
|
|
97
|
-
const klasses = node.getClasses();
|
|
98
|
-
if (!klasses.length) {
|
|
99
|
-
throw new Error("No classes found");
|
|
100
|
-
}
|
|
101
|
-
return klasses.map((klass) => {
|
|
102
|
-
const className = klass.getName();
|
|
103
|
-
if (!className) {
|
|
104
|
-
throw new Error("Class name not found");
|
|
105
|
-
}
|
|
106
|
-
return {
|
|
107
|
-
className,
|
|
108
|
-
klass,
|
|
109
|
-
};
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
export function getClassNameFromClassNode(klass) {
|
|
113
|
-
const className = klass.getName();
|
|
114
|
-
if (!className) {
|
|
115
|
-
throw new Error("Class name not found");
|
|
116
|
-
}
|
|
117
|
-
return className;
|
|
118
|
-
}
|
|
119
32
|
export function formatOptions(options) {
|
|
120
33
|
// loop through properties on the options object
|
|
121
34
|
// if the property is a string of number then convert it to a number
|
package/dist/constants.d.mts
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
export declare const defaultOutputPath = "openapi";
|
|
2
2
|
export declare const queriesOutputPath = "queries";
|
|
3
3
|
export declare const requestsOutputPath = "requests";
|
|
4
|
-
export declare const serviceFileName = "sdk.gen";
|
|
5
|
-
export declare const modelsFileName = "types.gen";
|
|
6
4
|
export declare const OpenApiRqFiles: {
|
|
7
5
|
readonly queries: "queries";
|
|
8
6
|
readonly queryOptions: "queryOptions";
|
package/dist/constants.mjs
CHANGED
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
export const defaultOutputPath = "openapi";
|
|
2
2
|
export const queriesOutputPath = "queries";
|
|
3
3
|
export const requestsOutputPath = "requests";
|
|
4
|
-
export const serviceFileName = "sdk.gen";
|
|
5
|
-
export const modelsFileName = "types.gen";
|
|
6
4
|
export const OpenApiRqFiles = {
|
|
7
5
|
queries: "queries",
|
|
8
6
|
queryOptions: "queryOptions",
|