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.
Files changed (183) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +228 -2
  3. package/dist/bin.js +4 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.js +24 -0
  6. package/dist/command-diff.js +310 -0
  7. package/dist/command-explain-cap.js +36 -0
  8. package/dist/command-explain-inline.js +17 -0
  9. package/dist/command-explain-name.js +31 -0
  10. package/dist/command-explain-operation.js +85 -0
  11. package/dist/command-explain-text.js +21 -0
  12. package/dist/command-explain.js +54 -0
  13. package/dist/command-lint.js +280 -0
  14. package/dist/command-migrate.js +70 -0
  15. package/dist/command-plugin.js +32 -0
  16. package/dist/command-props.js +116 -0
  17. package/dist/commands.js +7 -0
  18. package/dist/core/index.d.ts +2 -0
  19. package/dist/core/index.js +2 -0
  20. package/dist/core/model.d.ts +46 -0
  21. package/dist/core/model.js +1 -0
  22. package/dist/core/resolve.d.ts +22 -0
  23. package/dist/core/resolve.js +71 -0
  24. package/dist/diff-classify.js +30 -0
  25. package/dist/diff-contract.js +176 -0
  26. package/dist/diff-decisions.js +446 -0
  27. package/dist/diff-normalise.js +143 -0
  28. package/dist/diff-rules.js +109 -0
  29. package/dist/diff-schema.js +335 -0
  30. package/dist/diff-security.js +33 -0
  31. package/dist/diff-transitive.js +26 -0
  32. package/dist/diff-usage.js +59 -0
  33. package/dist/extract-normalise.js +85 -0
  34. package/dist/extract-roundtrip.js +28 -0
  35. package/dist/extract-standard.js +79 -0
  36. package/dist/gen-ts-ast.d.ts +135 -0
  37. package/dist/gen-ts-ast.js +52 -0
  38. package/dist/gen-ts-bundle.js +233 -0
  39. package/dist/gen-ts-comment.js +48 -0
  40. package/dist/gen-ts-context.d.ts +83 -0
  41. package/dist/gen-ts-context.js +45 -0
  42. package/dist/gen-ts-dict.d.ts +14 -0
  43. package/dist/gen-ts-dict.js +14 -0
  44. package/dist/gen-ts-discriminators.d.ts +7 -0
  45. package/dist/gen-ts-discriminators.js +117 -0
  46. package/dist/gen-ts-document.d.ts +12 -0
  47. package/dist/gen-ts-document.js +82 -0
  48. package/dist/gen-ts-enums.js +139 -0
  49. package/dist/gen-ts-helpers.js +30 -0
  50. package/dist/gen-ts-index.d.ts +49 -0
  51. package/dist/gen-ts-index.js +110 -0
  52. package/dist/gen-ts-operations.js +277 -0
  53. package/dist/gen-ts-print.js +113 -0
  54. package/dist/gen-ts-ref.d.ts +30 -0
  55. package/dist/gen-ts-ref.js +75 -0
  56. package/dist/gen-ts-schema.js +283 -0
  57. package/dist/gen-ts-text.d.ts +24 -0
  58. package/dist/gen-ts-text.js +98 -0
  59. package/dist/host.d.ts +145 -0
  60. package/dist/host.js +273 -0
  61. package/dist/index.d.ts +6 -0
  62. package/dist/index.js +5 -0
  63. package/dist/input-asyncapi.js +167 -0
  64. package/dist/input-buf.js +58 -0
  65. package/dist/input-jsonschema.js +165 -0
  66. package/dist/input-mcp.js +111 -0
  67. package/dist/input-overlay-jsonpath.js +265 -0
  68. package/dist/input-overlay.js +138 -0
  69. package/dist/input-protobuf.js +212 -0
  70. package/dist/input-swagger2.js +331 -0
  71. package/dist/inputs.js +8 -0
  72. package/dist/lint-code-read.js +129 -0
  73. package/dist/lint-code.d.ts +56 -0
  74. package/dist/lint-code.js +64 -0
  75. package/dist/lint-engine.d.ts +93 -0
  76. package/dist/lint-engine.js +87 -0
  77. package/dist/lint-functions.js +95 -0
  78. package/dist/lint-history.js +133 -0
  79. package/dist/lint-jsonpath.js +92 -0
  80. package/dist/lint-names.d.ts +11 -0
  81. package/dist/lint-names.js +2 -0
  82. package/dist/lint-redocly.js +141 -0
  83. package/dist/lint-rules.js +189 -0
  84. package/dist/lint-select.d.ts +33 -0
  85. package/dist/lint-select.js +129 -0
  86. package/dist/lint-since.js +20 -0
  87. package/dist/lint-spectral.js +167 -0
  88. package/dist/lint-stats.js +58 -0
  89. package/dist/migrate-hey-api.js +144 -0
  90. package/dist/migrate-literal.js +139 -0
  91. package/dist/migrate-openapi-fetch.js +62 -0
  92. package/dist/migrate-openapi-typescript.js +159 -0
  93. package/dist/migrate-orval.js +119 -0
  94. package/dist/migrate-shared.js +31 -0
  95. package/dist/openapi-typescript.d.ts +9 -0
  96. package/dist/openapi-typescript.js +36 -0
  97. package/dist/openapi.d.ts +20 -0
  98. package/dist/openapi.js +94 -0
  99. package/dist/plugin-express.js +66 -0
  100. package/dist/plugin-extract-hono.js +1 -0
  101. package/dist/plugin-extract-nest.js +1 -0
  102. package/dist/plugin-extract-openapi.js +246 -0
  103. package/dist/plugin-extract-standard-schema.js +42 -0
  104. package/dist/plugin-extract-trpc.js +1 -0
  105. package/dist/plugin-extract-ts-rest.js +77 -0
  106. package/dist/plugin-fastify.js +68 -0
  107. package/dist/plugin-fetch-client.js +172 -0
  108. package/dist/plugin-fetch-routes.js +110 -0
  109. package/dist/plugin-fetch-sample.js +155 -0
  110. package/dist/plugin-fetch-text.js +5 -0
  111. package/dist/plugin-fetch.js +19 -0
  112. package/dist/plugin-hono.js +42 -0
  113. package/dist/plugin-json-schema-build.js +289 -0
  114. package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
  115. package/dist/plugin-json-schema-dialect-gemini.js +29 -0
  116. package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
  117. package/dist/plugin-json-schema-dialect-mcp.js +13 -0
  118. package/dist/plugin-json-schema-dialect-openai.js +37 -0
  119. package/dist/plugin-json-schema-dialect.js +180 -0
  120. package/dist/plugin-json-schema.js +125 -0
  121. package/dist/plugin-markdown.js +114 -0
  122. package/dist/plugin-mcp-code.js +28 -0
  123. package/dist/plugin-mcp-tools.js +152 -0
  124. package/dist/plugin-mcp.js +107 -0
  125. package/dist/plugin-msw-files.js +50 -0
  126. package/dist/plugin-msw-sample.js +45 -0
  127. package/dist/plugin-msw-synth.js +116 -0
  128. package/dist/plugin-msw.js +30 -0
  129. package/dist/plugin-nest-code.js +68 -0
  130. package/dist/plugin-nest-contract.js +23 -0
  131. package/dist/plugin-nest.js +44 -0
  132. package/dist/plugin-server-code.js +61 -0
  133. package/dist/plugin-server-contract.js +48 -0
  134. package/dist/plugin-server-example.js +62 -0
  135. package/dist/plugin-server-router.js +77 -0
  136. package/dist/plugin-server-routes.js +155 -0
  137. package/dist/plugin-server-runtime.js +3 -0
  138. package/dist/plugin-server-sample.js +40 -0
  139. package/dist/plugin-swr-sample.js +21 -0
  140. package/dist/plugin-swr.js +40 -0
  141. package/dist/plugin-tanstack-query-sample.js +21 -0
  142. package/dist/plugin-tanstack-query.js +59 -0
  143. package/dist/plugin-types.js +80 -0
  144. package/dist/plugin-validator-code.js +41 -0
  145. package/dist/plugin-validator-names.js +27 -0
  146. package/dist/plugin-validator.js +103 -0
  147. package/dist/plugins.js +21 -0
  148. package/dist/props-emit.js +194 -0
  149. package/dist/props-generate.js +408 -0
  150. package/dist/props-judge.js +30 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +170 -0
  154. package/dist/props-shrink.js +75 -0
  155. package/dist/run-apply.js +25 -0
  156. package/dist/run-command.js +31 -0
  157. package/dist/run-commit.d.ts +51 -0
  158. package/dist/run-commit.js +48 -0
  159. package/dist/run-config.d.ts +193 -0
  160. package/dist/run-config.js +256 -0
  161. package/dist/run-diff.js +24 -0
  162. package/dist/run-extract.d.ts +13 -0
  163. package/dist/run-extract.js +21 -0
  164. package/dist/run-gen.d.ts +15 -0
  165. package/dist/run-gen.js +43 -0
  166. package/dist/run-header.js +37 -0
  167. package/dist/run-input.js +31 -0
  168. package/dist/run-load.js +32 -0
  169. package/dist/run-map.d.ts +41 -0
  170. package/dist/run-map.js +52 -0
  171. package/dist/run-plan.d.ts +31 -0
  172. package/dist/run-plan.js +35 -0
  173. package/dist/scaffold-seed.js +43 -0
  174. package/dist/scaffold-write.js +17 -0
  175. package/dist/scaffold.js +196 -0
  176. package/dist/testing-lint.js +43 -0
  177. package/dist/testing-owner.js +17 -0
  178. package/dist/testing-probe.js +25 -0
  179. package/dist/testing-rules.d.ts +65 -0
  180. package/dist/testing-rules.js +115 -0
  181. package/dist/testing.d.ts +32 -0
  182. package/dist/testing.js +79 -0
  183. package/package.json +108 -4
@@ -0,0 +1,283 @@
1
+ import { BOOLEAN, NEVER, NULL, NUMBER, STRING, UNKNOWN, alias, array, intersection, isPrimitive, nullable, object, property, readonlyOf, record, reference, rest, tuple, union, } from './gen-ts-ast.js';
2
+ import { jsDoc } from './gen-ts-comment.js';
3
+ import { dict, entries, isDict, list, size } from './gen-ts-dict.js';
4
+ import { enumType, literalType } from './gen-ts-enums.js';
5
+ import { WITH_REQUIRED, requireHelper } from './gen-ts-helpers.js';
6
+ import { createRef, pointerOf, refType } from './gen-ts-ref.js';
7
+ import { propertyName } from './gen-ts-text.js';
8
+ const SCALAR_TYPES = new Map([
9
+ ['null', NULL],
10
+ ['string', STRING],
11
+ ['number', NUMBER],
12
+ ['integer', NUMBER],
13
+ ['boolean', BOOLEAN],
14
+ ]);
15
+ const repeated = (type, count) => Array.from({ length: count }, () => type);
16
+ const TUPLE_BUDGET = 30;
17
+ const NO_MAXIMUM = -1;
18
+ const count = (value) => (typeof value === 'number' && value >= 0 ? value : undefined);
19
+ const boundedArray = (schema, itemType) => {
20
+ const min = count(schema.minItems) ?? 0;
21
+ const declaredMax = count(schema.maxItems) ?? NO_MAXIMUM;
22
+ const max = min <= declaredMax ? declaredMax : undefined;
23
+ const size = max === undefined ? min : (max * (max + 1) - min * (min - 1)) / 2;
24
+ if ((min === 0 && max === undefined) || size >= TUPLE_BUDGET)
25
+ return undefined;
26
+ if (min === max)
27
+ return tuple(repeated(itemType, min));
28
+ if (schema.maxItems > 0) {
29
+ const lengths = Array.from({ length: declaredMax - min + 1 }, (_unused, extra) => extra);
30
+ return union(lengths.map((extra) => tuple(repeated(itemType, extra))));
31
+ }
32
+ return tuple([...repeated(itemType, min), rest(array(itemType))]);
33
+ };
34
+ const itemsType = (schema, options) => {
35
+ const { items, prefixItems } = schema;
36
+ if (prefixItems || Array.isArray(items)) {
37
+ return tuple(list(prefixItems ?? items).map((item) => transformSchemaObject(item, options)));
38
+ }
39
+ if (!items)
40
+ return UNKNOWN;
41
+ const type = transformSchemaObject(items, options);
42
+ return dict(items).type === 'array' ? array(type) : type;
43
+ };
44
+ const arrayType = (schema, options) => {
45
+ const itemType = itemsType(schema, options);
46
+ const bounded = options.ctx.arrayLength ? boundedArray(schema, itemType) : undefined;
47
+ if (bounded !== undefined)
48
+ return bounded;
49
+ const type = itemType.kind === 'tuple' || itemType.kind === 'array' ? itemType : array(itemType);
50
+ return options.ctx.immutable ? readonlyOf(type) : type;
51
+ };
52
+ const ONE_OF_SCALARS = new Set(['boolean', 'string', 'number', 'integer', 'null']);
53
+ const polymorphicType = (schema, types, options) => {
54
+ const listed = new Set(list(schema.oneOf).map((item) => dict(item).type));
55
+ const override = Array.isArray(schema.oneOf) ? { oneOf: undefined } : {};
56
+ return union(types
57
+ .filter((type) => !(ONE_OF_SCALARS.has(type) && listed.has(type)))
58
+ .map((type) => (type === 'null' || type === null ? NULL : transformSchemaObject({ ...schema, type, ...override }, options))));
59
+ };
60
+ const typedCore = (schema, options) => {
61
+ const { type } = schema;
62
+ if (type === 'array')
63
+ return arrayType(schema, options);
64
+ if (Array.isArray(type))
65
+ return polymorphicType(schema, type, options);
66
+ return SCALAR_TYPES.get(type);
67
+ };
68
+ export const discriminatorProperty = (discriminator, path, readonly) => {
69
+ const inferred = pointerOf(path).pop();
70
+ const mapped = Object.entries(discriminator.mapping ?? {}).find(([, target]) => target.startsWith('#') ? pointerOf(target).pop() === inferred : target === inferred);
71
+ return property({
72
+ readonly,
73
+ name: propertyName(discriminator.propertyName),
74
+ type: literalType(mapped?.[0] ?? inferred),
75
+ });
76
+ };
77
+ const marked = (type, schema, ctx) => {
78
+ const readOnly = Boolean(schema.readOnly);
79
+ const writeOnly = Boolean(schema.writeOnly);
80
+ if (!ctx.readWriteMarkers || readOnly === writeOnly)
81
+ return type;
82
+ return reference(readOnly ? '$Read' : '$Write', [type]);
83
+ };
84
+ const isReadonly = (schema, ctx) => ctx.immutable || (!ctx.readWriteMarkers && Boolean(schema.readOnly));
85
+ const REQUEST_PATHS = ['parameters', 'requestBody', 'requestBodies'];
86
+ const defaultsApply = (schema, options) => {
87
+ return schema.default !== undefined && options.ctx.defaultNonNullable && !REQUEST_PATHS.some((part) => options.path?.includes(part));
88
+ };
89
+ const isRequired = (parent, key, ctx) => list(parent.required).includes(key) || (parent.required === undefined && ctx.propertiesRequiredByDefault);
90
+ const isExcluded = (schema, ctx) => {
91
+ if (!ctx.excludeDeprecated)
92
+ return false;
93
+ const resolved = schema.$ref ? ctx.resolve(String(schema.$ref)) : schema;
94
+ return Boolean(dict(resolved).deprecated);
95
+ };
96
+ const describeKind = (value) => {
97
+ if (value === null)
98
+ return 'null';
99
+ return Array.isArray(value) ? 'Array' : typeof value;
100
+ };
101
+ const propertyMember = (parent, entry, options) => {
102
+ const [key, value] = entry;
103
+ if (typeof value !== 'boolean' && !isDict(value)) {
104
+ throw new Error(`${String(options.path)}: invalid property ${key}. Expected Schema Object or boolean, got ${describeKind(value)}. fix: make \`${key}\` a schema object or a boolean`);
105
+ }
106
+ const schema = dict(value);
107
+ const { ctx } = options;
108
+ if (isExcluded(schema, ctx))
109
+ return [];
110
+ const type = schema.$ref
111
+ ? schemaRef(String(schema.$ref), { ...options, behindObject: true })
112
+ :
113
+ transformSchemaObject(value, { ...options, path: createRef([options.path, key]), behindObject: true });
114
+ return [
115
+ property({
116
+ readonly: isReadonly(schema, ctx),
117
+ name: propertyName(key),
118
+ optional: !(isRequired(parent, key, ctx) || defaultsApply(schema, options)),
119
+ type: marked(type, schema, ctx),
120
+ comment: jsDoc(value),
121
+ }),
122
+ ];
123
+ };
124
+ const definitionsMember = (definitions, options) => {
125
+ const members = Object.entries(dict(definitions)).map(([key, value]) => {
126
+ const schema = dict(value);
127
+ const type = transformSchemaObject(value, { ...options, path: createRef([options.path, '$defs', key]) });
128
+ return property({
129
+ readonly: isReadonly(schema, options.ctx),
130
+ name: propertyName(key),
131
+ type: marked(type, schema, options.ctx),
132
+ comment: jsDoc(value),
133
+ });
134
+ });
135
+ return members.length > 0 ? [property({ name: '$defs', type: object(members) })] : [];
136
+ };
137
+ const indexTypes = (schema, options) => {
138
+ const { additionalProperties, patternProperties } = schema;
139
+ const declared = size(additionalProperties);
140
+ const types = [];
141
+ const behind = { ...options, behindObject: true };
142
+ if ((declared ?? 0) > 0)
143
+ types.push(transformSchemaObject(additionalProperties, behind, true));
144
+ if (additionalProperties === true || declared === 0 || (!additionalProperties && options.ctx.additionalProperties)) {
145
+ types.push(UNKNOWN);
146
+ }
147
+ for (const [, pattern] of entries(patternProperties, options.ctx)) {
148
+ types.push(transformSchemaObject(pattern, behind));
149
+ }
150
+ return types;
151
+ };
152
+ const inheritedDiscriminator = (schema, options) => {
153
+ const path = options.path ?? '';
154
+ const { discriminators } = options.ctx;
155
+ const isChild = Boolean(schema.allOf || schema.anyOf) && !schema.discriminator;
156
+ const discriminator = isChild && !discriminators.refsHandled.includes(path) ? discriminators.objects[path] : undefined;
157
+ return discriminator === undefined ? [] : [discriminatorProperty(discriminator, path, options.ctx.immutable)];
158
+ };
159
+ const objectCore = (schema, options) => {
160
+ const hasProperties = (size(schema.properties) ?? 0) > 0;
161
+ const inherited = inheritedDiscriminator(schema, options);
162
+ const stated = new Set(inherited.map((member) => member.name));
163
+ const members = [
164
+ ...inherited,
165
+ ...(hasProperties ? entries(schema.properties, options.ctx) : [])
166
+ .filter(([key]) => !stated.has(propertyName(key)))
167
+ .flatMap((entry) => propertyMember(schema, entry, options)),
168
+ ...definitionsMember(schema.$defs, options),
169
+ ];
170
+ const isObjectLike = hasProperties || schema.additionalProperties || schema.patternProperties || schema.$defs;
171
+ const named = members.length > 0 ? [object(members)] : [];
172
+ const index = isObjectLike ? indexTypes(schema, options) : [];
173
+ if (index.length === 0)
174
+ return named[0];
175
+ const signature = { kind: 'index', readonly: options.ctx.immutable, parameter: 'key', parameterType: 'string', type: union(index) };
176
+ return intersection([...named, object([signature])]);
177
+ };
178
+ const ROOT_TOKENS = 3;
179
+ const STRUCTURAL = new Set(['allOf', 'anyOf', 'oneOf', 'not', 'items', 'prefixItems', 'additionalProperties', 'patternProperties', 'if', 'then', 'else', 'definitions']);
180
+ const PRINTED_AS_VALUE = new Set(['parameters', 'headers', 'requestBody']);
181
+ const indexable = (ref) => {
182
+ const tokens = pointerOf(ref);
183
+ const deep = tokens.slice(ROOT_TOKENS);
184
+ if (tokens.slice(1, -1).some((token) => PRINTED_AS_VALUE.has(token)))
185
+ return false;
186
+ return !deep.some((token) => STRUCTURAL.has(token)) && deep.filter((token) => token === 'properties').length <= 1;
187
+ };
188
+ const deepAliases = new WeakMap();
189
+ const aliasName = (ref, taken) => {
190
+ const base = `Ref_${pointerOf(ref).join('_').replaceAll(/[^\w$]/g, '_')}`;
191
+ let name = base;
192
+ for (let n = 2; taken.has(name); n += 1)
193
+ name = `${base}_${n}`;
194
+ return name;
195
+ };
196
+ const bareSelfReference = (ref, options) => options.behindObject !== true && `${String(options.path)}/`.startsWith(`${ref}/`);
197
+ function schemaRef(written, options) {
198
+ const { ctx } = options;
199
+ const ref = pointerOf(written).length > ROOT_TOKENS ? ctx.lastRef(written) : written;
200
+ const target = ctx.resolve(ref);
201
+ if ((indexable(ref) && !bareSelfReference(ref, options)) || target === undefined)
202
+ return refType(ref);
203
+ const names = deepAliases.get(ctx) ?? new Map();
204
+ deepAliases.set(ctx, names);
205
+ const known = names.get(ref);
206
+ if (known !== undefined)
207
+ return reference(known);
208
+ const name = aliasName(ref, new Set(names.values()));
209
+ names.set(ref, name);
210
+ ctx.injectFooter.push(alias(name, transformSchemaObject(target, { ...options, path: ref, behindObject: false })));
211
+ return reference(name);
212
+ }
213
+ const unionMembers = (items, key, options) => list(items).map((item, index) => transformSchemaObject(item, { ...options, path: createRef([options.path, key, String(index)]) }));
214
+ const mayBeAbsent = (resolved, ref) => resolved.nullable === true || (Array.isArray(resolved.type) && resolved.type.includes('null')) || pointerOf(ref).length > ROOT_TOKENS;
215
+ const referencedMember = (item, required, options) => {
216
+ const { ctx } = options;
217
+ const ref = String(item.$ref);
218
+ const type = schemaRef(ref, options);
219
+ const resolved = ctx.resolve(ref);
220
+ if (!isDict(resolved) || !('properties' in resolved) || ctx.discriminators.refsHandled.includes(ref))
221
+ return type;
222
+ const properties = dict(resolved.properties);
223
+ const keys = required.filter((key) => Boolean(properties[String(key)]));
224
+ if (keys.length === 0)
225
+ return type;
226
+ requireHelper(ctx.injectFooter, WITH_REQUIRED);
227
+ const base = mayBeAbsent(resolved, ref) ? reference('NonNullable', [type]) : type;
228
+ return reference('WithRequired', [base, union(keys.map((key) => literalType(key)))]);
229
+ };
230
+ const allOfMember = (item, required, options) => {
231
+ if (!isDict(item))
232
+ return transformSchemaObject(item, options);
233
+ const isReference = '$ref' in item;
234
+ const type = isReference
235
+ ? referencedMember(item, required, options)
236
+ :
237
+ transformSchemaObject({ ...item, required: [...required, ...list(item.required)] }, options);
238
+ const inherited = isReference ? options.ctx.discriminators.objects[String(item.$ref)] : undefined;
239
+ const discriminator = inherited ?? item.discriminator;
240
+ return discriminator ? reference('Omit', [type, literalType(dict(discriminator).propertyName)]) : type;
241
+ };
242
+ const withAnyOf = (type, schema, options) => {
243
+ const anyOf = unionMembers(schema.anyOf, 'anyOf', options);
244
+ return anyOf.length > 0 ? union([...(type ? [type] : []), ...anyOf]) : type;
245
+ };
246
+ const withOneOf = (type, schema, options) => {
247
+ const items = schema.oneOf || (schema.type === 'object' && schema.enum);
248
+ const oneOf = unionMembers(items, 'oneOf', options);
249
+ if (oneOf.length === 0)
250
+ return type;
251
+ const before = type ? [type] : [];
252
+ return oneOf.every((member) => isPrimitive(member)) ? union([...before, ...oneOf]) : intersection([...before, union(oneOf)]);
253
+ };
254
+ const composed = (schema, options) => {
255
+ const typed = schema.type ? typedCore(schema, options) : undefined;
256
+ const core = typed ?? objectCore(schema, options);
257
+ const allOf = list(schema.allOf).map((item) => allOfMember(item, list(schema.required), options));
258
+ const base = [...(core ? [core] : []), ...(allOf.length > 0 ? [intersection(allOf)] : [])];
259
+ const start = base.length > 0 ? intersection(base) : undefined;
260
+ const type = withOneOf(withAnyOf(start, schema, options), schema, options);
261
+ if (type !== undefined)
262
+ return type !== UNKNOWN && schema.nullable ? nullable(type) : type;
263
+ if (!('type' in schema))
264
+ return UNKNOWN;
265
+ const empty = record(STRING, options.ctx.emptyObjectsUnknown ? UNKNOWN : NEVER);
266
+ return schema.nullable ? nullable(empty) : empty;
267
+ };
268
+ export function transformSchemaObject(schema, options, fromAdditionalProperties = false) {
269
+ if (!schema)
270
+ return NEVER;
271
+ if (schema === true)
272
+ return UNKNOWN;
273
+ if (!isDict(schema)) {
274
+ throw new Error(`Expected SchemaObject, received ${Array.isArray(schema) ? 'Array' : typeof schema} at ${String(options.path)}. fix: write a schema object, \`true\` or \`false\` there`);
275
+ }
276
+ if ('$ref' in schema)
277
+ return schemaRef(String(schema.$ref), options);
278
+ if (schema.type === 'null' && (schema.oneOf || schema.anyOf))
279
+ return composed({ ...schema, type: undefined, nullable: true }, options);
280
+ if (schema.const !== null && schema.const !== undefined)
281
+ return literalType(schema.const);
282
+ return enumType(schema, options, fromAdditionalProperties) ?? composed(schema, options);
283
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Source text for names and literals, as the TypeScript printer writes them: string escapes,
3
+ * property names, enum member names, and the `PascalCase` used for root type aliases.
4
+ */
5
+ /** A double-quoted string literal: control and non-ASCII code units become escapes. */
6
+ export declare const quote: (text: string) => string;
7
+ /** A property name: a number or an identifier stays bare, anything else is quoted. */
8
+ export declare const propertyName: (index: unknown) => string;
9
+ /**
10
+ * Upstream tests a trailing invalid character with a global regular expression, whose `lastIndex`
11
+ * survives the call: after one hit the next test misses, whatever it is given. The flag stands in
12
+ * for that `lastIndex`, so the names come out the same.
13
+ */
14
+ export interface NameState {
15
+ /** Whether that expression stands at its start, where a test reads what it is given. */
16
+ rewound: boolean;
17
+ }
18
+ export declare const newNameState: () => NameState;
19
+ /** A name for an enum or a values array: runs of invalid characters go, the next letter is raised. */
20
+ export declare const memberName: (name: string, state: NameState) => string;
21
+ /** The name of one enum member: `Value` before a leading digit, `ValueMinus` for a leading `-`. */
22
+ export declare const enumMemberName: (given: string, state: NameState) => string;
23
+ /** `change-case`'s `pascalCase` with its default options. */
24
+ export declare const pascalCase: (value: string) => string;
@@ -0,0 +1,98 @@
1
+ const HEX = 16;
2
+ const UNIT_WIDTH = 4;
3
+ const SPACE = 0x20;
4
+ const ASCII_MAX = 0x7f;
5
+ const NAMED_ESCAPES = new Map([
6
+ ['\t', String.raw `\t`],
7
+ ['\v', String.raw `\v`],
8
+ ['\f', String.raw `\f`],
9
+ ['\b', String.raw `\b`],
10
+ ['\r', String.raw `\r`],
11
+ ['\n', String.raw `\n`],
12
+ ['\\', String.raw `\\`],
13
+ ['"', String.raw `\"`],
14
+ ]);
15
+ const DIGIT = /\d/;
16
+ const escapeUnit = (unit, next) => {
17
+ const named = NAMED_ESCAPES.get(unit);
18
+ if (named !== undefined)
19
+ return named;
20
+ const code = unit.charCodeAt(0);
21
+ if (code === 0)
22
+ return DIGIT.test(next) ? String.raw `\x00` : String.raw `\0`;
23
+ if (code >= SPACE && code <= ASCII_MAX)
24
+ return unit;
25
+ return String.raw `\u${code.toString(HEX).toUpperCase().padStart(UNIT_WIDTH, '0')}`;
26
+ };
27
+ export const quote = (text) => {
28
+ let out = '"';
29
+ for (let index = 0; index < text.length; index++) {
30
+ out += escapeUnit(text.charAt(index), text.charAt(index + 1));
31
+ }
32
+ return `${out}"`;
33
+ };
34
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z_$0-9]*$/;
35
+ const INVALID_RUN = /[^A-Za-z_$0-9]+/g;
36
+ const INVALID_RUN_THEN_NEXT = /[^A-Za-z_$0-9]+(.)?/g;
37
+ const INVALID_UNIT = /[^A-Za-z_$0-9]/;
38
+ export const propertyName = (index) => {
39
+ if (typeof index === 'number' && !(index < 0))
40
+ return String(index);
41
+ if (typeof index !== 'string')
42
+ return quote(String(index));
43
+ if (String(Number(index)) === index && !index.startsWith('-'))
44
+ return index;
45
+ return IDENTIFIER.test(index) ? index : quote(index);
46
+ };
47
+ export const newNameState = () => ({ rewound: true });
48
+ const lastUnit = (state, last) => {
49
+ if (!state.rewound) {
50
+ state.rewound = true;
51
+ return last.toUpperCase();
52
+ }
53
+ if (INVALID_UNIT.test(last)) {
54
+ state.rewound = false;
55
+ return '';
56
+ }
57
+ return last.toUpperCase();
58
+ };
59
+ export const memberName = (name, state) => {
60
+ const sanitized = name.replaceAll(INVALID_RUN_THEN_NEXT, (match) => lastUnit(state, match.charAt(match.length - 1)));
61
+ return Number(name[0]) >= 0 ? `Value${name}` : sanitized;
62
+ };
63
+ const SPECIAL = new Map([['+', 'Plus']]);
64
+ const invalidRunsReplaced = (name, state) => {
65
+ state.rewound = true;
66
+ const runs = name.match(INVALID_RUN);
67
+ if (runs === null)
68
+ return name;
69
+ return runs[0] === name ? `"${name}"` : name.replaceAll(INVALID_RUN, (run) => SPECIAL.get(run) ?? '_');
70
+ };
71
+ export const enumMemberName = (given, state) => {
72
+ if (IDENTIFIER.test(given))
73
+ return given;
74
+ let name = given;
75
+ if (Number(name[0]) >= 0)
76
+ name = `Value${name}`.replace('.', '_');
77
+ else if (name.startsWith('-'))
78
+ name = `ValueMinus${name.slice(1)}`;
79
+ return invalidRunsReplaced(name, state);
80
+ };
81
+ const LOWER_UPPER = /([\p{Ll}\d])(\p{Lu})/gu;
82
+ const UPPER_UPPER_LOWER = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu;
83
+ const NOT_WORD = /[^\p{L}\d]/giu;
84
+ const BOUNDARY = '\0';
85
+ const SPLIT = `$1${BOUNDARY}$2`;
86
+ const words = (value) => {
87
+ const marked = value
88
+ .replaceAll(LOWER_UPPER, SPLIT)
89
+ .replaceAll(UPPER_UPPER_LOWER, SPLIT)
90
+ .replaceAll(NOT_WORD, BOUNDARY);
91
+ return marked.split(BOUNDARY).filter((word) => word !== '');
92
+ };
93
+ const pascalWord = (word, index) => {
94
+ const first = word.charAt(0);
95
+ const initial = index > 0 && first <= '9' ? `_${first}` : first.toUpperCase();
96
+ return initial + word.slice(1).toLowerCase();
97
+ };
98
+ export const pascalCase = (value) => words(value).map(pascalWord).join('');
package/dist/host.d.ts ADDED
@@ -0,0 +1,145 @@
1
+ /**
2
+ * The plugin host for contractdiff's half of the family contract (spec.md R-PL; `plugin-contract`).
3
+ */
4
+ import { type Contract, type ContractFinding } from './core/model.js';
5
+ import { type Rule } from './lint-engine.js';
6
+ /** The plugin contract version: one number for the family. */
7
+ export declare const CONTRACT = 1;
8
+ /** `generated` is rewritten on every run. `user` is written once and never touched again (R-PL4). */
9
+ export type Owner = 'generated' | 'user';
10
+ /** One symbol a generated file declares for an operation: what `contractdiff.map.json` records (R-BL1). */
11
+ export interface GeneratedSymbol {
12
+ /** The operation's id in the contract. */
13
+ readonly operation: string;
14
+ /** The name the file declares for it, e.g. `ListPetsResponse`. */
15
+ readonly symbol: string;
16
+ }
17
+ export interface GeneratedFile {
18
+ /** Relative to the output folder, with `/` separators. */
19
+ readonly path: string;
20
+ /** The body: the writer adds the generated header, so a generator never writes one. */
21
+ readonly content: string;
22
+ readonly owner: Owner;
23
+ /** The symbols this file declares per operation. Optional: a file without them is still mapped by its path. */
24
+ readonly symbols?: readonly GeneratedSymbol[];
25
+ }
26
+ export type Options = Readonly<Record<string, unknown>>;
27
+ /** An input format: a parsed document in, the model out. */
28
+ export interface Adapter {
29
+ readonly description: string;
30
+ readonly detect: (document: unknown) => boolean;
31
+ readonly read: (document: unknown) => Contract;
32
+ }
33
+ /** The generator's static projection (R-PL5): a small document and exactly what it produces. */
34
+ export interface Sample {
35
+ readonly document: unknown;
36
+ readonly options?: Options;
37
+ readonly files: readonly GeneratedFile[];
38
+ }
39
+ /** What a generator may return when it has something to report besides files. */
40
+ export interface GeneratorResult {
41
+ readonly files: readonly GeneratedFile[];
42
+ readonly findings: readonly ContractFinding[];
43
+ }
44
+ /** Spec → code: data plus one function (R-PL2). */
45
+ export interface Generator {
46
+ readonly description: string;
47
+ /** Names of the input formats it accepts, e.g. `openapi`. */
48
+ readonly inputs: readonly string[];
49
+ /** burgee option declarations, keyed by option name. */
50
+ readonly options?: Readonly<Record<string, unknown>>;
51
+ readonly sample: Sample;
52
+ readonly run: (contract: Contract, options: Options) => readonly GeneratedFile[] | GeneratorResult | Promise<readonly GeneratedFile[] | GeneratorResult>;
53
+ }
54
+ /** An extractor's static projection: the options it is run with, and the document it returns. */
55
+ export interface ExtractorSample {
56
+ readonly options: Options;
57
+ readonly document: unknown;
58
+ }
59
+ /** What an extractor may return when it has something to report besides the document: what the document could not say. */
60
+ export interface ExtractorResult {
61
+ readonly document: unknown;
62
+ readonly findings: readonly ContractFinding[];
63
+ }
64
+ /** Code → spec (spec.md R-TE2): reads the user's code, named by its options, and returns a document, or `{ document, findings }`. */
65
+ export interface Extractor {
66
+ readonly description: string;
67
+ readonly options?: Readonly<Record<string, unknown>>;
68
+ readonly sample: ExtractorSample;
69
+ readonly run: (options: Options) => unknown;
70
+ }
71
+ /** The keys contractdiff reads. Any object with these fields is a plugin here, whatever else it carries. */
72
+ export interface Plugin {
73
+ readonly name: string;
74
+ readonly contract?: number;
75
+ readonly adapters?: Readonly<Record<string, Adapter>>;
76
+ readonly generators?: Readonly<Record<string, Generator>>;
77
+ readonly extractors?: Readonly<Record<string, Extractor>>;
78
+ /** `lint` rules (apicontract-lint R4): each with the sample that is its test. */
79
+ readonly rules?: Readonly<Record<string, Rule>>;
80
+ }
81
+ export type PluginErrorCode = 'E_PLUGIN_SCHEMA' | 'E_PLUGIN_CONTRACT' | 'E_NO_STATIC_PROJECTION' | 'E_NO_CONTRIBUTION';
82
+ /** A refusal says what is wrong and what to do about it: the family's one vocabulary. */
83
+ export declare class PluginError extends Error {
84
+ readonly code: PluginErrorCode;
85
+ readonly fix: string;
86
+ constructor(code: PluginErrorCode, message: string, fix: string);
87
+ }
88
+ /** A generator's return value, with the files and the findings apart. */
89
+ export declare const resultOf: (value: unknown) => {
90
+ files: unknown;
91
+ findings: readonly ContractFinding[];
92
+ };
93
+ /**
94
+ * An extractor's return value, with the document and the findings apart. Only an object carrying
95
+ * both keys is a result: a spec may well have a `document` key of its own.
96
+ */
97
+ export declare const documentOf: (value: unknown) => {
98
+ document: unknown;
99
+ findings: readonly ContractFinding[];
100
+ };
101
+ /** Refuse a list of files a host must not write. `where` names who produced it. */
102
+ export declare const validateFiles: (files: unknown, where: string) => GeneratedFile[];
103
+ /** Refuse, at the door, a plugin this host cannot use. */
104
+ export declare function validate(plugin: unknown): asserts plugin is Plugin;
105
+ /** A set of registered plugins. One per program run; tests make their own. */
106
+ export interface Host {
107
+ readonly register: (plugin: unknown) => void;
108
+ readonly plugins: () => readonly Plugin[];
109
+ /** Forget every registered plugin. */
110
+ readonly reset: () => void;
111
+ /** Read a parsed document with the adapter that recognises it. */
112
+ readonly read: (document: unknown) => Contract;
113
+ /** The generator registered under `target`. */
114
+ readonly generator: (target: string) => Generator;
115
+ /** The extractor registered under `name`. */
116
+ readonly extractor: (name: string) => Extractor;
117
+ /** Every rule the plugins contribute, by id: a later plugin wins an id. */
118
+ readonly rules: () => Readonly<Record<string, Rule>>;
119
+ /** Run a generator on a document and return the files it would write. `run` returns its findings too. */
120
+ readonly generate: (target: string, document: unknown, options?: Options) => Promise<GeneratedFile[]>;
121
+ /** Run a generator on a document: the files it would write, and what the reader and the generator report. */
122
+ readonly run: (target: string, document: unknown, options?: Options) => Promise<{
123
+ files: GeneratedFile[];
124
+ findings: ContractFinding[];
125
+ }>;
126
+ }
127
+ export declare const createHost: () => Host;
128
+ export interface Finding {
129
+ readonly generator: string;
130
+ readonly path: string;
131
+ readonly problem: 'missing' | 'unexpected' | 'different' | 'not deterministic';
132
+ readonly fix: string;
133
+ }
134
+ /**
135
+ * `contractdiff check <plugin>` (R-PL5): run every generator on its own sample, twice, and compare
136
+ * both runs with the files the sample declares, byte for byte. It proves the output is what the
137
+ * author says it is, and that it is the same on every run.
138
+ */
139
+ export declare const checkPlugin: (plugin: unknown) => Promise<Finding[]>;
140
+ /** Register a plugin with the program's host. Later wins a name. */
141
+ export declare const register: (plugin: unknown) => void;
142
+ /** The plugins registered with the program's host, oldest first. */
143
+ export declare const registered: () => readonly Plugin[];
144
+ /** Forget every plugin registered with the program's host. For tests, and a program that re-registers. */
145
+ export declare const reset: () => void;