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.
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 +409 -0
  150. package/dist/props-judge.js +61 -0
  151. package/dist/props-mutate.js +144 -0
  152. package/dist/props-random.js +25 -0
  153. package/dist/props-run.js +176 -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,409 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ import { canonical, has, isDict } from './diff-normalise.js';
3
+ export const GENERATED = [
4
+ '$ref',
5
+ 'type',
6
+ 'nullable',
7
+ 'const',
8
+ 'enum',
9
+ 'allOf',
10
+ 'anyOf',
11
+ 'minimum',
12
+ 'maximum',
13
+ 'exclusiveMinimum',
14
+ 'exclusiveMaximum',
15
+ 'multipleOf',
16
+ 'minLength',
17
+ 'maxLength',
18
+ 'format',
19
+ 'items',
20
+ 'prefixItems',
21
+ 'additionalItems',
22
+ 'minItems',
23
+ 'maxItems',
24
+ 'properties',
25
+ 'required',
26
+ 'additionalProperties',
27
+ 'minProperties',
28
+ 'maxProperties',
29
+ ];
30
+ const REPORTED_ANYWHERE = ['oneOf', 'not', 'if', 'unevaluatedProperties', 'unevaluatedItems', '$dynamicRef', '$recursiveRef', 'contentSchema'];
31
+ const REPORTED_STRING = ['pattern'];
32
+ const REPORTED_ARRAY = ['uniqueItems', 'contains'];
33
+ const REPORTED_OBJECT = ['propertyNames', 'patternProperties', 'dependentRequired', 'dependentSchemas', 'dependencies'];
34
+ export const REPORTED = [...REPORTED_ANYWHERE, ...REPORTED_STRING, ...REPORTED_ARRAY, ...REPORTED_OBJECT];
35
+ export const FORMATS = ['date', 'date-time', 'time', 'duration', 'email', 'hostname', 'ipv4', 'ipv6', 'uuid', 'regex', 'byte'];
36
+ export const drawFrom = (random, root, draft) => ({ random, root, draft, exact: true, reported: new Map() });
37
+ export const SOFT_DEPTH = 4;
38
+ export const HARD_DEPTH = 24;
39
+ const WINDOW = 100;
40
+ const SPREAD = 4;
41
+ const EDGE = 0.3;
42
+ const HALF = 0.5;
43
+ const EXTRA = 0.2;
44
+ const PLACES = 1000;
45
+ export const report = (draw, keyword, pointer) => {
46
+ draw.exact = false;
47
+ const at = draw.reported.get(keyword) ?? new Set();
48
+ at.add(pointer === '' ? '/' : pointer);
49
+ draw.reported.set(keyword, at);
50
+ };
51
+ const reportPresent = (draw, schema, keywords, pointer) => {
52
+ for (const keyword of keywords)
53
+ if (has(schema, keyword))
54
+ report(draw, keyword, pointer);
55
+ };
56
+ export const without = (schema, keys) => Object.fromEntries(Object.entries(schema).filter(([key]) => !keys.includes(key)));
57
+ export const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
58
+ const target = (draw, ref, pointer) => {
59
+ try {
60
+ return pointerGet(draw.root, String(ref));
61
+ }
62
+ catch {
63
+ report(draw, '$ref', pointer);
64
+ return undefined;
65
+ }
66
+ };
67
+ export const itemsOf = (schema) => {
68
+ if (Array.isArray(schema.prefixItems))
69
+ return { tuple: schema.prefixItems, tupleKey: 'prefixItems', rest: schema.items ?? true, restKey: 'items' };
70
+ if (Array.isArray(schema.items))
71
+ return { tuple: schema.items, tupleKey: 'items', rest: schema.additionalItems ?? true, restKey: 'additionalItems' };
72
+ return { tuple: [], tupleKey: 'prefixItems', rest: schema.items ?? true, restKey: 'items' };
73
+ };
74
+ const LOWER_BOUNDS = new Set(['minimum', 'exclusiveMinimum', 'minLength', 'minItems', 'minProperties']);
75
+ const UPPER_BOUNDS = new Set(['maximum', 'exclusiveMaximum', 'maxLength', 'maxItems', 'maxProperties']);
76
+ const typeList = (type) => (Array.isArray(type) ? type.map(String) : [String(type)]);
77
+ export const bothTypes = (a, b) => {
78
+ const right = typeList(b);
79
+ const left = typeList(a);
80
+ const shared = left.filter((type) => right.includes(type));
81
+ const whole = (left.includes('integer') && right.includes('number')) || (left.includes('number') && right.includes('integer'));
82
+ return whole && !shared.includes('integer') ? [...shared, 'integer'] : shared;
83
+ };
84
+ const mergeProperties = (mine, theirs) => Object.fromEntries([...new Set([...Object.keys(mine), ...Object.keys(theirs)])].map((name) => [name, has(mine, name) && has(theirs, name) ? { allOf: [mine[name], theirs[name]] } : (mine[name] ?? theirs[name])]));
85
+ const mergeKey = (draw, key, values, pointer) => {
86
+ const [mine, theirs] = values;
87
+ if (key === 'type') {
88
+ const types = bothTypes(mine, theirs);
89
+ return types.length === 0 ? false : types;
90
+ }
91
+ if (key === 'required')
92
+ return [...new Set([...mine, ...theirs])];
93
+ if (key === 'properties')
94
+ return mergeProperties(mine, theirs);
95
+ if (typeof mine === 'number' && typeof theirs === 'number' && LOWER_BOUNDS.has(key))
96
+ return Math.max(mine, theirs);
97
+ if (typeof mine === 'number' && typeof theirs === 'number' && UPPER_BOUNDS.has(key))
98
+ return Math.min(mine, theirs);
99
+ if (canonical(mine) !== canonical(theirs))
100
+ report(draw, key, pointer);
101
+ return mine;
102
+ };
103
+ const resolvePart = (draw, part, pointer, depth) => {
104
+ if (depth > HARD_DEPTH)
105
+ return false;
106
+ if (part === true)
107
+ return {};
108
+ if (!isDict(part))
109
+ return false;
110
+ if (!has(part, '$ref'))
111
+ return part;
112
+ const found = target(draw, part.$ref, pointer);
113
+ const rest = without(part, ['$ref']);
114
+ if (draw.draft !== '2020-12' || Object.keys(rest).length === 0)
115
+ return resolvePart(draw, found, pointer, depth + 1);
116
+ return merge(draw, [found, rest], pointer, depth + 1);
117
+ };
118
+ export function merge(draw, parts, pointer, depth = 0) {
119
+ if (parts.length > 1 && parts.some((part) => isDict(part) && has(part, 'additionalProperties')))
120
+ report(draw, 'additionalProperties', pointer);
121
+ let out = {};
122
+ for (const raw of parts) {
123
+ const part = resolvePart(draw, raw, pointer, depth);
124
+ if (part === false)
125
+ return false;
126
+ const flat = Array.isArray(part.allOf) ? merge(draw, [without(part, ['allOf']), ...part.allOf], pointer, depth + 1) : part;
127
+ if (flat === false)
128
+ return false;
129
+ out = mergeTwo(draw, [out, flat], pointer, depth);
130
+ if (out.type === false)
131
+ return false;
132
+ }
133
+ return out;
134
+ }
135
+ const mergeTwo = (draw, [mine, theirs], pointer, depth) => {
136
+ const entries = new Map(Object.entries(mine));
137
+ let second;
138
+ for (const [key, value] of Object.entries(theirs)) {
139
+ if (key === 'anyOf' && Array.isArray(value) && entries.has('anyOf'))
140
+ second = value;
141
+ else
142
+ entries.set(key, entries.has(key) ? mergeKey(draw, key, [entries.get(key), value], pointer) : value);
143
+ }
144
+ if (second === undefined)
145
+ return Object.fromEntries(entries);
146
+ const branch = merge(draw, [Object.fromEntries(entries), draw.random.pick(second)], pointer, depth + 1);
147
+ return branch === false ? { type: false } : branch;
148
+ };
149
+ const TYPES = ['null', 'boolean', 'integer', 'number', 'string', 'array', 'object'];
150
+ const SCALARS = TYPES.filter((type) => type !== 'array' && type !== 'object');
151
+ const IMPLIED = new Map([
152
+ ...['minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum', 'multipleOf'].map((key) => [key, 'number']),
153
+ ...['minLength', 'maxLength', 'format'].map((key) => [key, 'string']),
154
+ ...['items', 'prefixItems', 'minItems', 'maxItems'].map((key) => [key, 'array']),
155
+ ...['properties', 'required', 'additionalProperties', 'minProperties', 'maxProperties'].map((key) => [key, 'object']),
156
+ ]);
157
+ export const typesOf = (schema, draft) => {
158
+ if (has(schema, 'type')) {
159
+ const declared = typeList(schema.type);
160
+ return draft === 'openapi-3.0' && schema.nullable === true && !declared.includes('null') ? [...declared, 'null'] : declared;
161
+ }
162
+ const implied = [...new Set(Object.keys(schema).flatMap((key) => IMPLIED.get(key) ?? []))];
163
+ return implied.length > 0 ? implied : [...TYPES];
164
+ };
165
+ const end = (schema, draft, side) => {
166
+ const inclusive = schema[side === 'Minimum' ? 'minimum' : 'maximum'];
167
+ const exclusive = schema[`exclusive${side}`];
168
+ const at = typeof inclusive === 'number' ? inclusive : undefined;
169
+ if (typeof exclusive !== 'number')
170
+ return { at, out: draft === 'openapi-3.0' && exclusive === true };
171
+ const tighter = at === undefined || (side === 'Minimum' ? exclusive >= at : exclusive <= at);
172
+ return tighter ? { at: exclusive, out: true } : { at, out: false };
173
+ };
174
+ export const rangeOf = (schema, draft) => {
175
+ const low = end(schema, draft, 'Minimum');
176
+ const high = end(schema, draft, 'Maximum');
177
+ const from = low.at ?? (high.at === undefined ? -WINDOW : high.at - WINDOW);
178
+ const to = high.at ?? (low.at === undefined ? WINDOW : from + WINDOW);
179
+ return { low: from, lowOut: low.out, high: to, highOut: high.out };
180
+ };
181
+ export const wholeIn = (range) => [range.lowOut ? Math.floor(range.low) + 1 : Math.ceil(range.low), range.highOut ? Math.ceil(range.high) - 1 : Math.floor(range.high)];
182
+ const integer = (draw, schema, pointer) => {
183
+ const [low, high] = wholeIn(rangeOf(schema, draw.draft));
184
+ const step = schema.multipleOf;
185
+ if (typeof step === 'number') {
186
+ if (!Number.isInteger(step))
187
+ report(draw, 'multipleOf', pointer);
188
+ const from = Math.ceil(low / step);
189
+ const to = Math.floor(high / step);
190
+ return from > to ? undefined : { value: draw.random.int(from, to) * step };
191
+ }
192
+ if (low > high)
193
+ return undefined;
194
+ return { value: draw.random.chance(EDGE) ? draw.random.pick([low, high]) : draw.random.int(low, high) };
195
+ };
196
+ export const inside = (range, value) => (value > range.low || (!range.lowOut && value === range.low)) && (value < range.high || (!range.highOut && value === range.high));
197
+ const number = (draw, schema, pointer) => {
198
+ if (typeof schema.multipleOf === 'number' || draw.random.chance(HALF))
199
+ return integer(draw, schema, pointer);
200
+ const range = rangeOf(schema, draw.draft);
201
+ if (range.low > range.high || (range.low === range.high && (range.lowOut || range.highOut)))
202
+ return undefined;
203
+ const drawn = Math.round((range.low + draw.random.next() * (range.high - range.low)) * PLACES) / PLACES;
204
+ return { value: inside(range, drawn) ? drawn : (range.low + range.high) / 2 };
205
+ };
206
+ const CHARACTERS = ['a', 'b', 'z', 'A', 'Q', '0', '7', ' ', '-', '_', '.', 'é', '中', '😀'];
207
+ const WORD = ['a', 'b', 'k', 'x', 'z', '0', '9'];
208
+ const HEX = [...'0123456789abcdef'];
209
+ const VARIANT = ['8', '9', 'a', 'b'];
210
+ const PATTERNS = ['^a$', '[0-9]+', 'x|y', String.raw `\d{2,4}`];
211
+ const OFFSETS = ['Z', '+00:00', '.5Z'];
212
+ const YEAR = [1970, 2099];
213
+ const MONTH = [1, 12];
214
+ const DAY = [1, 28];
215
+ const HOUR = [0, 23];
216
+ const MINUTE = [0, 59];
217
+ const COUNT = [1, 9];
218
+ const BYTE = [0, 255];
219
+ const BYTES = [0, 9];
220
+ const IPV4_PARTS = 4;
221
+ const IPV6_PARTS = 8;
222
+ const HEX_GROUP = [1, 4];
223
+ const UUID = [8, 4, 3, 3, 12];
224
+ const within = (draw, [low, high]) => draw.random.int(low, high);
225
+ const pad = (value) => String(value).padStart(2, '0');
226
+ const hex = (draw, count) => Array.from({ length: count }, () => draw.random.pick(HEX)).join('');
227
+ const word = (draw) => Array.from({ length: draw.random.int(1, SPREAD + 2) }, () => draw.random.pick(WORD)).join('');
228
+ const date = (draw) => `${String(within(draw, YEAR))}-${pad(within(draw, MONTH))}-${pad(within(draw, DAY))}`;
229
+ const time = (draw) => `${pad(within(draw, HOUR))}:${pad(within(draw, MINUTE))}:${pad(within(draw, MINUTE))}${draw.random.pick(OFFSETS)}`;
230
+ const count = (draw) => String(within(draw, COUNT));
231
+ const FORMAT = {
232
+ date,
233
+ 'date-time': (draw) => `${date(draw)}T${time(draw)}`,
234
+ time,
235
+ duration: (draw) => draw.random.pick([`P${count(draw)}D`, `PT${count(draw)}H`, `P${count(draw)}Y${count(draw)}M`]),
236
+ email: (draw) => `${word(draw)}@${word(draw)}.com`,
237
+ hostname: (draw) => `${word(draw)}.${word(draw)}.org`,
238
+ ipv4: (draw) => Array.from({ length: IPV4_PARTS }, () => String(within(draw, BYTE))).join('.'),
239
+ ipv6: (draw) => Array.from({ length: IPV6_PARTS }, () => hex(draw, within(draw, HEX_GROUP))).join(':'),
240
+ uuid: (draw) => {
241
+ const [first, second, third, fourth, fifth] = UUID;
242
+ return `${hex(draw, first)}-${hex(draw, second)}-4${hex(draw, third)}-${draw.random.pick(VARIANT)}${hex(draw, fourth)}-${hex(draw, fifth)}`;
243
+ },
244
+ regex: (draw) => draw.random.pick(PATTERNS),
245
+ byte: (draw) => Buffer.from(Array.from({ length: within(draw, BYTES) }, () => within(draw, BYTE))).toString('base64'),
246
+ };
247
+ const WRITERS = new Map(Object.entries(FORMAT));
248
+ export const isFormat = (name) => FORMATS.includes(name);
249
+ const string = (draw, schema, pointer) => {
250
+ reportPresent(draw, schema, REPORTED_STRING, pointer);
251
+ if (isFormat(schema.format)) {
252
+ if (has(schema, 'minLength') || has(schema, 'maxLength'))
253
+ report(draw, 'format-length', pointer);
254
+ const write = WRITERS.get(schema.format);
255
+ return { value: write(draw) };
256
+ }
257
+ if (has(schema, 'format'))
258
+ report(draw, `format:${String(schema.format)}`, pointer);
259
+ const low = typeof schema.minLength === 'number' ? schema.minLength : 0;
260
+ const high = Math.min(typeof schema.maxLength === 'number' ? schema.maxLength : Infinity, low + SPREAD * 2);
261
+ if (low > high)
262
+ return undefined;
263
+ return { value: Array.from({ length: draw.random.int(low, high) }, () => draw.random.pick(CHARACTERS)).join('') };
264
+ };
265
+ export const anyValue = (draw, depth) => {
266
+ const kind = draw.random.pick(depth < SOFT_DEPTH ? TYPES : SCALARS);
267
+ if (kind === 'null')
268
+ return null;
269
+ if (kind === 'boolean')
270
+ return draw.random.chance(HALF);
271
+ if (kind === 'integer')
272
+ return draw.random.int(-WINDOW, WINDOW);
273
+ if (kind === 'number')
274
+ return draw.random.int(-WINDOW * PLACES, WINDOW * PLACES) / PLACES;
275
+ if (kind === 'string')
276
+ return word(draw);
277
+ if (kind === 'array')
278
+ return Array.from({ length: draw.random.int(0, 2) }, () => anyValue(draw, depth + 1));
279
+ return Object.fromEntries(Array.from({ length: draw.random.int(0, 2) }, () => [word(draw), anyValue(draw, depth + 1)]));
280
+ };
281
+ const array = (draw, schema, at) => {
282
+ reportPresent(draw, schema, REPORTED_ARRAY, at.pointer);
283
+ const { tuple, tupleKey, rest, restKey } = itemsOf(schema);
284
+ const low = typeof schema.minItems === 'number' ? schema.minItems : 0;
285
+ const caps = [typeof schema.maxItems === 'number' ? schema.maxItems : Infinity, rest === false ? tuple.length : Infinity, at.depth >= SOFT_DEPTH ? low : Infinity, low + SPREAD];
286
+ const high = Math.min(...caps);
287
+ if (low > high)
288
+ return undefined;
289
+ const items = [];
290
+ for (let index = 0, length = draw.random.int(low, high); index < length; index += 1) {
291
+ const fromTuple = index < tuple.length;
292
+ const made = make(draw, fromTuple ? tuple[index] : rest, fromTuple ? `${at.pointer}/${tupleKey}/${String(index)}` : `${at.pointer}/${restKey}`, at.depth + 1);
293
+ if (made === undefined)
294
+ return undefined;
295
+ items.push(made.value);
296
+ }
297
+ return { value: items };
298
+ };
299
+ export const freshName = (taken) => {
300
+ let name = 'extra';
301
+ while (taken.has(name))
302
+ name = `${name}_`;
303
+ return name;
304
+ };
305
+ const add = (building, name, schema, pointer) => {
306
+ const made = make(building.draw, schema, pointer, building.at.depth + 1);
307
+ if (made !== undefined)
308
+ building.entries.set(name, made.value);
309
+ return made !== undefined;
310
+ };
311
+ const optionalProperties = (building, properties, bounds) => {
312
+ const { draw, entries, at } = building;
313
+ const [low, high] = bounds;
314
+ for (const name of Object.keys(properties)) {
315
+ const wanted = entries.size < low || (at.depth < SOFT_DEPTH && draw.random.chance(HALF));
316
+ if (!entries.has(name) && entries.size < high && wanted)
317
+ add(building, name, properties[name], `${at.pointer}/properties/${token(name)}`);
318
+ }
319
+ };
320
+ const extraProperties = (building, schema, bounds) => {
321
+ const { draw, entries, at } = building;
322
+ const [low, high] = bounds;
323
+ const extra = schema.additionalProperties ?? true;
324
+ if (extra === false || has(schema, 'patternProperties'))
325
+ return;
326
+ const named = Object.keys(isDict(schema.properties) ? schema.properties : {});
327
+ const more = () => entries.size < high && (entries.size < low || (at.depth < SOFT_DEPTH && draw.random.chance(EXTRA)));
328
+ while (more() && add(building, freshName(new Set([...named, ...entries.keys()])), extra, `${at.pointer}/additionalProperties`))
329
+ ;
330
+ };
331
+ const object = (draw, schema, at) => {
332
+ reportPresent(draw, schema, REPORTED_OBJECT, at.pointer);
333
+ const properties = isDict(schema.properties) ? schema.properties : {};
334
+ const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
335
+ const building = { draw, entries: new Map(), at };
336
+ for (const name of required) {
337
+ const [sub, pointer] = has(properties, name) ? [properties[name], `${at.pointer}/properties/${token(name)}`] : [schema.additionalProperties ?? true, `${at.pointer}/additionalProperties`];
338
+ if (!add(building, name, sub, pointer))
339
+ return undefined;
340
+ }
341
+ const low = typeof schema.minProperties === 'number' ? schema.minProperties : 0;
342
+ const high = typeof schema.maxProperties === 'number' ? schema.maxProperties : Infinity;
343
+ optionalProperties(building, properties, [low, high]);
344
+ extraProperties(building, schema, [low, high]);
345
+ const { size } = building.entries;
346
+ return size < low || size > high ? undefined : { value: Object.fromEntries(building.entries) };
347
+ };
348
+ const KNOWN = new Set([...GENERATED, ...REPORTED]);
349
+ const constraints = (schema) => Object.keys(schema).filter((key) => KNOWN.has(key));
350
+ const combined = (draw, schema, at) => {
351
+ if (has(schema, '$ref')) {
352
+ const rest = without(schema, ['$ref']);
353
+ const found = target(draw, schema.$ref, at.pointer);
354
+ const whole = draw.draft !== '2020-12' || constraints(rest).length === 0;
355
+ return whole ? make(draw, found, String(schema.$ref), at.depth + 1) : make(draw, { allOf: [found, rest] }, at.pointer, at.depth + 1);
356
+ }
357
+ if (Array.isArray(schema.allOf)) {
358
+ return make(draw, merge(draw, [without(schema, ['allOf']), ...schema.allOf], at.pointer, at.depth), at.pointer, at.depth + 1);
359
+ }
360
+ const keyword = ['anyOf', 'oneOf'].find((key) => Array.isArray(schema[key]) && schema[key].length > 0);
361
+ if (keyword === undefined)
362
+ return null;
363
+ const branches = schema[keyword];
364
+ const index = draw.random.int(0, branches.length - 1);
365
+ const pointer = `${at.pointer}/${keyword}/${String(index)}`;
366
+ return make(draw, merge(draw, [without(schema, [keyword]), branches[index]], pointer, at.depth), pointer, at.depth + 1);
367
+ };
368
+ const listed = (draw, schema, pointer) => {
369
+ if (!has(schema, 'const') && !has(schema, 'enum'))
370
+ return null;
371
+ if (constraints(schema).some((key) => key !== 'const' && key !== 'enum'))
372
+ report(draw, 'enum-with-constraints', pointer);
373
+ if (has(schema, 'const'))
374
+ return { value: structuredClone(schema.const) };
375
+ const values = Array.isArray(schema.enum) ? schema.enum : [];
376
+ return values.length === 0 ? undefined : { value: structuredClone(draw.random.pick(values)) };
377
+ };
378
+ const typed = (draw, schema, at) => {
379
+ const type = draw.random.pick(typesOf(schema, draw.draft));
380
+ if (type === 'null')
381
+ return { value: null };
382
+ if (type === 'boolean')
383
+ return { value: draw.random.chance(HALF) };
384
+ if (type === 'integer')
385
+ return integer(draw, schema, at.pointer);
386
+ if (type === 'number')
387
+ return number(draw, schema, at.pointer);
388
+ if (type === 'string')
389
+ return string(draw, schema, at.pointer);
390
+ if (type === 'array')
391
+ return array(draw, schema, at);
392
+ if (type === 'object')
393
+ return object(draw, schema, at);
394
+ report(draw, `type:${type}`, at.pointer);
395
+ return undefined;
396
+ };
397
+ export function make(draw, schema, pointer = '', depth = 0) {
398
+ if (schema === true)
399
+ return { value: anyValue(draw, depth) };
400
+ if (!isDict(schema) || depth > HARD_DEPTH)
401
+ return undefined;
402
+ const at = { pointer, depth };
403
+ reportPresent(draw, schema, REPORTED_ANYWHERE, pointer);
404
+ const viaParts = combined(draw, schema, at);
405
+ if (viaParts !== null)
406
+ return viaParts;
407
+ const fromList = listed(draw, schema, pointer);
408
+ return fromList === null ? typed(draw, schema, at) : fromList;
409
+ }
@@ -0,0 +1,61 @@
1
+ import { check, parse } from 'truefit';
2
+ import { fromJsonSchema, jsonSchemaReader } from 'truefit/json-schema';
3
+ import { isDict } from './diff-normalise.js';
4
+ const judgeOf = (read) => ({
5
+ accepts: (value) => check(read, value),
6
+ paths: (value) => {
7
+ const parsed = parse(read, value);
8
+ return parsed.ok ? [] : parsed.issues.map((issue) => issue.path);
9
+ },
10
+ });
11
+ export const validatorJudge = (document, draft) => judgeOf(fromJsonSchema(document, { draft }).schema);
12
+ const readers = new WeakMap();
13
+ const readerFor = (document, draft) => {
14
+ const byDraft = readers.get(document) ?? new Map();
15
+ readers.set(document, byDraft);
16
+ const known = byDraft.get(draft);
17
+ if (known !== undefined)
18
+ return known;
19
+ const reader = jsonSchemaReader(rooted({}, document), { draft });
20
+ byDraft.set(draft, reader);
21
+ return reader;
22
+ };
23
+ const intoPayload = (ref) => {
24
+ if (typeof ref !== 'string')
25
+ return false;
26
+ if (ref === '#')
27
+ return true;
28
+ if (!ref.startsWith('#/'))
29
+ return false;
30
+ return !DEFINITIONS.includes(decodeURIComponent(ref.slice(2).split('/')[0]));
31
+ };
32
+ const refersInside = (schema) => {
33
+ if (Array.isArray(schema))
34
+ return schema.some(refersInside);
35
+ if (!isDict(schema))
36
+ return false;
37
+ return intoPayload(schema.$ref) || Object.values(schema).some(refersInside);
38
+ };
39
+ const selfReferent = (schema) => DEFINITIONS.some((key) => key in schema) || refersInside(schema);
40
+ export const payloadJudge = (schema, document, draft) => {
41
+ if (!isDict(document) || (isDict(schema) && selfReferent(schema)))
42
+ return validatorJudge(rooted(schema, document), draft);
43
+ return judgeOf(readerFor(document, draft).read(rooted(schema, null)));
44
+ };
45
+ export const draftOf = (contract) => {
46
+ const document = isDict(contract.document) ? contract.document : {};
47
+ if (typeof document.openapi === 'string' && document.openapi.startsWith('3.0'))
48
+ return 'openapi-3.0';
49
+ if (typeof document.$schema === 'string' && document.$schema.includes('draft-07'))
50
+ return 'draft-07';
51
+ return '2020-12';
52
+ };
53
+ const DEFINITIONS = ['components', 'definitions', '$defs'];
54
+ export const rooted = (schema, document) => {
55
+ if (schema === true)
56
+ return {};
57
+ if (!isDict(schema))
58
+ return { not: {} };
59
+ const definitions = isDict(document) ? Object.fromEntries(DEFINITIONS.filter((key) => key in document).map((key) => [key, document[key]])) : {};
60
+ return { ...definitions, ...schema };
61
+ };
@@ -0,0 +1,144 @@
1
+ import { pointerGet } from './core/resolve.js';
2
+ import { canonical, has, isDict } from './diff-normalise.js';
3
+ import { freshName, GENERATED, itemsOf, rangeOf, REPORTED, token, typesOf, wholeIn } from './props-generate.js';
4
+ const HELD = new Set(GENERATED);
5
+ const LOOSE = new Set(REPORTED);
6
+ const OPEN = ['anyOf', 'allOf', ...REPORTED];
7
+ const LIMIT = 8;
8
+ const RARER = 0.75;
9
+ const FRACTION = 1.5;
10
+ const plain = (draw, schema, depth = 0) => {
11
+ if (!isDict(schema) || depth > LIMIT)
12
+ return undefined;
13
+ if (has(schema, '$ref')) {
14
+ const siblings = Object.keys(schema).some((key) => key !== '$ref' && (HELD.has(key) || LOOSE.has(key)));
15
+ if (draw.draft === '2020-12' && siblings)
16
+ return undefined;
17
+ try {
18
+ return plain(draw, pointerGet(draw.root, String(schema.$ref)), depth + 1);
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ return has(schema, 'type') && !OPEN.some((key) => has(schema, key)) ? schema : undefined;
25
+ };
26
+ const jsonType = (value) => {
27
+ if (value === null)
28
+ return 'null';
29
+ if (Array.isArray(value))
30
+ return 'array';
31
+ return typeof value;
32
+ };
33
+ const allows = (types, value) => types.includes(jsonType(value));
34
+ const SAMPLES = [null, true, 'x', FRACTION, [], {}];
35
+ const listBreaks = (schema, tokens) => {
36
+ const out = [];
37
+ if (has(schema, 'const'))
38
+ out.push({ keyword: 'const', tokens, replace: { value: { not: schema.const } } });
39
+ if (Array.isArray(schema.enum)) {
40
+ out.push({ keyword: 'enum', tokens, replace: { value: `${schema.enum.map((entry) => canonical(entry)).join('')}x` } });
41
+ }
42
+ return out;
43
+ };
44
+ const past = (excluded) => (excluded ? 0 : 1);
45
+ const numberBreaks = (draw, schema, value, tokens) => {
46
+ const out = [];
47
+ const range = rangeOf(schema, draw.draft);
48
+ const whole = !typesOf(schema, draw.draft).includes('number');
49
+ const [low, high] = wholeIn(range);
50
+ const below = whole ? low - 1 : range.low - past(range.lowOut);
51
+ const above = whole ? high + 1 : range.high + past(range.highOut);
52
+ const lowKey = range.lowOut && has(schema, 'exclusiveMinimum') ? 'exclusiveMinimum' : 'minimum';
53
+ const highKey = range.highOut && has(schema, 'exclusiveMaximum') ? 'exclusiveMaximum' : 'maximum';
54
+ if (has(schema, lowKey))
55
+ out.push({ keyword: lowKey, tokens, replace: { value: below } });
56
+ if (has(schema, highKey))
57
+ out.push({ keyword: highKey, tokens, replace: { value: above } });
58
+ const multiple = schema.multipleOf;
59
+ if (typeof multiple === 'number' && Number.isInteger(multiple) && multiple > 1 && Number.isInteger(value)) {
60
+ const next = [value + 1, value - 1].find((candidate) => candidate >= low && candidate <= high);
61
+ if (next !== undefined)
62
+ out.push({ keyword: 'multipleOf', tokens, replace: { value: next } });
63
+ }
64
+ return out;
65
+ };
66
+ const stringBreaks = (schema, value, tokens) => {
67
+ const out = [];
68
+ const points = [...value];
69
+ if (typeof schema.minLength === 'number' && schema.minLength > 0)
70
+ out.push({ keyword: 'minLength', tokens, replace: { value: points.slice(0, schema.minLength - 1).join('') } });
71
+ if (typeof schema.maxLength === 'number')
72
+ out.push({ keyword: 'maxLength', tokens, replace: { value: value + 'a'.repeat(schema.maxLength + 1 - points.length) } });
73
+ return out;
74
+ };
75
+ const arrayBreaks = (walk, schema, value) => {
76
+ const { tokens } = walk;
77
+ const out = [];
78
+ if (typeof schema.minItems === 'number' && schema.minItems > 0)
79
+ out.push({ keyword: 'minItems', tokens, replace: { value: value.slice(0, schema.minItems - 1) } });
80
+ if (typeof schema.maxItems === 'number' && value.length > 0) {
81
+ out.push({ keyword: 'maxItems', tokens, replace: { value: [...value, ...Array.from({ length: schema.maxItems + 1 - value.length }, () => structuredClone(value[0]))] } });
82
+ }
83
+ const { tuple, rest } = itemsOf(schema);
84
+ for (const [index, item] of value.entries()) {
85
+ out.push(...breaksOf({ ...walk, tokens: [...tokens, String(index)], depth: walk.depth + 1 }, index < tuple.length ? tuple[index] : rest, item));
86
+ }
87
+ return out;
88
+ };
89
+ const objectBreaks = (walk, schema, value) => {
90
+ const { tokens } = walk;
91
+ const out = [];
92
+ const properties = isDict(schema.properties) ? schema.properties : {};
93
+ const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
94
+ const size = Object.keys(value).length;
95
+ const roomBelow = typeof schema.minProperties !== 'number' || size > schema.minProperties;
96
+ if (roomBelow)
97
+ for (const name of required)
98
+ if (has(value, name))
99
+ out.push({ keyword: 'required', tokens: [...tokens, name], replace: undefined });
100
+ const roomAbove = typeof schema.maxProperties !== 'number' || size < schema.maxProperties;
101
+ if (schema.additionalProperties === false && roomAbove) {
102
+ out.push({ keyword: 'additionalProperties', tokens: [...tokens, freshName(new Set([...Object.keys(properties), ...Object.keys(value)]))], replace: { value: null } });
103
+ }
104
+ for (const [name, item] of Object.entries(value)) {
105
+ if (has(properties, name))
106
+ out.push(...breaksOf({ ...walk, tokens: [...tokens, name], depth: walk.depth + 1 }, properties[name], item));
107
+ }
108
+ return out;
109
+ };
110
+ function breaksOf(walk, raw, value) {
111
+ const schema = plain(walk.draw, raw);
112
+ if (schema === undefined || walk.depth > LIMIT)
113
+ return [];
114
+ const { tokens } = walk;
115
+ const wrong = SAMPLES.find((sample) => !allows(typesOf(schema, walk.draw.draft), sample));
116
+ return [
117
+ ...(wrong === undefined ? [] : [{ keyword: 'type', tokens, replace: { value: wrong } }]),
118
+ ...listBreaks(schema, tokens),
119
+ ...(typeof value === 'number' ? numberBreaks(walk.draw, schema, value, tokens) : []),
120
+ ...(typeof value === 'string' ? stringBreaks(schema, value, tokens) : []),
121
+ ...(Array.isArray(value) ? arrayBreaks(walk, schema, value) : []),
122
+ ...(isDict(value) ? objectBreaks(walk, schema, value) : []),
123
+ ];
124
+ }
125
+ const setAt = (root, trail, replace) => {
126
+ if (trail.length === 0)
127
+ return replace.value;
128
+ const [first, ...rest] = trail;
129
+ if (Array.isArray(root))
130
+ return root.map((item, index) => (String(index) === first ? setAt(item, rest, replace) : item));
131
+ const entries = Object.entries(root);
132
+ if (rest.length === 0 && replace === undefined)
133
+ return Object.fromEntries(entries.filter(([name]) => name !== first));
134
+ const changed = entries.map(([name, item]) => [name, name === first ? setAt(item, rest, replace) : item]);
135
+ return Object.fromEntries(has(root, first) ? changed : [...changed, [first, setAt(undefined, rest, replace)]]);
136
+ };
137
+ export const mutants = (draw, schema, value) => breaksOf({ draw, tokens: [], depth: 0 }, schema, value).map((found) => ({ value: setAt(value, found.tokens, found.replace), keyword: found.keyword, path: found.tokens.map((part) => `/${token(part)}`).join('') }));
138
+ export const mutate = (draw, schema, value) => {
139
+ const all = mutants(draw, schema, value);
140
+ if (all.length === 0)
141
+ return undefined;
142
+ const rarer = all.filter((found) => found.keyword !== 'type');
143
+ return draw.random.pick(rarer.length > 0 && draw.random.chance(RARER) ? rarer : all);
144
+ };
@@ -0,0 +1,25 @@
1
+ const SPAN = 4_294_967_296;
2
+ const STEP = 0x6d_2b_79_f5;
3
+ const SHIFT_A = 15;
4
+ const SHIFT_B = 7;
5
+ const SHIFT_C = 14;
6
+ const ODD = 61;
7
+ export const randomFrom = (seed) => {
8
+ const start = seed >>> 0;
9
+ let state = start;
10
+ const next = () => {
11
+ state = (state + STEP) >>> 0;
12
+ let t = state;
13
+ t = Math.imul(t ^ (t >>> SHIFT_A), t | 1);
14
+ t ^= t + Math.imul(t ^ (t >>> SHIFT_B), t | ODD);
15
+ return ((t ^ (t >>> SHIFT_C)) >>> 0) / SPAN;
16
+ };
17
+ const int = (min, max) => min + Math.floor(next() * (max - min + 1));
18
+ return {
19
+ seed: start,
20
+ next,
21
+ int,
22
+ pick: (items) => items[int(0, items.length - 1)],
23
+ chance: (p) => next() < p,
24
+ };
25
+ };