@contractkit/plugin-bruno 0.9.1
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/.turbo/turbo-build$colon$ci.log +35 -0
- package/.turbo/turbo-build.log +15 -0
- package/.turbo/turbo-test$colon$ci.log +128 -0
- package/.turbo/turbo-test.log +14 -0
- package/CHANGELOG.md +110 -0
- package/README.md +80 -0
- package/coverage/base.css +224 -0
- package/coverage/block-navigation.js +87 -0
- package/coverage/clover.xml +313 -0
- package/coverage/coverage-final.json +3 -0
- package/coverage/favicon.png +0 -0
- package/coverage/index.html +131 -0
- package/coverage/prettify.css +1 -0
- package/coverage/prettify.js +2 -0
- package/coverage/sort-arrow-sprite.png +0 -0
- package/coverage/sorter.js +210 -0
- package/coverage/src/codegen-bruno.ts.html +1903 -0
- package/coverage/src/index.html +116 -0
- package/coverage/tests/helpers.ts.html +604 -0
- package/coverage/tests/index.html +116 -0
- package/dist/codegen-bruno.d.ts +50 -0
- package/dist/codegen-bruno.d.ts.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +631 -0
- package/dist/index.js.map +1 -0
- package/eslint.config.js +6 -0
- package/package.json +43 -0
- package/src/codegen-bruno.ts +606 -0
- package/src/index.ts +130 -0
- package/tests/codegen-bruno.test.ts +1008 -0
- package/tests/helpers.ts +173 -0
- package/tsconfig.json +9 -0
- package/vitest.config.ts +14 -0
|
@@ -0,0 +1,606 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
OpRootNode,
|
|
3
|
+
OpRouteNode,
|
|
4
|
+
OpOperationNode,
|
|
5
|
+
OpResponseNode,
|
|
6
|
+
ParamSource,
|
|
7
|
+
ContractTypeNode,
|
|
8
|
+
ContractRootNode,
|
|
9
|
+
ModelNode,
|
|
10
|
+
FieldNode,
|
|
11
|
+
} from '@contractkit/core';
|
|
12
|
+
import { resolveSecurity, resolveModifiers, SECURITY_NONE } from '@contractkit/core';
|
|
13
|
+
import { basename } from 'path';
|
|
14
|
+
|
|
15
|
+
export interface OpenCollectionFile {
|
|
16
|
+
relativePath: string;
|
|
17
|
+
content: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Manifest filename — tracks which files this plugin previously generated so subsequent runs can clean up only those, leaving any user-added files alone. */
|
|
21
|
+
export const MANIFEST_FILENAME = '.contractkit-bruno-manifest.json';
|
|
22
|
+
|
|
23
|
+
/** Subset of a security scheme sufficient for Bruno auth generation (non-HMAC). */
|
|
24
|
+
export interface BrunoSecurityScheme {
|
|
25
|
+
type: string; // "http" | "apiKey" | "oauth2" | "openIdConnect"
|
|
26
|
+
scheme?: string; // "bearer" | "basic" (when type === "http")
|
|
27
|
+
name?: string; // header/query param name (when type === "apiKey")
|
|
28
|
+
in?: string; // "header" | "query" (when type === "apiKey")
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export interface BrunoAuthOptions {
|
|
32
|
+
/** Name of the default scheme (from config.security.default) */
|
|
33
|
+
defaultScheme?: string;
|
|
34
|
+
/** Scheme definitions keyed by name (non-HMAC only) */
|
|
35
|
+
schemes?: Record<string, BrunoSecurityScheme>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface OpenCollectionOptions {
|
|
39
|
+
collectionName: string;
|
|
40
|
+
contractRoots?: ContractRootNode[];
|
|
41
|
+
auth?: BrunoAuthOptions;
|
|
42
|
+
/**
|
|
43
|
+
* When true, emit Bruno faker template strings (e.g. `{{$randomUUID}}`,
|
|
44
|
+
* `{{$randomEmail}}`) for compatible scalar types so each send produces
|
|
45
|
+
* fresh data. When false (default), use deterministic placeholders.
|
|
46
|
+
*/
|
|
47
|
+
randomExamples?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Whether to generate request files for operations marked `internal`. Defaults to
|
|
50
|
+
* `true` — Bruno collections are typically used by the team that owns the API and
|
|
51
|
+
* benefit from full coverage. Set to `false` to omit internal ops.
|
|
52
|
+
*/
|
|
53
|
+
includeInternal?: boolean;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Generates an OpenCollection (https://spec.opencollection.com/) API collection
|
|
58
|
+
* from a set of operation roots. Produces opencollection.yml, an environment
|
|
59
|
+
* file, and one .yml request file per operation.
|
|
60
|
+
*/
|
|
61
|
+
export function generateOpenCollection(roots: OpRootNode[], options: OpenCollectionOptions): OpenCollectionFile[] {
|
|
62
|
+
const files: OpenCollectionFile[] = [];
|
|
63
|
+
|
|
64
|
+
const modelMap = buildModelMap(options.contractRoots ?? []);
|
|
65
|
+
const authOpts = options.auth;
|
|
66
|
+
const defaultScheme = authOpts?.defaultScheme ? authOpts.schemes?.[authOpts.defaultScheme] : undefined;
|
|
67
|
+
const randomExamples = options.randomExamples ?? false;
|
|
68
|
+
const includeInternal = options.includeInternal ?? true;
|
|
69
|
+
|
|
70
|
+
files.push({ relativePath: 'opencollection.yml', content: generateCollectionRoot(options.collectionName, defaultScheme) });
|
|
71
|
+
files.push({ relativePath: 'environments/local.yml', content: generateEnvFile(defaultScheme) });
|
|
72
|
+
// Manifest is appended at the end so it lists every generated path including itself.
|
|
73
|
+
|
|
74
|
+
for (let rootIdx = 0; rootIdx < roots.length; rootIdx++) {
|
|
75
|
+
const root = roots[rootIdx]!;
|
|
76
|
+
const folder = root.meta['area'] ? slugifyName(root.meta['area']) : deriveFolderName(root.file);
|
|
77
|
+
const displayName = (root.meta['area'] ?? folder).charAt(0).toUpperCase() + (root.meta['area'] ?? folder).slice(1);
|
|
78
|
+
|
|
79
|
+
files.push({ relativePath: `${folder}/folder.yml`, content: generateFolderFile(displayName, rootIdx + 1) });
|
|
80
|
+
|
|
81
|
+
const subarea = root.meta['subarea'];
|
|
82
|
+
const subareaSlug = subarea ? slugifyName(subarea) : undefined;
|
|
83
|
+
const requestDir = subareaSlug ? `${folder}/${subareaSlug}` : folder;
|
|
84
|
+
|
|
85
|
+
if (subareaSlug) {
|
|
86
|
+
const subareaDisplayName = subarea!.charAt(0).toUpperCase() + subarea!.slice(1);
|
|
87
|
+
files.push({ relativePath: `${requestDir}/folder.yml`, content: generateFolderFile(subareaDisplayName, 1) });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let seq = 1;
|
|
91
|
+
for (const route of root.routes) {
|
|
92
|
+
for (const op of route.operations) {
|
|
93
|
+
if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
|
|
94
|
+
const requestName = op.name ?? route.path;
|
|
95
|
+
const fileName = op.name ? `${slugifyName(op.name)}.yml` : `${op.method}-${sanitizePath(route.path)}.yml`;
|
|
96
|
+
files.push({
|
|
97
|
+
relativePath: `${requestDir}/${fileName}`,
|
|
98
|
+
content: generateRequestFile(route, op, requestName, seq, modelMap, root, defaultScheme, randomExamples),
|
|
99
|
+
});
|
|
100
|
+
seq++;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const trackedPaths = [...files.map(f => f.relativePath), MANIFEST_FILENAME].sort();
|
|
106
|
+
files.push({
|
|
107
|
+
relativePath: MANIFEST_FILENAME,
|
|
108
|
+
content: JSON.stringify({ files: trackedPaths }, null, 2) + '\n',
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
return files;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Parse a previously-written manifest. Returns the list of relative paths to clean up. Returns [] if missing or unreadable so a stale/garbled manifest never blocks regeneration. */
|
|
115
|
+
export function parseManifest(content: string): string[] {
|
|
116
|
+
try {
|
|
117
|
+
const parsed = JSON.parse(content);
|
|
118
|
+
if (Array.isArray(parsed?.files) && parsed.files.every((f: unknown) => typeof f === 'string')) {
|
|
119
|
+
return parsed.files as string[];
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
// fall through
|
|
123
|
+
}
|
|
124
|
+
return [];
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ─── File generators ───────────────────────────────────────────────────────
|
|
128
|
+
|
|
129
|
+
function generateCollectionRoot(name: string, scheme?: BrunoSecurityScheme): string {
|
|
130
|
+
const lines = [`opencollection: "1.0.0"`, `info:`, ` name: ${yamlString(name)}`];
|
|
131
|
+
if (scheme) {
|
|
132
|
+
lines.push(``);
|
|
133
|
+
lines.push(`request:`);
|
|
134
|
+
lines.push(...renderAuthBlock(scheme, ' '));
|
|
135
|
+
}
|
|
136
|
+
lines.push(``);
|
|
137
|
+
return lines.join('\n');
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function generateEnvFile(scheme?: BrunoSecurityScheme): string {
|
|
141
|
+
const lines = [`name: Local`, `variables:`, ` - name: baseUrl`, ` value: "http://localhost:3000"`];
|
|
142
|
+
if (scheme) {
|
|
143
|
+
for (const varName of authEnvVarNames(scheme)) {
|
|
144
|
+
lines.push(` - name: ${varName}`);
|
|
145
|
+
lines.push(` value: ""`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
lines.push(``);
|
|
149
|
+
return lines.join('\n');
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function generateFolderFile(name: string, seq: number): string {
|
|
153
|
+
return [`info:`, ` name: ${yamlString(name)}`, ` type: folder`, ` seq: ${seq}`, ``].join('\n');
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function generateRequestFile(
|
|
157
|
+
route: OpRouteNode,
|
|
158
|
+
op: OpOperationNode,
|
|
159
|
+
name: string,
|
|
160
|
+
seq: number,
|
|
161
|
+
modelMap: Map<string, ModelNode>,
|
|
162
|
+
root?: OpRootNode,
|
|
163
|
+
defaultScheme?: BrunoSecurityScheme,
|
|
164
|
+
randomExamples = false,
|
|
165
|
+
): string {
|
|
166
|
+
const lines: string[] = [];
|
|
167
|
+
|
|
168
|
+
lines.push(`info:`);
|
|
169
|
+
lines.push(` name: ${yamlString(name)}`);
|
|
170
|
+
lines.push(` type: http`);
|
|
171
|
+
lines.push(` seq: ${seq}`);
|
|
172
|
+
lines.push(``);
|
|
173
|
+
lines.push(`http:`);
|
|
174
|
+
lines.push(` method: ${op.method.toUpperCase()}`);
|
|
175
|
+
lines.push(` url: ${yamlString(`{{baseUrl}}${openCollectionPath(route.path)}`)}`);
|
|
176
|
+
|
|
177
|
+
// Params — flat array with type: "path" | "query". Optional query params are
|
|
178
|
+
// emitted with disabled: true so users opt in before sending.
|
|
179
|
+
const pathParams: Array<ParamEntry & { kind: 'path' | 'query' }> = extractPathParamNames(route.path).map(n => ({
|
|
180
|
+
name: n,
|
|
181
|
+
type: findParamType(route.params, n, modelMap),
|
|
182
|
+
optional: false,
|
|
183
|
+
kind: 'path' as const,
|
|
184
|
+
}));
|
|
185
|
+
const queryParams: Array<ParamEntry & { kind: 'path' | 'query' }> = op.query
|
|
186
|
+
? expandParamSource(op.query, modelMap).map(e => ({ ...e, kind: 'query' as const }))
|
|
187
|
+
: [];
|
|
188
|
+
const allParams = [...pathParams, ...queryParams];
|
|
189
|
+
|
|
190
|
+
if (allParams.length > 0) {
|
|
191
|
+
lines.push(` params:`);
|
|
192
|
+
for (const p of allParams) {
|
|
193
|
+
lines.push(` - name: ${p.name}`);
|
|
194
|
+
lines.push(` value: ${paramExampleValue(p.type, p.default, randomExamples)}`);
|
|
195
|
+
lines.push(` type: ${p.kind}`);
|
|
196
|
+
if (p.optional && p.kind === 'query') lines.push(` disabled: true`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Headers
|
|
201
|
+
if (op.headers) {
|
|
202
|
+
const headerEntries = expandParamSource(op.headers, modelMap);
|
|
203
|
+
if (headerEntries.length > 0) {
|
|
204
|
+
lines.push(` headers:`);
|
|
205
|
+
for (const h of headerEntries) {
|
|
206
|
+
lines.push(` - name: ${h.name}`);
|
|
207
|
+
lines.push(` value: ${paramExampleValue(h.type, h.default, randomExamples)}`);
|
|
208
|
+
if (h.optional) lines.push(` disabled: true`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Auth — inside http block; inherit collection default unless this op is explicitly public
|
|
214
|
+
if (defaultScheme) {
|
|
215
|
+
const security = root ? resolveSecurity(route, op, root) : (op.security ?? route.security);
|
|
216
|
+
if (security === SECURITY_NONE) {
|
|
217
|
+
lines.push(` auth:`);
|
|
218
|
+
lines.push(` type: none`);
|
|
219
|
+
} else {
|
|
220
|
+
lines.push(` auth: inherit`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Body — Bruno supports a single body per request, so prefer JSON, then form-urlencoded, then multipart.
|
|
225
|
+
if (op.request && op.request.bodies.length > 0) {
|
|
226
|
+
const preferredOrder: Array<(typeof op.request.bodies)[number]['contentType']> = [
|
|
227
|
+
'application/json',
|
|
228
|
+
'application/x-www-form-urlencoded',
|
|
229
|
+
'multipart/form-data',
|
|
230
|
+
];
|
|
231
|
+
const primary =
|
|
232
|
+
preferredOrder.map(ct => op.request!.bodies.find(b => b.contentType === ct)).find(b => b !== undefined) ?? op.request.bodies[0]!;
|
|
233
|
+
|
|
234
|
+
lines.push(` body:`);
|
|
235
|
+
if (primary.contentType === 'multipart/form-data') {
|
|
236
|
+
lines.push(` type: multipart-form`);
|
|
237
|
+
lines.push(` data: []`);
|
|
238
|
+
} else if (primary.contentType === 'application/x-www-form-urlencoded') {
|
|
239
|
+
lines.push(` type: form-urlencoded`);
|
|
240
|
+
lines.push(` data: []`);
|
|
241
|
+
} else {
|
|
242
|
+
const json = JSON.stringify(typeToExampleValue(primary.bodyType, modelMap, randomExamples), null, 2);
|
|
243
|
+
lines.push(` type: json`);
|
|
244
|
+
lines.push(` data: |`);
|
|
245
|
+
for (const jsonLine of json.split('\n')) {
|
|
246
|
+
lines.push(` ${jsonLine}`);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// runtime.assertions — auto-generate a status-code check and presence checks for required response headers.
|
|
252
|
+
const expectedStatus = pickAssertionStatus(op.responses);
|
|
253
|
+
const assertedResponse = op.responses.find(r => r.statusCode === expectedStatus);
|
|
254
|
+
const requiredHeaders = (assertedResponse?.headers ?? []).filter(h => !h.optional);
|
|
255
|
+
if (expectedStatus !== undefined) {
|
|
256
|
+
lines.push(``);
|
|
257
|
+
lines.push(`runtime:`);
|
|
258
|
+
lines.push(` assertions:`);
|
|
259
|
+
lines.push(` - expression: res.status`);
|
|
260
|
+
lines.push(` operator: eq`);
|
|
261
|
+
// Always quote — the OpenCollection schema types `value` as a string,
|
|
262
|
+
// so we must keep "200" from being parsed as YAML number 200.
|
|
263
|
+
lines.push(` value: "${expectedStatus}"`);
|
|
264
|
+
for (const h of requiredHeaders) {
|
|
265
|
+
lines.push(` - expression: res.headers["${h.name.toLowerCase()}"]`);
|
|
266
|
+
lines.push(` operator: isDefined`);
|
|
267
|
+
lines.push(` value: ""`);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// docs — combine route- and operation-level descriptions plus the declared response-header summary.
|
|
272
|
+
const docs = buildRequestDocs(route, op, assertedResponse);
|
|
273
|
+
if (docs) {
|
|
274
|
+
lines.push(``);
|
|
275
|
+
lines.push(`docs: |-`);
|
|
276
|
+
for (const docLine of docs.split('\n')) {
|
|
277
|
+
lines.push(` ${docLine}`);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
lines.push(``);
|
|
282
|
+
return lines.join('\n');
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** Pick the response whose status code we'll assert against. Prefers the first declared 2xx; otherwise falls back to the first declared response. Returns undefined if no responses are declared. */
|
|
286
|
+
function pickAssertionStatus(responses: OpResponseNode[]): number | undefined {
|
|
287
|
+
const success = responses.find(r => r.statusCode >= 200 && r.statusCode < 300);
|
|
288
|
+
return success?.statusCode ?? responses[0]?.statusCode;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** Build a markdown docs block from route- and operation-level descriptions, plus declared response-header summary. */
|
|
292
|
+
function buildRequestDocs(route: OpRouteNode, op: OpOperationNode, assertedResponse?: OpResponseNode): string | undefined {
|
|
293
|
+
const parts: string[] = [];
|
|
294
|
+
if (route.description) parts.push(route.description.trim());
|
|
295
|
+
if (op.description) parts.push(op.description.trim());
|
|
296
|
+
const headers = assertedResponse?.headers ?? [];
|
|
297
|
+
if (headers.length > 0) {
|
|
298
|
+
const lines = ['**Response headers**', ''];
|
|
299
|
+
for (const h of headers) {
|
|
300
|
+
const tag = h.optional ? 'optional' : 'required';
|
|
301
|
+
const desc = h.description ? ` — ${h.description}` : '';
|
|
302
|
+
lines.push(`- \`${h.name}\` (${tag})${desc}`);
|
|
303
|
+
}
|
|
304
|
+
parts.push(lines.join('\n'));
|
|
305
|
+
}
|
|
306
|
+
return parts.length > 0 ? parts.join('\n\n') : undefined;
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// ─── Auth helpers ──────────────────────────────────────────────────────────
|
|
310
|
+
|
|
311
|
+
/** Generate the YAML lines for an auth block (flat, per spec), indented by `indent`. */
|
|
312
|
+
function renderAuthBlock(scheme: BrunoSecurityScheme, indent: string): string[] {
|
|
313
|
+
const i = indent;
|
|
314
|
+
if (scheme.type === 'http' && scheme.scheme === 'bearer') {
|
|
315
|
+
return [`${i}auth:`, `${i} type: bearer`, `${i} token: "{{token}}"`];
|
|
316
|
+
}
|
|
317
|
+
if (scheme.type === 'http' && scheme.scheme === 'basic') {
|
|
318
|
+
return [`${i}auth:`, `${i} type: basic`, `${i} username: "{{username}}"`, `${i} password: "{{password}}"`];
|
|
319
|
+
}
|
|
320
|
+
if (scheme.type === 'apiKey' && scheme.in === 'header') {
|
|
321
|
+
const headerName = scheme.name ?? 'X-Api-Key';
|
|
322
|
+
return [`${i}auth:`, `${i} type: apikey`, `${i} key: ${headerName}`, `${i} value: "{{apiKey}}"`, `${i} placement: header`];
|
|
323
|
+
}
|
|
324
|
+
return [];
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** Return the environment variable names needed for a given auth scheme. */
|
|
328
|
+
function authEnvVarNames(scheme: BrunoSecurityScheme): string[] {
|
|
329
|
+
if (scheme.type === 'http' && scheme.scheme === 'bearer') return ['token'];
|
|
330
|
+
if (scheme.type === 'http' && scheme.scheme === 'basic') return ['username', 'password'];
|
|
331
|
+
if (scheme.type === 'apiKey') return ['apiKey'];
|
|
332
|
+
return [];
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// ─── Model registry ────────────────────────────────────────────────────────
|
|
336
|
+
|
|
337
|
+
function buildModelMap(contractRoots: ContractRootNode[]): Map<string, ModelNode> {
|
|
338
|
+
const map = new Map<string, ModelNode>();
|
|
339
|
+
for (const root of contractRoots) {
|
|
340
|
+
for (const model of root.models) {
|
|
341
|
+
map.set(model.name, model);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
return map;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/** Resolve all fields for a model, including inherited base fields (bases first, in declaration order). */
|
|
348
|
+
function resolveModelFields(model: ModelNode, modelMap: Map<string, ModelNode>): FieldNode[] {
|
|
349
|
+
const collected: FieldNode[] = [];
|
|
350
|
+
if (model.bases) {
|
|
351
|
+
for (const base of model.bases) {
|
|
352
|
+
const baseModel = modelMap.get(base);
|
|
353
|
+
if (baseModel) collected.push(...resolveModelFields(baseModel, modelMap));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return [...collected, ...model.fields];
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// ─── Param helpers ─────────────────────────────────────────────────────────
|
|
360
|
+
|
|
361
|
+
interface ParamEntry {
|
|
362
|
+
name: string;
|
|
363
|
+
type: ContractTypeNode | undefined;
|
|
364
|
+
default?: string | number | boolean;
|
|
365
|
+
optional: boolean;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** Expand a ParamSource into a flat list of named entries with their types. */
|
|
369
|
+
function expandParamSource(source: ParamSource, modelMap: Map<string, ModelNode>): ParamEntry[] {
|
|
370
|
+
if (source.kind === 'params') {
|
|
371
|
+
return source.nodes.map(n => ({ name: n.name, type: n.type, default: n.default, optional: n.optional }));
|
|
372
|
+
}
|
|
373
|
+
if (source.kind === 'ref') {
|
|
374
|
+
const model = modelMap.get(source.name);
|
|
375
|
+
if (model) {
|
|
376
|
+
return resolveModelFields(model, modelMap)
|
|
377
|
+
.filter(f => f.visibility !== 'readonly')
|
|
378
|
+
.map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));
|
|
379
|
+
}
|
|
380
|
+
// Fallback: single placeholder entry
|
|
381
|
+
const name = source.name.charAt(0).toLowerCase() + source.name.slice(1);
|
|
382
|
+
return [{ name, type: undefined, optional: false }];
|
|
383
|
+
}
|
|
384
|
+
// kind === 'type': if it's an inline object, expand its fields
|
|
385
|
+
if (source.node.kind === 'inlineObject') {
|
|
386
|
+
return source.node.fields.map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));
|
|
387
|
+
}
|
|
388
|
+
return [];
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Look up a named path param's type from route.params. */
|
|
392
|
+
function findParamType(source: ParamSource | undefined, name: string, modelMap: Map<string, ModelNode>): ContractTypeNode | undefined {
|
|
393
|
+
if (!source) return undefined;
|
|
394
|
+
if (source.kind === 'params') return source.nodes.find(n => n.name === name)?.type;
|
|
395
|
+
if (source.kind === 'ref') {
|
|
396
|
+
const model = modelMap.get(source.name);
|
|
397
|
+
if (model) return resolveModelFields(model, modelMap).find(f => f.name === name)?.type;
|
|
398
|
+
}
|
|
399
|
+
if (source.kind === 'type' && source.node.kind === 'inlineObject') {
|
|
400
|
+
return source.node.fields.find(f => f.name === name)?.type;
|
|
401
|
+
}
|
|
402
|
+
return undefined;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** Return a YAML-quoted example value string for a param, preferring a default value when provided. */
|
|
406
|
+
function paramExampleValue(type: ContractTypeNode | undefined, defaultValue?: string | number | boolean, randomExamples = false): string {
|
|
407
|
+
if (defaultValue !== undefined) return `"${defaultValue}"`;
|
|
408
|
+
if (!type) return '""';
|
|
409
|
+
if (type.kind === 'enum') return type.values.length > 0 ? `"${type.values[0]}"` : '""';
|
|
410
|
+
if (type.kind === 'literal') return `"${type.value}"`;
|
|
411
|
+
if (type.kind !== 'scalar') return '""';
|
|
412
|
+
if (randomExamples) {
|
|
413
|
+
const random = randomScalarTemplate(type.name);
|
|
414
|
+
if (random !== undefined) return `"${random}"`;
|
|
415
|
+
}
|
|
416
|
+
switch (type.name) {
|
|
417
|
+
case 'uuid':
|
|
418
|
+
return '"00000000-0000-0000-0000-000000000000"';
|
|
419
|
+
case 'email':
|
|
420
|
+
return '"user@example.com"';
|
|
421
|
+
case 'url':
|
|
422
|
+
return '"https://example.com"';
|
|
423
|
+
case 'number':
|
|
424
|
+
case 'int':
|
|
425
|
+
case 'bigint':
|
|
426
|
+
return '"0"';
|
|
427
|
+
case 'boolean':
|
|
428
|
+
return '"true"';
|
|
429
|
+
case 'date':
|
|
430
|
+
return '"2024-01-01"';
|
|
431
|
+
case 'time':
|
|
432
|
+
return '"00:00:00"';
|
|
433
|
+
case 'datetime':
|
|
434
|
+
return '"2024-01-01T00:00:00Z"';
|
|
435
|
+
case 'duration':
|
|
436
|
+
return '"PT1H"';
|
|
437
|
+
default:
|
|
438
|
+
return '""';
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** Bruno faker template for a scalar type, or undefined when no clean equivalent exists (date, time, duration, raw string). */
|
|
443
|
+
function randomScalarTemplate(name: string): string | undefined {
|
|
444
|
+
switch (name) {
|
|
445
|
+
case 'uuid':
|
|
446
|
+
return '{{$randomUUID}}';
|
|
447
|
+
case 'email':
|
|
448
|
+
return '{{$randomEmail}}';
|
|
449
|
+
case 'url':
|
|
450
|
+
return '{{$randomUrl}}';
|
|
451
|
+
case 'number':
|
|
452
|
+
case 'int':
|
|
453
|
+
case 'bigint':
|
|
454
|
+
return '{{$randomInt}}';
|
|
455
|
+
case 'boolean':
|
|
456
|
+
return '{{$randomBoolean}}';
|
|
457
|
+
case 'datetime':
|
|
458
|
+
return '{{$isoTimestamp}}';
|
|
459
|
+
default:
|
|
460
|
+
return undefined;
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// ─── Body helpers ──────────────────────────────────────────────────────────
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Recursively build an example JSON value from a ContractTypeNode.
|
|
468
|
+
*
|
|
469
|
+
* When `randomExamples` is true we substitute Bruno faker templates only for
|
|
470
|
+
* scalars whose JSON representation is a string (uuid/email/url/datetime).
|
|
471
|
+
* Numbers and booleans stay deterministic — embedding `{{$randomInt}}` as a
|
|
472
|
+
* bare JSON number would require sentinel-stripping the surrounding quotes,
|
|
473
|
+
* and the body skeleton is meant as a starting point users edit anyway.
|
|
474
|
+
*/
|
|
475
|
+
function typeToExampleValue(type: ContractTypeNode, modelMap: Map<string, ModelNode>, randomExamples = false): unknown {
|
|
476
|
+
switch (type.kind) {
|
|
477
|
+
case 'scalar':
|
|
478
|
+
switch (type.name) {
|
|
479
|
+
case 'string':
|
|
480
|
+
return '';
|
|
481
|
+
case 'email':
|
|
482
|
+
return randomExamples ? '{{$randomEmail}}' : 'user@example.com';
|
|
483
|
+
case 'url':
|
|
484
|
+
return randomExamples ? '{{$randomUrl}}' : 'https://example.com';
|
|
485
|
+
case 'uuid':
|
|
486
|
+
return randomExamples ? '{{$randomUUID}}' : '00000000-0000-0000-0000-000000000000';
|
|
487
|
+
case 'number':
|
|
488
|
+
case 'int':
|
|
489
|
+
case 'bigint':
|
|
490
|
+
return 0;
|
|
491
|
+
case 'boolean':
|
|
492
|
+
return true;
|
|
493
|
+
case 'date':
|
|
494
|
+
return '2024-01-01';
|
|
495
|
+
case 'time':
|
|
496
|
+
return '00:00:00';
|
|
497
|
+
case 'datetime':
|
|
498
|
+
return randomExamples ? '{{$isoTimestamp}}' : '2024-01-01T00:00:00Z';
|
|
499
|
+
case 'duration':
|
|
500
|
+
return 'PT1H';
|
|
501
|
+
case 'null':
|
|
502
|
+
return null;
|
|
503
|
+
default:
|
|
504
|
+
return null;
|
|
505
|
+
}
|
|
506
|
+
case 'enum':
|
|
507
|
+
return type.values[0] ?? '';
|
|
508
|
+
case 'literal':
|
|
509
|
+
return type.value;
|
|
510
|
+
case 'array':
|
|
511
|
+
return [typeToExampleValue(type.item, modelMap, randomExamples)];
|
|
512
|
+
case 'tuple':
|
|
513
|
+
return type.items.map(t => typeToExampleValue(t, modelMap, randomExamples));
|
|
514
|
+
case 'record':
|
|
515
|
+
return {};
|
|
516
|
+
case 'union':
|
|
517
|
+
return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;
|
|
518
|
+
case 'discriminatedUnion':
|
|
519
|
+
return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;
|
|
520
|
+
case 'intersection':
|
|
521
|
+
return {};
|
|
522
|
+
case 'ref': {
|
|
523
|
+
const model = modelMap.get(type.name);
|
|
524
|
+
if (!model) return {};
|
|
525
|
+
// Type alias — recurse into the aliased type
|
|
526
|
+
if (model.type) return typeToExampleValue(model.type, modelMap, randomExamples);
|
|
527
|
+
return modelToExampleObject(model, modelMap, randomExamples);
|
|
528
|
+
}
|
|
529
|
+
case 'lazy':
|
|
530
|
+
return typeToExampleValue(type.inner, modelMap, randomExamples);
|
|
531
|
+
case 'inlineObject':
|
|
532
|
+
return fieldsToExampleObject(type.fields, modelMap, randomExamples);
|
|
533
|
+
default:
|
|
534
|
+
return null;
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/** Build an example object from a ModelNode's fields (including inherited base fields). */
|
|
539
|
+
function modelToExampleObject(model: ModelNode, modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {
|
|
540
|
+
return fieldsToExampleObject(resolveModelFields(model, modelMap), modelMap, randomExamples);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/** Build an example object from a list of FieldNodes. Excludes readonly; uses defaults when available, null for optional fields without one. */
|
|
544
|
+
function fieldsToExampleObject(fields: FieldNode[], modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {
|
|
545
|
+
const obj: Record<string, unknown> = {};
|
|
546
|
+
for (const field of fields) {
|
|
547
|
+
if (field.visibility === 'readonly') continue;
|
|
548
|
+
if (field.default !== undefined) {
|
|
549
|
+
obj[field.name] = field.default;
|
|
550
|
+
} else if (field.optional) {
|
|
551
|
+
obj[field.name] = null;
|
|
552
|
+
} else {
|
|
553
|
+
obj[field.name] = typeToExampleValue(field.type, modelMap, randomExamples);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
return obj;
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
// ─── Path helpers ──────────────────────────────────────────────────────────
|
|
560
|
+
|
|
561
|
+
/** Convert /users/{id}/posts → /users/:id/posts (Bruno path parameter syntax) */
|
|
562
|
+
function openCollectionPath(path: string): string {
|
|
563
|
+
return path.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, ':$1');
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** Convert "Create an Offer" → create-an-offer (for .yml file names) */
|
|
567
|
+
export function slugifyName(name: string): string {
|
|
568
|
+
const result = name
|
|
569
|
+
.toLowerCase()
|
|
570
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
571
|
+
.replace(/^-|-$/g, '');
|
|
572
|
+
return result || 'request';
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Convert /users/{id}/posts → users-id-posts (for .yml file names) */
|
|
576
|
+
export function sanitizePath(path: string): string {
|
|
577
|
+
const result = path
|
|
578
|
+
.replace(/^\//, '')
|
|
579
|
+
.replace(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g, '$1')
|
|
580
|
+
.replace(/\//g, '-')
|
|
581
|
+
.replace(/[^a-zA-Z0-9-]/g, '')
|
|
582
|
+
.replace(/-+/g, '-')
|
|
583
|
+
.replace(/^-|-$/g, '');
|
|
584
|
+
return result || 'root';
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
/** Extract param names from a URL template, e.g. /users/{id} → ['id'] */
|
|
588
|
+
function extractPathParamNames(path: string): string[] {
|
|
589
|
+
return [...path.matchAll(/\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g)].map(m => m[1]!);
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Derive folder name from op file path, e.g. src/users.op → users */
|
|
593
|
+
function deriveFolderName(file: string): string {
|
|
594
|
+
return basename(file).replace(/\.(op|ck)$/, '');
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Wrap a string in YAML double quotes if it contains characters that require quoting
|
|
599
|
+
* (flow indicators, colons, braces, etc.).
|
|
600
|
+
*/
|
|
601
|
+
function yamlString(value: string): string {
|
|
602
|
+
if (/[:{}[\],&*#?|<>=!%@`"']/.test(value) || /^\s|\s$/.test(value)) {
|
|
603
|
+
return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
|
604
|
+
}
|
|
605
|
+
return value;
|
|
606
|
+
}
|