@t0.labs/daxta 0.2.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/README.md +40 -0
- package/assets/favicon.png +0 -0
- package/assets/viewer.html +1835 -0
- package/bin/daxta.js +2 -0
- package/dist/build/build-spec.d.ts +28 -0
- package/dist/build/build-spec.js +704 -0
- package/dist/build/incremental.d.ts +12 -0
- package/dist/build/incremental.js +121 -0
- package/dist/call/index.d.ts +24 -0
- package/dist/call/index.js +204 -0
- package/dist/catalog/index.d.ts +27 -0
- package/dist/catalog/index.js +111 -0
- package/dist/cli/install.d.ts +6 -0
- package/dist/cli/install.js +333 -0
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +102 -0
- package/dist/config.d.ts +31 -0
- package/dist/config.js +106 -0
- package/dist/fields/dto-fields.d.ts +4 -0
- package/dist/fields/dto-fields.js +372 -0
- package/dist/fields/export-fields.d.ts +23 -0
- package/dist/fields/export-fields.js +218 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +42 -0
- package/dist/jest/global-setup.d.ts +1 -0
- package/dist/jest/global-setup.js +7 -0
- package/dist/jest/global-teardown.d.ts +1 -0
- package/dist/jest/global-teardown.js +20 -0
- package/dist/jest/reporter.d.ts +7 -0
- package/dist/jest/reporter.js +29 -0
- package/dist/path.util.d.ts +6 -0
- package/dist/path.util.js +108 -0
- package/dist/recorder/index.d.ts +15 -0
- package/dist/recorder/index.js +176 -0
- package/dist/register.d.ts +1 -0
- package/dist/register.js +27 -0
- package/dist/serve/index.d.ts +9 -0
- package/dist/serve/index.js +126 -0
- package/dist/serve/middleware.d.ts +38 -0
- package/dist/serve/middleware.js +131 -0
- package/dist/serve/paths.d.ts +7 -0
- package/dist/serve/paths.js +66 -0
- package/dist/serve/proxy.d.ts +16 -0
- package/dist/serve/proxy.js +52 -0
- package/dist/serve/spec-utils.d.ts +2 -0
- package/dist/serve/spec-utils.js +27 -0
- package/dist/setup.d.ts +1 -0
- package/dist/setup.js +7 -0
- package/package.json +75 -0
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.buildOpenApi = void 0;
|
|
37
|
+
exports.loadHits = loadHits;
|
|
38
|
+
exports.buildDaxtaSpec = buildDaxtaSpec;
|
|
39
|
+
const fs_1 = require("fs");
|
|
40
|
+
const path = __importStar(require("path"));
|
|
41
|
+
const catalog_1 = require("../catalog");
|
|
42
|
+
const config_1 = require("../config");
|
|
43
|
+
const dto_fields_1 = require("../fields/dto-fields");
|
|
44
|
+
const path_util_1 = require("../path.util");
|
|
45
|
+
const paths_1 = require("../serve/paths");
|
|
46
|
+
const METHOD_RANK = { get: 0, post: 1, put: 2, patch: 3, delete: 4 };
|
|
47
|
+
function readPackageMeta() {
|
|
48
|
+
try {
|
|
49
|
+
const pkg = JSON.parse((0, fs_1.readFileSync)(path.join(process.cwd(), 'package.json'), 'utf8'));
|
|
50
|
+
const title = pkg.name?.replace(/-/g, ' ').replace(/\b\w/g, (char) => char.toUpperCase()) ?? 'API';
|
|
51
|
+
return {
|
|
52
|
+
title,
|
|
53
|
+
version: pkg.version ?? '0.0.0',
|
|
54
|
+
description: pkg.description || 'Generated from integration test traffic.',
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return { title: 'API', version: '0.0.0', description: 'Generated from integration test traffic.' };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
function specInfo() {
|
|
62
|
+
const pkg = readPackageMeta();
|
|
63
|
+
const custom = (0, config_1.getConfig)().specInfo?.();
|
|
64
|
+
const workspace = (0, config_1.getConfig)().workspace;
|
|
65
|
+
return {
|
|
66
|
+
title: custom?.title ?? pkg.title,
|
|
67
|
+
version: custom?.version ?? pkg.version,
|
|
68
|
+
description: custom?.description ?? pkg.description,
|
|
69
|
+
workspace,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function schemeIdFromHeader(headerName) {
|
|
73
|
+
const custom = (0, config_1.getConfig)().securitySchemeId?.(headerName);
|
|
74
|
+
if (custom)
|
|
75
|
+
return custom;
|
|
76
|
+
const parts = headerName.replace(/^x-/, '').split('-').filter(Boolean);
|
|
77
|
+
if (!parts.length)
|
|
78
|
+
return headerName.replace(/[^a-zA-Z0-9]/g, '');
|
|
79
|
+
return (parts[0] +
|
|
80
|
+
parts
|
|
81
|
+
.slice(1)
|
|
82
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
83
|
+
.join(''));
|
|
84
|
+
}
|
|
85
|
+
function inferSchema(value) {
|
|
86
|
+
if (value === null || value === undefined)
|
|
87
|
+
return { nullable: true };
|
|
88
|
+
if (Array.isArray(value))
|
|
89
|
+
return { type: 'array', items: inferSchema(value[0] ?? {}) };
|
|
90
|
+
if (typeof value === 'object') {
|
|
91
|
+
return {
|
|
92
|
+
type: 'object',
|
|
93
|
+
properties: Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, inferSchema(nested)])),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (typeof value === 'number')
|
|
97
|
+
return { type: Number.isInteger(value) ? 'integer' : 'number' };
|
|
98
|
+
if (typeof value === 'boolean')
|
|
99
|
+
return { type: 'boolean' };
|
|
100
|
+
return { type: 'string' };
|
|
101
|
+
}
|
|
102
|
+
function mergeSchema(left, right) {
|
|
103
|
+
if (!left)
|
|
104
|
+
return right ?? {};
|
|
105
|
+
if (!right)
|
|
106
|
+
return left;
|
|
107
|
+
const leftNullOnly = Boolean(left.nullable && !left.type);
|
|
108
|
+
const rightNullOnly = Boolean(right.nullable && !right.type);
|
|
109
|
+
if (leftNullOnly && rightNullOnly)
|
|
110
|
+
return { nullable: true };
|
|
111
|
+
if (leftNullOnly)
|
|
112
|
+
return { ...right, nullable: true };
|
|
113
|
+
if (rightNullOnly)
|
|
114
|
+
return { ...left, nullable: true };
|
|
115
|
+
if (left.type && right.type && left.type !== right.type)
|
|
116
|
+
return { anyOf: [left, right] };
|
|
117
|
+
if (left.type === 'object' || right.type === 'object') {
|
|
118
|
+
const keys = new Set([...Object.keys(left.properties ?? {}), ...Object.keys(right.properties ?? {})]);
|
|
119
|
+
const properties = {};
|
|
120
|
+
for (const key of keys)
|
|
121
|
+
properties[key] = mergeSchema(left.properties?.[key], right.properties?.[key]);
|
|
122
|
+
return { type: 'object', properties, description: left.description ?? right.description };
|
|
123
|
+
}
|
|
124
|
+
if (left.type === 'array' || right.type === 'array') {
|
|
125
|
+
return { type: 'array', items: mergeSchema(left.items, right.items), description: left.description ?? right.description };
|
|
126
|
+
}
|
|
127
|
+
return { ...left, description: left.description ?? right.description };
|
|
128
|
+
}
|
|
129
|
+
function slug(value, index) {
|
|
130
|
+
const base = value
|
|
131
|
+
.toLowerCase()
|
|
132
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
133
|
+
.replace(/^-|-$/g, '')
|
|
134
|
+
.slice(0, 72);
|
|
135
|
+
return base || `example-${index + 1}`;
|
|
136
|
+
}
|
|
137
|
+
function isPrimaryHit(hit) {
|
|
138
|
+
if (!hit.test)
|
|
139
|
+
return false;
|
|
140
|
+
if ((0, config_1.getConfig)().includeHit?.(hit.method, hit.path, hit.test) === false)
|
|
141
|
+
return false;
|
|
142
|
+
const methods = (0, catalog_1.declaredMethods)(hit.test);
|
|
143
|
+
if (!methods)
|
|
144
|
+
return true;
|
|
145
|
+
return methods.includes(hit.method);
|
|
146
|
+
}
|
|
147
|
+
function addUniqueExample(store, name, value) {
|
|
148
|
+
const serialized = JSON.stringify(value);
|
|
149
|
+
if (Object.values(store).some((example) => JSON.stringify(example.value) === serialized))
|
|
150
|
+
return;
|
|
151
|
+
let key = slug(name, Object.keys(store).length);
|
|
152
|
+
if (store[key])
|
|
153
|
+
key = `${key}-${Object.keys(store).length}`;
|
|
154
|
+
store[key] = { summary: name, value };
|
|
155
|
+
}
|
|
156
|
+
function pathParamsFromHit(hit) {
|
|
157
|
+
if (hit.pathParams && Object.keys(hit.pathParams).length)
|
|
158
|
+
return hit.pathParams;
|
|
159
|
+
const responsePath = hit.resBody && typeof hit.resBody === 'object' ? hit.resBody.path : undefined;
|
|
160
|
+
if (!responsePath)
|
|
161
|
+
return {};
|
|
162
|
+
return (0, path_util_1.extractPathParams)(hit.path, responsePath);
|
|
163
|
+
}
|
|
164
|
+
function inferParamSchema(values) {
|
|
165
|
+
const meaningful = values.filter((value) => value !== '');
|
|
166
|
+
if (!meaningful.length)
|
|
167
|
+
return { type: 'string' };
|
|
168
|
+
if (meaningful.every((value) => /^-?(0|[1-9]\d*)$/.test(value)))
|
|
169
|
+
return { type: 'integer' };
|
|
170
|
+
if (meaningful.every((value) => value === 'true' || value === 'false'))
|
|
171
|
+
return { type: 'boolean' };
|
|
172
|
+
return { type: 'string' };
|
|
173
|
+
}
|
|
174
|
+
function firstSuccessValue(opHits, read) {
|
|
175
|
+
const success = opHits.find((hit) => hit.status >= 200 && hit.status < 300 && read(hit) !== undefined);
|
|
176
|
+
return success ? read(success) : opHits.map(read).find((value) => value !== undefined);
|
|
177
|
+
}
|
|
178
|
+
function buildParameters(pathTemplate, opHits) {
|
|
179
|
+
const parameters = [];
|
|
180
|
+
const successHits = opHits.filter((hit) => hit.status >= 200 && hit.status < 300);
|
|
181
|
+
for (const name of (0, path_util_1.pathParamNames)(pathTemplate)) {
|
|
182
|
+
const values = opHits.map((hit) => pathParamsFromHit(hit)[name]).filter((value) => value !== undefined);
|
|
183
|
+
parameters.push({
|
|
184
|
+
name,
|
|
185
|
+
in: 'path',
|
|
186
|
+
required: true,
|
|
187
|
+
schema: inferParamSchema(values),
|
|
188
|
+
example: firstSuccessValue(opHits, (hit) => pathParamsFromHit(hit)[name]),
|
|
189
|
+
});
|
|
190
|
+
}
|
|
191
|
+
const queryNames = [...new Set(opHits.flatMap((hit) => Object.keys(hit.query ?? {})))];
|
|
192
|
+
for (const name of queryNames) {
|
|
193
|
+
const values = opHits.map((hit) => hit.query?.[name]).filter((value) => value !== undefined);
|
|
194
|
+
const required = successHits.length > 0 && successHits.every((hit) => hit.query?.[name] !== undefined);
|
|
195
|
+
parameters.push({
|
|
196
|
+
name,
|
|
197
|
+
in: 'query',
|
|
198
|
+
required,
|
|
199
|
+
schema: inferParamSchema(values),
|
|
200
|
+
example: firstSuccessValue(opHits, (hit) => hit.query?.[name]),
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
const headerNames = [...new Set(opHits.flatMap((hit) => Object.keys(hit.headers ?? {}).filter((name) => name !== 'content-type')))];
|
|
204
|
+
for (const name of headerNames) {
|
|
205
|
+
const required = successHits.length > 0 && successHits.every((hit) => hit.headers?.[name] !== undefined);
|
|
206
|
+
parameters.push({
|
|
207
|
+
name,
|
|
208
|
+
in: 'header',
|
|
209
|
+
required,
|
|
210
|
+
schema: { type: 'string' },
|
|
211
|
+
example: firstSuccessValue(opHits, (hit) => hit.headers?.[name]),
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return parameters;
|
|
215
|
+
}
|
|
216
|
+
function valueTypeLabel(value) {
|
|
217
|
+
if (value === null)
|
|
218
|
+
return 'null';
|
|
219
|
+
if (Array.isArray(value)) {
|
|
220
|
+
const item = value.find((entry) => entry !== null && entry !== undefined);
|
|
221
|
+
if (item === undefined)
|
|
222
|
+
return 'array';
|
|
223
|
+
if (Array.isArray(item))
|
|
224
|
+
return 'array';
|
|
225
|
+
if (typeof item === 'object')
|
|
226
|
+
return 'array<object>';
|
|
227
|
+
if (typeof item === 'number')
|
|
228
|
+
return Number.isInteger(item) ? 'array<integer>' : 'array<number>';
|
|
229
|
+
return `array<${typeof item}>`;
|
|
230
|
+
}
|
|
231
|
+
if (typeof value === 'object')
|
|
232
|
+
return 'object';
|
|
233
|
+
if (typeof value === 'number')
|
|
234
|
+
return Number.isInteger(value) ? 'integer' : 'number';
|
|
235
|
+
return typeof value;
|
|
236
|
+
}
|
|
237
|
+
/** Flatten request-body values into dotted / [] field paths (nested objects & arrays). */
|
|
238
|
+
function collectBodyFields(value, prefix, add) {
|
|
239
|
+
if (value === null || value === undefined) {
|
|
240
|
+
if (prefix)
|
|
241
|
+
add({ name: prefix, in: 'body', type: 'null' });
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (Array.isArray(value)) {
|
|
245
|
+
if (prefix)
|
|
246
|
+
add({ name: prefix, in: 'body', type: valueTypeLabel(value) });
|
|
247
|
+
const sample = value.find((entry) => entry !== null && entry !== undefined);
|
|
248
|
+
if (sample === undefined)
|
|
249
|
+
return;
|
|
250
|
+
if (Array.isArray(sample)) {
|
|
251
|
+
collectBodyFields(sample, `${prefix}[]`, add);
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
if (typeof sample === 'object') {
|
|
255
|
+
for (const [key, nested] of Object.entries(sample)) {
|
|
256
|
+
const nestedPath = `${prefix}[].${key}`;
|
|
257
|
+
if (nested !== null && typeof nested === 'object')
|
|
258
|
+
collectBodyFields(nested, nestedPath, add);
|
|
259
|
+
else
|
|
260
|
+
add({ name: nestedPath, in: 'body', type: valueTypeLabel(nested) });
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
return;
|
|
264
|
+
}
|
|
265
|
+
if (typeof value === 'object') {
|
|
266
|
+
if (prefix)
|
|
267
|
+
add({ name: prefix, in: 'body', type: 'object' });
|
|
268
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
269
|
+
const nestedPath = prefix ? `${prefix}.${key}` : key;
|
|
270
|
+
if (nested !== null && typeof nested === 'object')
|
|
271
|
+
collectBodyFields(nested, nestedPath, add);
|
|
272
|
+
else
|
|
273
|
+
add({ name: nestedPath, in: 'body', type: valueTypeLabel(nested) });
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function inferDocs(method, pathTemplate, opHits) {
|
|
278
|
+
const fields = [];
|
|
279
|
+
const seen = new Set();
|
|
280
|
+
const add = (field) => {
|
|
281
|
+
const key = `${field.in}:${field.name}`;
|
|
282
|
+
if (seen.has(key))
|
|
283
|
+
return;
|
|
284
|
+
seen.add(key);
|
|
285
|
+
const required = (0, dto_fields_1.dtoRequired)(method, pathTemplate, field.in, field.name);
|
|
286
|
+
fields.push({ ...field, ...(required === undefined ? {} : { required }) });
|
|
287
|
+
};
|
|
288
|
+
for (const name of (0, path_util_1.pathParamNames)(pathTemplate))
|
|
289
|
+
add({ name, in: 'path', type: 'string' });
|
|
290
|
+
for (const hit of opHits) {
|
|
291
|
+
for (const name of Object.keys(hit.query ?? {}))
|
|
292
|
+
add({ name, in: 'query', type: 'string' });
|
|
293
|
+
for (const name of Object.keys(hit.headers ?? {})) {
|
|
294
|
+
if (name === 'content-type')
|
|
295
|
+
continue;
|
|
296
|
+
add({ name, in: 'header', type: 'string' });
|
|
297
|
+
}
|
|
298
|
+
if (hit.reqBody && typeof hit.reqBody === 'object') {
|
|
299
|
+
collectBodyFields(hit.reqBody, '', add);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
return { title: (0, catalog_1.defaultTitle)(method, pathTemplate), fields };
|
|
303
|
+
}
|
|
304
|
+
function securityForHits(opHits) {
|
|
305
|
+
const headers = new Set();
|
|
306
|
+
for (const hit of opHits) {
|
|
307
|
+
for (const name of Object.keys(hit.headers ?? {})) {
|
|
308
|
+
if (name.startsWith('x-'))
|
|
309
|
+
headers.add(name);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
if (!headers.size)
|
|
313
|
+
return undefined;
|
|
314
|
+
// One requirement object = AND (all headers used together on this operation).
|
|
315
|
+
const requirement = {};
|
|
316
|
+
for (const header of headers)
|
|
317
|
+
requirement[schemeIdFromHeader(header)] = [];
|
|
318
|
+
return [requirement];
|
|
319
|
+
}
|
|
320
|
+
function exampleLabel(hit) {
|
|
321
|
+
return `${hit.status} - ${(0, catalog_1.caseName)(hit.test)}`;
|
|
322
|
+
}
|
|
323
|
+
function toScenario(hit) {
|
|
324
|
+
return {
|
|
325
|
+
name: (0, catalog_1.caseName)(hit.test),
|
|
326
|
+
group: (0, catalog_1.caseGroup)(hit.test),
|
|
327
|
+
status: hit.status,
|
|
328
|
+
pathParams: pathParamsFromHit(hit),
|
|
329
|
+
query: hit.query,
|
|
330
|
+
headers: hit.headers,
|
|
331
|
+
reqBody: hit.reqBody,
|
|
332
|
+
resBody: hit.resBody,
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
function sortScenarios(scenarios) {
|
|
336
|
+
const groupRank = (group) => {
|
|
337
|
+
const order = ['Success', 'Business errors', 'Invalid input', 'Missing fields', 'Auth', 'Other'];
|
|
338
|
+
const index = order.indexOf(group);
|
|
339
|
+
return index === -1 ? order.length : index;
|
|
340
|
+
};
|
|
341
|
+
return [...scenarios].sort((left, right) => {
|
|
342
|
+
const byGroup = groupRank(left.group) - groupRank(right.group);
|
|
343
|
+
if (byGroup !== 0)
|
|
344
|
+
return byGroup;
|
|
345
|
+
if (left.status !== right.status)
|
|
346
|
+
return left.status - right.status;
|
|
347
|
+
return left.name.localeCompare(right.name);
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
function dedupeScenarios(scenarios) {
|
|
351
|
+
const seen = new Set();
|
|
352
|
+
return scenarios.filter((scenario) => {
|
|
353
|
+
const key = JSON.stringify([scenario.group, scenario.name, scenario.status, scenario.reqBody, scenario.query, scenario.pathParams]);
|
|
354
|
+
if (seen.has(key))
|
|
355
|
+
return false;
|
|
356
|
+
seen.add(key);
|
|
357
|
+
return true;
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
function loadHits() {
|
|
361
|
+
if (!(0, fs_1.existsSync)((0, paths_1.getOutDir)()))
|
|
362
|
+
return [];
|
|
363
|
+
const workerFiles = (0, fs_1.readdirSync)((0, paths_1.getOutDir)()).filter((fileName) => fileName.startsWith('hits-w') && fileName.endsWith('.json'));
|
|
364
|
+
if (workerFiles.length) {
|
|
365
|
+
return workerFiles.flatMap((fileName) => {
|
|
366
|
+
try {
|
|
367
|
+
const parsed = JSON.parse((0, fs_1.readFileSync)(path.join((0, paths_1.getOutDir)(), fileName), 'utf8'));
|
|
368
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
369
|
+
}
|
|
370
|
+
catch (error) {
|
|
371
|
+
console.error(`DAxTA: skipped corrupt hits file ${fileName}:`, error);
|
|
372
|
+
return [];
|
|
373
|
+
}
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
// Fallback after workers were cleaned — rebuild from last merged hits.json
|
|
377
|
+
try {
|
|
378
|
+
if (!(0, fs_1.existsSync)((0, paths_1.getHitsJsonPath)()))
|
|
379
|
+
return [];
|
|
380
|
+
const parsed = JSON.parse((0, fs_1.readFileSync)((0, paths_1.getHitsJsonPath)(), 'utf8'));
|
|
381
|
+
return Array.isArray(parsed) ? parsed : [];
|
|
382
|
+
}
|
|
383
|
+
catch (error) {
|
|
384
|
+
console.error('DAxTA: skipped corrupt hits.json:', error);
|
|
385
|
+
return [];
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
function sortOperations(entries) {
|
|
389
|
+
return [...entries].sort((left, right) => {
|
|
390
|
+
const leftRank = (0, config_1.getConfig)().operationOrder?.(left[0]);
|
|
391
|
+
const rightRank = (0, config_1.getConfig)().operationOrder?.(right[0]);
|
|
392
|
+
if (leftRank != null || rightRank != null) {
|
|
393
|
+
return (leftRank ?? Number.MAX_SAFE_INTEGER) - (rightRank ?? Number.MAX_SAFE_INTEGER);
|
|
394
|
+
}
|
|
395
|
+
const [leftMethod, ...leftPathParts] = left[0].split(' ');
|
|
396
|
+
const [rightMethod, ...rightPathParts] = right[0].split(' ');
|
|
397
|
+
const leftPath = leftPathParts.join(' ');
|
|
398
|
+
const rightPath = rightPathParts.join(' ');
|
|
399
|
+
const pathCompare = leftPath.localeCompare(rightPath);
|
|
400
|
+
if (pathCompare !== 0)
|
|
401
|
+
return pathCompare;
|
|
402
|
+
return (METHOD_RANK[leftMethod] ?? 99) - (METHOD_RANK[rightMethod] ?? 99);
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
function buildSpec(hits) {
|
|
406
|
+
const grouped = new Map();
|
|
407
|
+
for (const hit of hits.filter(isPrimaryHit)) {
|
|
408
|
+
const key = `${hit.method} ${hit.path}`;
|
|
409
|
+
const opHits = grouped.get(key) ?? [];
|
|
410
|
+
opHits.push(hit);
|
|
411
|
+
grouped.set(key, opHits);
|
|
412
|
+
}
|
|
413
|
+
const paths = {};
|
|
414
|
+
const tags = new Set();
|
|
415
|
+
const securitySchemes = {};
|
|
416
|
+
for (const [key, opHits] of sortOperations([...grouped.entries()])) {
|
|
417
|
+
const method = key.split(' ')[0];
|
|
418
|
+
const pathTemplate = key.slice(method.length + 1);
|
|
419
|
+
const docs = inferDocs(method, pathTemplate, opHits);
|
|
420
|
+
const tag = (0, catalog_1.operationTag)(pathTemplate, method);
|
|
421
|
+
tags.add(tag);
|
|
422
|
+
const security = securityForHits(opHits);
|
|
423
|
+
for (const item of security ?? []) {
|
|
424
|
+
for (const schemeId of Object.keys(item)) {
|
|
425
|
+
const headerName = [...new Set(opHits.flatMap((hit) => Object.keys(hit.headers ?? {})))].find((header) => schemeIdFromHeader(header) === schemeId);
|
|
426
|
+
if (headerName)
|
|
427
|
+
securitySchemes[schemeId] = { type: 'apiKey', in: 'header', name: headerName };
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const pathItem = (paths[pathTemplate] ??= {});
|
|
431
|
+
const operation = (pathItem[method] ??= {
|
|
432
|
+
tags: [tag],
|
|
433
|
+
summary: docs.title,
|
|
434
|
+
security,
|
|
435
|
+
responses: {},
|
|
436
|
+
'x-docs': docs,
|
|
437
|
+
'x-scenarios': [],
|
|
438
|
+
'x-tree-segments': (0, catalog_1.treePathSegments)(pathTemplate),
|
|
439
|
+
});
|
|
440
|
+
const parameters = buildParameters(pathTemplate, opHits);
|
|
441
|
+
if (parameters.length)
|
|
442
|
+
operation.parameters = parameters;
|
|
443
|
+
for (const hit of opHits) {
|
|
444
|
+
const label = exampleLabel(hit);
|
|
445
|
+
if (hit.reqBody !== undefined) {
|
|
446
|
+
operation.requestBody ??= { required: method === 'post' || method === 'put', content: { 'application/json': { schema: inferSchema(hit.reqBody), examples: {} } } };
|
|
447
|
+
const media = operation.requestBody.content['application/json'];
|
|
448
|
+
media.schema = mergeSchema(media.schema, inferSchema(hit.reqBody));
|
|
449
|
+
media.examples ??= {};
|
|
450
|
+
addUniqueExample(media.examples, label, hit.reqBody);
|
|
451
|
+
}
|
|
452
|
+
const status = String(hit.status);
|
|
453
|
+
operation.responses[status] ??= {
|
|
454
|
+
description: catalog_1.STATUS_TEXT[status] ?? status,
|
|
455
|
+
content: hit.resBody === undefined || hit.resBody === '' || status === '204' ? undefined : { 'application/json': { schema: inferSchema(hit.resBody), examples: {} } },
|
|
456
|
+
};
|
|
457
|
+
if (operation.responses[status].content) {
|
|
458
|
+
const responseMedia = operation.responses[status].content['application/json'];
|
|
459
|
+
responseMedia.schema = mergeSchema(responseMedia.schema, inferSchema(hit.resBody));
|
|
460
|
+
responseMedia.examples ??= {};
|
|
461
|
+
addUniqueExample(responseMedia.examples, label, hit.resBody);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
operation['x-scenarios'] = sortScenarios(dedupeScenarios(opHits.map(toScenario)));
|
|
465
|
+
}
|
|
466
|
+
const info = specInfo();
|
|
467
|
+
return {
|
|
468
|
+
openapi: '3.0.3',
|
|
469
|
+
info: {
|
|
470
|
+
title: info.title,
|
|
471
|
+
version: info.version,
|
|
472
|
+
description: info.description,
|
|
473
|
+
'x-workspace': info.workspace,
|
|
474
|
+
},
|
|
475
|
+
'x-viewer': (0, catalog_1.viewerTreeConfig)(),
|
|
476
|
+
servers: [{ url: (0, config_1.getConfig)().baseUrl }],
|
|
477
|
+
tags: [...tags].sort().map((name) => ({ name })),
|
|
478
|
+
paths,
|
|
479
|
+
components: { securitySchemes },
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function writeJson(filePath, value) {
|
|
483
|
+
(0, fs_1.mkdirSync)(path.dirname(filePath), { recursive: true });
|
|
484
|
+
(0, fs_1.writeFileSync)(filePath, `${JSON.stringify(value, null, 2)}\n`);
|
|
485
|
+
}
|
|
486
|
+
function readJson(filePath) {
|
|
487
|
+
if (!(0, fs_1.existsSync)(filePath))
|
|
488
|
+
return null;
|
|
489
|
+
return JSON.parse((0, fs_1.readFileSync)(filePath, 'utf8'));
|
|
490
|
+
}
|
|
491
|
+
function sortedKeys(value) {
|
|
492
|
+
return Object.keys(value ?? {}).sort();
|
|
493
|
+
}
|
|
494
|
+
function signatureSchema(value) {
|
|
495
|
+
if (value === null || value === undefined)
|
|
496
|
+
return { nullable: true };
|
|
497
|
+
if (Array.isArray(value))
|
|
498
|
+
return { type: 'array' };
|
|
499
|
+
if (typeof value === 'object') {
|
|
500
|
+
return {
|
|
501
|
+
type: 'object',
|
|
502
|
+
properties: Object.fromEntries(Object.entries(value).map(([key, nested]) => [key, signatureSchema(nested)])),
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
if (typeof value === 'number')
|
|
506
|
+
return { type: Number.isInteger(value) ? 'integer' : 'number' };
|
|
507
|
+
if (typeof value === 'boolean')
|
|
508
|
+
return { type: 'boolean' };
|
|
509
|
+
return { type: 'string' };
|
|
510
|
+
}
|
|
511
|
+
function scenarioSignature(scenario) {
|
|
512
|
+
return JSON.stringify({
|
|
513
|
+
group: scenario.group,
|
|
514
|
+
name: scenario.name,
|
|
515
|
+
status: scenario.status,
|
|
516
|
+
queryKeys: sortedKeys(scenario.query),
|
|
517
|
+
pathParamKeys: sortedKeys(scenario.pathParams),
|
|
518
|
+
reqSchema: signatureSchema(scenario.reqBody),
|
|
519
|
+
resSchema: signatureSchema(scenario.resBody),
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
function exampleSummaries(operation) {
|
|
523
|
+
const summaries = [];
|
|
524
|
+
const collect = (examples) => {
|
|
525
|
+
for (const example of Object.values(examples ?? {})) {
|
|
526
|
+
summaries.push(String(example?.summary ?? ''));
|
|
527
|
+
}
|
|
528
|
+
};
|
|
529
|
+
const requestBody = operation.requestBody;
|
|
530
|
+
collect(requestBody?.content?.['application/json']?.examples);
|
|
531
|
+
const responses = operation.responses ?? {};
|
|
532
|
+
for (const response of Object.values(responses)) {
|
|
533
|
+
collect(response?.content?.['application/json']?.examples);
|
|
534
|
+
}
|
|
535
|
+
return summaries.sort((left, right) => left.localeCompare(right));
|
|
536
|
+
}
|
|
537
|
+
function operationSignature(operation) {
|
|
538
|
+
const scenarios = (operation['x-scenarios'] ?? []).map(scenarioSignature).sort((left, right) => left.localeCompare(right));
|
|
539
|
+
const parameters = (operation.parameters ?? []).map((parameter) => ({
|
|
540
|
+
name: parameter.name,
|
|
541
|
+
in: parameter.in,
|
|
542
|
+
required: parameter.required,
|
|
543
|
+
schema: parameter.schema,
|
|
544
|
+
}));
|
|
545
|
+
return JSON.stringify({
|
|
546
|
+
summary: operation.summary,
|
|
547
|
+
parameters,
|
|
548
|
+
security: operation.security,
|
|
549
|
+
docs: operation['x-docs'],
|
|
550
|
+
responseStatuses: Object.keys(operation.responses ?? {}).sort(),
|
|
551
|
+
examples: exampleSummaries(operation),
|
|
552
|
+
scenarios,
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
function operationsEquivalent(existing, fresh) {
|
|
556
|
+
return operationSignature(existing) === operationSignature(fresh);
|
|
557
|
+
}
|
|
558
|
+
function hitSignature(hit) {
|
|
559
|
+
return JSON.stringify({
|
|
560
|
+
method: hit.method,
|
|
561
|
+
path: hit.path,
|
|
562
|
+
status: hit.status,
|
|
563
|
+
test: hit.test,
|
|
564
|
+
queryKeys: sortedKeys(hit.query),
|
|
565
|
+
pathParamKeys: sortedKeys(hit.pathParams),
|
|
566
|
+
reqSchema: signatureSchema(hit.reqBody),
|
|
567
|
+
resSchema: signatureSchema(hit.resBody),
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
function hitsStructureSame(existing, fresh) {
|
|
571
|
+
if (!existing)
|
|
572
|
+
return false;
|
|
573
|
+
const left = existing.filter(isPrimaryHit).map(hitSignature).sort();
|
|
574
|
+
const right = fresh.filter(isPrimaryHit).map(hitSignature).sort();
|
|
575
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
576
|
+
}
|
|
577
|
+
function mergeSpecs(existing, fresh) {
|
|
578
|
+
// Spec mirrors this run's recorded hits only — no carry-over of stale endpoints from older runs.
|
|
579
|
+
if (!existing)
|
|
580
|
+
return { spec: fresh, updated: countOperations(fresh), unchanged: 0, changed: true };
|
|
581
|
+
const mergedPaths = {};
|
|
582
|
+
let updated = 0;
|
|
583
|
+
let unchanged = 0;
|
|
584
|
+
for (const [pathTemplate, freshPathItem] of Object.entries(fresh.paths)) {
|
|
585
|
+
mergedPaths[pathTemplate] = {};
|
|
586
|
+
for (const [method, freshOperation] of Object.entries(freshPathItem)) {
|
|
587
|
+
const existingOperation = existing.paths[pathTemplate]?.[method];
|
|
588
|
+
if (existingOperation && operationsEquivalent(existingOperation, freshOperation)) {
|
|
589
|
+
mergedPaths[pathTemplate][method] = existingOperation;
|
|
590
|
+
unchanged += 1;
|
|
591
|
+
}
|
|
592
|
+
else {
|
|
593
|
+
mergedPaths[pathTemplate][method] = freshOperation;
|
|
594
|
+
updated += 1;
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
const spec = {
|
|
599
|
+
...fresh,
|
|
600
|
+
paths: mergedPaths,
|
|
601
|
+
};
|
|
602
|
+
const removed = countOperations(existing) !== countOperations(spec) ||
|
|
603
|
+
Object.keys(existing.paths).some((pathTemplate) => !fresh.paths[pathTemplate]) ||
|
|
604
|
+
Object.entries(existing.paths).some(([pathTemplate, pathItem]) => Object.keys(pathItem).some((method) => !fresh.paths[pathTemplate]?.[method]));
|
|
605
|
+
return {
|
|
606
|
+
spec,
|
|
607
|
+
updated,
|
|
608
|
+
unchanged,
|
|
609
|
+
changed: updated > 0 || removed,
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
function countOperations(spec) {
|
|
613
|
+
return Object.values(spec.paths).reduce((count, pathItem) => count + Object.keys(pathItem).length, 0);
|
|
614
|
+
}
|
|
615
|
+
function toStandaloneHtml(spec) {
|
|
616
|
+
const template = (0, fs_1.readFileSync)((0, paths_1.getViewerAssetPath)(), 'utf8');
|
|
617
|
+
const faviconUri = (0, fs_1.existsSync)((0, paths_1.getFaviconAssetPath)())
|
|
618
|
+
? `data:image/png;base64,${(0, fs_1.readFileSync)((0, paths_1.getFaviconAssetPath)()).toString('base64')}`
|
|
619
|
+
: '';
|
|
620
|
+
return template
|
|
621
|
+
.replace('__SPEC_JSON__', JSON.stringify(spec).replace(/</g, '\\u003c'))
|
|
622
|
+
.replaceAll('__FAVICON_DATA_URI__', faviconUri);
|
|
623
|
+
}
|
|
624
|
+
function viewerTemplateNewerThanHtml() {
|
|
625
|
+
if (!(0, fs_1.existsSync)((0, paths_1.getHtmlPath)()))
|
|
626
|
+
return true;
|
|
627
|
+
const htmlMtime = (0, fs_1.statSync)((0, paths_1.getHtmlPath)()).mtimeMs;
|
|
628
|
+
const newerThan = (filePath) => (0, fs_1.existsSync)(filePath) && (0, fs_1.statSync)(filePath).mtimeMs > htmlMtime;
|
|
629
|
+
return newerThan((0, paths_1.getViewerAssetPath)()) || newerThan((0, paths_1.getFaviconAssetPath)());
|
|
630
|
+
}
|
|
631
|
+
function applyViewerMeta(spec) {
|
|
632
|
+
const info = specInfo();
|
|
633
|
+
return {
|
|
634
|
+
...spec,
|
|
635
|
+
info: {
|
|
636
|
+
...spec.info,
|
|
637
|
+
title: info.title,
|
|
638
|
+
version: info.version,
|
|
639
|
+
description: info.description,
|
|
640
|
+
'x-workspace': info.workspace,
|
|
641
|
+
},
|
|
642
|
+
'x-viewer': (0, catalog_1.viewerTreeConfig)(),
|
|
643
|
+
servers: [{ url: (0, config_1.getConfig)().baseUrl }],
|
|
644
|
+
};
|
|
645
|
+
}
|
|
646
|
+
function buildDaxtaSpec(options = {}) {
|
|
647
|
+
const hits = loadHits();
|
|
648
|
+
const existingHits = readJson((0, paths_1.getHitsJsonPath)());
|
|
649
|
+
const existingSpec = readJson((0, paths_1.getSpecJsonPath)());
|
|
650
|
+
const writeHtml = options.html !== false;
|
|
651
|
+
if (!hits.length) {
|
|
652
|
+
if (existingSpec && writeHtml && viewerTemplateNewerThanHtml()) {
|
|
653
|
+
const refreshed = applyViewerMeta(existingSpec);
|
|
654
|
+
writeJson((0, paths_1.getSpecJsonPath)(), refreshed);
|
|
655
|
+
(0, fs_1.writeFileSync)((0, paths_1.getHtmlPath)(), toStandaloneHtml(refreshed));
|
|
656
|
+
if (!options.silent)
|
|
657
|
+
console.log(`Wrote ${(0, paths_1.getHtmlPath)()} from existing spec (viewer template updated)`);
|
|
658
|
+
return { skipped: false, reason: 'viewer only', hits: 0, operations: countOperations(existingSpec), updated: 0, unchanged: countOperations(existingSpec), changed: true };
|
|
659
|
+
}
|
|
660
|
+
if (options.requireHits) {
|
|
661
|
+
throw new Error('No HTTP hits recorded. Run integration tests first.');
|
|
662
|
+
}
|
|
663
|
+
return { skipped: true, reason: 'no hits', hits: 0, operations: 0, updated: 0, unchanged: 0, changed: false };
|
|
664
|
+
}
|
|
665
|
+
const freshSpec = applyViewerMeta(buildSpec(hits));
|
|
666
|
+
const { spec: merged, updated, unchanged, changed: operationsChanged } = mergeSpecs(existingSpec, freshSpec);
|
|
667
|
+
const spec = applyViewerMeta(merged);
|
|
668
|
+
const hitsChanged = !hitsStructureSame(existingHits, hits);
|
|
669
|
+
const metaChanged = !existingSpec ||
|
|
670
|
+
JSON.stringify(existingSpec.info) !== JSON.stringify(spec.info) ||
|
|
671
|
+
JSON.stringify(existingSpec['x-viewer']) !== JSON.stringify(spec['x-viewer']) ||
|
|
672
|
+
JSON.stringify(existingSpec.servers) !== JSON.stringify(spec.servers);
|
|
673
|
+
const refreshHtml = writeHtml && (operationsChanged || metaChanged || viewerTemplateNewerThanHtml());
|
|
674
|
+
const changed = operationsChanged || hitsChanged || metaChanged || refreshHtml;
|
|
675
|
+
if (changed) {
|
|
676
|
+
if (hitsChanged)
|
|
677
|
+
writeJson((0, paths_1.getHitsJsonPath)(), hits);
|
|
678
|
+
if (operationsChanged || metaChanged)
|
|
679
|
+
writeJson((0, paths_1.getSpecJsonPath)(), spec);
|
|
680
|
+
if (refreshHtml)
|
|
681
|
+
(0, fs_1.writeFileSync)((0, paths_1.getHtmlPath)(), toStandaloneHtml(spec));
|
|
682
|
+
}
|
|
683
|
+
const operations = countOperations(spec);
|
|
684
|
+
const result = {
|
|
685
|
+
skipped: false,
|
|
686
|
+
hits: hits.length,
|
|
687
|
+
operations,
|
|
688
|
+
updated,
|
|
689
|
+
unchanged,
|
|
690
|
+
changed,
|
|
691
|
+
};
|
|
692
|
+
if (!options.silent) {
|
|
693
|
+
if (!changed) {
|
|
694
|
+
console.log(`DAxTA unchanged (${hits.length} hits, ${operations} operations — ${unchanged} kept as-is)`);
|
|
695
|
+
}
|
|
696
|
+
else {
|
|
697
|
+
console.log(`Wrote ${(0, paths_1.getSpecJsonPath)()} from ${hits.length} hits (${operations} operations — ${updated} updated, ${unchanged} unchanged)`);
|
|
698
|
+
console.log(`Wrote ${(0, paths_1.getHtmlPath)()}`);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return result;
|
|
702
|
+
}
|
|
703
|
+
/** @deprecated Use `buildDaxtaSpec` */
|
|
704
|
+
exports.buildOpenApi = buildDaxtaSpec;
|