contractdiff 0.0.0-stage → 0.4.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/LICENSE +21 -0
- package/README.md +228 -2
- package/dist/bin.js +4 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +24 -0
- package/dist/command-diff.js +310 -0
- package/dist/command-explain-cap.js +36 -0
- package/dist/command-explain-inline.js +17 -0
- package/dist/command-explain-name.js +31 -0
- package/dist/command-explain-operation.js +85 -0
- package/dist/command-explain-text.js +21 -0
- package/dist/command-explain.js +54 -0
- package/dist/command-lint.js +280 -0
- package/dist/command-migrate.js +70 -0
- package/dist/command-plugin.js +32 -0
- package/dist/command-props.js +116 -0
- package/dist/commands.js +7 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/model.d.ts +46 -0
- package/dist/core/model.js +1 -0
- package/dist/core/resolve.d.ts +22 -0
- package/dist/core/resolve.js +71 -0
- package/dist/diff-classify.js +30 -0
- package/dist/diff-contract.js +176 -0
- package/dist/diff-decisions.js +446 -0
- package/dist/diff-normalise.js +143 -0
- package/dist/diff-rules.js +109 -0
- package/dist/diff-schema.js +335 -0
- package/dist/diff-security.js +33 -0
- package/dist/diff-transitive.js +26 -0
- package/dist/diff-usage.js +59 -0
- package/dist/extract-normalise.js +85 -0
- package/dist/extract-roundtrip.js +28 -0
- package/dist/extract-standard.js +79 -0
- package/dist/gen-ts-ast.d.ts +135 -0
- package/dist/gen-ts-ast.js +52 -0
- package/dist/gen-ts-bundle.js +233 -0
- package/dist/gen-ts-comment.js +48 -0
- package/dist/gen-ts-context.d.ts +83 -0
- package/dist/gen-ts-context.js +45 -0
- package/dist/gen-ts-dict.d.ts +14 -0
- package/dist/gen-ts-dict.js +14 -0
- package/dist/gen-ts-discriminators.d.ts +7 -0
- package/dist/gen-ts-discriminators.js +117 -0
- package/dist/gen-ts-document.d.ts +12 -0
- package/dist/gen-ts-document.js +82 -0
- package/dist/gen-ts-enums.js +139 -0
- package/dist/gen-ts-helpers.js +30 -0
- package/dist/gen-ts-index.d.ts +49 -0
- package/dist/gen-ts-index.js +110 -0
- package/dist/gen-ts-operations.js +277 -0
- package/dist/gen-ts-print.js +113 -0
- package/dist/gen-ts-ref.d.ts +30 -0
- package/dist/gen-ts-ref.js +75 -0
- package/dist/gen-ts-schema.js +283 -0
- package/dist/gen-ts-text.d.ts +24 -0
- package/dist/gen-ts-text.js +98 -0
- package/dist/host.d.ts +145 -0
- package/dist/host.js +273 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/input-asyncapi.js +167 -0
- package/dist/input-buf.js +58 -0
- package/dist/input-jsonschema.js +165 -0
- package/dist/input-mcp.js +111 -0
- package/dist/input-overlay-jsonpath.js +265 -0
- package/dist/input-overlay.js +138 -0
- package/dist/input-protobuf.js +212 -0
- package/dist/input-swagger2.js +331 -0
- package/dist/inputs.js +8 -0
- package/dist/lint-code-read.js +129 -0
- package/dist/lint-code.d.ts +56 -0
- package/dist/lint-code.js +64 -0
- package/dist/lint-engine.d.ts +93 -0
- package/dist/lint-engine.js +87 -0
- package/dist/lint-functions.js +95 -0
- package/dist/lint-history.js +133 -0
- package/dist/lint-jsonpath.js +92 -0
- package/dist/lint-names.d.ts +11 -0
- package/dist/lint-names.js +2 -0
- package/dist/lint-redocly.js +141 -0
- package/dist/lint-rules.js +189 -0
- package/dist/lint-select.d.ts +33 -0
- package/dist/lint-select.js +129 -0
- package/dist/lint-since.js +20 -0
- package/dist/lint-spectral.js +167 -0
- package/dist/lint-stats.js +58 -0
- package/dist/migrate-hey-api.js +144 -0
- package/dist/migrate-literal.js +139 -0
- package/dist/migrate-openapi-fetch.js +62 -0
- package/dist/migrate-openapi-typescript.js +159 -0
- package/dist/migrate-orval.js +119 -0
- package/dist/migrate-shared.js +31 -0
- package/dist/openapi-typescript.d.ts +9 -0
- package/dist/openapi-typescript.js +36 -0
- package/dist/openapi.d.ts +20 -0
- package/dist/openapi.js +94 -0
- package/dist/plugin-express.js +66 -0
- package/dist/plugin-extract-hono.js +1 -0
- package/dist/plugin-extract-nest.js +1 -0
- package/dist/plugin-extract-openapi.js +246 -0
- package/dist/plugin-extract-standard-schema.js +42 -0
- package/dist/plugin-extract-trpc.js +1 -0
- package/dist/plugin-extract-ts-rest.js +77 -0
- package/dist/plugin-fastify.js +68 -0
- package/dist/plugin-fetch-client.js +172 -0
- package/dist/plugin-fetch-routes.js +110 -0
- package/dist/plugin-fetch-sample.js +155 -0
- package/dist/plugin-fetch-text.js +5 -0
- package/dist/plugin-fetch.js +19 -0
- package/dist/plugin-hono.js +42 -0
- package/dist/plugin-json-schema-build.js +289 -0
- package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
- package/dist/plugin-json-schema-dialect-gemini.js +29 -0
- package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
- package/dist/plugin-json-schema-dialect-mcp.js +13 -0
- package/dist/plugin-json-schema-dialect-openai.js +37 -0
- package/dist/plugin-json-schema-dialect.js +180 -0
- package/dist/plugin-json-schema.js +125 -0
- package/dist/plugin-markdown.js +114 -0
- package/dist/plugin-mcp-code.js +28 -0
- package/dist/plugin-mcp-tools.js +152 -0
- package/dist/plugin-mcp.js +107 -0
- package/dist/plugin-msw-files.js +50 -0
- package/dist/plugin-msw-sample.js +45 -0
- package/dist/plugin-msw-synth.js +116 -0
- package/dist/plugin-msw.js +30 -0
- package/dist/plugin-nest-code.js +68 -0
- package/dist/plugin-nest-contract.js +23 -0
- package/dist/plugin-nest.js +44 -0
- package/dist/plugin-server-code.js +61 -0
- package/dist/plugin-server-contract.js +48 -0
- package/dist/plugin-server-example.js +62 -0
- package/dist/plugin-server-router.js +77 -0
- package/dist/plugin-server-routes.js +155 -0
- package/dist/plugin-server-runtime.js +3 -0
- package/dist/plugin-server-sample.js +40 -0
- package/dist/plugin-swr-sample.js +21 -0
- package/dist/plugin-swr.js +40 -0
- package/dist/plugin-tanstack-query-sample.js +21 -0
- package/dist/plugin-tanstack-query.js +59 -0
- package/dist/plugin-types.js +80 -0
- package/dist/plugin-validator-code.js +41 -0
- package/dist/plugin-validator-names.js +27 -0
- package/dist/plugin-validator.js +103 -0
- package/dist/plugins.js +21 -0
- package/dist/props-emit.js +194 -0
- package/dist/props-generate.js +409 -0
- package/dist/props-judge.js +61 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +176 -0
- package/dist/props-shrink.js +75 -0
- package/dist/run-apply.js +25 -0
- package/dist/run-command.js +31 -0
- package/dist/run-commit.d.ts +51 -0
- package/dist/run-commit.js +48 -0
- package/dist/run-config.d.ts +193 -0
- package/dist/run-config.js +256 -0
- package/dist/run-diff.js +24 -0
- package/dist/run-extract.d.ts +13 -0
- package/dist/run-extract.js +21 -0
- package/dist/run-gen.d.ts +15 -0
- package/dist/run-gen.js +43 -0
- package/dist/run-header.js +37 -0
- package/dist/run-input.js +31 -0
- package/dist/run-load.js +32 -0
- package/dist/run-map.d.ts +41 -0
- package/dist/run-map.js +52 -0
- package/dist/run-plan.d.ts +31 -0
- package/dist/run-plan.js +35 -0
- package/dist/scaffold-seed.js +43 -0
- package/dist/scaffold-write.js +17 -0
- package/dist/scaffold.js +196 -0
- package/dist/testing-lint.js +43 -0
- package/dist/testing-owner.js +17 -0
- package/dist/testing-probe.js +25 -0
- package/dist/testing-rules.d.ts +65 -0
- package/dist/testing-rules.js +115 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.js +79 -0
- package/package.json +108 -4
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { lastRef, resolveRef } from './gen-ts-ref.js';
|
|
2
|
+
import { newNameState } from './gen-ts-text.js';
|
|
3
|
+
const STATES = new WeakMap();
|
|
4
|
+
export const stateOf = (ctx) => {
|
|
5
|
+
let state = STATES.get(ctx);
|
|
6
|
+
if (state === undefined) {
|
|
7
|
+
state = { names: newNameState(), enums: new Map() };
|
|
8
|
+
STATES.set(ctx, state);
|
|
9
|
+
}
|
|
10
|
+
return state;
|
|
11
|
+
};
|
|
12
|
+
export const DEFAULTS = {
|
|
13
|
+
additionalProperties: false,
|
|
14
|
+
alphabetize: false,
|
|
15
|
+
arrayLength: false,
|
|
16
|
+
defaultNonNullable: true,
|
|
17
|
+
emptyObjectsUnknown: false,
|
|
18
|
+
enum: false,
|
|
19
|
+
enumValues: false,
|
|
20
|
+
conditionalEnums: false,
|
|
21
|
+
dedupeEnums: false,
|
|
22
|
+
excludeDeprecated: false,
|
|
23
|
+
exportType: false,
|
|
24
|
+
immutable: false,
|
|
25
|
+
rootTypes: false,
|
|
26
|
+
rootTypesNoSchemaPrefix: false,
|
|
27
|
+
rootTypesKeepCasing: false,
|
|
28
|
+
pathParamsAsTypes: false,
|
|
29
|
+
propertiesRequiredByDefault: false,
|
|
30
|
+
makePathsEnum: false,
|
|
31
|
+
generatePathParams: false,
|
|
32
|
+
readWriteMarkers: false,
|
|
33
|
+
inject: '',
|
|
34
|
+
};
|
|
35
|
+
export const createContext = (document, options = {}, discriminators = { objects: {}, refsHandled: [] }) => {
|
|
36
|
+
const given = Object.entries(options).filter(([name, value]) => name in DEFAULTS && value !== undefined);
|
|
37
|
+
return {
|
|
38
|
+
...DEFAULTS,
|
|
39
|
+
...Object.fromEntries(given),
|
|
40
|
+
discriminators,
|
|
41
|
+
injectFooter: [],
|
|
42
|
+
resolve: (ref) => resolveRef(document, ref),
|
|
43
|
+
lastRef: (ref) => lastRef(document, ref),
|
|
44
|
+
};
|
|
45
|
+
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Reading a parsed document without trusting its shape. */
|
|
2
|
+
export type Dict = Record<string, unknown>;
|
|
3
|
+
export declare const isDict: (value: unknown) => value is Dict;
|
|
4
|
+
/** A non-object reads as an object with no members. */
|
|
5
|
+
export declare const dict: (value: unknown) => Dict;
|
|
6
|
+
export declare const list: (value: unknown) => readonly unknown[];
|
|
7
|
+
/** The number of members of an object or array; nothing else has any. */
|
|
8
|
+
export declare const size: (value: unknown) => number | undefined;
|
|
9
|
+
export interface EntryOptions {
|
|
10
|
+
readonly alphabetize?: boolean;
|
|
11
|
+
readonly excludeDeprecated?: boolean;
|
|
12
|
+
}
|
|
13
|
+
/** An object's entries in document order, optionally sorted and with deprecated members dropped. */
|
|
14
|
+
export declare const entries: (value: unknown, options?: EntryOptions) => [string, unknown][];
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
export const dict = (value) => (isDict(value) ? value : {});
|
|
3
|
+
export const list = (value) => (Array.isArray(value) ? value : []);
|
|
4
|
+
export const size = (value) => typeof value === 'object' && value !== null ? Object.keys(value).length : undefined;
|
|
5
|
+
export const entries = (value, options = {}) => {
|
|
6
|
+
let found = Object.entries(dict(value));
|
|
7
|
+
if (options.alphabetize === true) {
|
|
8
|
+
found.sort(([left], [right]) => left.localeCompare(right, 'en-us', { numeric: true }));
|
|
9
|
+
}
|
|
10
|
+
if (options.excludeDeprecated === true) {
|
|
11
|
+
found = found.filter(([, member]) => !dict(member).deprecated);
|
|
12
|
+
}
|
|
13
|
+
return found;
|
|
14
|
+
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Discriminators, found before anything is transformed: which schema declares or inherits one,
|
|
3
|
+
* and, where a mapping names the value, that value written into the mapped schema as an enum.
|
|
4
|
+
*/
|
|
5
|
+
import { type Discriminators } from './gen-ts-context.js';
|
|
6
|
+
/** Every discriminator in `document`. The document is changed: mapped schemas gain their enum property. */
|
|
7
|
+
export declare const scanDiscriminators: (document: unknown) => Discriminators;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { dict, isDict, list } from './gen-ts-dict.js';
|
|
2
|
+
import { createRef, resolveRef } from './gen-ts-ref.js';
|
|
3
|
+
const NO_PATH = [];
|
|
4
|
+
const walk = (node, visit, path = NO_PATH) => {
|
|
5
|
+
if (Array.isArray(node)) {
|
|
6
|
+
for (const [index, item] of node.entries())
|
|
7
|
+
walk(item, visit, [...path, index]);
|
|
8
|
+
return;
|
|
9
|
+
}
|
|
10
|
+
if (!isDict(node))
|
|
11
|
+
return;
|
|
12
|
+
visit(node, path);
|
|
13
|
+
for (const key of Object.keys(node))
|
|
14
|
+
walk(node[key], visit, [...path, key]);
|
|
15
|
+
};
|
|
16
|
+
const discriminatorEnum = (values, previous) => {
|
|
17
|
+
const { description } = dict(previous);
|
|
18
|
+
return {
|
|
19
|
+
type: 'string',
|
|
20
|
+
enum: values,
|
|
21
|
+
description: description
|
|
22
|
+
? `${String(description)} (enum property replaced by openapi-typescript)`
|
|
23
|
+
: 'discriminator enum property added by openapi-typescript',
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
const patch = (document, ref, values, name) => {
|
|
27
|
+
const schema = dict(resolveRef(document, ref));
|
|
28
|
+
if (Array.isArray(schema.allOf)) {
|
|
29
|
+
schema.allOf.push({ type: 'object', required: [name], properties: { [name]: discriminatorEnum(values, undefined) } });
|
|
30
|
+
return true;
|
|
31
|
+
}
|
|
32
|
+
if (schema.type !== 'object')
|
|
33
|
+
return false;
|
|
34
|
+
if (!Array.isArray(schema.required))
|
|
35
|
+
schema.required = [name];
|
|
36
|
+
else if (!schema.required.includes(name))
|
|
37
|
+
schema.required.push(name);
|
|
38
|
+
if (!schema.properties)
|
|
39
|
+
schema.properties = {};
|
|
40
|
+
const properties = dict(schema.properties);
|
|
41
|
+
setOwn(properties, name, discriminatorEnum(values, new Map(Object.entries(properties)).get(name)));
|
|
42
|
+
return true;
|
|
43
|
+
};
|
|
44
|
+
const mappedValues = (oneOf, discriminator) => {
|
|
45
|
+
const inferred = new Map();
|
|
46
|
+
for (const item of oneOf) {
|
|
47
|
+
const ref = dict(item).$ref;
|
|
48
|
+
if (typeof ref !== 'string')
|
|
49
|
+
continue;
|
|
50
|
+
const name = ref.split('/').pop();
|
|
51
|
+
if (name)
|
|
52
|
+
inferred.set(ref, [name]);
|
|
53
|
+
}
|
|
54
|
+
const defined = new Map();
|
|
55
|
+
for (const [value, ref] of Object.entries(discriminator.mapping ?? {})) {
|
|
56
|
+
defined.set(ref, [...(defined.get(ref) ?? []), value]);
|
|
57
|
+
}
|
|
58
|
+
return new Map([...inferred, ...defined]);
|
|
59
|
+
};
|
|
60
|
+
const asDiscriminator = (value) => {
|
|
61
|
+
const { propertyName, mapping } = dict(value);
|
|
62
|
+
if (typeof propertyName !== 'string' || propertyName === '')
|
|
63
|
+
return undefined;
|
|
64
|
+
const targets = Object.entries(dict(mapping)).filter((entry) => typeof entry[1] === 'string');
|
|
65
|
+
return isDict(mapping) ? { propertyName, mapping: Object.fromEntries(targets) } : { propertyName };
|
|
66
|
+
};
|
|
67
|
+
const setOwn = (target, key, value) => {
|
|
68
|
+
Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
|
|
69
|
+
};
|
|
70
|
+
const collectDeclared = (document, found) => {
|
|
71
|
+
walk(document, (node, path) => {
|
|
72
|
+
const discriminator = asDiscriminator(node.discriminator);
|
|
73
|
+
if (discriminator === undefined)
|
|
74
|
+
return;
|
|
75
|
+
setOwn(found.objects, createRef(path), discriminator);
|
|
76
|
+
if (!Array.isArray(node.oneOf))
|
|
77
|
+
return;
|
|
78
|
+
for (const [ref, values] of mappedValues(node.oneOf, discriminator)) {
|
|
79
|
+
if (found.refsHandled.includes(ref))
|
|
80
|
+
continue;
|
|
81
|
+
if (patch(document, ref, values, discriminator.propertyName))
|
|
82
|
+
found.refsHandled.push(ref);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
};
|
|
86
|
+
const inherit = (document, found, child, parent) => {
|
|
87
|
+
const values = Object.entries(parent.mapping ?? {})
|
|
88
|
+
.filter(([, target]) => target === child)
|
|
89
|
+
.map(([value]) => value);
|
|
90
|
+
if (values.length > 0 && patch(document, child, values, parent.propertyName))
|
|
91
|
+
found.refsHandled.push(child);
|
|
92
|
+
setOwn(found.objects, child, { ...parent });
|
|
93
|
+
};
|
|
94
|
+
const collectInherited = (document, found) => {
|
|
95
|
+
walk(document, (node, path) => {
|
|
96
|
+
for (const item of list(node.allOf)) {
|
|
97
|
+
const member = dict(item);
|
|
98
|
+
if ('$ref' in member) {
|
|
99
|
+
const parent = found.objects[String(member.$ref)];
|
|
100
|
+
if (parent === undefined)
|
|
101
|
+
return;
|
|
102
|
+
inherit(document, found, createRef(path), parent);
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
const own = asDiscriminator(member.discriminator);
|
|
106
|
+
if (own !== undefined)
|
|
107
|
+
setOwn(found.objects, createRef(path), { ...own });
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
});
|
|
111
|
+
};
|
|
112
|
+
export const scanDiscriminators = (document) => {
|
|
113
|
+
const found = { objects: {}, refsHandled: [] };
|
|
114
|
+
collectDeclared(document, found);
|
|
115
|
+
collectInherited(document, found);
|
|
116
|
+
return found;
|
|
117
|
+
};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/** The whole file: components, then every root in upstream's order, then what the transforms hoisted. */
|
|
2
|
+
import { type AliasStatement, type Statement, type TypeNode } from './gen-ts-ast.js';
|
|
3
|
+
import { type Context } from './gen-ts-context.js';
|
|
4
|
+
/**
|
|
5
|
+
* Whether a schema is an enum that `enum: true` turns into a TypeScript enum of its own, so that
|
|
6
|
+
* `rootTypes` must not also export an alias under the same name.
|
|
7
|
+
*/
|
|
8
|
+
export declare const isEnumSchema: (schema: unknown) => boolean;
|
|
9
|
+
/** The Components Object as one type, followed by the root aliases when asked for. */
|
|
10
|
+
export declare const transformComponentsObject: (components: unknown, ctx: Context) => (TypeNode | AliasStatement)[];
|
|
11
|
+
/** Every statement of the generated file, for a document whose discriminators are already in `ctx`. */
|
|
12
|
+
export declare const transformSchema: (document: unknown, ctx: Context) => Statement[];
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { NEVER, STRING, alias, object, property, record, reference, } from './gen-ts-ast.js';
|
|
2
|
+
import { jsDoc } from './gen-ts-comment.js';
|
|
3
|
+
import { dict, entries, isDict } from './gen-ts-dict.js';
|
|
4
|
+
import { READ_WRITE_MARKERS } from './gen-ts-helpers.js';
|
|
5
|
+
import { pathsEnum, transformHeaderObject, transformPathItemObject, transformPathsObject, transformRequestBodyObject, transformResponseObject, transformWebhooksObject, } from './gen-ts-operations.js';
|
|
6
|
+
import { createRef } from './gen-ts-ref.js';
|
|
7
|
+
import { transformSchemaObject } from './gen-ts-schema.js';
|
|
8
|
+
import { pascalCase, propertyName } from './gen-ts-text.js';
|
|
9
|
+
export const isEnumSchema = (schema) => isDict(schema) &&
|
|
10
|
+
Array.isArray(schema.enum) &&
|
|
11
|
+
schema.type !== 'object' &&
|
|
12
|
+
!('properties' in schema) &&
|
|
13
|
+
!('additionalProperties' in schema);
|
|
14
|
+
const parameterType = (parameter, options) => {
|
|
15
|
+
const { schema } = dict(parameter);
|
|
16
|
+
return schema ? transformSchemaObject(schema, options) : STRING;
|
|
17
|
+
};
|
|
18
|
+
const COMPONENTS = [
|
|
19
|
+
['schemas', 'schema', transformSchemaObject],
|
|
20
|
+
['responses', 'response', transformResponseObject],
|
|
21
|
+
['parameters', 'parameter', parameterType],
|
|
22
|
+
['requestBodies', 'requestBody', transformRequestBodyObject],
|
|
23
|
+
['headers', 'header', transformHeaderObject],
|
|
24
|
+
['pathItems', 'pathItem', transformPathItemObject],
|
|
25
|
+
];
|
|
26
|
+
const rootAlias = ({ key, singular, name }, taken, ctx) => {
|
|
27
|
+
const isSchema = key === 'schemas';
|
|
28
|
+
const prefix = pascalCase(singular);
|
|
29
|
+
const base = prefix + (ctx.rootTypesKeepCasing && isSchema ? name : pascalCase(name));
|
|
30
|
+
let aliasName = base;
|
|
31
|
+
for (let counter = 2; taken.has(aliasName); counter++)
|
|
32
|
+
aliasName = `${base}_${counter}`;
|
|
33
|
+
if (ctx.rootTypesNoSchemaPrefix && isSchema)
|
|
34
|
+
aliasName = aliasName.replace(prefix, '');
|
|
35
|
+
return alias(aliasName, reference(`components['${key}']['${name}']`));
|
|
36
|
+
};
|
|
37
|
+
export const transformComponentsObject = (components, ctx) => {
|
|
38
|
+
const declared = dict(components);
|
|
39
|
+
const aliases = new Map();
|
|
40
|
+
const groups = COMPONENTS.map(([key, singular, transform]) => {
|
|
41
|
+
const members = entries(declared[key], ctx).map(([name, item]) => {
|
|
42
|
+
const type = transform(item, { path: createRef(['components', key, name]), ctx });
|
|
43
|
+
if (ctx.rootTypes && !(ctx.enum && key === 'schemas' && isEnumSchema(item))) {
|
|
44
|
+
const statement = rootAlias({ key, singular, name }, aliases, ctx);
|
|
45
|
+
aliases.set(statement.name, statement);
|
|
46
|
+
}
|
|
47
|
+
return property({ readonly: ctx.immutable, name: propertyName(name), type, comment: jsDoc(item) });
|
|
48
|
+
});
|
|
49
|
+
return property({ name: key, type: members.length > 0 ? object(members) : NEVER });
|
|
50
|
+
});
|
|
51
|
+
return [object(groups), ...aliases.values()];
|
|
52
|
+
};
|
|
53
|
+
const ROOTS = [
|
|
54
|
+
['paths', (node, ctx) => [transformPathsObject(node, ctx)]],
|
|
55
|
+
['webhooks', (node, ctx) => [transformWebhooksObject(node, ctx)]],
|
|
56
|
+
['components', transformComponentsObject],
|
|
57
|
+
['$defs', (node, ctx) => [transformSchemaObject(node, { path: createRef(['$defs']), ctx })]],
|
|
58
|
+
];
|
|
59
|
+
const empty = (name) => alias(name, record(STRING, NEVER));
|
|
60
|
+
const rootStatement = (root, node, ctx) => {
|
|
61
|
+
if (node.kind === 'alias')
|
|
62
|
+
return node;
|
|
63
|
+
if (node.kind !== 'object' || node.members.length === 0)
|
|
64
|
+
return empty(root);
|
|
65
|
+
return ctx.exportType ? alias(root, node) : { kind: 'interface', name: root, members: [...node.members] };
|
|
66
|
+
};
|
|
67
|
+
export const transformSchema = (document, ctx) => {
|
|
68
|
+
const declared = dict(document);
|
|
69
|
+
const statements = ctx.readWriteMarkers ? [READ_WRITE_MARKERS] : [];
|
|
70
|
+
for (const [root, transform] of ROOTS) {
|
|
71
|
+
const node = declared[root];
|
|
72
|
+
const isDeclared = node && typeof node === 'object';
|
|
73
|
+
statements.push(...(isDeclared ? transform(node, ctx).map((item) => rootStatement(root, item, ctx)) : [empty(root)]));
|
|
74
|
+
}
|
|
75
|
+
statements.push(...ctx.injectFooter);
|
|
76
|
+
const hasOperations = ctx.injectFooter.some((statement) => statement.name === 'operations');
|
|
77
|
+
if (!hasOperations)
|
|
78
|
+
statements.push(empty('operations'));
|
|
79
|
+
if (ctx.makePathsEnum && declared.paths)
|
|
80
|
+
statements.push(pathsEnum(declared.paths));
|
|
81
|
+
return statements;
|
|
82
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { NEVER, NULL, STRING, access, array, intersection, object, property, raw, record, reference, tuple, union, FALSE, TRUE, UNKNOWN, } from './gen-ts-ast.js';
|
|
2
|
+
import { stateOf } from './gen-ts-context.js';
|
|
3
|
+
import { list } from './gen-ts-dict.js';
|
|
4
|
+
import { FLATTENED_DEEP_REQUIRED, READONLY_ARRAY, requireHelper } from './gen-ts-helpers.js';
|
|
5
|
+
import { createRef, pathTokens, refType } from './gen-ts-ref.js';
|
|
6
|
+
import { enumMemberName, memberName, propertyName } from './gen-ts-text.js';
|
|
7
|
+
const objectLiteral = (value) => {
|
|
8
|
+
const members = Object.entries(value).map(([key, member]) => property({ name: propertyName(key), type: literalType(member) }));
|
|
9
|
+
return members.length > 0 ? object(members) : record(STRING, NEVER);
|
|
10
|
+
};
|
|
11
|
+
const SCALARS = {
|
|
12
|
+
string: (value) => raw(JSON.stringify(value)),
|
|
13
|
+
number: (value) => ({ kind: 'literal', text: String(value) }),
|
|
14
|
+
boolean: (value) => (value ? TRUE : FALSE),
|
|
15
|
+
};
|
|
16
|
+
export function literalType(value) {
|
|
17
|
+
const scalar = SCALARS[typeof value];
|
|
18
|
+
if (scalar !== undefined)
|
|
19
|
+
return scalar(value);
|
|
20
|
+
if (Array.isArray(value))
|
|
21
|
+
return value.length === 0 ? array(NEVER) : tuple(value.map((item) => literalType(item)));
|
|
22
|
+
if (typeof value === 'object' && value !== null)
|
|
23
|
+
return objectLiteral(value);
|
|
24
|
+
return value === null ? NULL : UNKNOWN;
|
|
25
|
+
}
|
|
26
|
+
const memberComment = (description) => {
|
|
27
|
+
const trimmed = typeof description === 'string' ? description.trim() : '';
|
|
28
|
+
return trimmed === '' ? undefined : ` ${trimmed}`;
|
|
29
|
+
};
|
|
30
|
+
const describedAs = (entry) => String(entry.description || '');
|
|
31
|
+
const cacheKey = (entries) => {
|
|
32
|
+
const sorted = entries.map((entry) => entry.value).sort();
|
|
33
|
+
return entries.map((entry, index) => `${String(entry.name ?? sorted[index])}:${describedAs(entry)}`).join(',');
|
|
34
|
+
};
|
|
35
|
+
const withFirst = (name, change) => change(name.charAt(0)) + name.slice(1);
|
|
36
|
+
const upper = (letter) => letter.toUpperCase();
|
|
37
|
+
const lower = (letter) => letter.toLowerCase();
|
|
38
|
+
export const enumStatement = (init, names) => {
|
|
39
|
+
const sanitized = memberName(init.name, names);
|
|
40
|
+
if (sanitized === '') {
|
|
41
|
+
throw new Error(`cannot name the enum at \`${init.name}\`: nothing is left of its path. fix: give the schema a path with letters or digits in it`);
|
|
42
|
+
}
|
|
43
|
+
const name = withFirst(sanitized, upper);
|
|
44
|
+
const key = cacheKey(init.entries);
|
|
45
|
+
const cached = init.cache?.get(key);
|
|
46
|
+
if (cached !== undefined)
|
|
47
|
+
return cached;
|
|
48
|
+
const members = init.entries.map(({ value, name: given, description }) => ({
|
|
49
|
+
name: enumMemberName(String(given ?? value), names),
|
|
50
|
+
value,
|
|
51
|
+
comment: memberComment(description),
|
|
52
|
+
}));
|
|
53
|
+
const statement = { kind: 'enum', name, members };
|
|
54
|
+
init.cache?.set(key, statement);
|
|
55
|
+
return statement;
|
|
56
|
+
};
|
|
57
|
+
const NAME_KEYS = ['x-enum-varnames', 'x-enumNames'];
|
|
58
|
+
const DESCRIPTION_KEYS = ['x-enum-descriptions', 'x-enumDescriptions'];
|
|
59
|
+
const META_KEYS = [...NAME_KEYS, ...DESCRIPTION_KEYS];
|
|
60
|
+
const metaAt = (schema, [first, second], index) => list(schema[first])[index] ?? list(schema[second])[index];
|
|
61
|
+
const isScalar = (value) => typeof value === 'string' || typeof value === 'number';
|
|
62
|
+
const becomesTsEnum = (schema, ctx) => {
|
|
63
|
+
if (!ctx.enum || !list(schema.enum).every((value) => isScalar(value)))
|
|
64
|
+
return false;
|
|
65
|
+
return !ctx.conditionalEnums || META_KEYS.some((key) => Array.isArray(schema[key]));
|
|
66
|
+
};
|
|
67
|
+
const SCHEMAS_PREFIX = 'components/schemas';
|
|
68
|
+
const nameAt = (path) => pathTokens(path).join('/').replace(SCHEMAS_PREFIX, '');
|
|
69
|
+
const tsEnumType = (schema, options) => {
|
|
70
|
+
const { ctx } = options;
|
|
71
|
+
const entries = list(schema.enum).map((value, index) => ({
|
|
72
|
+
value,
|
|
73
|
+
name: metaAt(schema, NAME_KEYS, index),
|
|
74
|
+
description: metaAt(schema, DESCRIPTION_KEYS, index),
|
|
75
|
+
}));
|
|
76
|
+
const state = stateOf(ctx);
|
|
77
|
+
const cache = ctx.dedupeEnums ? state.enums : undefined;
|
|
78
|
+
const statement = enumStatement({ name: nameAt(options.path), entries, cache }, state.names);
|
|
79
|
+
if (!ctx.injectFooter.includes(statement))
|
|
80
|
+
ctx.injectFooter.push(statement);
|
|
81
|
+
return reference(statement.name);
|
|
82
|
+
};
|
|
83
|
+
const UNION_KEYWORDS = new Set(['anyOf', 'oneOf']);
|
|
84
|
+
const DIGITS = /^\d+$/;
|
|
85
|
+
const isUnionIndex = (pointer, index) => UNION_KEYWORDS.has(pointer[index]) && DIGITS.test(String(pointer[index + 1]));
|
|
86
|
+
const isPropertySegment = (segment) => !UNION_KEYWORDS.has(segment) && !DIGITS.test(segment);
|
|
87
|
+
const UNION_STEP = 2;
|
|
88
|
+
const withoutUnionSteps = (pointer) => {
|
|
89
|
+
const cleaned = [];
|
|
90
|
+
const extract = new Set();
|
|
91
|
+
let resume = 0;
|
|
92
|
+
for (const [index, segment] of pointer.entries()) {
|
|
93
|
+
if (index < resume)
|
|
94
|
+
continue;
|
|
95
|
+
if (isUnionIndex(pointer, index)) {
|
|
96
|
+
resume = index + UNION_STEP;
|
|
97
|
+
for (const later of pointer.slice(resume).filter((segment) => isPropertySegment(segment)))
|
|
98
|
+
extract.add(later);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
cleaned.push(segment);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { cleaned, extract };
|
|
105
|
+
};
|
|
106
|
+
const declareValues = (schema, options, fromAdditionalProperties) => {
|
|
107
|
+
const { ctx } = options;
|
|
108
|
+
const { cleaned, extract } = withoutUnionSteps(pathTokens(options.path));
|
|
109
|
+
const name = withFirst(memberName(`${nameAt(options.path)}Values`, stateOf(ctx).names), lower);
|
|
110
|
+
requireHelper(ctx.injectFooter, FLATTENED_DEEP_REQUIRED);
|
|
111
|
+
requireHelper(ctx.injectFooter, READONLY_ARRAY);
|
|
112
|
+
const element = refType(createRef(cleaned), { deep: true, extract });
|
|
113
|
+
ctx.injectFooter.push({
|
|
114
|
+
kind: 'values',
|
|
115
|
+
name,
|
|
116
|
+
type: reference('ReadonlyArray', [fromAdditionalProperties ? access(element, 'string') : element]),
|
|
117
|
+
values: list(schema.enum),
|
|
118
|
+
});
|
|
119
|
+
};
|
|
120
|
+
const openEnded = (type, isOpen) => isOpen ? union([type, intersection([STRING, object([])])]) : type;
|
|
121
|
+
const literalUnion = (schema) => {
|
|
122
|
+
const members = list(schema.enum).map((value) => literalType(value));
|
|
123
|
+
const isNullable = (Array.isArray(schema.type) && schema.type.includes('null')) || Boolean(schema.nullable);
|
|
124
|
+
return union(isNullable ? [...members, NULL] : members);
|
|
125
|
+
};
|
|
126
|
+
export const enumType = (schema, options, fromAdditionalProperties) => {
|
|
127
|
+
if (!Array.isArray(schema.enum) || schema.type === 'object' || 'properties' in schema)
|
|
128
|
+
return undefined;
|
|
129
|
+
const isOpen = Boolean(schema.additionalProperties);
|
|
130
|
+
if (isOpen && schema.type !== 'string')
|
|
131
|
+
return undefined;
|
|
132
|
+
if (becomesTsEnum(schema, options.ctx))
|
|
133
|
+
return openEnded(tsEnumType(schema, options), isOpen);
|
|
134
|
+
const type = openEnded(literalUnion(schema), isOpen);
|
|
135
|
+
if (options.ctx.enumValues && schema.enum.every((value) => isScalar(value))) {
|
|
136
|
+
declareValues(schema, options, fromAdditionalProperties);
|
|
137
|
+
}
|
|
138
|
+
return type;
|
|
139
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
const helper = (name, text) => ({ kind: 'helper', name, text });
|
|
2
|
+
export const WITH_REQUIRED = helper('WithRequired', `type WithRequired<T, K extends keyof T> = T & {
|
|
3
|
+
[P in K]-?: T[P];
|
|
4
|
+
};`);
|
|
5
|
+
export const FLATTENED_DEEP_REQUIRED = helper('FlattenedDeepRequired', `type FlattenedDeepRequired<T> = {
|
|
6
|
+
[K in keyof T]-?: FlattenedDeepRequired<T[K] extends unknown[] | undefined | null ? Extract<T[K], unknown[]>[number] : T[K]>;
|
|
7
|
+
};`);
|
|
8
|
+
export const READONLY_ARRAY = helper('ReadonlyArray', `type ReadonlyArray<T> = [
|
|
9
|
+
Exclude<T, undefined>
|
|
10
|
+
] extends [
|
|
11
|
+
unknown[]
|
|
12
|
+
] ? Readonly<Exclude<T, undefined>> : Readonly<Exclude<T, undefined>[]>;`);
|
|
13
|
+
export const READ_WRITE_MARKERS = helper('$Read', `export type $Read<T> = {
|
|
14
|
+
readonly $read: T;
|
|
15
|
+
};
|
|
16
|
+
export type $Write<T> = {
|
|
17
|
+
readonly $write: T;
|
|
18
|
+
};
|
|
19
|
+
export type Readable<T> = T extends $Write<any> ? never : T extends $Read<infer U> ? Readable<U> : T extends (infer E)[] ? Readable<E>[] : T extends object ? {
|
|
20
|
+
[K in keyof T as NonNullable<T[K]> extends $Write<any> ? never : K]: Readable<T[K]>;
|
|
21
|
+
} : T;
|
|
22
|
+
export type Writable<T> = T extends $Read<any> ? never : T extends $Write<infer U> ? Writable<U> : T extends (infer E)[] ? Writable<E>[] : T extends object ? {
|
|
23
|
+
[K in keyof T as NonNullable<T[K]> extends $Read<any> ? never : K]: Writable<T[K]>;
|
|
24
|
+
} & {
|
|
25
|
+
[K in keyof T as NonNullable<T[K]> extends $Read<any> ? K : never]?: never;
|
|
26
|
+
} : T;`);
|
|
27
|
+
export const requireHelper = (footer, wanted) => {
|
|
28
|
+
if (!footer.includes(wanted))
|
|
29
|
+
footer.push(wanted);
|
|
30
|
+
};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TypeScript types from an OpenAPI 3.x document, byte for byte what openapi-typescript 7 prints,
|
|
3
|
+
* without the TypeScript compiler: the types are written as text. Nothing here imports
|
|
4
|
+
* `typescript`, so it runs the same under TypeScript 7, which ships no compiler API.
|
|
5
|
+
*/
|
|
6
|
+
import { type Context, type GenerateOptions, type TransformOptions } from './gen-ts-context.js';
|
|
7
|
+
/** The comment upstream's CLI writes above the generated types. `generate` does not add it. */
|
|
8
|
+
export declare const COMMENT_HEADER = "/**\n * This file was auto-generated by openapi-typescript.\n * Do not make direct changes to the file.\n */\n\n";
|
|
9
|
+
/** A document this generator does not read. The message ends in a `fix:` line. */
|
|
10
|
+
export declare class GenerateError extends Error {
|
|
11
|
+
constructor(reason: string, fix: string);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The pointer of every object whose local `$ref` leads nowhere, in document order: what
|
|
15
|
+
* upstream's bundler reports as `Can't resolve $ref at <pointer>`. A reference to another file
|
|
16
|
+
* is not checked here: {@link checkRefs} refuses it.
|
|
17
|
+
*/
|
|
18
|
+
export declare const unresolvedRefs: (root: unknown) => string[];
|
|
19
|
+
/** The schema type of one Schema Object. */
|
|
20
|
+
export declare const transformSchemaObject: (schema: unknown, options: TransformOptions) => string;
|
|
21
|
+
/** The Components Object, and the root aliases after it when `rootTypes` is on. */
|
|
22
|
+
export declare const transformComponentsObject: (components: unknown, ctx: Context) => string;
|
|
23
|
+
/** The Paths Object. */
|
|
24
|
+
export declare const transformPathsObject: (paths: unknown, ctx: Context) => string;
|
|
25
|
+
/** The Webhooks Object. */
|
|
26
|
+
export declare const transformWebhooksObject: (webhooks: unknown, ctx: Context) => string;
|
|
27
|
+
/** One Path Item Object. */
|
|
28
|
+
export declare const transformPathItemObject: (pathItem: unknown, options: TransformOptions) => string;
|
|
29
|
+
/** One Operation Object: its `parameters`, `requestBody` and `responses` members. */
|
|
30
|
+
export declare const transformOperationObject: (operation: unknown, options: TransformOptions) => string;
|
|
31
|
+
/** One Request Body Object. */
|
|
32
|
+
export declare const transformRequestBodyObject: (requestBody: unknown, options: TransformOptions) => string;
|
|
33
|
+
/** One Response Object. */
|
|
34
|
+
export declare const transformResponseObject: (response: unknown, options: TransformOptions) => string;
|
|
35
|
+
/** One Header Object. */
|
|
36
|
+
export declare const transformHeaderObject: (header: unknown, options: TransformOptions) => string;
|
|
37
|
+
/** The `ApiPaths` enum of a Paths Object. */
|
|
38
|
+
export declare const makeApiPathsEnum: (paths: unknown) => string;
|
|
39
|
+
/** The whole file for a document, under a context the caller built: discriminators are not scanned here. */
|
|
40
|
+
export declare const transformSchema: (root: unknown, ctx: Context) => string;
|
|
41
|
+
/**
|
|
42
|
+
* The whole file for a parsed OpenAPI 3.x document: upstream's `astToString(await openapiTS(…))`.
|
|
43
|
+
* The document is not changed.
|
|
44
|
+
*/
|
|
45
|
+
export declare const generate: (root: unknown, options?: GenerateOptions) => string;
|
|
46
|
+
export { type Context, type Discriminator, type Discriminators, type GenerateOptions, type TransformOptions, createContext, } from './gen-ts-context.js';
|
|
47
|
+
export { scanDiscriminators } from './gen-ts-discriminators.js';
|
|
48
|
+
export { isEnumSchema } from './gen-ts-document.js';
|
|
49
|
+
export { createRef, resolveRef } from './gen-ts-ref.js';
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { createContext } from './gen-ts-context.js';
|
|
2
|
+
import { isDict } from './gen-ts-dict.js';
|
|
3
|
+
import { scanDiscriminators } from './gen-ts-discriminators.js';
|
|
4
|
+
import { transformComponentsObject as componentsNodes, transformSchema as documentStatements } from './gen-ts-document.js';
|
|
5
|
+
import { pathsEnum, transformHeaderObject as headerType, transformOperationObject as operationMembers, transformPathItemObject as pathItemType, transformPathsObject as pathsType, transformRequestBodyObject as requestBodyType, transformResponseObject as responseType, transformWebhooksObject as webhooksType, } from './gen-ts-operations.js';
|
|
6
|
+
import { printFile } from './gen-ts-print.js';
|
|
7
|
+
import { childPath, pointerOf } from './gen-ts-ref.js';
|
|
8
|
+
import { transformSchemaObject as schemaType } from './gen-ts-schema.js';
|
|
9
|
+
export const COMMENT_HEADER = `/**
|
|
10
|
+
* This file was auto-generated by openapi-typescript.
|
|
11
|
+
* Do not make direct changes to the file.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
`;
|
|
15
|
+
export class GenerateError extends Error {
|
|
16
|
+
constructor(reason, fix) {
|
|
17
|
+
super(`${reason} fix: ${fix}`);
|
|
18
|
+
this.name = 'GenerateError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const FIRST_MAJOR = 3;
|
|
22
|
+
const checkVersion = (root) => {
|
|
23
|
+
if (root.swagger) {
|
|
24
|
+
throw new GenerateError('Unsupported Swagger version: 2.x. Use OpenAPI 3.x instead.', 'convert the document to OpenAPI 3.1 first');
|
|
25
|
+
}
|
|
26
|
+
const version = Number.parseFloat(String(root.openapi));
|
|
27
|
+
if (!root.openapi) {
|
|
28
|
+
throw new GenerateError('Unsupported schema format, expected `openapi: 3.x`.', 'pass an OpenAPI 3.x document, with its `openapi` member');
|
|
29
|
+
}
|
|
30
|
+
if (!(version >= FIRST_MAJOR && version < FIRST_MAJOR + 1)) {
|
|
31
|
+
throw new GenerateError(`Unsupported OpenAPI version: ${String(root.openapi)}.`, 'pass an OpenAPI 3.x document');
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
const COMPILER_OPTIONS = new Set(['transform', 'postTransform', 'transformProperty']);
|
|
35
|
+
const checkOptions = (options) => {
|
|
36
|
+
const found = Object.entries(options).find(([name, value]) => COMPILER_OPTIONS.has(name) && value !== undefined);
|
|
37
|
+
if (found !== undefined) {
|
|
38
|
+
throw new GenerateError(`The \`${found[0]}\` option needs the TypeScript compiler, which this generator does not use.`, 'drop the option and edit the generated text instead');
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const DATA_MEMBERS = new Set(['example', 'default', 'enum', 'const']);
|
|
42
|
+
const exists = (root, ref) => {
|
|
43
|
+
let node = root;
|
|
44
|
+
for (const token of pointerOf(ref)) {
|
|
45
|
+
if (typeof node !== 'object' || node === null || !Object.hasOwn(node, token))
|
|
46
|
+
return false;
|
|
47
|
+
node = node[token];
|
|
48
|
+
}
|
|
49
|
+
return true;
|
|
50
|
+
};
|
|
51
|
+
const refsOf = (root) => {
|
|
52
|
+
const found = [];
|
|
53
|
+
const walk = (node, path) => {
|
|
54
|
+
if (typeof node !== 'object' || node === null)
|
|
55
|
+
return;
|
|
56
|
+
const { $ref } = node;
|
|
57
|
+
if (typeof $ref === 'string')
|
|
58
|
+
found.push({ at: path, ref: $ref });
|
|
59
|
+
for (const [key, member] of Object.entries(node)) {
|
|
60
|
+
if (!DATA_MEMBERS.has(key) && !key.startsWith('x-'))
|
|
61
|
+
walk(member, childPath(path, key));
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
walk(root, '#');
|
|
65
|
+
return found;
|
|
66
|
+
};
|
|
67
|
+
export const unresolvedRefs = (root) => refsOf(root)
|
|
68
|
+
.filter(({ ref }) => ref.startsWith('#') && !exists(root, ref))
|
|
69
|
+
.map(({ at }) => at);
|
|
70
|
+
const checkRefs = (root) => {
|
|
71
|
+
const unresolved = unresolvedRefs(root);
|
|
72
|
+
const last = unresolved.at(-1);
|
|
73
|
+
if (last !== undefined) {
|
|
74
|
+
const others = unresolved.slice(0, -1);
|
|
75
|
+
throw new GenerateError(`Can't resolve $ref at ${last}${others.length === 0 ? '' : ` (and at ${others.join(', ')})`}.`, 'point each `$ref` at a member the document has, or bundle the files it names into one document first');
|
|
76
|
+
}
|
|
77
|
+
const external = refsOf(root).find(({ ref }) => !ref.startsWith('#'));
|
|
78
|
+
if (external === undefined)
|
|
79
|
+
return;
|
|
80
|
+
const file = external.ref.replace(/#.*/su, '');
|
|
81
|
+
throw new GenerateError(`\`${external.ref}\` at ${external.at} is in another file, ${file}, which is not part of the document.`, `generate from the document's own file, so ${file} is read next to it, or bundle ${file} into the document first`);
|
|
82
|
+
};
|
|
83
|
+
export const transformSchemaObject = (schema, options) => printFile([schemaType(schema, options)]);
|
|
84
|
+
export const transformComponentsObject = (components, ctx) => printFile(componentsNodes(components, ctx));
|
|
85
|
+
export const transformPathsObject = (paths, ctx) => printFile([pathsType(paths, ctx)]);
|
|
86
|
+
export const transformWebhooksObject = (webhooks, ctx) => printFile([webhooksType(webhooks, ctx)]);
|
|
87
|
+
export const transformPathItemObject = (pathItem, options) => printFile([pathItemType(pathItem, options)]);
|
|
88
|
+
export const transformOperationObject = (operation, options) => printFile(operationMembers(operation, options));
|
|
89
|
+
export const transformRequestBodyObject = (requestBody, options) => printFile([requestBodyType(requestBody, options)]);
|
|
90
|
+
export const transformResponseObject = (response, options) => printFile([responseType(response, options)]);
|
|
91
|
+
export const transformHeaderObject = (header, options) => printFile([headerType(header, options)]);
|
|
92
|
+
export const makeApiPathsEnum = (paths) => printFile([pathsEnum(paths)]);
|
|
93
|
+
export const transformSchema = (root, ctx) => printFile(documentStatements(root, ctx));
|
|
94
|
+
export const generate = (root, options = {}) => {
|
|
95
|
+
if (!isDict(root)) {
|
|
96
|
+
throw new GenerateError('Expected a parsed OpenAPI document, an object.', 'parse the JSON or YAML first and pass the result');
|
|
97
|
+
}
|
|
98
|
+
checkOptions(options);
|
|
99
|
+
checkVersion(root);
|
|
100
|
+
checkRefs(root);
|
|
101
|
+
const copy = structuredClone(root);
|
|
102
|
+
copy.components ||= {};
|
|
103
|
+
const ctx = createContext(copy, options, scanDiscriminators(copy));
|
|
104
|
+
const body = printFile(documentStatements(copy, ctx));
|
|
105
|
+
return typeof ctx.inject === 'string' && ctx.inject !== '' ? `${ctx.inject.trimEnd()}\n${body}` : body;
|
|
106
|
+
};
|
|
107
|
+
export { createContext, } from './gen-ts-context.js';
|
|
108
|
+
export { scanDiscriminators } from './gen-ts-discriminators.js';
|
|
109
|
+
export { isEnumSchema } from './gen-ts-document.js';
|
|
110
|
+
export { createRef, resolveRef } from './gen-ts-ref.js';
|