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,277 @@
|
|
|
1
|
+
import { NEVER, STRING, UNKNOWN, object, property, } from './gen-ts-ast.js';
|
|
2
|
+
import { jsDoc } from './gen-ts-comment.js';
|
|
3
|
+
import { dict, entries, isDict, list } from './gen-ts-dict.js';
|
|
4
|
+
import { enumStatement } from './gen-ts-enums.js';
|
|
5
|
+
import { childPath, createRef, refType } from './gen-ts-ref.js';
|
|
6
|
+
import { transformSchemaObject } from './gen-ts-schema.js';
|
|
7
|
+
import { newNameState, propertyName } from './gen-ts-text.js';
|
|
8
|
+
export const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
|
|
9
|
+
const never = (name, readonly) => property({ readonly, name, optional: true, type: NEVER });
|
|
10
|
+
const mediaType = (media, options) => {
|
|
11
|
+
const { schema } = dict(media);
|
|
12
|
+
return schema ? transformSchemaObject(schema, options) : UNKNOWN;
|
|
13
|
+
};
|
|
14
|
+
const contentMembers = (content, options, pathOf) => entries(content, options.ctx).map(([name, media]) => {
|
|
15
|
+
const next = { ...options, path: pathOf(name) };
|
|
16
|
+
return property({
|
|
17
|
+
readonly: options.ctx.immutable,
|
|
18
|
+
name: propertyName(name),
|
|
19
|
+
type: '$ref' in dict(media) ? transformSchemaObject(media, next) : mediaType(media, next),
|
|
20
|
+
comment: jsDoc(media),
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
export const transformHeaderObject = (header, options) => {
|
|
24
|
+
const { schema, content } = dict(header);
|
|
25
|
+
if (schema)
|
|
26
|
+
return transformSchemaObject(schema, options);
|
|
27
|
+
return content ? object(contentMembers(content, options, (name) => childPath(options.path, name))) : UNKNOWN;
|
|
28
|
+
};
|
|
29
|
+
export const transformRequestBodyObject = (requestBody, options) => {
|
|
30
|
+
const members = contentMembers(dict(requestBody).content, options, (name) => createRef([options.path, 'content', name]));
|
|
31
|
+
const content = members.length > 0 ? members : [never('"*/*"', false)];
|
|
32
|
+
return object([property({ readonly: options.ctx.immutable, name: 'content', type: object(content) })]);
|
|
33
|
+
};
|
|
34
|
+
const headerMember = (name, header, options) => {
|
|
35
|
+
const declared = dict(header);
|
|
36
|
+
const isReference = '$ref' in declared;
|
|
37
|
+
return property({
|
|
38
|
+
readonly: options.ctx.immutable,
|
|
39
|
+
name: propertyName(name),
|
|
40
|
+
optional: !(isReference || Boolean(declared.required)),
|
|
41
|
+
type: isReference
|
|
42
|
+
? refType(String(declared.$ref))
|
|
43
|
+
: transformHeaderObject(header, { ...options, path: createRef([options.path, 'headers', name]) }),
|
|
44
|
+
comment: jsDoc(header),
|
|
45
|
+
});
|
|
46
|
+
};
|
|
47
|
+
export const transformResponseObject = (response, options) => {
|
|
48
|
+
const { headers, content } = dict(response);
|
|
49
|
+
const { ctx } = options;
|
|
50
|
+
const anyHeader = { kind: 'index', readonly: ctx.immutable, parameter: 'name', parameterType: 'string', type: UNKNOWN };
|
|
51
|
+
const headerMembers = entries(headers, ctx).map(([name, header]) => headerMember(name, header, options));
|
|
52
|
+
const body = entries(content, ctx).map(([name, media]) => property({
|
|
53
|
+
readonly: ctx.immutable,
|
|
54
|
+
name: propertyName(name),
|
|
55
|
+
type: mediaType(media, { ...options, path: createRef([options.path, 'content', name]) }),
|
|
56
|
+
comment: jsDoc(media),
|
|
57
|
+
}));
|
|
58
|
+
return object([
|
|
59
|
+
property({ name: 'headers', type: object([...headerMembers, anyHeader]) }),
|
|
60
|
+
body.length > 0 ? property({ name: 'content', type: object(body) }) : never('content', false),
|
|
61
|
+
]);
|
|
62
|
+
};
|
|
63
|
+
const responsesType = (responses, options) => {
|
|
64
|
+
const members = entries(responses, options.ctx).map(([code, response]) => {
|
|
65
|
+
const declared = dict(response);
|
|
66
|
+
return property({
|
|
67
|
+
readonly: options.ctx.immutable,
|
|
68
|
+
name: propertyName(code),
|
|
69
|
+
type: '$ref' in declared
|
|
70
|
+
? refType(String(declared.$ref))
|
|
71
|
+
: transformResponseObject(response, { ...options, path: createRef([options.path, 'responses', code]) }),
|
|
72
|
+
comment: jsDoc(response),
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
return members.length > 0 ? object(members) : NEVER;
|
|
76
|
+
};
|
|
77
|
+
const resolved = (value, ctx) => {
|
|
78
|
+
const declared = dict(value);
|
|
79
|
+
return dict('$ref' in declared ? ctx.resolve(String(declared.$ref)) : declared);
|
|
80
|
+
};
|
|
81
|
+
const bracedNames = (path) => {
|
|
82
|
+
const names = [];
|
|
83
|
+
let open = path.indexOf('{');
|
|
84
|
+
while (open !== -1) {
|
|
85
|
+
const close = path.indexOf('}', open);
|
|
86
|
+
if (close === -1)
|
|
87
|
+
break;
|
|
88
|
+
const named = close > open + 1;
|
|
89
|
+
if (named)
|
|
90
|
+
names.push(path.slice(open + 1, close));
|
|
91
|
+
open = path.indexOf('{', named ? close : open + 1);
|
|
92
|
+
}
|
|
93
|
+
return names;
|
|
94
|
+
};
|
|
95
|
+
const impliedPathParameters = (declared, path) => {
|
|
96
|
+
const names = bracedNames(path);
|
|
97
|
+
const added = [];
|
|
98
|
+
for (const name of names) {
|
|
99
|
+
const isDeclared = [...declared, ...added].some((known) => known.resolved.in === 'path' && known.resolved.name === name);
|
|
100
|
+
const implied = { name, in: 'path', schema: { type: 'string' } };
|
|
101
|
+
if (!isDeclared)
|
|
102
|
+
added.push({ original: implied, resolved: implied });
|
|
103
|
+
}
|
|
104
|
+
return added;
|
|
105
|
+
};
|
|
106
|
+
const isDeprecated = ({ resolved: parameter }) => Boolean(parameter.deprecated) || Boolean(dict(parameter.schema).deprecated);
|
|
107
|
+
const groupIsOptional = (ref, location, ctx) => {
|
|
108
|
+
const operation = ref.split('/').slice(0, -2).join('/');
|
|
109
|
+
const listed = list(dict(ctx.resolve(operation)).parameters).map((item) => dict(isDict(item) && typeof item.$ref === 'string' ? ctx.resolve(item.$ref) : item));
|
|
110
|
+
return location !== 'path' && !listed.some((item) => item.in === location && item.required === true);
|
|
111
|
+
};
|
|
112
|
+
const parameterMember = ({ original, resolved: parameter }, options) => {
|
|
113
|
+
const inline = () => {
|
|
114
|
+
const path = createRef([options.path, 'parameters', String(parameter.in), String(parameter.name)]);
|
|
115
|
+
return parameter.schema ? transformSchemaObject(parameter.schema, { ...options, path }) : STRING;
|
|
116
|
+
};
|
|
117
|
+
return property({
|
|
118
|
+
readonly: options.ctx.immutable,
|
|
119
|
+
name: propertyName(parameter.name),
|
|
120
|
+
optional: parameter.in !== 'path' && !parameter.required,
|
|
121
|
+
type: '$ref' in original
|
|
122
|
+
? refType(String(original.$ref), { parameter, optionalGroup: groupIsOptional(String(original.$ref), parameter.in, options.ctx) })
|
|
123
|
+
: inline(),
|
|
124
|
+
comment: jsDoc(parameter),
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
const LOCATIONS = ['query', 'header', 'path', 'cookie'];
|
|
128
|
+
export const parametersMember = (parameters, options) => {
|
|
129
|
+
const { ctx } = options;
|
|
130
|
+
let all = list(parameters).map((original) => ({ original: dict(original), resolved: resolved(original, ctx) }));
|
|
131
|
+
if (ctx.generatePathParams && options.path !== undefined)
|
|
132
|
+
all.push(...impliedPathParameters(all, options.path));
|
|
133
|
+
if (ctx.alphabetize) {
|
|
134
|
+
all = all.toSorted((left, right) => String(left.resolved.name ?? '').localeCompare(String(right.resolved.name ?? ''), 'en'));
|
|
135
|
+
}
|
|
136
|
+
if (ctx.excludeDeprecated)
|
|
137
|
+
all = all.filter((parameter) => !isDeprecated(parameter));
|
|
138
|
+
const locations = LOCATIONS.map((location) => {
|
|
139
|
+
const members = all.filter((parameter) => parameter.resolved.in === location).map((parameter) => parameterMember(parameter, options));
|
|
140
|
+
return property({
|
|
141
|
+
readonly: ctx.immutable,
|
|
142
|
+
name: location,
|
|
143
|
+
optional: members.every((member) => member.optional),
|
|
144
|
+
type: members.length > 0 ? object(members) : NEVER,
|
|
145
|
+
});
|
|
146
|
+
});
|
|
147
|
+
return property({ readonly: ctx.immutable, name: 'parameters', type: object(locations) });
|
|
148
|
+
};
|
|
149
|
+
const requestBodyMember = (requestBody, options) => {
|
|
150
|
+
const { ctx } = options;
|
|
151
|
+
if (!requestBody)
|
|
152
|
+
return never('requestBody', ctx.immutable);
|
|
153
|
+
const declared = dict(requestBody);
|
|
154
|
+
const isReference = '$ref' in declared;
|
|
155
|
+
return property({
|
|
156
|
+
readonly: ctx.immutable,
|
|
157
|
+
name: 'requestBody',
|
|
158
|
+
optional: !resolved(requestBody, ctx).required,
|
|
159
|
+
type: isReference
|
|
160
|
+
? refType(String(declared.$ref))
|
|
161
|
+
: transformRequestBodyObject(requestBody, { ...options, path: createRef([options.path, 'requestBody']) }),
|
|
162
|
+
comment: jsDoc(requestBody),
|
|
163
|
+
});
|
|
164
|
+
};
|
|
165
|
+
export const transformOperationObject = (operation, options) => {
|
|
166
|
+
const { parameters, requestBody, responses } = dict(operation);
|
|
167
|
+
return [
|
|
168
|
+
parametersMember(parameters, options),
|
|
169
|
+
requestBodyMember(requestBody, options),
|
|
170
|
+
property({ readonly: options.ctx.immutable, name: 'responses', type: responsesType(responses, options) }),
|
|
171
|
+
];
|
|
172
|
+
};
|
|
173
|
+
const operationsInterface = (ctx) => {
|
|
174
|
+
const found = ctx.injectFooter.find((statement) => statement.name === 'operations');
|
|
175
|
+
if (found !== undefined)
|
|
176
|
+
return found;
|
|
177
|
+
const created = { kind: 'interface', name: 'operations', members: [] };
|
|
178
|
+
ctx.injectFooter.push(created);
|
|
179
|
+
return created;
|
|
180
|
+
};
|
|
181
|
+
const foldedParameters = (pathItem, operation, ctx) => {
|
|
182
|
+
const keyed = new Map();
|
|
183
|
+
for (const parameter of [...list(pathItem.parameters), ...list(operation.parameters)]) {
|
|
184
|
+
const { in: location, name } = resolved(parameter, ctx);
|
|
185
|
+
keyed.set(`${String(location)}-${String(name)}`, parameter);
|
|
186
|
+
}
|
|
187
|
+
return [...keyed.values()];
|
|
188
|
+
};
|
|
189
|
+
const operationType = (pathItem, method, options) => {
|
|
190
|
+
const operation = dict(pathItem[method]);
|
|
191
|
+
if ('$ref' in operation)
|
|
192
|
+
return refType(String(operation.$ref));
|
|
193
|
+
const { ctx } = options;
|
|
194
|
+
const folded = { ...operation, parameters: foldedParameters(pathItem, operation, ctx) };
|
|
195
|
+
const members = () => transformOperationObject(folded, { ...options, path: createRef([options.path, method]) });
|
|
196
|
+
if (!operation.operationId)
|
|
197
|
+
return object(members());
|
|
198
|
+
const id = String(operation.operationId).replaceAll('#', '/');
|
|
199
|
+
const operations = operationsInterface(ctx);
|
|
200
|
+
operations.members.push(property({ readonly: ctx.immutable, name: propertyName(id), type: object(members()) }));
|
|
201
|
+
return refType(createRef(['operations', id]));
|
|
202
|
+
};
|
|
203
|
+
export const transformPathItemObject = (pathItem, options) => {
|
|
204
|
+
const item = dict(pathItem);
|
|
205
|
+
const { ctx } = options;
|
|
206
|
+
const shared = parametersMember(item.parameters, { ...options, path: createRef([options.path, 'parameters']) });
|
|
207
|
+
const methods = METHODS.map((method) => {
|
|
208
|
+
const operation = item[method];
|
|
209
|
+
if (!operation || (ctx.excludeDeprecated && Boolean(resolved(operation, ctx).deprecated)))
|
|
210
|
+
return never(method, ctx.immutable);
|
|
211
|
+
return property({
|
|
212
|
+
readonly: ctx.immutable,
|
|
213
|
+
name: method,
|
|
214
|
+
type: operationType(item, method, options),
|
|
215
|
+
comment: jsDoc(operation),
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
return object([shared, ...methods]);
|
|
219
|
+
};
|
|
220
|
+
const TEMPLATE_TYPES = new Map([
|
|
221
|
+
['number', 'number'],
|
|
222
|
+
['integer', 'number'],
|
|
223
|
+
['boolean', 'boolean'],
|
|
224
|
+
]);
|
|
225
|
+
const pathParameters = (pathItem, ctx) => {
|
|
226
|
+
const operations = METHODS.map((method) => resolved(pathItem[method], ctx));
|
|
227
|
+
const declared = [pathItem, ...operations].flatMap((holder) => list(holder.parameters));
|
|
228
|
+
const found = new Map();
|
|
229
|
+
for (const parameter of declared.map((item) => resolved(item, ctx))) {
|
|
230
|
+
if (parameter.in === 'path')
|
|
231
|
+
found.set(parameter.name, parameter);
|
|
232
|
+
}
|
|
233
|
+
return found;
|
|
234
|
+
};
|
|
235
|
+
const templateType = (url, pathItem, ctx) => {
|
|
236
|
+
const names = bracedNames(url);
|
|
237
|
+
if (names.length === 0)
|
|
238
|
+
return undefined;
|
|
239
|
+
const parameters = pathParameters(pathItem, ctx);
|
|
240
|
+
let template = `\`${url}\``;
|
|
241
|
+
for (const name of names) {
|
|
242
|
+
const type = TEMPLATE_TYPES.get(dict(parameters.get(name)?.schema).type) ?? 'string';
|
|
243
|
+
template = template.replace(`{${name}}`, () => `\${${type}}`);
|
|
244
|
+
}
|
|
245
|
+
return template;
|
|
246
|
+
};
|
|
247
|
+
const pathMember = (url, pathItem, ctx) => {
|
|
248
|
+
const { immutable: readonly } = ctx;
|
|
249
|
+
if ('$ref' in pathItem) {
|
|
250
|
+
return property({ readonly, name: propertyName(url), type: refType(String(pathItem.$ref)), comment: jsDoc(pathItem) });
|
|
251
|
+
}
|
|
252
|
+
const type = transformPathItemObject(pathItem, { path: createRef(['paths', url]), ctx });
|
|
253
|
+
const template = ctx.pathParamsAsTypes ? templateType(url, pathItem, ctx) : undefined;
|
|
254
|
+
if (template === undefined)
|
|
255
|
+
return property({ readonly, name: propertyName(url), type });
|
|
256
|
+
return { kind: 'index', readonly, parameter: 'path', parameterType: template, type };
|
|
257
|
+
};
|
|
258
|
+
export const transformPathsObject = (paths, ctx) => object(entries(paths, ctx)
|
|
259
|
+
.filter((entry) => isDict(entry[1]))
|
|
260
|
+
.map(([url, pathItem]) => pathMember(url, pathItem, ctx)));
|
|
261
|
+
export const transformWebhooksObject = (webhooks, ctx) => object(entries(webhooks, ctx).map(([name, pathItem]) => property({
|
|
262
|
+
readonly: ctx.immutable,
|
|
263
|
+
name: propertyName(name),
|
|
264
|
+
type: transformPathItemObject(pathItem, { path: createRef(['webhooks', name]), ctx }),
|
|
265
|
+
})));
|
|
266
|
+
const NOT_NAME = /\{.*\}|:.*|[^a-zA-Z\d_]+/;
|
|
267
|
+
const pathName = (method, url) => `${method}${url}`
|
|
268
|
+
.split('/')
|
|
269
|
+
.map((part) => (part.charAt(0).toUpperCase() + part.slice(1)).replace(NOT_NAME, ''))
|
|
270
|
+
.join('');
|
|
271
|
+
const METHOD_NAMES = new Set(METHODS);
|
|
272
|
+
export const pathsEnum = (paths) => {
|
|
273
|
+
const operations = entries(paths).flatMap(([url, pathItem]) => Object.entries(dict(pathItem))
|
|
274
|
+
.filter(([method]) => METHOD_NAMES.has(method))
|
|
275
|
+
.map(([method, operation]) => ({ value: url, name: dict(operation).operationId || pathName(method, url) })));
|
|
276
|
+
return enumStatement({ name: 'ApiPaths', entries: operations }, newNameState());
|
|
277
|
+
};
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { quote } from './gen-ts-text.js';
|
|
2
|
+
const INDENT = ' ';
|
|
3
|
+
const TAB_STOP = INDENT.length;
|
|
4
|
+
const pad = (level) => INDENT.repeat(level);
|
|
5
|
+
const COMMENT_LINE = /\r\n|[\r\n\u2028\u2029]/;
|
|
6
|
+
const TEXT_ONWARDS = /[^ \t\v\f\u0085\u00A0\u1680\u2000-\u200B\u202F\u205F\u3000\uFEFF][^]*/;
|
|
7
|
+
const leadingWidth = (line) => {
|
|
8
|
+
let width = 0;
|
|
9
|
+
for (const unit of line.replace(TEXT_ONWARDS, '')) {
|
|
10
|
+
width += unit === '\t' ? TAB_STOP - (width % TAB_STOP) : 1;
|
|
11
|
+
}
|
|
12
|
+
return width;
|
|
13
|
+
};
|
|
14
|
+
const blockComment = (text, level) => {
|
|
15
|
+
const lines = `/*${text}*/`.split(COMMENT_LINE);
|
|
16
|
+
return lines.map((line) => ' '.repeat(level * TAB_STOP + leadingWidth(line)) + line.trim()).join('\n');
|
|
17
|
+
};
|
|
18
|
+
const LIST_KINDS = new Set(['union', 'intersection']);
|
|
19
|
+
const POSTFIX_OPERAND_KINDS = new Set(['union', 'intersection', 'readonly']);
|
|
20
|
+
const parenthesised = (type, level, kinds) => {
|
|
21
|
+
const text = printType(type, level);
|
|
22
|
+
return kinds.has(type.kind) ? `(${text})` : text;
|
|
23
|
+
};
|
|
24
|
+
const printList = (type, level) => {
|
|
25
|
+
const { kind, types } = type;
|
|
26
|
+
if (kind === 'tuple') {
|
|
27
|
+
const elements = types.map((element) => `${pad(level + 1)}${printType(element, level + 1)}`);
|
|
28
|
+
return `[\n${elements.join(',\n')}${elements.length > 0 ? '\n' : ''}${pad(level)}]`;
|
|
29
|
+
}
|
|
30
|
+
return types.map((member) => parenthesised(member, level, LIST_KINDS)).join(kind === 'union' ? ' | ' : ' & ');
|
|
31
|
+
};
|
|
32
|
+
const printWrap = (type, level) => {
|
|
33
|
+
const { kind, type: inner } = type;
|
|
34
|
+
if (kind === 'array')
|
|
35
|
+
return `${parenthesised(inner, level, POSTFIX_OPERAND_KINDS)}[]`;
|
|
36
|
+
if (kind === 'readonly')
|
|
37
|
+
return `readonly ${parenthesised(inner, level, POSTFIX_OPERAND_KINDS)}`;
|
|
38
|
+
return `...${printType(inner, level)}`;
|
|
39
|
+
};
|
|
40
|
+
export const printMember = (member, level) => {
|
|
41
|
+
const modifier = member.readonly ? 'readonly ' : '';
|
|
42
|
+
const type = printType(member.type, level);
|
|
43
|
+
if (member.kind === 'index') {
|
|
44
|
+
return `${pad(level)}${modifier}[${member.parameter}: ${member.parameterType}]: ${type};`;
|
|
45
|
+
}
|
|
46
|
+
const comment = member.comment === undefined ? '' : `${blockComment(member.comment, level)}\n`;
|
|
47
|
+
return `${comment}${pad(level)}${modifier}${member.name}${member.optional ? '?' : ''}: ${type};`;
|
|
48
|
+
};
|
|
49
|
+
const printMembers = (members, level) => members.map((member) => `${printMember(member, level + 1)}\n`).join('');
|
|
50
|
+
const PRINTERS = {
|
|
51
|
+
keyword: (type) => type.name,
|
|
52
|
+
literal: (type) => type.text,
|
|
53
|
+
raw: (type) => type.text,
|
|
54
|
+
union: printList,
|
|
55
|
+
intersection: printList,
|
|
56
|
+
tuple: printList,
|
|
57
|
+
array: printWrap,
|
|
58
|
+
readonly: printWrap,
|
|
59
|
+
rest: printWrap,
|
|
60
|
+
object: (type, level) => {
|
|
61
|
+
const { members } = type;
|
|
62
|
+
return members.length === 0 ? '{}' : `{\n${printMembers(members, level)}${pad(level)}}`;
|
|
63
|
+
},
|
|
64
|
+
reference: (type, level) => {
|
|
65
|
+
const { name, args } = type;
|
|
66
|
+
return args.length === 0 ? name : `${name}<${args.map((arg) => printType(arg, level)).join(', ')}>`;
|
|
67
|
+
},
|
|
68
|
+
access: (type, level) => {
|
|
69
|
+
const { type: target, index } = type;
|
|
70
|
+
return `${parenthesised(target, level, POSTFIX_OPERAND_KINDS)}[${index}]`;
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
export function printType(type, level) {
|
|
74
|
+
return PRINTERS[type.kind](type, level);
|
|
75
|
+
}
|
|
76
|
+
const printValue = (value) => (typeof value === 'number' ? String(value) : quote(value));
|
|
77
|
+
const printEnumMember = (member) => {
|
|
78
|
+
const comment = member.comment === undefined ? '' : `${INDENT}//${member.comment}\n`;
|
|
79
|
+
return `${comment}${INDENT}${member.name} = ${printValue(member.value)}`;
|
|
80
|
+
};
|
|
81
|
+
const printValues = (statement) => {
|
|
82
|
+
const values = statement.values.map((value) => printValue(value)).join(', ');
|
|
83
|
+
return `export const ${statement.name}: ${printType(statement.type, 0)} = [${values}];`;
|
|
84
|
+
};
|
|
85
|
+
const printStatement = (statement) => {
|
|
86
|
+
switch (statement.kind) {
|
|
87
|
+
case 'interface': {
|
|
88
|
+
return `export interface ${statement.name} {\n${printMembers(statement.members, 0)}}`;
|
|
89
|
+
}
|
|
90
|
+
case 'alias': {
|
|
91
|
+
return `export type ${statement.name} = ${printType(statement.type, 0)};`;
|
|
92
|
+
}
|
|
93
|
+
case 'enum': {
|
|
94
|
+
const members = statement.members.map((member) => printEnumMember(member)).join(',\n');
|
|
95
|
+
return `export enum ${statement.name} {\n${members}${members === '' ? '' : '\n'}}`;
|
|
96
|
+
}
|
|
97
|
+
case 'values': {
|
|
98
|
+
return printValues(statement);
|
|
99
|
+
}
|
|
100
|
+
default: {
|
|
101
|
+
return statement.text;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
const isMember = (node) => node.kind === 'property';
|
|
106
|
+
const STATEMENT_KINDS = new Set(['interface', 'alias', 'enum', 'values', 'helper']);
|
|
107
|
+
const isStatement = (node) => STATEMENT_KINDS.has(node.kind);
|
|
108
|
+
const printNode = (node) => {
|
|
109
|
+
if (isMember(node))
|
|
110
|
+
return printMember(node, 0);
|
|
111
|
+
return isStatement(node) ? printStatement(node) : printType(node, 0);
|
|
112
|
+
};
|
|
113
|
+
export const printFile = (nodes) => nodes.map((node) => `${printNode(node)}\n`).join('');
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* References: reading a `$ref`, writing the pointer of the node being transformed, and turning a
|
|
3
|
+
* pointer into the indexed access that names the same thing in the generated types.
|
|
4
|
+
*/
|
|
5
|
+
import { type TypeNode } from './gen-ts-ast.js';
|
|
6
|
+
import { type Dict } from './gen-ts-dict.js';
|
|
7
|
+
/** The tokens after `#/`. A string with no `#/` has none. */
|
|
8
|
+
export declare const pointerOf: (ref: string) => string[];
|
|
9
|
+
/** Join parts into one pointer. A part that is itself a pointer contributes its tokens. */
|
|
10
|
+
export declare const createRef: (parts: readonly (string | number | undefined)[]) => string;
|
|
11
|
+
/** The last token of a pointer, with `/` escaped the way the next pointer segment would be. */
|
|
12
|
+
export declare const childPath: (path: string | undefined, token: string) => string;
|
|
13
|
+
/** The tokens of the pointer a transform stands at; a transform given no path stands nowhere. */
|
|
14
|
+
export declare const pathTokens: (path: string | undefined) => string[];
|
|
15
|
+
/** The reference a chain ends on: `ref` itself unless what it names is another `$ref`, followed until it is not. */
|
|
16
|
+
export declare const lastRef: (document: unknown, ref: string, visited?: ReadonlySet<string>) => string;
|
|
17
|
+
/** What a local reference points at, following references to references; `undefined` when it leads nowhere. */
|
|
18
|
+
export declare const resolveRef: (document: unknown, ref: string, visited?: ReadonlySet<string>) => unknown;
|
|
19
|
+
export interface RefOptions {
|
|
20
|
+
/** Wrap the root in `FlattenedDeepRequired<>`. */
|
|
21
|
+
readonly deep?: boolean;
|
|
22
|
+
/** Segments to reach through `Extract<T, { segment: unknown }>`, for members only some variants have. */
|
|
23
|
+
readonly extract?: ReadonlySet<string>;
|
|
24
|
+
/** The parameter a reference into a `parameters` array points at: it is indexed by location and name. */
|
|
25
|
+
readonly parameter?: Dict | undefined;
|
|
26
|
+
/** That parameter's location group is optional in the operation it points into (`query?: {…}`). */
|
|
27
|
+
readonly optionalGroup?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** A reference as an indexed access, e.g. `components["schemas"]["Pet"]`. */
|
|
30
|
+
export declare const refType: (ref: string, options?: RefOptions) => TypeNode;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { UNKNOWN, access, object, property, reference } from './gen-ts-ast.js';
|
|
2
|
+
import { dict, isDict } from './gen-ts-dict.js';
|
|
3
|
+
import { quote } from './gen-ts-text.js';
|
|
4
|
+
const unescape = (token) => decodeURIComponent(token.replaceAll('~1', '/').replaceAll('~0', '~'));
|
|
5
|
+
const escape = (token) => token.replaceAll('~', '~0').replaceAll('/', '~1');
|
|
6
|
+
export const pointerOf = (ref) => {
|
|
7
|
+
const [, pointer = ''] = ref.split('#/');
|
|
8
|
+
return pointer
|
|
9
|
+
.split('/')
|
|
10
|
+
.map((token) => unescape(token))
|
|
11
|
+
.filter((token) => token !== '');
|
|
12
|
+
};
|
|
13
|
+
export const createRef = (parts) => {
|
|
14
|
+
let pointer = '#';
|
|
15
|
+
for (const part of parts) {
|
|
16
|
+
if (part === undefined || part === '')
|
|
17
|
+
continue;
|
|
18
|
+
const text = String(part);
|
|
19
|
+
const tokens = pointerOf(text);
|
|
20
|
+
pointer += tokens.length > 0 ? tokens.map((token) => `/${escape(token)}`).join('') : `/${escape(text)}`;
|
|
21
|
+
}
|
|
22
|
+
return pointer;
|
|
23
|
+
};
|
|
24
|
+
export const childPath = (path, token) => `${path ?? '#'}/${escape(token)}`;
|
|
25
|
+
export const pathTokens = (path) => (path === undefined ? [] : pointerOf(path));
|
|
26
|
+
const memberAt = (node, token) => typeof node === 'object' && node !== null && Object.hasOwn(node, token) ? node[token] : undefined;
|
|
27
|
+
const follow = (document, ref) => {
|
|
28
|
+
let node = document;
|
|
29
|
+
for (const token of pointerOf(ref))
|
|
30
|
+
node = memberAt(node, token);
|
|
31
|
+
return node || undefined;
|
|
32
|
+
};
|
|
33
|
+
export const lastRef = (document, ref, visited = new Set([ref])) => {
|
|
34
|
+
const node = follow(document, ref);
|
|
35
|
+
if (!isDict(node) || typeof node.$ref !== 'string' || !node.$ref.startsWith('#/') || visited.has(node.$ref))
|
|
36
|
+
return ref;
|
|
37
|
+
return lastRef(document, node.$ref, new Set([...visited, node.$ref]));
|
|
38
|
+
};
|
|
39
|
+
export const resolveRef = (document, ref, visited = new Set()) => {
|
|
40
|
+
if (pointerOf(ref).length === 0)
|
|
41
|
+
return undefined;
|
|
42
|
+
const node = follow(document, ref);
|
|
43
|
+
if (!isDict(node) || typeof node.$ref !== 'string' || node.$ref === '')
|
|
44
|
+
return node;
|
|
45
|
+
return visited.has(node.$ref) ? undefined : resolveRef(document, node.$ref, new Set([...visited, node.$ref]));
|
|
46
|
+
};
|
|
47
|
+
const indexed = (type, segment) => access(type, typeof segment === 'number' ? String(segment) : quote(String(segment)));
|
|
48
|
+
const extracted = (type, segment) => indexed(reference('Extract', [type, object([property({ name: segment, type: UNKNOWN })])]), segment);
|
|
49
|
+
const ROOT_SEGMENTS = 3;
|
|
50
|
+
const parameterAccess = (type, parameter, optionalGroup) => {
|
|
51
|
+
const group = indexed(type, parameter.in);
|
|
52
|
+
return indexed(optionalGroup ? reference('NonNullable', [group]) : group, parameter.name);
|
|
53
|
+
};
|
|
54
|
+
export const refType = (ref, options = {}) => {
|
|
55
|
+
const [root, ...segments] = pointerOf(ref);
|
|
56
|
+
if (root === undefined) {
|
|
57
|
+
throw new Error(`Error parsing $ref: ${ref}. Is this a valid $ref? fix: point it at a value inside the document, as \`#/…\``);
|
|
58
|
+
}
|
|
59
|
+
const parameter = dict(options.parameter);
|
|
60
|
+
const isParameter = !parameter.$ref && Boolean(parameter.in);
|
|
61
|
+
let type = reference(options.deep === true ? `FlattenedDeepRequired<${root}>` : root);
|
|
62
|
+
for (const [index, segment] of segments.entries()) {
|
|
63
|
+
if (index < ROOT_SEGMENTS - 1)
|
|
64
|
+
type = indexed(type, segment);
|
|
65
|
+
else if (segment === 'properties')
|
|
66
|
+
continue;
|
|
67
|
+
else if (segment === 'schema' && segments[index - 2] === 'content')
|
|
68
|
+
continue;
|
|
69
|
+
else if (isParameter && index === segments.length - 1)
|
|
70
|
+
type = parameterAccess(type, parameter, options.optionalGroup === true);
|
|
71
|
+
else
|
|
72
|
+
type = options.extract?.has(segment) ? extracted(type, segment) : indexed(type, segment);
|
|
73
|
+
}
|
|
74
|
+
return type;
|
|
75
|
+
};
|