contractdiff 0.0.0-stage → 0.4.0
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 +408 -0
- package/dist/props-judge.js +30 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +170 -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,17 @@
|
|
|
1
|
+
import { inline } from './core/resolve.js';
|
|
2
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
const mark = (value) => {
|
|
4
|
+
if (Array.isArray(value))
|
|
5
|
+
return value.map((item) => mark(item));
|
|
6
|
+
if (!isObject(value))
|
|
7
|
+
return value;
|
|
8
|
+
const entries = Object.entries(value).map(([key, child]) => [key, mark(child)]);
|
|
9
|
+
const ref = value.$ref;
|
|
10
|
+
if (typeof ref !== 'string' || !ref.startsWith('#'))
|
|
11
|
+
return Object.fromEntries(entries);
|
|
12
|
+
return { ...Object.fromEntries(entries.filter(([key]) => key !== '$ref')), $comment: `cycle: ${ref}` };
|
|
13
|
+
};
|
|
14
|
+
export const explainInline = (document, schema) => {
|
|
15
|
+
const { value, cycles, external } = inline(document, schema);
|
|
16
|
+
return { value: mark(value), cycles, external };
|
|
17
|
+
};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
const FNV_OFFSET = 0x81_1c_9d_c5;
|
|
2
|
+
const FNV_PRIME = 0x01_00_01_93;
|
|
3
|
+
const RADIX = 36;
|
|
4
|
+
const MAX_FILE = 100;
|
|
5
|
+
export const stableHash = (text) => {
|
|
6
|
+
let hash = FNV_OFFSET;
|
|
7
|
+
for (const char of new TextEncoder().encode(text)) {
|
|
8
|
+
hash ^= char;
|
|
9
|
+
hash = Math.imul(hash, FNV_PRIME) >>> 0;
|
|
10
|
+
}
|
|
11
|
+
return hash.toString(RADIX);
|
|
12
|
+
};
|
|
13
|
+
export const fitted = (text, full, max) => {
|
|
14
|
+
if (text.length <= max)
|
|
15
|
+
return text;
|
|
16
|
+
const suffix = `_${stableHash(full)}`;
|
|
17
|
+
return `${text.slice(0, max - suffix.length)}${suffix}`;
|
|
18
|
+
};
|
|
19
|
+
export const unique = (ids, nameOf, max) => {
|
|
20
|
+
const named = ids.map((id) => [id, nameOf(id)]);
|
|
21
|
+
const counts = new Map();
|
|
22
|
+
for (const [, name] of named)
|
|
23
|
+
counts.set(name.toLowerCase(), (counts.get(name.toLowerCase()) ?? 0) + 1);
|
|
24
|
+
return new Map(named.map(([id, name]) => {
|
|
25
|
+
if (counts.get(name.toLowerCase()) === 1)
|
|
26
|
+
return [id, name];
|
|
27
|
+
const suffix = `_${stableHash(id)}`;
|
|
28
|
+
return [id, `${name.slice(0, max - suffix.length)}${suffix}`];
|
|
29
|
+
}));
|
|
30
|
+
};
|
|
31
|
+
export const fileSlug = (id) => fitted(id.replaceAll(/[^\w.-]+/gu, '-').replaceAll(/^[-.]+|-+$/gu, '') || 'operation', id, MAX_FILE);
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { bytesOf, cap } from './command-explain-cap.js';
|
|
2
|
+
import { explainInline } from './command-explain-inline.js';
|
|
3
|
+
import { pointerGet } from './core/resolve.js';
|
|
4
|
+
const membersOf = (value) => Object(value);
|
|
5
|
+
const untoken = (token) => token.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
6
|
+
const HTTP_TOKENS = 4;
|
|
7
|
+
const http = (source) => {
|
|
8
|
+
const tokens = source.split('/');
|
|
9
|
+
if (tokens[1] !== 'paths' || tokens.length < HTTP_TOKENS)
|
|
10
|
+
return undefined;
|
|
11
|
+
return { method: untoken(tokens.at(-1)).toUpperCase(), path: untoken(tokens[2]) };
|
|
12
|
+
};
|
|
13
|
+
const declared = (contract, operation) => {
|
|
14
|
+
try {
|
|
15
|
+
const node = pointerGet(contract.document, operation.source);
|
|
16
|
+
return membersOf(node);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return {};
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
const prose = (source, key) => {
|
|
23
|
+
const value = source[key];
|
|
24
|
+
return typeof value === 'string' && value !== '' ? { [key]: value } : {};
|
|
25
|
+
};
|
|
26
|
+
export const tagsOf = (contract, operation) => {
|
|
27
|
+
const { tags } = declared(contract, operation);
|
|
28
|
+
return Array.isArray(tags) ? tags.filter((tag) => typeof tag === 'string') : [];
|
|
29
|
+
};
|
|
30
|
+
export const describe = (contract, operation) => {
|
|
31
|
+
const cycles = new Set();
|
|
32
|
+
const external = new Set();
|
|
33
|
+
const payloads = operation.payloads.map((payload) => {
|
|
34
|
+
const resolved = explainInline(contract.document, payload.schema);
|
|
35
|
+
for (const ref of resolved.cycles)
|
|
36
|
+
cycles.add(ref);
|
|
37
|
+
for (const ref of resolved.external)
|
|
38
|
+
external.add(ref);
|
|
39
|
+
return { name: payload.name, direction: payload.direction, required: payload.required, schema: resolved.value };
|
|
40
|
+
});
|
|
41
|
+
const source = declared(contract, operation);
|
|
42
|
+
const tags = tagsOf(contract, operation);
|
|
43
|
+
return {
|
|
44
|
+
id: operation.id,
|
|
45
|
+
format: contract.format,
|
|
46
|
+
source: operation.source,
|
|
47
|
+
...http(operation.source),
|
|
48
|
+
...prose(source, 'summary'),
|
|
49
|
+
...prose(source, 'description'),
|
|
50
|
+
...(tags.length === 0 ? {} : { tags }),
|
|
51
|
+
payloads,
|
|
52
|
+
...(cycles.size === 0 ? {} : { cycles: [...cycles] }),
|
|
53
|
+
...(external.size === 0 ? {} : { external: [...external] }),
|
|
54
|
+
};
|
|
55
|
+
};
|
|
56
|
+
export class BudgetError extends Error {
|
|
57
|
+
code = 'USAGE';
|
|
58
|
+
constructor(id, max, smallest) {
|
|
59
|
+
super(`"${id}" does not fit in ${String(max)} bytes even with every schema emptied (${String(smallest)} bytes). fix: pass --max-bytes ${String(smallest)} or more`);
|
|
60
|
+
this.name = 'BudgetError';
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const SCHEMA_DEPTH = 3;
|
|
64
|
+
const smallest = (result) => {
|
|
65
|
+
let size = bytesOf(result);
|
|
66
|
+
while (bytesOf({ ...result, truncated: { ...result.truncated, maxBytes: size } }) !== size) {
|
|
67
|
+
size = bytesOf({ ...result, truncated: { ...result.truncated, maxBytes: size } });
|
|
68
|
+
}
|
|
69
|
+
return size;
|
|
70
|
+
};
|
|
71
|
+
export const capped = (explanation, max) => {
|
|
72
|
+
if (max === undefined || bytesOf(explanation) <= max)
|
|
73
|
+
return explanation;
|
|
74
|
+
let budget = max;
|
|
75
|
+
for (;;) {
|
|
76
|
+
const { value, cut } = cap(explanation, budget, SCHEMA_DEPTH);
|
|
77
|
+
const result = { ...value, truncated: { maxBytes: max, cut } };
|
|
78
|
+
const over = bytesOf(result) - max;
|
|
79
|
+
if (over <= 0)
|
|
80
|
+
return result;
|
|
81
|
+
if (budget <= 0)
|
|
82
|
+
throw new BudgetError(explanation.id, max, smallest(result));
|
|
83
|
+
budget -= over;
|
|
84
|
+
}
|
|
85
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
const code = (text) => `\`${text}\``;
|
|
2
|
+
const where = (explanation) => {
|
|
3
|
+
const route = explanation.method === undefined ? [] : [code(`${explanation.method} ${explanation.path}`)];
|
|
4
|
+
return [...route, `${explanation.format} ${code(explanation.source)}`].join(' · ');
|
|
5
|
+
};
|
|
6
|
+
const list = (title, items) => items === undefined ? [] : [`${title}: ${items.map((item) => code(item)).join(', ')}`, ''];
|
|
7
|
+
export const toMarkdown = (explanation) => {
|
|
8
|
+
const lines = [`# ${explanation.id}`, '', where(explanation), ''];
|
|
9
|
+
for (const prose of [explanation.summary, explanation.description])
|
|
10
|
+
if (prose !== undefined)
|
|
11
|
+
lines.push(prose, '');
|
|
12
|
+
lines.push(...list('Tags', explanation.tags));
|
|
13
|
+
for (const payload of explanation.payloads) {
|
|
14
|
+
lines.push(`## ${payload.name}`, '', `${payload.direction}, ${payload.required ? 'required' : 'optional'}`, '', '```json', JSON.stringify(payload.schema, null, 2), '```', '');
|
|
15
|
+
}
|
|
16
|
+
lines.push(...list('Cycles, each cut to `{ "$comment": "cycle: <pointer>" }`', explanation.cycles), ...list('External references, not followed', explanation.external));
|
|
17
|
+
if (explanation.truncated !== undefined) {
|
|
18
|
+
lines.push(...list(`Truncated to ${String(explanation.truncated.maxBytes)} bytes; emptied`, explanation.truncated.cut));
|
|
19
|
+
}
|
|
20
|
+
return `${lines.join('\n').trimEnd()}\n`;
|
|
21
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { defineCommand } from 'burgee';
|
|
3
|
+
import { capped, describe } from './command-explain-operation.js';
|
|
4
|
+
import { toMarkdown } from './command-explain-text.js';
|
|
5
|
+
import { createHost } from './host.js';
|
|
6
|
+
import { builtinAdapters } from './inputs.js';
|
|
7
|
+
import { ConfigError, loadConfig, UsageError } from './run-config.js';
|
|
8
|
+
import { readDocument, readInput } from './run-input.js';
|
|
9
|
+
const SHOWN = 10;
|
|
10
|
+
const TEXT = Symbol.for('burgee.text');
|
|
11
|
+
const documentOf = async (cwd, input) => {
|
|
12
|
+
if (input !== undefined)
|
|
13
|
+
return readDocument(resolve(cwd, input), '--input');
|
|
14
|
+
const config = await loadConfig(cwd);
|
|
15
|
+
if (config?.input === undefined) {
|
|
16
|
+
throw new ConfigError(resolve(cwd, 'contractdiff.config.json'), ['no spec was named. fix: pass --input <file>, or add `"input"` to contractdiff.config.json']);
|
|
17
|
+
}
|
|
18
|
+
return readInput({ root: config.root, file: config.file, input: config.input, overlays: config.overlays });
|
|
19
|
+
};
|
|
20
|
+
const withText = (data, text) => Object.defineProperty(data, TEXT, { value: () => text, enumerable: false });
|
|
21
|
+
export const explain = async (options) => {
|
|
22
|
+
const { maxBytes } = options;
|
|
23
|
+
if (maxBytes !== undefined && (!Number.isInteger(maxBytes) || maxBytes < 1)) {
|
|
24
|
+
throw new UsageError(`--max-bytes takes a whole number of bytes above 0, not ${String(maxBytes)}. fix: pass a number such as --max-bytes 4096`);
|
|
25
|
+
}
|
|
26
|
+
const host = createHost();
|
|
27
|
+
host.register({ name: 'contractdiff', adapters: builtinAdapters });
|
|
28
|
+
const contract = host.read(await documentOf(options.cwd, options.input));
|
|
29
|
+
const ids = contract.operations.map((operation) => operation.id);
|
|
30
|
+
if (options.list === true)
|
|
31
|
+
return ids;
|
|
32
|
+
if (options.operation === undefined)
|
|
33
|
+
throw new UsageError('name the operation to explain. fix: run `contractdiff explain --list` for the ids, then `contractdiff explain <id>`');
|
|
34
|
+
const operation = contract.operations.find((candidate) => candidate.id === options.operation);
|
|
35
|
+
if (operation === undefined) {
|
|
36
|
+
const shown = ids.slice(0, SHOWN).join(', ');
|
|
37
|
+
throw new UsageError(`no operation is named "${options.operation}". fix: pass one of: ${shown}${ids.length > SHOWN ? ', …' : ''} (\`--list\` prints them all)`);
|
|
38
|
+
}
|
|
39
|
+
const explanation = capped(describe(contract, operation), maxBytes);
|
|
40
|
+
return withText({ ...explanation }, toMarkdown(explanation));
|
|
41
|
+
};
|
|
42
|
+
const HERE = '.';
|
|
43
|
+
export const command = defineCommand({
|
|
44
|
+
name: 'explain',
|
|
45
|
+
description: 'One operation, message or tool, fully resolved and size-capped for an agent',
|
|
46
|
+
effects: 'read_only',
|
|
47
|
+
arguments: [{ name: 'operation', required: false, description: 'the operation id; `--list` prints them' }],
|
|
48
|
+
options: {
|
|
49
|
+
input: { type: 'string', description: 'the spec, JSON or YAML (default: `input` in contractdiff.config.json)', placeholder: 'file' },
|
|
50
|
+
list: { type: 'boolean', description: 'print the operation ids, one per line' },
|
|
51
|
+
maxBytes: { type: 'number', description: 'cut the deepest schemas first until the JSON fits; the cuts are listed under `truncated`', placeholder: 'n' },
|
|
52
|
+
},
|
|
53
|
+
run: async ({ args, options }) => explain({ cwd: HERE, input: options.input, operation: args.operation, list: options.list, maxBytes: options.maxBytes }),
|
|
54
|
+
});
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { relative, resolve } from 'node:path';
|
|
3
|
+
import { defineCommand, ExitCode } from 'burgee';
|
|
4
|
+
import { parse as parseYaml } from 'seniority/yaml';
|
|
5
|
+
import { uriOf } from './command-diff.js';
|
|
6
|
+
import { bufIn, builtImages } from './input-buf.js';
|
|
7
|
+
import { builtinAdapters } from './inputs.js';
|
|
8
|
+
import { codeIndexOf, mapIn, typescriptIn } from './lint-code-read.js';
|
|
9
|
+
import { lint } from './lint-engine.js';
|
|
10
|
+
import { DEFAULT_RULESETS, gitIn, historyOf, RULESET_FILE, rulesetOfText, sourcesOf } from './lint-history.js';
|
|
11
|
+
import { rules, rulesets } from './lint-rules.js';
|
|
12
|
+
import { sinceOf } from './lint-since.js';
|
|
13
|
+
import { countRun, idleCutoff, idleDays, idleOf, statsOf } from './lint-stats.js';
|
|
14
|
+
import { ConfigError, loadConfig, UsageError } from './run-config.js';
|
|
15
|
+
import { loadPlugins } from './run-load.js';
|
|
16
|
+
const TEXT = Symbol.for('burgee.text');
|
|
17
|
+
const PREFIX = /^contractdiff:/u;
|
|
18
|
+
const PERCENT = 100;
|
|
19
|
+
const CONFIG_FILE = 'contractdiff.config.json';
|
|
20
|
+
const RULESETS = new Map(Object.entries(rulesets));
|
|
21
|
+
const RULES = new Map(Object.entries(rules));
|
|
22
|
+
const COLUMN = 'error'.length;
|
|
23
|
+
const DATE = 'yyyy-mm-dd'.length;
|
|
24
|
+
export const readRulesets = (names, root) => Object.fromEntries(names.filter((name) => RULESET_FILE.test(name)).map((name) => [name, rulesetOfText(name, () => readFileSync(resolve(root, name), 'utf8'), CONFIG_FILE)]));
|
|
25
|
+
const rulesetOf = (name, files) => new Map(Object.entries(files)).get(name)?.levels ?? RULESETS.get(name.replace(PREFIX, ''));
|
|
26
|
+
export const levelsOf = (names, overrides = {}, contributed = {}, files = {}) => {
|
|
27
|
+
const chosen = names.map((name) => {
|
|
28
|
+
const ruleset = rulesetOf(name, files);
|
|
29
|
+
if (ruleset === undefined)
|
|
30
|
+
throw new UsageError(`there is no ruleset \`${name}\`. fix: use one of ${Object.keys(rulesets).join(', ')}, or a .spectral.yaml file`);
|
|
31
|
+
return ruleset;
|
|
32
|
+
});
|
|
33
|
+
const known = new Set([...RULES.keys(), ...Object.values(files).flatMap((file) => Object.keys(file.rules)), ...Object.keys(contributed)]);
|
|
34
|
+
const unknown = Object.keys(overrides).filter((id) => !known.has(id));
|
|
35
|
+
if (unknown.length > 0) {
|
|
36
|
+
throw new ConfigError(CONFIG_FILE, unknown.map((id) => `\`lint.rules\` names \`${id}\`, which is not a rule. fix: use one of ${[...known].sort().join(', ')}, or add the plugin that contributes it to \`plugins\``));
|
|
37
|
+
}
|
|
38
|
+
const plugins = Object.fromEntries(Object.keys(contributed).map((id) => [id, 'warn']));
|
|
39
|
+
return Object.fromEntries([...chosen, plugins, overrides].flatMap((levels) => Object.entries(levels)));
|
|
40
|
+
};
|
|
41
|
+
export const scoreOf = (ruleset, counts) => {
|
|
42
|
+
const run = Object.keys(ruleset).flatMap((id) => (counts[id] === undefined ? [] : [counts[id]]));
|
|
43
|
+
const checked = run.reduce((sum, count) => sum + count.checked, 0);
|
|
44
|
+
const passed = checked - run.reduce((sum, count) => sum + count.failed, 0);
|
|
45
|
+
return { passed, checked, percent: checked === 0 ? PERCENT : Math.floor((passed / checked) * PERCENT) };
|
|
46
|
+
};
|
|
47
|
+
const contractOf = (document) => Object.values(builtinAdapters).find((adapter) => adapter.detect(document))?.read(document);
|
|
48
|
+
export const readInput = (file, cwd, built = new Map()) => {
|
|
49
|
+
let document;
|
|
50
|
+
try {
|
|
51
|
+
document = parseYaml(built.get(file) ?? readFileSync(resolve(cwd, file), 'utf8'));
|
|
52
|
+
}
|
|
53
|
+
catch (error) {
|
|
54
|
+
throw new UsageError(`cannot read ${file}: ${error.message}. fix: pass a JSON or YAML document that exists`);
|
|
55
|
+
}
|
|
56
|
+
const contract = contractOf(document);
|
|
57
|
+
if (contract === undefined)
|
|
58
|
+
throw new UsageError(`no input format reads ${file}. fix: pass a document one of these reads: ${Object.keys(builtinAdapters).join(', ')}`);
|
|
59
|
+
return { file, contract };
|
|
60
|
+
};
|
|
61
|
+
export const contractAt = (text) => {
|
|
62
|
+
try {
|
|
63
|
+
return contractOf(parseYaml(text));
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
const LEVEL = { error: 'error', warn: 'warning' };
|
|
70
|
+
const specLocation = (finding) => ({ physicalLocation: { artifactLocation: { uri: uriOf(finding.file) } }, logicalLocations: [{ fullyQualifiedName: finding.pointer }] });
|
|
71
|
+
const locationsOf = (finding) => finding.code === undefined
|
|
72
|
+
? { locations: [specLocation(finding)] }
|
|
73
|
+
: { locations: [{ physicalLocation: { artifactLocation: { uri: uriOf(finding.code.file) }, region: { startLine: finding.code.line } } }], relatedLocations: [{ id: 0, ...specLocation(finding) }] };
|
|
74
|
+
const placeOf = (finding) => (finding.code === undefined ? finding.pointer : `${finding.code.file}:${String(finding.code.line)} (${finding.pointer})`);
|
|
75
|
+
export const toSarif = (result, all = rules) => ({
|
|
76
|
+
version: '2.1.0',
|
|
77
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
78
|
+
runs: [
|
|
79
|
+
{
|
|
80
|
+
tool: { driver: { name: 'contractdiff lint', rules: Object.keys(result.counts).map((id) => ({ id, shortDescription: { text: new Map(Object.entries(all)).get(id).description } })) } },
|
|
81
|
+
results: result.findings.map((finding) => ({
|
|
82
|
+
ruleId: finding.rule,
|
|
83
|
+
level: LEVEL[finding.level],
|
|
84
|
+
message: { text: `${finding.message}. fix: ${finding.fix}` },
|
|
85
|
+
...locationsOf(finding),
|
|
86
|
+
})),
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
const changeOf = (change) => {
|
|
91
|
+
if (change.from === change.to)
|
|
92
|
+
return 'its definition changed';
|
|
93
|
+
return `${change.from ?? 'not run'} → ${change.to ?? 'not run'}${change.definition ? ', and its definition changed' : ''}`;
|
|
94
|
+
};
|
|
95
|
+
const changedLines = (history) => {
|
|
96
|
+
const changed = history.changed ?? [];
|
|
97
|
+
if (changed.length === 0)
|
|
98
|
+
return [];
|
|
99
|
+
return [
|
|
100
|
+
`rules changed since ${history.from}, not applied`,
|
|
101
|
+
...changed.map((change) => ` ${'info'.padEnd(COLUMN)} ruleset-changed ${change.id}: ${changeOf(change)}`),
|
|
102
|
+
` ${''.padEnd(COLUMN)} fix: merge the change first; until then the rules come from ${history.from}`,
|
|
103
|
+
'',
|
|
104
|
+
];
|
|
105
|
+
};
|
|
106
|
+
const sinceNote = (since) => {
|
|
107
|
+
if (since === undefined)
|
|
108
|
+
return [];
|
|
109
|
+
return ['unapplied' in since ? `; since not applied: ${since.unapplied}` : `; since ${since.from}: ${String(since.skipped)} untouched operation(s) skipped`];
|
|
110
|
+
};
|
|
111
|
+
const statsNote = (stats) => {
|
|
112
|
+
if (stats === undefined)
|
|
113
|
+
return [];
|
|
114
|
+
return [`; stats: ${stats.counted ? 'this run counted in' : 'this commit already counted in'} ${stats.file}`, ...(stats.idle === undefined ? [] : [`; idle ${stats.idleFor}: ${String(stats.idle.length)}`])];
|
|
115
|
+
};
|
|
116
|
+
const idleLines = (stats) => {
|
|
117
|
+
if (stats?.idle === undefined || stats.idle.length === 0)
|
|
118
|
+
return [];
|
|
119
|
+
return [
|
|
120
|
+
`rules with no finding in ${stats.idleFor}`,
|
|
121
|
+
...stats.idle.map((entry) => ` ${'info'.padEnd(COLUMN)} rule-idle ${entry.id}: ${entry.found ? 'last found something' : 'has found nothing since its first run'} ${entry.since.slice(0, DATE)}, in ${String(entry.runs)} run(s)`),
|
|
122
|
+
` ${''.padEnd(COLUMN)} fix: set each to "off" in \`lint.rules\` if what it guards cannot come back; keep it if it is a tripwire`,
|
|
123
|
+
'',
|
|
124
|
+
];
|
|
125
|
+
};
|
|
126
|
+
const historyNote = (history) => [
|
|
127
|
+
...(history.from === undefined ? [] : [`; rules from ${history.from}`]),
|
|
128
|
+
...(history.warnFirst === undefined || history.warnFirst.length === 0 ? [] : [`; warn first: ${String(history.warnFirst.length)} (${history.warnFirst.join(', ')})`]),
|
|
129
|
+
...(history.unchecked === undefined ? [] : [`; warn first not checked: ${history.unchecked}`]),
|
|
130
|
+
...sinceNote(history.since),
|
|
131
|
+
...statsNote(history.stats),
|
|
132
|
+
].join('');
|
|
133
|
+
export const toText = (result, scores, notCarried = [], history = {}) => {
|
|
134
|
+
const lines = [...changedLines(history), ...idleLines(history.stats)];
|
|
135
|
+
for (const file of [...new Set(notCarried.map((entry) => entry.file))]) {
|
|
136
|
+
lines.push(file);
|
|
137
|
+
for (const entry of notCarried.filter((each) => each.file === file))
|
|
138
|
+
lines.push(` ${'warn'.padEnd(COLUMN)} rule-not-carried ${entry.pointer} ${entry.id}: ${entry.reason}`, ` ${''.padEnd(COLUMN)} fix: ${entry.fix}`);
|
|
139
|
+
lines.push('');
|
|
140
|
+
}
|
|
141
|
+
for (const file of result.inputs) {
|
|
142
|
+
const findings = result.findings.filter((finding) => finding.file === file);
|
|
143
|
+
if (findings.length === 0)
|
|
144
|
+
continue;
|
|
145
|
+
lines.push(file);
|
|
146
|
+
for (const finding of findings)
|
|
147
|
+
lines.push(` ${finding.level.padEnd(COLUMN)} ${finding.rule} ${placeOf(finding)} ${finding.message}`, ` ${''.padEnd(COLUMN)} fix: ${finding.fix}`);
|
|
148
|
+
lines.push('');
|
|
149
|
+
}
|
|
150
|
+
const errors = result.findings.filter((finding) => finding.level === 'error').length;
|
|
151
|
+
const nodes = Object.values(result.counts).reduce((sum, count) => sum + count.checked, 0);
|
|
152
|
+
lines.push(`${String(errors)} error(s), ${String(result.findings.length - errors)} warning(s). Checked ${String(Object.keys(result.counts).length)} rule(s) on ${String(result.inputs.length)} input(s), ${String(nodes)} node(s); not carried: ${notCarried.length === 0 ? 'none' : `${String(notCarried.length)} (${notCarried.map((entry) => entry.id).join(', ')})`}${historyNote(history)}.`, ...Object.entries(scores).map(([name, score]) => `${name}: ${String(score.percent)}% (${String(score.passed)} of ${String(score.checked)} checks passed)`));
|
|
153
|
+
return lines.join('\n');
|
|
154
|
+
};
|
|
155
|
+
const historyData = (history) => ({
|
|
156
|
+
...(history.from === undefined ? {} : { rulesFrom: history.from, rulesetChanged: history.changed }),
|
|
157
|
+
...(history.warnFirst.length === 0 ? {} : { warnFirst: history.warnFirst }),
|
|
158
|
+
...(history.unchecked === undefined ? {} : { warnFirstUnchecked: history.unchecked }),
|
|
159
|
+
});
|
|
160
|
+
const resolverOf = (contributed) => (sources) => ({
|
|
161
|
+
all: { ...rules, ...Object.assign({}, ...Object.values(sources.files).map((file) => file.rules)), ...contributed },
|
|
162
|
+
levels: levelsOf(sources.names, sources.overrides, contributed, sources.files),
|
|
163
|
+
});
|
|
164
|
+
const legacyOf = (names, all) => {
|
|
165
|
+
const known = new Set(Object.keys(all));
|
|
166
|
+
const unknown = names.filter((id) => !known.has(id));
|
|
167
|
+
if (unknown.length > 0)
|
|
168
|
+
throw new ConfigError(CONFIG_FILE, unknown.map((id) => `\`lint.legacy\` names \`${id}\`, which is not a rule. fix: use one of ${[...known].sort().join(', ')}`));
|
|
169
|
+
return new Set(names);
|
|
170
|
+
};
|
|
171
|
+
const inputsOf = async (read) => {
|
|
172
|
+
const built = await builtImages(read.specs, read.base, read.buf ?? bufIn());
|
|
173
|
+
const inputs = read.specs.map((spec) => readInput(spec, read.base, built));
|
|
174
|
+
if (read.since === undefined)
|
|
175
|
+
return { inputs };
|
|
176
|
+
return sinceOf({ git: read.git, ref: read.since, inputs: inputs.map((input) => ({ input, path: relative(read.root, resolve(read.base, input.file)) })), read: contractAt });
|
|
177
|
+
};
|
|
178
|
+
const idleOption = (options) => {
|
|
179
|
+
if (options.idle === undefined)
|
|
180
|
+
return undefined;
|
|
181
|
+
if (options.stats === undefined)
|
|
182
|
+
throw new UsageError('`--idle` reads the counts `--stats` keeps. fix: add `--stats lint-stats.json`, a file your CI caches');
|
|
183
|
+
return idleDays(options.idle);
|
|
184
|
+
};
|
|
185
|
+
const recordOf = async ({ options, result, git, now }, days) => {
|
|
186
|
+
if (options.stats === undefined)
|
|
187
|
+
return undefined;
|
|
188
|
+
const path = resolve(options.cwd, options.stats);
|
|
189
|
+
const stats = statsOf(existsSync(path) ? readFileSync(path, 'utf8') : undefined, options.stats);
|
|
190
|
+
const next = countRun(stats, result, { key: (await git.commit('HEAD')) ?? now.toISOString().slice(0, DATE), now });
|
|
191
|
+
if (next !== stats)
|
|
192
|
+
writeFileSync(path, `${JSON.stringify(next, undefined, 2)}\n`);
|
|
193
|
+
return {
|
|
194
|
+
file: options.stats,
|
|
195
|
+
counted: next !== stats,
|
|
196
|
+
...(days === undefined ? {} : { idle: idleOf(next, Object.keys(result.counts), idleCutoff(days, now)), idleFor: options.idle }),
|
|
197
|
+
};
|
|
198
|
+
};
|
|
199
|
+
const dataOf = ({ result, scores, notCarried, notes, sarif }) => {
|
|
200
|
+
const errors = result.findings.filter((finding) => finding.level === 'error').length;
|
|
201
|
+
const data = {
|
|
202
|
+
...result,
|
|
203
|
+
scores,
|
|
204
|
+
notCarried,
|
|
205
|
+
...historyData(notes),
|
|
206
|
+
...(notes.since === undefined ? {} : { since: notes.since }),
|
|
207
|
+
...(notes.stats === undefined ? {} : { stats: notes.stats }),
|
|
208
|
+
changed: notes.stats?.counted ?? false,
|
|
209
|
+
...(sarif === undefined ? {} : { sarif }),
|
|
210
|
+
...(errors > 0 ? { exitCode: ExitCode.RUNTIME, fix: 'correct each error as its own fix line says, or set its rule to "warn" in `lint.rules`' } : {}),
|
|
211
|
+
};
|
|
212
|
+
data[TEXT] = () => (sarif === undefined ? toText(result, scores, notCarried, notes) : JSON.stringify(sarif, undefined, 2));
|
|
213
|
+
return data;
|
|
214
|
+
};
|
|
215
|
+
const withCode = (inputs, root, typescript) => {
|
|
216
|
+
const code = codeIndexOf(() => mapIn(root), root, typescript ?? (() => typescriptIn(root)));
|
|
217
|
+
return inputs.map((input) => ({ ...input, code }));
|
|
218
|
+
};
|
|
219
|
+
export const runLint = async (options) => {
|
|
220
|
+
const config = options.config ?? (await loadConfig(options.cwd));
|
|
221
|
+
const root = config?.root ?? options.cwd;
|
|
222
|
+
const configured = config?.input === undefined ? [] : [config.input];
|
|
223
|
+
const specs = options.specs.length > 0 ? options.specs : configured;
|
|
224
|
+
if (specs.length === 0)
|
|
225
|
+
throw new UsageError('nothing to lint. fix: pass a spec, e.g. `contractdiff lint openapi.yaml`, or set `input` in contractdiff.config.json');
|
|
226
|
+
const days = idleOption(options);
|
|
227
|
+
const now = options.now ?? new Date();
|
|
228
|
+
const flagged = options.rulesets !== undefined && options.rulesets.length > 0 ? options.rulesets : undefined;
|
|
229
|
+
const contributed = config === undefined ? {} : (await loadPlugins(config)).rules();
|
|
230
|
+
const working = sourcesOf(config?.lint, flagged, (name) => rulesetOfText(name, () => readFileSync(resolve(root, name), 'utf8'), CONFIG_FILE));
|
|
231
|
+
const git = options.git ?? gitIn(root);
|
|
232
|
+
const history = await historyOf({
|
|
233
|
+
git,
|
|
234
|
+
config: config === undefined ? undefined : { file: config.file, name: relative(root, config.file) },
|
|
235
|
+
flagged,
|
|
236
|
+
working,
|
|
237
|
+
resolve: resolverOf(contributed),
|
|
238
|
+
rulesFrom: options.rulesFrom,
|
|
239
|
+
now,
|
|
240
|
+
});
|
|
241
|
+
const { all, levels } = history.resolved;
|
|
242
|
+
const { names, files } = history.sources;
|
|
243
|
+
const notCarried = Object.values(files).flatMap((file) => file.notCarried);
|
|
244
|
+
const legacy = legacyOf(config?.lint?.legacy ?? [], all);
|
|
245
|
+
const { inputs, since } = await inputsOf({ specs, base: options.specs.length > 0 ? options.cwd : root, root, git, since: options.since ?? config?.lint?.since, buf: options.buf });
|
|
246
|
+
const result = lint(withCode(inputs, root, options.typescript), all, levels, legacy);
|
|
247
|
+
const scores = Object.fromEntries(names.map((name) => [name.replace(PREFIX, ''), scoreOf(rulesetOf(name, files), result.counts)]));
|
|
248
|
+
const stats = await recordOf({ options, result, git, now }, days);
|
|
249
|
+
return dataOf({ result, scores, notCarried, notes: { ...history, since, stats }, sarif: options.sarif === true ? toSarif(result, all) : undefined });
|
|
250
|
+
};
|
|
251
|
+
const HERE = '.';
|
|
252
|
+
export const command = defineCommand({
|
|
253
|
+
name: 'lint',
|
|
254
|
+
description: "A contract's form checked by rules: standards, and whether an agent can use it as tools",
|
|
255
|
+
effects: 'idempotent',
|
|
256
|
+
examples: [
|
|
257
|
+
{ command: 'contractdiff lint openapi.yaml', description: 'the recommended rules, as warnings' },
|
|
258
|
+
{ command: 'contractdiff lint openapi.yaml --ruleset agent-ready', description: 'can an agent call this API as tools: descriptions, examples, ids' },
|
|
259
|
+
],
|
|
260
|
+
arguments: [{ name: 'specs', variadic: true, required: false, description: "the contracts to lint (default: the config's input)" }],
|
|
261
|
+
options: {
|
|
262
|
+
ruleset: { type: 'string', multiple: true, choices: Object.keys(rulesets), description: "a ruleset to run, over the config's lint.extends (default recommended)" },
|
|
263
|
+
sarif: { type: 'boolean', description: 'print SARIF 2.1.0 for code scanning instead of text' },
|
|
264
|
+
rulesFrom: { type: 'string', description: 'read the config and its ruleset files at this git ref, so a change to the rules is judged by the old ones; `merge-base` is the base with origin/main' },
|
|
265
|
+
since: { type: 'string', description: "lint in full only the operations added or changed since this git ref; the rest run lint.legacy (default: none). `merge-base` is the base with origin/main; over the config's lint.since" },
|
|
266
|
+
stats: { type: 'string', description: "count this run into a JSON file of per-rule runs, findings and last finding date, once per commit; meant for a CI cache" },
|
|
267
|
+
idle: { type: 'string', description: 'with --stats: list the rules that ran and found nothing in this many days, e.g. 90d, as rule-idle' },
|
|
268
|
+
},
|
|
269
|
+
run: ({ positionals, options }) => runLint({
|
|
270
|
+
cwd: HERE,
|
|
271
|
+
specs: positionals,
|
|
272
|
+
rulesets: options.ruleset,
|
|
273
|
+
sarif: options.sarif,
|
|
274
|
+
rulesFrom: options.rulesFrom,
|
|
275
|
+
since: options.since,
|
|
276
|
+
stats: options.stats,
|
|
277
|
+
idle: options.idle,
|
|
278
|
+
}),
|
|
279
|
+
});
|
|
280
|
+
export { DEFAULT_RULESETS };
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { readdir, readFile, writeFile } from 'node:fs/promises';
|
|
2
|
+
import { join, resolve } from 'node:path';
|
|
3
|
+
import { defineCommand } from 'burgee';
|
|
4
|
+
import { migrate as heyApi } from './migrate-hey-api.js';
|
|
5
|
+
import { migrate as openapiFetch } from './migrate-openapi-fetch.js';
|
|
6
|
+
import { migrate as openapiTypescript } from './migrate-openapi-typescript.js';
|
|
7
|
+
import { migrate as orval } from './migrate-orval.js';
|
|
8
|
+
import { configText } from './migrate-shared.js';
|
|
9
|
+
import { writeFiles } from './scaffold-write.js';
|
|
10
|
+
export const SOURCES = {
|
|
11
|
+
'openapi-typescript': { migrate: openapiTypescript, configs: ['redocly.yaml', '.redocly.yaml'] },
|
|
12
|
+
'openapi-fetch': { migrate: openapiFetch, configs: ['redocly.yaml', '.redocly.yaml'] },
|
|
13
|
+
'hey-api': { migrate: heyApi, configs: ['openapi-ts.config.ts', 'openapi-ts.config.mts', 'openapi-ts.config.cts', 'openapi-ts.config.js', 'openapi-ts.config.mjs', 'openapi-ts.config.cjs'] },
|
|
14
|
+
orval: { migrate: orval, configs: ['orval.config.ts', 'orval.config.mts', 'orval.config.js', 'orval.config.mjs', 'orval.config.cjs'] },
|
|
15
|
+
};
|
|
16
|
+
const SKIPPED = new Set(['node_modules', 'dist', 'build', 'coverage', '.git', '.next', '.turbo']);
|
|
17
|
+
const READ = /(?:^package\.json|\.(?:[cm]?[jt]s|[jt]sx))$/u;
|
|
18
|
+
const walk = async (root, directory) => {
|
|
19
|
+
const entries = await readdir(join(root, directory), { withFileTypes: true });
|
|
20
|
+
const nested = await Promise.all(entries.map(async (entry) => {
|
|
21
|
+
const path = directory === '' ? entry.name : `${directory}/${entry.name}`;
|
|
22
|
+
if (entry.isDirectory())
|
|
23
|
+
return SKIPPED.has(entry.name) ? [] : walk(root, path);
|
|
24
|
+
return entry.isFile() && READ.test(entry.name) ? [path] : [];
|
|
25
|
+
}));
|
|
26
|
+
return nested.flat();
|
|
27
|
+
};
|
|
28
|
+
export const project = async (root) => {
|
|
29
|
+
const paths = await walk(root, '');
|
|
30
|
+
return Object.fromEntries(await Promise.all(paths.map(async (path) => [path, await readFile(join(root, path), 'utf8')])));
|
|
31
|
+
};
|
|
32
|
+
const firstConfig = async (root, names) => {
|
|
33
|
+
const found = await Promise.all(names.map(async (name) => readFile(join(root, name), 'utf8').then((text) => ({ name, text }), () => undefined)));
|
|
34
|
+
return found.find((one) => one !== undefined);
|
|
35
|
+
};
|
|
36
|
+
export const command = defineCommand({
|
|
37
|
+
name: 'migrate',
|
|
38
|
+
description: 'Switch from openapi-typescript, openapi-fetch, Hey API or orval: their config in, ours out',
|
|
39
|
+
arguments: [
|
|
40
|
+
{ name: 'from', description: 'the tool to migrate from', choices: Object.keys(SOURCES), required: true },
|
|
41
|
+
{ name: 'dir', description: 'the project to migrate. Defaults to the current directory', required: false },
|
|
42
|
+
],
|
|
43
|
+
options: {
|
|
44
|
+
dryRun: { type: 'boolean', description: 'report what would change; write nothing' },
|
|
45
|
+
},
|
|
46
|
+
effects: 'idempotent',
|
|
47
|
+
examples: [
|
|
48
|
+
{ command: 'contractdiff migrate openapi-typescript', description: 'redocly.yaml and the scripts that run it, as contractdiff.config.json' },
|
|
49
|
+
{ command: 'contractdiff migrate orval --dry-run --json', description: 'the config, the edits and every finding, as data; nothing written' },
|
|
50
|
+
],
|
|
51
|
+
run: async ({ args, options }) => {
|
|
52
|
+
const root = resolve(args.dir ?? '');
|
|
53
|
+
const source = SOURCES[args.from];
|
|
54
|
+
const [config, files] = await Promise.all([firstConfig(root, source.configs), project(root)]);
|
|
55
|
+
const result = source.migrate(config?.text, files);
|
|
56
|
+
const written = result.config === undefined ? [] : [{ path: 'contractdiff.config.json', owner: 'user', content: configText(result.config) }];
|
|
57
|
+
const dryRun = options.dryRun === true;
|
|
58
|
+
const report = dryRun ? { written: [], unchanged: [], kept: [] } : await writeFiles(root, written);
|
|
59
|
+
await Promise.all((dryRun ? [] : result.edits).map(async (edit) => writeFile(join(root, edit.path), edit.after)));
|
|
60
|
+
return {
|
|
61
|
+
changed: !dryRun && (report.written.length > 0 || result.edits.length > 0),
|
|
62
|
+
read: config?.name ?? null,
|
|
63
|
+
config: result.config ?? null,
|
|
64
|
+
...report,
|
|
65
|
+
edited: result.edits.map((edit) => edit.path),
|
|
66
|
+
findings: result.findings,
|
|
67
|
+
uninstall: result.uninstall,
|
|
68
|
+
};
|
|
69
|
+
},
|
|
70
|
+
});
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { defineCommand } from 'burgee';
|
|
3
|
+
import { UsageError } from './run-config.js';
|
|
4
|
+
import { seedOf } from './scaffold-seed.js';
|
|
5
|
+
import { writeFiles } from './scaffold-write.js';
|
|
6
|
+
import { KINDS, scaffold } from './scaffold.js';
|
|
7
|
+
export const command = defineCommand({
|
|
8
|
+
name: 'plugin',
|
|
9
|
+
description: 'Scaffold a plugin that passes the conformance suite as generated',
|
|
10
|
+
arguments: [
|
|
11
|
+
{ name: 'action', description: '`new`: scaffold a plugin', choices: ['new'], required: true },
|
|
12
|
+
{ name: 'name', description: 'the plugin name: lowercase letters, digits and single dashes', required: true },
|
|
13
|
+
],
|
|
14
|
+
options: {
|
|
15
|
+
kind: { type: 'string', choices: KINDS, default: 'generator', description: 'what the plugin contributes: spec to code, code to spec, an input format, or lint rules' },
|
|
16
|
+
from: { type: 'string', placeholder: 'finding.json', description: 'with --kind rules: seed the rule from one finding of `contractdiff lint --json`' },
|
|
17
|
+
out: { type: 'string', placeholder: 'dir', description: 'directory to write into. Defaults to the current directory' },
|
|
18
|
+
},
|
|
19
|
+
effects: 'idempotent',
|
|
20
|
+
examples: [
|
|
21
|
+
{ command: 'contractdiff plugin new my-target', description: 'a generator plugin, its conformance test and a README' },
|
|
22
|
+
{ command: 'contractdiff plugin new my-source --kind extractor --out plugins', description: 'an extractor, written under plugins/' },
|
|
23
|
+
{ command: 'contractdiff plugin new no-bare-ids --kind rules --from finding.json', description: 'a lint rule that finds the mistake one finding named, with that as its sample' },
|
|
24
|
+
],
|
|
25
|
+
run: async ({ args, options }) => {
|
|
26
|
+
if (options.from !== undefined && options.kind !== 'rules')
|
|
27
|
+
throw new UsageError(`--from seeds a rule, and --kind is ${options.kind}. fix: pass --kind rules with --from`);
|
|
28
|
+
const files = scaffold(args.name, options.kind, options.from === undefined ? undefined : seedOf(options.from, '.'));
|
|
29
|
+
const written = await writeFiles(resolve(options.out ?? ''), files);
|
|
30
|
+
return { changed: written.written.length > 0, ...written, next: `node --test plugin-${args.name}.test.ts` };
|
|
31
|
+
},
|
|
32
|
+
});
|