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,212 @@
|
|
|
1
|
+
const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
const list = (value) => (Array.isArray(value) ? value.filter(isDict) : []);
|
|
3
|
+
const indexed = (value) => (Array.isArray(value) ? value.flatMap((each, index) => (isDict(each) ? [[index, each]] : [])) : []);
|
|
4
|
+
const text = (value) => (typeof value === 'string' ? value : undefined);
|
|
5
|
+
export class ProtobufError extends Error {
|
|
6
|
+
constructor(reason, fix) {
|
|
7
|
+
super(`not a buf image: ${reason}. fix: ${fix}`);
|
|
8
|
+
this.name = 'ProtobufError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const isFile = (file) => isDict(file) && text(file.name)?.endsWith('.proto') === true;
|
|
12
|
+
export const detect = (document) => isDict(document) && Array.isArray(document.file) && document.file.length > 0 && document.file.every(isFile);
|
|
13
|
+
const INT = { type: 'integer' };
|
|
14
|
+
const LONG = { type: ['string', 'integer'] };
|
|
15
|
+
const SCALARS = {
|
|
16
|
+
TYPE_DOUBLE: { type: 'number' },
|
|
17
|
+
TYPE_FLOAT: { type: 'number' },
|
|
18
|
+
TYPE_INT32: INT,
|
|
19
|
+
TYPE_SINT32: INT,
|
|
20
|
+
TYPE_SFIXED32: INT,
|
|
21
|
+
TYPE_UINT32: INT,
|
|
22
|
+
TYPE_FIXED32: INT,
|
|
23
|
+
TYPE_INT64: LONG,
|
|
24
|
+
TYPE_SINT64: LONG,
|
|
25
|
+
TYPE_SFIXED64: LONG,
|
|
26
|
+
TYPE_UINT64: LONG,
|
|
27
|
+
TYPE_FIXED64: LONG,
|
|
28
|
+
TYPE_BOOL: { type: 'boolean' },
|
|
29
|
+
TYPE_STRING: { type: 'string' },
|
|
30
|
+
TYPE_BYTES: { type: 'string', contentEncoding: 'base64' },
|
|
31
|
+
};
|
|
32
|
+
const nullable = (type) => ({ type: [...(typeof type === 'string' ? [type] : type), 'null'] });
|
|
33
|
+
const WELL_KNOWN = {
|
|
34
|
+
'.google.protobuf.Timestamp': { type: 'string', format: 'date-time' },
|
|
35
|
+
'.google.protobuf.Duration': { type: 'string', pattern: String.raw `^-?\d+(\.\d+)?s$` },
|
|
36
|
+
'.google.protobuf.FieldMask': { type: 'string' },
|
|
37
|
+
'.google.protobuf.Struct': { type: 'object' },
|
|
38
|
+
'.google.protobuf.Value': {},
|
|
39
|
+
'.google.protobuf.ListValue': { type: 'array' },
|
|
40
|
+
'.google.protobuf.NullValue': { type: 'null' },
|
|
41
|
+
'.google.protobuf.Empty': { type: 'object' },
|
|
42
|
+
'.google.protobuf.Any': { type: 'object', properties: { '@type': { type: 'string' } }, required: ['@type'] },
|
|
43
|
+
'.google.protobuf.DoubleValue': nullable('number'),
|
|
44
|
+
'.google.protobuf.FloatValue': nullable('number'),
|
|
45
|
+
'.google.protobuf.Int32Value': nullable('integer'),
|
|
46
|
+
'.google.protobuf.UInt32Value': nullable('integer'),
|
|
47
|
+
'.google.protobuf.Int64Value': nullable(['string', 'integer']),
|
|
48
|
+
'.google.protobuf.UInt64Value': nullable(['string', 'integer']),
|
|
49
|
+
'.google.protobuf.BoolValue': nullable('boolean'),
|
|
50
|
+
'.google.protobuf.StringValue': nullable('string'),
|
|
51
|
+
'.google.protobuf.BytesValue': { type: ['string', 'null'], contentEncoding: 'base64' },
|
|
52
|
+
};
|
|
53
|
+
const declarationsOf = (files) => {
|
|
54
|
+
const found = new Map();
|
|
55
|
+
const walk = (scope, node, pointer, messages) => {
|
|
56
|
+
for (const each of list(node.enumType))
|
|
57
|
+
found.set(`${scope}.${String(each.name)}`, { isEnum: true, node: each });
|
|
58
|
+
for (const [index, each] of indexed(node[messages])) {
|
|
59
|
+
const name = `${scope}.${String(each.name)}`;
|
|
60
|
+
const at = `${pointer}/${messages}/${index}`;
|
|
61
|
+
found.set(name, { isEnum: false, node: each, pointer: at });
|
|
62
|
+
walk(name, each, at, 'nestedType');
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
for (const [index, file] of files.entries()) {
|
|
66
|
+
const pkg = text(file.package);
|
|
67
|
+
walk(pkg === undefined || pkg === '' ? '' : `.${pkg}`, file, `/file/${index}`, 'messageType');
|
|
68
|
+
}
|
|
69
|
+
return found;
|
|
70
|
+
};
|
|
71
|
+
const defKey = (name) => name.slice(1);
|
|
72
|
+
const refTo = (name) => ({ $ref: `#/$defs/${defKey(name)}` });
|
|
73
|
+
class Schemas {
|
|
74
|
+
declared;
|
|
75
|
+
findings = [];
|
|
76
|
+
reached = new Set();
|
|
77
|
+
constructor(declared) {
|
|
78
|
+
this.declared = declared;
|
|
79
|
+
}
|
|
80
|
+
payload(name, pointer) {
|
|
81
|
+
return this.typeOf(name, pointer, this.reached);
|
|
82
|
+
}
|
|
83
|
+
defs() {
|
|
84
|
+
const defs = new Map();
|
|
85
|
+
const seen = new Set(this.reached);
|
|
86
|
+
const todo = [...this.reached];
|
|
87
|
+
for (let next = todo.pop(); next !== undefined; next = todo.pop()) {
|
|
88
|
+
const def = this.definition(next);
|
|
89
|
+
defs.set(defKey(next), def.schema);
|
|
90
|
+
for (const ref of def.refs) {
|
|
91
|
+
if (!seen.has(ref)) {
|
|
92
|
+
seen.add(ref);
|
|
93
|
+
todo.push(ref);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return Object.fromEntries(defs);
|
|
98
|
+
}
|
|
99
|
+
typeOf(name, pointer, refs) {
|
|
100
|
+
const known = WELL_KNOWN[name];
|
|
101
|
+
if (known !== undefined) {
|
|
102
|
+
if (name === '.google.protobuf.Any')
|
|
103
|
+
this.finding('any-payload-unread', pointer, `\`${defKey(name)}\` is read as its \`@type\` only: the message it wraps is not known from the contract`, 'name the wrapped type in a field of its own, or accept that it is not checked');
|
|
104
|
+
return known;
|
|
105
|
+
}
|
|
106
|
+
if (!this.declared.has(name)) {
|
|
107
|
+
this.finding('type-not-found', pointer, `\`${defKey(name)}\` is not in the image, so it is read as anything`, 'build the image with its imports (`buf build` includes them unless `--exclude-imports` is given)');
|
|
108
|
+
return {};
|
|
109
|
+
}
|
|
110
|
+
refs.add(name);
|
|
111
|
+
return refTo(name);
|
|
112
|
+
}
|
|
113
|
+
definition(name) {
|
|
114
|
+
const declared = this.declared.get(name);
|
|
115
|
+
const refs = new Set();
|
|
116
|
+
const schema = declared.isEnum ? { enum: list(declared.node.value).map((value) => String(value.name)) } : this.message(name, declared, refs);
|
|
117
|
+
return { schema, refs };
|
|
118
|
+
}
|
|
119
|
+
message(name, { node, pointer }, refs) {
|
|
120
|
+
const properties = new Map();
|
|
121
|
+
const required = [];
|
|
122
|
+
const oneofs = new Map();
|
|
123
|
+
for (const [index, field] of indexed(node.field)) {
|
|
124
|
+
const key = text(field.jsonName) ?? String(field.name);
|
|
125
|
+
properties.set(key, { ...this.field(field, `${pointer}/field/${index}`, refs), 'x-protobuf-field': field.number });
|
|
126
|
+
if (field.label === 'LABEL_REQUIRED')
|
|
127
|
+
required.push(key);
|
|
128
|
+
if (typeof field.oneofIndex === 'number' && field.proto3Optional !== true)
|
|
129
|
+
oneofs.set(field.oneofIndex, [...(oneofs.get(field.oneofIndex) ?? []), key]);
|
|
130
|
+
}
|
|
131
|
+
return { type: 'object', properties: Object.fromEntries(properties), ...(required.length === 0 ? {} : { required }), ...this.oneofsOf(name, node, pointer, oneofs) };
|
|
132
|
+
}
|
|
133
|
+
oneofsOf(name, node, pointer, oneofs) {
|
|
134
|
+
const decls = new Map(indexed(node.oneofDecl));
|
|
135
|
+
const groups = [...oneofs].map(([index, members]) => {
|
|
136
|
+
const group = String(decls.get(index)?.name ?? index);
|
|
137
|
+
this.finding('oneof-not-enforced', `${pointer}/oneofDecl/${index}`, `\`${defKey(name)}.${group}\` holds at most one of ${members.map((member) => `\`${member}\``).join(', ')}; the schema does not enforce that`, 'check the choice in code, or read the group from `x-protobuf-oneof`');
|
|
138
|
+
return [group, members];
|
|
139
|
+
});
|
|
140
|
+
return groups.length === 0 ? {} : { 'x-protobuf-oneof': Object.fromEntries(groups) };
|
|
141
|
+
}
|
|
142
|
+
field(field, pointer, refs) {
|
|
143
|
+
const repeated = field.label === 'LABEL_REPEATED';
|
|
144
|
+
const entry = this.mapEntry(field);
|
|
145
|
+
if (repeated && entry !== undefined) {
|
|
146
|
+
const value = list(entry.field).find((each) => each.number === 2) ?? {};
|
|
147
|
+
return { type: 'object', additionalProperties: this.single(value, pointer, refs) };
|
|
148
|
+
}
|
|
149
|
+
const one = this.single(field, pointer, refs);
|
|
150
|
+
return repeated ? { type: 'array', items: one } : one;
|
|
151
|
+
}
|
|
152
|
+
mapEntry(field) {
|
|
153
|
+
const node = this.declared.get(String(field.typeName))?.node;
|
|
154
|
+
const options = node?.options;
|
|
155
|
+
return isDict(options) && options.mapEntry === true ? node : undefined;
|
|
156
|
+
}
|
|
157
|
+
single(field, pointer, refs) {
|
|
158
|
+
const scalar = SCALARS[String(field.type)];
|
|
159
|
+
if (scalar !== undefined)
|
|
160
|
+
return scalar;
|
|
161
|
+
if (field.type === 'TYPE_GROUP')
|
|
162
|
+
this.finding('group-read-as-message', pointer, `\`${String(field.name)}\` is a proto2 group, read as the message it declares`, 'replace the group with a message field; groups are deprecated');
|
|
163
|
+
return this.typeOf(String(field.typeName), pointer, refs);
|
|
164
|
+
}
|
|
165
|
+
finding(code, pointer, message, fix) {
|
|
166
|
+
this.findings.push({ code, pointer, message, fix });
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
const streamFinding = (id, side, pointer) => ({
|
|
170
|
+
code: 'stream-read-as-message',
|
|
171
|
+
pointer,
|
|
172
|
+
message: `\`${id}\` streams its ${side}: one message of it is read`,
|
|
173
|
+
fix: 'diff and lint judge the message; a change to streaming itself is buf\'s to judge (`diff --level`)',
|
|
174
|
+
});
|
|
175
|
+
const operationsOf = (file, index, schemas, findings) => {
|
|
176
|
+
const pkg = text(file.package);
|
|
177
|
+
return indexed(file.service).flatMap(([at, service]) => indexed(service.method).map(([position, method]) => {
|
|
178
|
+
const id = [pkg, service.name, method.name].filter((part) => part !== undefined && part !== '').join('.');
|
|
179
|
+
const source = `/file/${index}/service/${at}/method/${position}`;
|
|
180
|
+
if (method.clientStreaming === true)
|
|
181
|
+
findings.push(streamFinding(id, 'request', source));
|
|
182
|
+
if (method.serverStreaming === true)
|
|
183
|
+
findings.push(streamFinding(id, 'response', source));
|
|
184
|
+
return {
|
|
185
|
+
id,
|
|
186
|
+
source,
|
|
187
|
+
payloads: [
|
|
188
|
+
{ name: 'request', direction: 'request', required: true, schema: schemas.payload(String(method.inputType), `${source}/inputType`) },
|
|
189
|
+
{ name: 'response', direction: 'response', required: true, schema: schemas.payload(String(method.outputType), `${source}/outputType`) },
|
|
190
|
+
],
|
|
191
|
+
};
|
|
192
|
+
}));
|
|
193
|
+
};
|
|
194
|
+
const isImport = (file) => isDict(file.bufExtension) && file.bufExtension.isImport === true;
|
|
195
|
+
export const read = (document) => {
|
|
196
|
+
if (!detect(document))
|
|
197
|
+
throw new ProtobufError('it has no `file` list of `.proto` file descriptors', 'pass the JSON image `buf build -o image.json` writes, or a `.proto` file for buf to build');
|
|
198
|
+
const files = list(document.file);
|
|
199
|
+
const schemas = new Schemas(declarationsOf(files));
|
|
200
|
+
const findings = [];
|
|
201
|
+
const operations = files.flatMap((file, index) => (isImport(file) ? [] : operationsOf(file, index, schemas, findings)));
|
|
202
|
+
const withDefs = { ...document, $defs: schemas.defs() };
|
|
203
|
+
if (operations.length === 0)
|
|
204
|
+
findings.push({ code: 'no-service', pointer: '', message: 'the image declares no service, so there is no operation to read', fix: 'build the image from the files that declare your services' });
|
|
205
|
+
return { format: 'protobuf', document: withDefs, operations, findings: [...findings, ...schemas.findings] };
|
|
206
|
+
};
|
|
207
|
+
export const adapter = Object.freeze({
|
|
208
|
+
name: 'protobuf',
|
|
209
|
+
description: 'protobuf, as the JSON image `buf build -o image.json` writes: one operation per RPC method',
|
|
210
|
+
detect,
|
|
211
|
+
read,
|
|
212
|
+
});
|
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { pointerGet } from './core/resolve.js';
|
|
2
|
+
import { read as readOpenApi } from './openapi.js';
|
|
3
|
+
const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
4
|
+
const dict = (value) => (isDict(value) ? value : {});
|
|
5
|
+
const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
|
|
6
|
+
const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch'];
|
|
7
|
+
const VALUE_KEYWORDS = new Set([
|
|
8
|
+
'type',
|
|
9
|
+
'format',
|
|
10
|
+
'items',
|
|
11
|
+
'collectionFormat',
|
|
12
|
+
'default',
|
|
13
|
+
'maximum',
|
|
14
|
+
'exclusiveMaximum',
|
|
15
|
+
'minimum',
|
|
16
|
+
'exclusiveMinimum',
|
|
17
|
+
'maxLength',
|
|
18
|
+
'minLength',
|
|
19
|
+
'pattern',
|
|
20
|
+
'maxItems',
|
|
21
|
+
'minItems',
|
|
22
|
+
'uniqueItems',
|
|
23
|
+
'enum',
|
|
24
|
+
'multipleOf',
|
|
25
|
+
'x-nullable',
|
|
26
|
+
]);
|
|
27
|
+
const SUBSCHEMA = new Set(['items', 'additionalProperties', 'allOf', 'anyOf', 'oneOf', 'not']);
|
|
28
|
+
const DEFINITIONS = '#/definitions/';
|
|
29
|
+
const QUERY_STYLES = new Map([
|
|
30
|
+
['ssv', { style: 'spaceDelimited', explode: false }],
|
|
31
|
+
['pipes', { style: 'pipeDelimited', explode: false }],
|
|
32
|
+
['multi', { style: 'form', explode: true }],
|
|
33
|
+
]);
|
|
34
|
+
const FLOWS = { implicit: 'implicit', password: 'password', application: 'clientCredentials', accessCode: 'authorizationCode' };
|
|
35
|
+
const BOUNDS = [
|
|
36
|
+
['exclusiveMaximum', 'maximum'],
|
|
37
|
+
['exclusiveMinimum', 'minimum'],
|
|
38
|
+
];
|
|
39
|
+
const FORM_TYPES = new Set(['application/x-www-form-urlencoded', 'multipart/form-data']);
|
|
40
|
+
export class Swagger2Error extends Error {
|
|
41
|
+
constructor(reason, fix) {
|
|
42
|
+
super(`not a Swagger 2.0 document: ${reason}. fix: ${fix}`);
|
|
43
|
+
this.name = 'Swagger2Error';
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export const detect = (document) => isDict(document) && (document.swagger === '2.0' || document.swagger === 2);
|
|
47
|
+
const partition = (holder) => {
|
|
48
|
+
const value = {};
|
|
49
|
+
const rest = {};
|
|
50
|
+
for (const [key, entry] of Object.entries(holder))
|
|
51
|
+
(VALUE_KEYWORDS.has(key) ? value : rest)[key] = entry;
|
|
52
|
+
return { value, rest };
|
|
53
|
+
};
|
|
54
|
+
const createConverter = (root, report) => {
|
|
55
|
+
const bound = (out, at, [exclusive, limit]) => {
|
|
56
|
+
const { [exclusive]: flag, [limit]: value } = out;
|
|
57
|
+
if (typeof flag !== 'boolean')
|
|
58
|
+
return;
|
|
59
|
+
const excluded = flag && typeof value === 'number';
|
|
60
|
+
report('exclusive-bound', `${at}/${exclusive}`, excluded
|
|
61
|
+
? `\`${exclusive}: true\` is written as \`${exclusive}: ${String(value)}\``
|
|
62
|
+
: `\`${exclusive}: ${String(flag)}\` without a \`${limit}\` excludes nothing, and is dropped`, 'nothing to do: OpenAPI 3.1 states the excluded bound as a number');
|
|
63
|
+
delete out[excluded ? limit : exclusive];
|
|
64
|
+
if (excluded)
|
|
65
|
+
out[exclusive] = value;
|
|
66
|
+
};
|
|
67
|
+
const nullable = (out, at) => {
|
|
68
|
+
const flag = out['x-nullable'];
|
|
69
|
+
delete out['x-nullable'];
|
|
70
|
+
report('x-nullable', `${at}/x-nullable`, `\`x-nullable: ${String(flag)}\` is written as a \`null\` type`, 'nothing to do: OpenAPI 3.1 states nullability in `type`');
|
|
71
|
+
if (flag !== true)
|
|
72
|
+
return out;
|
|
73
|
+
const withEnum = Array.isArray(out.enum) ? { ...out, enum: [...out.enum, null] } : out;
|
|
74
|
+
return typeof out.type === 'string' ? { ...withEnum, type: [out.type, 'null'] } : { anyOf: [withEnum, { type: 'null' }] };
|
|
75
|
+
};
|
|
76
|
+
const schema = (node, at) => {
|
|
77
|
+
if (Array.isArray(node))
|
|
78
|
+
return node.map((item, index) => schema(item, `${at}/${String(index)}`));
|
|
79
|
+
if (!isDict(node))
|
|
80
|
+
return node;
|
|
81
|
+
const out = {};
|
|
82
|
+
for (const [key, value] of Object.entries(node)) {
|
|
83
|
+
const where = `${at}/${token(key)}`;
|
|
84
|
+
if (key === 'properties')
|
|
85
|
+
out[key] = Object.fromEntries(Object.entries(dict(value)).map(([name, child]) => [name, schema(child, `${where}/${token(name)}`)]));
|
|
86
|
+
else
|
|
87
|
+
out[key] = SUBSCHEMA.has(key) ? schema(value, where) : value;
|
|
88
|
+
}
|
|
89
|
+
if (typeof out.$ref === 'string' && out.$ref.startsWith(DEFINITIONS))
|
|
90
|
+
out.$ref = `#/components/schemas/${out.$ref.slice(DEFINITIONS.length)}`;
|
|
91
|
+
else if (typeof out.$ref === 'string' && !out.$ref.startsWith('#'))
|
|
92
|
+
report('ref-external', `${at}/$ref`, `\`${out.$ref}\` is in another file and is not read`, 'bundle the document into one file first');
|
|
93
|
+
return translate(out, at);
|
|
94
|
+
};
|
|
95
|
+
const translate = (out, at) => {
|
|
96
|
+
if (out.type === 'file') {
|
|
97
|
+
out.type = 'string';
|
|
98
|
+
out.contentMediaType = 'application/octet-stream';
|
|
99
|
+
report('file-type', `${at}/type`, '`type: file` is written as `type: string, contentMediaType: application/octet-stream`', 'nothing to do: OpenAPI 3.1 has no file type');
|
|
100
|
+
}
|
|
101
|
+
if (typeof out.discriminator === 'string') {
|
|
102
|
+
out.discriminator = { propertyName: out.discriminator };
|
|
103
|
+
report('discriminator', `${at}/discriminator`, 'a string `discriminator` is written as `{ propertyName }`', 'nothing to do: OpenAPI 3 names the property in an object');
|
|
104
|
+
}
|
|
105
|
+
if (out.collectionFormat !== undefined) {
|
|
106
|
+
report('collection-format', `${at}/collectionFormat`, `\`collectionFormat: ${String(out.collectionFormat)}\` here has no OpenAPI 3 equivalent, and is dropped`, 'describe the nested format in `description`');
|
|
107
|
+
delete out.collectionFormat;
|
|
108
|
+
}
|
|
109
|
+
for (const pair of BOUNDS)
|
|
110
|
+
bound(out, at, pair);
|
|
111
|
+
return 'x-nullable' in out ? nullable(out, at) : out;
|
|
112
|
+
};
|
|
113
|
+
const follow = (value, at) => {
|
|
114
|
+
if (!isDict(value) || typeof value.$ref !== 'string')
|
|
115
|
+
return isDict(value) ? { node: value, at } : undefined;
|
|
116
|
+
const ref = value.$ref;
|
|
117
|
+
if (!ref.startsWith('#')) {
|
|
118
|
+
report('ref-external', `${at}/$ref`, `\`${ref}\` is in another file and is not read`, 'bundle the document into one file first');
|
|
119
|
+
return undefined;
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
return { node: dict(pointerGet(root, ref)), at: ref };
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
report('ref-broken', `${at}/$ref`, error.message.replace(/\. fix: .*/, ''), 'point the reference at a value the document defines');
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
const parameter = (declared, at) => {
|
|
130
|
+
const { value, rest } = partition(declared);
|
|
131
|
+
const format = value.collectionFormat;
|
|
132
|
+
delete value.collectionFormat;
|
|
133
|
+
const out = { ...rest, schema: schema(value, at) };
|
|
134
|
+
if (value.type !== 'array' && format === undefined)
|
|
135
|
+
return out;
|
|
136
|
+
const style = declared.in === 'query' ? (QUERY_STYLES.get(format) ?? { style: 'form', explode: false }) : { style: 'simple', explode: false };
|
|
137
|
+
report('collection-format', `${at}/collectionFormat`, `\`collectionFormat: ${String(format ?? 'csv')}\` is written as \`style: ${style.style}, explode: ${String(style.explode)}\``, format === 'tsv' ? 'tab-separated values have no OpenAPI 3 style: use `ssv`, `pipes`, `csv` or `multi`' : 'nothing to do: OpenAPI 3 states the array format in `style`');
|
|
138
|
+
return { ...out, ...style };
|
|
139
|
+
};
|
|
140
|
+
return { schema, follow, parameter };
|
|
141
|
+
};
|
|
142
|
+
const mediaTypes = (context, operation, key, at) => {
|
|
143
|
+
for (const declared of [operation[key], context.root[key]]) {
|
|
144
|
+
if (Array.isArray(declared) && declared.length > 0)
|
|
145
|
+
return declared.filter((type) => typeof type === 'string');
|
|
146
|
+
}
|
|
147
|
+
context.report(`${key}-assumed`, at, `no \`${key}\` is declared here or for the document, so \`application/json\` is assumed`, `declare \`${key}\` on the operation or the document`);
|
|
148
|
+
return ['application/json'];
|
|
149
|
+
};
|
|
150
|
+
const formTypes = (context, operation, form) => {
|
|
151
|
+
const declared = [operation.consumes, context.root.consumes].find((list) => Array.isArray(list));
|
|
152
|
+
const listed = declared?.filter((type) => FORM_TYPES.has(type)) ?? [];
|
|
153
|
+
if (listed.length > 0)
|
|
154
|
+
return listed;
|
|
155
|
+
return [form.some(({ node }) => node.type === 'file') ? 'multipart/form-data' : 'application/x-www-form-urlencoded'];
|
|
156
|
+
};
|
|
157
|
+
const formBody = (context, operation, at, form) => {
|
|
158
|
+
const types = formTypes(context, operation, form);
|
|
159
|
+
const properties = Object.fromEntries(form.map(({ node, at: where }) => {
|
|
160
|
+
const { value } = partition(node);
|
|
161
|
+
const described = node.description === undefined ? value : { ...value, description: node.description };
|
|
162
|
+
return [String(node.name), context.converter.schema(described, where)];
|
|
163
|
+
}));
|
|
164
|
+
const required = form.filter(({ node }) => node.required === true).map(({ node }) => String(node.name));
|
|
165
|
+
context.report('form-data', `${at}/parameters`, `the \`in: formData\` parameters ${form.map(({ node }) => `\`${String(node.name)}\``).join(', ')} are written as one \`${types.join('`, `')}\` request body object`, 'nothing to do: OpenAPI 3 sends form fields as a request body');
|
|
166
|
+
return { required: required.length > 0, content: Object.fromEntries(types.map((type) => [type, { schema: { type: 'object', properties, required } }])) };
|
|
167
|
+
};
|
|
168
|
+
const bodyOf = (context, operation, at, body) => {
|
|
169
|
+
const types = mediaTypes(context, operation, 'consumes', at);
|
|
170
|
+
const description = body.node.description === undefined ? {} : { description: body.node.description };
|
|
171
|
+
const content = Object.fromEntries(types.map((type) => [type, { schema: context.converter.schema(body.node.schema, `${body.at}/schema`) }]));
|
|
172
|
+
return { ...description, required: body.node.required === true, content };
|
|
173
|
+
};
|
|
174
|
+
const mergedParameters = (context, shared, operation, at) => {
|
|
175
|
+
const merged = new Map();
|
|
176
|
+
const lists = [
|
|
177
|
+
[shared, `${at.slice(0, at.lastIndexOf('/'))}/parameters`],
|
|
178
|
+
[operation.parameters, `${at}/parameters`],
|
|
179
|
+
];
|
|
180
|
+
for (const [list, where] of lists) {
|
|
181
|
+
if (!Array.isArray(list))
|
|
182
|
+
continue;
|
|
183
|
+
for (const [index, entry] of list.entries()) {
|
|
184
|
+
const followed = context.converter.follow(entry, `${where}/${String(index)}`);
|
|
185
|
+
if (followed !== undefined)
|
|
186
|
+
merged.set(`${String(followed.node.in)}:${String(followed.node.name)}`, followed);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return [...merged.values()];
|
|
190
|
+
};
|
|
191
|
+
const parametersOf = (context, shared, operation, at) => {
|
|
192
|
+
const all = mergedParameters(context, shared, operation, at);
|
|
193
|
+
const body = all.find(({ node }) => node.in === 'body');
|
|
194
|
+
const form = all.filter(({ node }) => node.in === 'formData');
|
|
195
|
+
const parameters = all.filter(({ node }) => node.in !== 'body' && node.in !== 'formData').map(({ node, at: where }) => context.converter.parameter(node, where));
|
|
196
|
+
if (body === undefined)
|
|
197
|
+
return { parameters, body: form.length > 0 ? formBody(context, operation, at, form) : undefined };
|
|
198
|
+
if (form.length > 0) {
|
|
199
|
+
context.report('form-data', `${at}/parameters`, 'an operation with a `body` parameter cannot also have `formData` ones; they are not read', 'send the fields in the body schema');
|
|
200
|
+
}
|
|
201
|
+
return { parameters, body: bodyOf(context, operation, at, body) };
|
|
202
|
+
};
|
|
203
|
+
const responseOf = (context, operation, at, { node: response, at: where }) => {
|
|
204
|
+
if (response.examples !== undefined) {
|
|
205
|
+
context.report('examples-not-read', `${where}/examples`, 'response `examples` are not read', 'move them into the schema as `examples`');
|
|
206
|
+
}
|
|
207
|
+
const headers = Object.fromEntries(Object.entries(dict(response.headers)).map(([name, header]) => {
|
|
208
|
+
const { value, rest } = partition(dict(header));
|
|
209
|
+
return [name, { ...rest, schema: context.converter.schema(value, `${where}/headers/${token(name)}`) }];
|
|
210
|
+
}));
|
|
211
|
+
const out = { description: typeof response.description === 'string' ? response.description : '' };
|
|
212
|
+
if (Object.keys(headers).length > 0)
|
|
213
|
+
out.headers = headers;
|
|
214
|
+
if (response.schema !== undefined) {
|
|
215
|
+
const types = mediaTypes(context, operation, 'produces', at);
|
|
216
|
+
out.content = Object.fromEntries(types.map((type) => [type, { schema: context.converter.schema(response.schema, `${where}/schema`) }]));
|
|
217
|
+
}
|
|
218
|
+
return out;
|
|
219
|
+
};
|
|
220
|
+
const responsesOf = (context, operation, at) => Object.fromEntries(Object.entries(dict(operation.responses)).flatMap(([status, entry]) => {
|
|
221
|
+
const where = `${at}/responses/${token(status)}`;
|
|
222
|
+
const followed = context.converter.follow(entry, where);
|
|
223
|
+
return followed === undefined ? [] : [[status, responseOf(context, operation, where, followed)]];
|
|
224
|
+
}));
|
|
225
|
+
const operationOf = (context, operation, shared, at) => {
|
|
226
|
+
const { parameters, body } = parametersOf(context, shared, operation, at);
|
|
227
|
+
if (operation.schemes !== undefined) {
|
|
228
|
+
context.report('schemes-not-read', `${at}/schemes`, "an operation's own `schemes` are not read; the document's servers apply", 'declare a server per scheme on the document');
|
|
229
|
+
}
|
|
230
|
+
const kept = Object.fromEntries(Object.entries(operation).filter(([key]) => !['parameters', 'consumes', 'produces', 'schemes'].includes(key)));
|
|
231
|
+
return {
|
|
232
|
+
...kept,
|
|
233
|
+
...(parameters.length > 0 ? { parameters } : {}),
|
|
234
|
+
...(body === undefined ? {} : { requestBody: body }),
|
|
235
|
+
responses: responsesOf(context, operation, at),
|
|
236
|
+
};
|
|
237
|
+
};
|
|
238
|
+
const isMethod = (key) => METHODS.includes(key);
|
|
239
|
+
const pathsOf = (context) => Object.fromEntries(Object.entries(dict(context.root.paths)).flatMap(([path, entry]) => {
|
|
240
|
+
const at = `#/paths/${token(path)}`;
|
|
241
|
+
const item = context.converter.follow(entry, at);
|
|
242
|
+
if (item === undefined)
|
|
243
|
+
return [];
|
|
244
|
+
const rest = Object.entries(item.node).filter(([key]) => key !== 'parameters' && !isMethod(key));
|
|
245
|
+
const operations = Object.entries(item.node)
|
|
246
|
+
.filter((pair) => isMethod(pair[0]) && isDict(pair[1]))
|
|
247
|
+
.map(([method, operation]) => [method, operationOf(context, operation, item.node.parameters, `${at}/${method}`)]);
|
|
248
|
+
return [[path, Object.fromEntries([...rest, ...operations])]];
|
|
249
|
+
}));
|
|
250
|
+
const serversOf = (root) => {
|
|
251
|
+
const basePath = typeof root.basePath === 'string' ? root.basePath : '';
|
|
252
|
+
if (typeof root.host !== 'string')
|
|
253
|
+
return basePath === '' ? undefined : [{ url: basePath }];
|
|
254
|
+
const schemes = Array.isArray(root.schemes) ? root.schemes.filter((scheme) => typeof scheme === 'string') : [];
|
|
255
|
+
return schemes.length === 0 ? [{ url: `//${root.host}${basePath}` }] : schemes.map((scheme) => ({ url: `${scheme}://${String(root.host)}${basePath}` }));
|
|
256
|
+
};
|
|
257
|
+
const securitySchemeOf = (scheme) => {
|
|
258
|
+
const { type, flow, authorizationUrl, tokenUrl, scopes, ...rest } = dict(scheme);
|
|
259
|
+
if (type === 'basic')
|
|
260
|
+
return { ...rest, type: 'http', scheme: 'basic' };
|
|
261
|
+
if (type !== 'oauth2')
|
|
262
|
+
return { ...rest, type, ...(scopes === undefined ? {} : { scopes }) };
|
|
263
|
+
const urls = { ...(authorizationUrl === undefined ? {} : { authorizationUrl }), ...(tokenUrl === undefined ? {} : { tokenUrl }) };
|
|
264
|
+
return { ...rest, type, flows: { [FLOWS[String(flow)] ?? String(flow)]: { ...urls, scopes: scopes ?? {} } } };
|
|
265
|
+
};
|
|
266
|
+
const RESPONSE_SCHEMA_REF = /^(#\/paths\/.+\/responses\/[^/]+)\/schema(\/.*)?$/u;
|
|
267
|
+
const memberAt = (document, pointer) => pointer
|
|
268
|
+
.slice('#/'.length)
|
|
269
|
+
.split('/')
|
|
270
|
+
.map((part) => decodeURIComponent(part).replaceAll('~1', '/').replaceAll('~0', '~'))
|
|
271
|
+
.reduce((node, key) => (isDict(node) && Object.hasOwn(node, key) ? node[key] : undefined), document);
|
|
272
|
+
const repointResponseRefs = (node, document, report, at = '#') => {
|
|
273
|
+
if (Array.isArray(node)) {
|
|
274
|
+
for (const [index, item] of node.entries())
|
|
275
|
+
repointResponseRefs(item, document, report, `${at}/${String(index)}`);
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
if (!isDict(node))
|
|
279
|
+
return;
|
|
280
|
+
const match = typeof node.$ref === 'string' ? RESPONSE_SCHEMA_REF.exec(node.$ref) : null;
|
|
281
|
+
if (match !== null) {
|
|
282
|
+
const response = match[1];
|
|
283
|
+
const rest = match[2] ?? '';
|
|
284
|
+
const content = dict(memberAt(document, `${response}/content`));
|
|
285
|
+
const [mediaType] = Object.keys(content);
|
|
286
|
+
if (mediaType !== undefined) {
|
|
287
|
+
const moved = `${response}/content/${token(mediaType)}/schema${rest}`;
|
|
288
|
+
report('ref-response-schema', `${at}/$ref`, `\`${String(node.$ref)}\` is written as \`${moved}\``, 'nothing to do: OpenAPI 3 keeps a response schema under its media type');
|
|
289
|
+
node.$ref = moved;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
for (const [key, value] of Object.entries(node))
|
|
293
|
+
repointResponseRefs(value, document, report, `${at}/${token(key)}`);
|
|
294
|
+
};
|
|
295
|
+
const MOVED = new Set(['swagger', 'host', 'basePath', 'schemes', 'consumes', 'produces', 'definitions', 'parameters', 'responses', 'securityDefinitions']);
|
|
296
|
+
export const convert = (document) => {
|
|
297
|
+
if (!detect(document))
|
|
298
|
+
throw new Swagger2Error('it has no `swagger: "2.0"` member', 'pass a Swagger 2.0 document, or read an OpenAPI 3 one with the `openapi` adapter');
|
|
299
|
+
const root = document;
|
|
300
|
+
const findings = new Map();
|
|
301
|
+
const report = (code, pointer, message, fix) => {
|
|
302
|
+
findings.set(`${code} ${pointer}`, { code, pointer, message, fix });
|
|
303
|
+
};
|
|
304
|
+
const converter = createConverter(root, report);
|
|
305
|
+
const schemas = Object.fromEntries(Object.entries(dict(root.definitions)).map(([name, value]) => [name, converter.schema(value, `#/definitions/${token(name)}`)]));
|
|
306
|
+
const securitySchemes = Object.fromEntries(Object.entries(dict(root.securityDefinitions)).map(([name, value]) => [name, securitySchemeOf(value)]));
|
|
307
|
+
const components = {
|
|
308
|
+
...(Object.keys(schemas).length > 0 ? { schemas } : {}),
|
|
309
|
+
...(Object.keys(securitySchemes).length > 0 ? { securitySchemes } : {}),
|
|
310
|
+
};
|
|
311
|
+
const servers = serversOf(root);
|
|
312
|
+
const converted = {
|
|
313
|
+
openapi: '3.1.0',
|
|
314
|
+
...Object.fromEntries(Object.entries(root).filter(([key]) => !MOVED.has(key))),
|
|
315
|
+
...(servers === undefined ? {} : { servers }),
|
|
316
|
+
paths: pathsOf({ root, report, converter }),
|
|
317
|
+
...(Object.keys(components).length > 0 ? { components } : {}),
|
|
318
|
+
};
|
|
319
|
+
repointResponseRefs(converted, converted, report);
|
|
320
|
+
return { document: converted, findings: [...findings.values()] };
|
|
321
|
+
};
|
|
322
|
+
export const read = (document) => {
|
|
323
|
+
const converted = convert(document);
|
|
324
|
+
return { format: 'swagger2', document: converted.document, operations: readOpenApi(converted.document).operations, findings: converted.findings };
|
|
325
|
+
};
|
|
326
|
+
export const adapter = Object.freeze({
|
|
327
|
+
name: 'swagger2',
|
|
328
|
+
description: 'Swagger 2.0 documents, read through their OpenAPI 3.1 form',
|
|
329
|
+
detect,
|
|
330
|
+
read,
|
|
331
|
+
});
|
package/dist/inputs.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { adapter as asyncapi } from './input-asyncapi.js';
|
|
2
|
+
import { adapter as jsonschema } from './input-jsonschema.js';
|
|
3
|
+
import { adapter as mcp } from './input-mcp.js';
|
|
4
|
+
import { adapter as protobuf } from './input-protobuf.js';
|
|
5
|
+
import { adapter as swagger2 } from './input-swagger2.js';
|
|
6
|
+
import { openapi } from './openapi.js';
|
|
7
|
+
const planned = { openapi, swagger2, asyncapi, mcp, protobuf, jsonschema };
|
|
8
|
+
export const builtinAdapters = Object.fromEntries(Object.entries(planned).filter((entry) => entry[1] !== undefined));
|