@contractkit/plugin-bruno 0.9.1 → 1.0.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/.turbo/turbo-build$colon$ci.log +19 -35
- package/.turbo/turbo-test$colon$ci.log +25 -128
- package/CHANGELOG.md +36 -0
- package/README.md +41 -0
- package/coverage/clover.xml +289 -275
- package/coverage/coverage-final.json +2 -2
- package/coverage/index.html +28 -28
- package/coverage/src/codegen-bruno.ts.html +242 -110
- package/coverage/src/index.html +18 -18
- package/coverage/tests/helpers.ts.html +28 -28
- package/coverage/tests/index.html +19 -19
- package/dist/codegen-bruno.d.ts +15 -0
- package/dist/codegen-bruno.d.ts.map +1 -1
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +32 -4
- package/dist/index.js.map +1 -1
- package/package.json +3 -2
- package/src/codegen-bruno.ts +52 -8
- package/src/index.ts +12 -0
- package/tests/codegen-bruno.test.ts +153 -3
- package/.turbo/turbo-build.log +0 -15
- package/.turbo/turbo-test.log +0 -14
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/codegen-bruno.ts"],"sourcesContent":["import { resolve, basename, dirname } from 'node:path';\nimport { existsSync, readFileSync, rmSync, readdirSync, rmdirSync } from 'node:fs';\nimport { generateOpenCollection, MANIFEST_FILENAME, parseManifest } from './codegen-bruno.js';\nimport type { BrunoSecurityScheme } from './codegen-bruno.js';\nimport type { ContractKitPlugin } from '@contractkit/core';\n\nexport interface BrunoPluginConfig {\n baseDir?: string;\n output?: string;\n collectionName?: string;\n /**\n * When true (default), example values use Bruno's faker templates\n * (`{{$randomUUID}}`, `{{$randomEmail}}`, etc.) so each send produces\n * fresh data. Set to false for deterministic placeholders.\n */\n randomExamples?: boolean;\n /**\n * Whether to generate request files for operations marked `internal`. Defaults to\n * `true` — Bruno collections are typically used by the team that owns the API and\n * benefit from full coverage. Set to `false` to omit internal ops.\n */\n includeInternal?: boolean;\n}\n\nexport interface BrunoPluginOptions extends BrunoPluginConfig {\n auth?: { defaultScheme: string; schemes?: Record<string, BrunoSecurityScheme> };\n}\n\n// ─── Default export: loaded via plugins array, reads config from ctx.options ─\n\nconst plugin: ContractKitPlugin = {\n name: 'bruno',\n cacheKey: 'bruno',\n async generateTargets({ opRoots, contractRoots }, ctx) {\n const { auth, ...config } = ctx.options as BrunoPluginOptions;\n const base = config.baseDir ? resolve(ctx.rootDir, config.baseDir) : ctx.rootDir;\n const outDir = resolve(base, config.output ?? 'bruno-collection');\n const collectionName = config.collectionName ?? basename(ctx.rootDir);\n\n cleanupTrackedFiles(outDir);\n\n const files = generateOpenCollection(opRoots, {\n collectionName,\n contractRoots,\n auth,\n randomExamples: config.randomExamples ?? true,\n includeInternal: config.includeInternal,\n });\n for (const { relativePath, content } of files) {\n ctx.emitFile(resolve(outDir, relativePath), content);\n }\n },\n};\n\nexport default plugin;\n\n// ─── Factory: for programmatic use with explicit config ────────────────────\n\nexport function createBrunoPlugin(\n config: BrunoPluginConfig,\n rootDir: string,\n auth?: { defaultScheme: string; schemes?: Record<string, BrunoSecurityScheme> },\n): ContractKitPlugin {\n return {\n name: 'bruno',\n cacheKey: `bruno:${JSON.stringify(config)}`,\n async generateTargets({ opRoots, contractRoots }, ctx) {\n const base = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;\n const outDir = resolve(base, config.output ?? 'bruno-collection');\n const collectionName = config.collectionName ?? basename(rootDir);\n\n cleanupTrackedFiles(outDir);\n\n const files = generateOpenCollection(opRoots, {\n collectionName,\n contractRoots,\n auth,\n randomExamples: config.randomExamples ?? true,\n });\n for (const { relativePath, content } of files) {\n ctx.emitFile(resolve(outDir, relativePath), content);\n }\n },\n };\n}\n\n/**\n * Delete files this plugin generated on the previous run, leaving anything\n * the user added (custom .bru files, scripts, secrets, etc.) untouched.\n *\n * On first run — or after manual deletion of the manifest — nothing is\n * removed; stale files from prior versions linger until manually cleaned.\n */\nfunction cleanupTrackedFiles(outDir: string): void {\n const manifestPath = resolve(outDir, MANIFEST_FILENAME);\n if (!existsSync(manifestPath)) return;\n\n let tracked: string[];\n try {\n tracked = parseManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return;\n }\n\n const removedDirs = new Set<string>();\n for (const rel of tracked) {\n const abs = resolve(outDir, rel);\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(dirname(abs));\n }\n }\n\n // Walk up from each affected directory and remove it if empty, stopping at outDir.\n for (const dir of removedDirs) {\n let current = dir;\n while (current.startsWith(outDir) && current !== outDir) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = dirname(current);\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n","import type {\n OpRootNode,\n OpRouteNode,\n OpOperationNode,\n OpResponseNode,\n ParamSource,\n ContractTypeNode,\n ContractRootNode,\n ModelNode,\n FieldNode,\n} from '@contractkit/core';\nimport { resolveSecurity, resolveModifiers, SECURITY_NONE } from '@contractkit/core';\nimport { basename } from 'path';\n\nexport interface OpenCollectionFile {\n relativePath: string;\n content: string;\n}\n\n/** Manifest filename — tracks which files this plugin previously generated so subsequent runs can clean up only those, leaving any user-added files alone. */\nexport const MANIFEST_FILENAME = '.contractkit-bruno-manifest.json';\n\n/** Subset of a security scheme sufficient for Bruno auth generation (non-HMAC). */\nexport interface BrunoSecurityScheme {\n type: string; // \"http\" | \"apiKey\" | \"oauth2\" | \"openIdConnect\"\n scheme?: string; // \"bearer\" | \"basic\" (when type === \"http\")\n name?: string; // header/query param name (when type === \"apiKey\")\n in?: string; // \"header\" | \"query\" (when type === \"apiKey\")\n}\n\nexport interface BrunoAuthOptions {\n /** Name of the default scheme (from config.security.default) */\n defaultScheme?: string;\n /** Scheme definitions keyed by name (non-HMAC only) */\n schemes?: Record<string, BrunoSecurityScheme>;\n}\n\nexport interface OpenCollectionOptions {\n collectionName: string;\n contractRoots?: ContractRootNode[];\n auth?: BrunoAuthOptions;\n /**\n * When true, emit Bruno faker template strings (e.g. `{{$randomUUID}}`,\n * `{{$randomEmail}}`) for compatible scalar types so each send produces\n * fresh data. When false (default), use deterministic placeholders.\n */\n randomExamples?: boolean;\n /**\n * Whether to generate request files for operations marked `internal`. Defaults to\n * `true` — Bruno collections are typically used by the team that owns the API and\n * benefit from full coverage. Set to `false` to omit internal ops.\n */\n includeInternal?: boolean;\n}\n\n/**\n * Generates an OpenCollection (https://spec.opencollection.com/) API collection\n * from a set of operation roots. Produces opencollection.yml, an environment\n * file, and one .yml request file per operation.\n */\nexport function generateOpenCollection(roots: OpRootNode[], options: OpenCollectionOptions): OpenCollectionFile[] {\n const files: OpenCollectionFile[] = [];\n\n const modelMap = buildModelMap(options.contractRoots ?? []);\n const authOpts = options.auth;\n const defaultScheme = authOpts?.defaultScheme ? authOpts.schemes?.[authOpts.defaultScheme] : undefined;\n const randomExamples = options.randomExamples ?? false;\n const includeInternal = options.includeInternal ?? true;\n\n files.push({ relativePath: 'opencollection.yml', content: generateCollectionRoot(options.collectionName, defaultScheme) });\n files.push({ relativePath: 'environments/local.yml', content: generateEnvFile(defaultScheme) });\n // Manifest is appended at the end so it lists every generated path including itself.\n\n for (let rootIdx = 0; rootIdx < roots.length; rootIdx++) {\n const root = roots[rootIdx]!;\n const folder = root.meta['area'] ? slugifyName(root.meta['area']) : deriveFolderName(root.file);\n const displayName = (root.meta['area'] ?? folder).charAt(0).toUpperCase() + (root.meta['area'] ?? folder).slice(1);\n\n files.push({ relativePath: `${folder}/folder.yml`, content: generateFolderFile(displayName, rootIdx + 1) });\n\n const subarea = root.meta['subarea'];\n const subareaSlug = subarea ? slugifyName(subarea) : undefined;\n const requestDir = subareaSlug ? `${folder}/${subareaSlug}` : folder;\n\n if (subareaSlug) {\n const subareaDisplayName = subarea!.charAt(0).toUpperCase() + subarea!.slice(1);\n files.push({ relativePath: `${requestDir}/folder.yml`, content: generateFolderFile(subareaDisplayName, 1) });\n }\n\n let seq = 1;\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n const requestName = op.name ?? route.path;\n const fileName = op.name ? `${slugifyName(op.name)}.yml` : `${op.method}-${sanitizePath(route.path)}.yml`;\n files.push({\n relativePath: `${requestDir}/${fileName}`,\n content: generateRequestFile(route, op, requestName, seq, modelMap, root, defaultScheme, randomExamples),\n });\n seq++;\n }\n }\n }\n\n const trackedPaths = [...files.map(f => f.relativePath), MANIFEST_FILENAME].sort();\n files.push({\n relativePath: MANIFEST_FILENAME,\n content: JSON.stringify({ files: trackedPaths }, null, 2) + '\\n',\n });\n\n return files;\n}\n\n/** 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. */\nexport function parseManifest(content: string): string[] {\n try {\n const parsed = JSON.parse(content);\n if (Array.isArray(parsed?.files) && parsed.files.every((f: unknown) => typeof f === 'string')) {\n return parsed.files as string[];\n }\n } catch {\n // fall through\n }\n return [];\n}\n\n// ─── File generators ───────────────────────────────────────────────────────\n\nfunction generateCollectionRoot(name: string, scheme?: BrunoSecurityScheme): string {\n const lines = [`opencollection: \"1.0.0\"`, `info:`, ` name: ${yamlString(name)}`];\n if (scheme) {\n lines.push(``);\n lines.push(`request:`);\n lines.push(...renderAuthBlock(scheme, ' '));\n }\n lines.push(``);\n return lines.join('\\n');\n}\n\nfunction generateEnvFile(scheme?: BrunoSecurityScheme): string {\n const lines = [`name: Local`, `variables:`, ` - name: baseUrl`, ` value: \"http://localhost:3000\"`];\n if (scheme) {\n for (const varName of authEnvVarNames(scheme)) {\n lines.push(` - name: ${varName}`);\n lines.push(` value: \"\"`);\n }\n }\n lines.push(``);\n return lines.join('\\n');\n}\n\nfunction generateFolderFile(name: string, seq: number): string {\n return [`info:`, ` name: ${yamlString(name)}`, ` type: folder`, ` seq: ${seq}`, ``].join('\\n');\n}\n\nfunction generateRequestFile(\n route: OpRouteNode,\n op: OpOperationNode,\n name: string,\n seq: number,\n modelMap: Map<string, ModelNode>,\n root?: OpRootNode,\n defaultScheme?: BrunoSecurityScheme,\n randomExamples = false,\n): string {\n const lines: string[] = [];\n\n lines.push(`info:`);\n lines.push(` name: ${yamlString(name)}`);\n lines.push(` type: http`);\n lines.push(` seq: ${seq}`);\n lines.push(``);\n lines.push(`http:`);\n lines.push(` method: ${op.method.toUpperCase()}`);\n lines.push(` url: ${yamlString(`{{baseUrl}}${openCollectionPath(route.path)}`)}`);\n\n // Params — flat array with type: \"path\" | \"query\". Optional query params are\n // emitted with disabled: true so users opt in before sending.\n const pathParams: Array<ParamEntry & { kind: 'path' | 'query' }> = extractPathParamNames(route.path).map(n => ({\n name: n,\n type: findParamType(route.params, n, modelMap),\n optional: false,\n kind: 'path' as const,\n }));\n const queryParams: Array<ParamEntry & { kind: 'path' | 'query' }> = op.query\n ? expandParamSource(op.query, modelMap).map(e => ({ ...e, kind: 'query' as const }))\n : [];\n const allParams = [...pathParams, ...queryParams];\n\n if (allParams.length > 0) {\n lines.push(` params:`);\n for (const p of allParams) {\n lines.push(` - name: ${p.name}`);\n lines.push(` value: ${paramExampleValue(p.type, p.default, randomExamples)}`);\n lines.push(` type: ${p.kind}`);\n if (p.optional && p.kind === 'query') lines.push(` disabled: true`);\n }\n }\n\n // Headers\n if (op.headers) {\n const headerEntries = expandParamSource(op.headers, modelMap);\n if (headerEntries.length > 0) {\n lines.push(` headers:`);\n for (const h of headerEntries) {\n lines.push(` - name: ${h.name}`);\n lines.push(` value: ${paramExampleValue(h.type, h.default, randomExamples)}`);\n if (h.optional) lines.push(` disabled: true`);\n }\n }\n }\n\n // Auth — inside http block; inherit collection default unless this op is explicitly public\n if (defaultScheme) {\n const security = root ? resolveSecurity(route, op, root) : (op.security ?? route.security);\n if (security === SECURITY_NONE) {\n lines.push(` auth:`);\n lines.push(` type: none`);\n } else {\n lines.push(` auth: inherit`);\n }\n }\n\n // Body — Bruno supports a single body per request, so prefer JSON, then form-urlencoded, then multipart.\n if (op.request && op.request.bodies.length > 0) {\n const preferredOrder: Array<(typeof op.request.bodies)[number]['contentType']> = [\n 'application/json',\n 'application/x-www-form-urlencoded',\n 'multipart/form-data',\n ];\n const primary =\n preferredOrder.map(ct => op.request!.bodies.find(b => b.contentType === ct)).find(b => b !== undefined) ?? op.request.bodies[0]!;\n\n lines.push(` body:`);\n if (primary.contentType === 'multipart/form-data') {\n lines.push(` type: multipart-form`);\n lines.push(` data: []`);\n } else if (primary.contentType === 'application/x-www-form-urlencoded') {\n lines.push(` type: form-urlencoded`);\n lines.push(` data: []`);\n } else {\n const json = JSON.stringify(typeToExampleValue(primary.bodyType, modelMap, randomExamples), null, 2);\n lines.push(` type: json`);\n lines.push(` data: |`);\n for (const jsonLine of json.split('\\n')) {\n lines.push(` ${jsonLine}`);\n }\n }\n }\n\n // runtime.assertions — auto-generate a status-code check and presence checks for required response headers.\n const expectedStatus = pickAssertionStatus(op.responses);\n const assertedResponse = op.responses.find(r => r.statusCode === expectedStatus);\n const requiredHeaders = (assertedResponse?.headers ?? []).filter(h => !h.optional);\n if (expectedStatus !== undefined) {\n lines.push(``);\n lines.push(`runtime:`);\n lines.push(` assertions:`);\n lines.push(` - expression: res.status`);\n lines.push(` operator: eq`);\n // Always quote — the OpenCollection schema types `value` as a string,\n // so we must keep \"200\" from being parsed as YAML number 200.\n lines.push(` value: \"${expectedStatus}\"`);\n for (const h of requiredHeaders) {\n lines.push(` - expression: res.headers[\"${h.name.toLowerCase()}\"]`);\n lines.push(` operator: isDefined`);\n lines.push(` value: \"\"`);\n }\n }\n\n // docs — combine route- and operation-level descriptions plus the declared response-header summary.\n const docs = buildRequestDocs(route, op, assertedResponse);\n if (docs) {\n lines.push(``);\n lines.push(`docs: |-`);\n for (const docLine of docs.split('\\n')) {\n lines.push(` ${docLine}`);\n }\n }\n\n lines.push(``);\n return lines.join('\\n');\n}\n\n/** 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. */\nfunction pickAssertionStatus(responses: OpResponseNode[]): number | undefined {\n const success = responses.find(r => r.statusCode >= 200 && r.statusCode < 300);\n return success?.statusCode ?? responses[0]?.statusCode;\n}\n\n/** Build a markdown docs block from route- and operation-level descriptions, plus declared response-header summary. */\nfunction buildRequestDocs(route: OpRouteNode, op: OpOperationNode, assertedResponse?: OpResponseNode): string | undefined {\n const parts: string[] = [];\n if (route.description) parts.push(route.description.trim());\n if (op.description) parts.push(op.description.trim());\n const headers = assertedResponse?.headers ?? [];\n if (headers.length > 0) {\n const lines = ['**Response headers**', ''];\n for (const h of headers) {\n const tag = h.optional ? 'optional' : 'required';\n const desc = h.description ? ` — ${h.description}` : '';\n lines.push(`- \\`${h.name}\\` (${tag})${desc}`);\n }\n parts.push(lines.join('\\n'));\n }\n return parts.length > 0 ? parts.join('\\n\\n') : undefined;\n}\n\n// ─── Auth helpers ──────────────────────────────────────────────────────────\n\n/** Generate the YAML lines for an auth block (flat, per spec), indented by `indent`. */\nfunction renderAuthBlock(scheme: BrunoSecurityScheme, indent: string): string[] {\n const i = indent;\n if (scheme.type === 'http' && scheme.scheme === 'bearer') {\n return [`${i}auth:`, `${i} type: bearer`, `${i} token: \"{{token}}\"`];\n }\n if (scheme.type === 'http' && scheme.scheme === 'basic') {\n return [`${i}auth:`, `${i} type: basic`, `${i} username: \"{{username}}\"`, `${i} password: \"{{password}}\"`];\n }\n if (scheme.type === 'apiKey' && scheme.in === 'header') {\n const headerName = scheme.name ?? 'X-Api-Key';\n return [`${i}auth:`, `${i} type: apikey`, `${i} key: ${headerName}`, `${i} value: \"{{apiKey}}\"`, `${i} placement: header`];\n }\n return [];\n}\n\n/** Return the environment variable names needed for a given auth scheme. */\nfunction authEnvVarNames(scheme: BrunoSecurityScheme): string[] {\n if (scheme.type === 'http' && scheme.scheme === 'bearer') return ['token'];\n if (scheme.type === 'http' && scheme.scheme === 'basic') return ['username', 'password'];\n if (scheme.type === 'apiKey') return ['apiKey'];\n return [];\n}\n\n// ─── Model registry ────────────────────────────────────────────────────────\n\nfunction buildModelMap(contractRoots: ContractRootNode[]): Map<string, ModelNode> {\n const map = new Map<string, ModelNode>();\n for (const root of contractRoots) {\n for (const model of root.models) {\n map.set(model.name, model);\n }\n }\n return map;\n}\n\n/** Resolve all fields for a model, including inherited base fields (bases first, in declaration order). */\nfunction resolveModelFields(model: ModelNode, modelMap: Map<string, ModelNode>): FieldNode[] {\n const collected: FieldNode[] = [];\n if (model.bases) {\n for (const base of model.bases) {\n const baseModel = modelMap.get(base);\n if (baseModel) collected.push(...resolveModelFields(baseModel, modelMap));\n }\n }\n return [...collected, ...model.fields];\n}\n\n// ─── Param helpers ─────────────────────────────────────────────────────────\n\ninterface ParamEntry {\n name: string;\n type: ContractTypeNode | undefined;\n default?: string | number | boolean;\n optional: boolean;\n}\n\n/** Expand a ParamSource into a flat list of named entries with their types. */\nfunction expandParamSource(source: ParamSource, modelMap: Map<string, ModelNode>): ParamEntry[] {\n if (source.kind === 'params') {\n return source.nodes.map(n => ({ name: n.name, type: n.type, default: n.default, optional: n.optional }));\n }\n if (source.kind === 'ref') {\n const model = modelMap.get(source.name);\n if (model) {\n return resolveModelFields(model, modelMap)\n .filter(f => f.visibility !== 'readonly')\n .map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));\n }\n // Fallback: single placeholder entry\n const name = source.name.charAt(0).toLowerCase() + source.name.slice(1);\n return [{ name, type: undefined, optional: false }];\n }\n // kind === 'type': if it's an inline object, expand its fields\n if (source.node.kind === 'inlineObject') {\n return source.node.fields.map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));\n }\n return [];\n}\n\n/** Look up a named path param's type from route.params. */\nfunction findParamType(source: ParamSource | undefined, name: string, modelMap: Map<string, ModelNode>): ContractTypeNode | undefined {\n if (!source) return undefined;\n if (source.kind === 'params') return source.nodes.find(n => n.name === name)?.type;\n if (source.kind === 'ref') {\n const model = modelMap.get(source.name);\n if (model) return resolveModelFields(model, modelMap).find(f => f.name === name)?.type;\n }\n if (source.kind === 'type' && source.node.kind === 'inlineObject') {\n return source.node.fields.find(f => f.name === name)?.type;\n }\n return undefined;\n}\n\n/** Return a YAML-quoted example value string for a param, preferring a default value when provided. */\nfunction paramExampleValue(type: ContractTypeNode | undefined, defaultValue?: string | number | boolean, randomExamples = false): string {\n if (defaultValue !== undefined) return `\"${defaultValue}\"`;\n if (!type) return '\"\"';\n if (type.kind === 'enum') return type.values.length > 0 ? `\"${type.values[0]}\"` : '\"\"';\n if (type.kind === 'literal') return `\"${type.value}\"`;\n if (type.kind !== 'scalar') return '\"\"';\n if (randomExamples) {\n const random = randomScalarTemplate(type.name);\n if (random !== undefined) return `\"${random}\"`;\n }\n switch (type.name) {\n case 'uuid':\n return '\"00000000-0000-0000-0000-000000000000\"';\n case 'email':\n return '\"user@example.com\"';\n case 'url':\n return '\"https://example.com\"';\n case 'number':\n case 'int':\n case 'bigint':\n return '\"0\"';\n case 'boolean':\n return '\"true\"';\n case 'date':\n return '\"2024-01-01\"';\n case 'time':\n return '\"00:00:00\"';\n case 'datetime':\n return '\"2024-01-01T00:00:00Z\"';\n case 'duration':\n return '\"PT1H\"';\n default:\n return '\"\"';\n }\n}\n\n/** Bruno faker template for a scalar type, or undefined when no clean equivalent exists (date, time, duration, raw string). */\nfunction randomScalarTemplate(name: string): string | undefined {\n switch (name) {\n case 'uuid':\n return '{{$randomUUID}}';\n case 'email':\n return '{{$randomEmail}}';\n case 'url':\n return '{{$randomUrl}}';\n case 'number':\n case 'int':\n case 'bigint':\n return '{{$randomInt}}';\n case 'boolean':\n return '{{$randomBoolean}}';\n case 'datetime':\n return '{{$isoTimestamp}}';\n default:\n return undefined;\n }\n}\n\n// ─── Body helpers ──────────────────────────────────────────────────────────\n\n/**\n * Recursively build an example JSON value from a ContractTypeNode.\n *\n * When `randomExamples` is true we substitute Bruno faker templates only for\n * scalars whose JSON representation is a string (uuid/email/url/datetime).\n * Numbers and booleans stay deterministic — embedding `{{$randomInt}}` as a\n * bare JSON number would require sentinel-stripping the surrounding quotes,\n * and the body skeleton is meant as a starting point users edit anyway.\n */\nfunction typeToExampleValue(type: ContractTypeNode, modelMap: Map<string, ModelNode>, randomExamples = false): unknown {\n switch (type.kind) {\n case 'scalar':\n switch (type.name) {\n case 'string':\n return '';\n case 'email':\n return randomExamples ? '{{$randomEmail}}' : 'user@example.com';\n case 'url':\n return randomExamples ? '{{$randomUrl}}' : 'https://example.com';\n case 'uuid':\n return randomExamples ? '{{$randomUUID}}' : '00000000-0000-0000-0000-000000000000';\n case 'number':\n case 'int':\n case 'bigint':\n return 0;\n case 'boolean':\n return true;\n case 'date':\n return '2024-01-01';\n case 'time':\n return '00:00:00';\n case 'datetime':\n return randomExamples ? '{{$isoTimestamp}}' : '2024-01-01T00:00:00Z';\n case 'duration':\n return 'PT1H';\n case 'null':\n return null;\n default:\n return null;\n }\n case 'enum':\n return type.values[0] ?? '';\n case 'literal':\n return type.value;\n case 'array':\n return [typeToExampleValue(type.item, modelMap, randomExamples)];\n case 'tuple':\n return type.items.map(t => typeToExampleValue(t, modelMap, randomExamples));\n case 'record':\n return {};\n case 'union':\n return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;\n case 'discriminatedUnion':\n return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;\n case 'intersection':\n return {};\n case 'ref': {\n const model = modelMap.get(type.name);\n if (!model) return {};\n // Type alias — recurse into the aliased type\n if (model.type) return typeToExampleValue(model.type, modelMap, randomExamples);\n return modelToExampleObject(model, modelMap, randomExamples);\n }\n case 'lazy':\n return typeToExampleValue(type.inner, modelMap, randomExamples);\n case 'inlineObject':\n return fieldsToExampleObject(type.fields, modelMap, randomExamples);\n default:\n return null;\n }\n}\n\n/** Build an example object from a ModelNode's fields (including inherited base fields). */\nfunction modelToExampleObject(model: ModelNode, modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {\n return fieldsToExampleObject(resolveModelFields(model, modelMap), modelMap, randomExamples);\n}\n\n/** Build an example object from a list of FieldNodes. Excludes readonly; uses defaults when available, null for optional fields without one. */\nfunction fieldsToExampleObject(fields: FieldNode[], modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {\n const obj: Record<string, unknown> = {};\n for (const field of fields) {\n if (field.visibility === 'readonly') continue;\n if (field.default !== undefined) {\n obj[field.name] = field.default;\n } else if (field.optional) {\n obj[field.name] = null;\n } else {\n obj[field.name] = typeToExampleValue(field.type, modelMap, randomExamples);\n }\n }\n return obj;\n}\n\n// ─── Path helpers ──────────────────────────────────────────────────────────\n\n/** Convert /users/{id}/posts → /users/:id/posts (Bruno path parameter syntax) */\nfunction openCollectionPath(path: string): string {\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, ':$1');\n}\n\n/** Convert \"Create an Offer\" → create-an-offer (for .yml file names) */\nexport function slugifyName(name: string): string {\n const result = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return result || 'request';\n}\n\n/** Convert /users/{id}/posts → users-id-posts (for .yml file names) */\nexport function sanitizePath(path: string): string {\n const result = path\n .replace(/^\\//, '')\n .replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, '$1')\n .replace(/\\//g, '-')\n .replace(/[^a-zA-Z0-9-]/g, '')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n return result || 'root';\n}\n\n/** Extract param names from a URL template, e.g. /users/{id} → ['id'] */\nfunction extractPathParamNames(path: string): string[] {\n return [...path.matchAll(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g)].map(m => m[1]!);\n}\n\n/** Derive folder name from op file path, e.g. src/users.op → users */\nfunction deriveFolderName(file: string): string {\n return basename(file).replace(/\\.(op|ck)$/, '');\n}\n\n/**\n * Wrap a string in YAML double quotes if it contains characters that require quoting\n * (flow indicators, colons, braces, etc.).\n */\nfunction yamlString(value: string): string {\n if (/[:{}[\\],&*#?|<>=!%@`\"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BhB,SAAS;QAC1CY;QACAX;QACAE;QACAc,gBAAgBb,OAAOa,kBAAkB;MAC7C,CAAA;AACA,iBAAW,EAAEE,cAAcC,QAAO,KAAML,OAAO;AAC3Cb,YAAImB,SAASb,QAAQE,QAAQS,YAAAA,GAAeC,OAAAA;MAChD;IACJ;EACJ;AACJ;AA1BgBE;AAmChB,SAASR,oBAAoBJ,QAAc;AACvC,QAAMe,eAAejB,QAAQE,QAAQgB,iBAAAA;AACrC,MAAI,CAACC,WAAWF,YAAAA,EAAe;AAE/B,MAAIG;AACJ,MAAI;AACAA,cAAUC,cAAcC,aAAaL,cAAc,OAAA,CAAA;EACvD,QAAQ;AACJ;EACJ;AAEA,QAAMM,cAAc,oBAAIC,IAAAA;AACxB,aAAWC,OAAOL,SAAS;AACvB,UAAMM,MAAM1B,QAAQE,QAAQuB,GAAAA;AAC5B,QAAIN,WAAWO,GAAAA,GAAM;AACjBC,aAAOD,KAAK;QAAEE,OAAO;MAAK,CAAA;AAC1BL,kBAAYM,IAAIC,QAAQJ,GAAAA,CAAAA;IAC5B;EACJ;AAGA,aAAWK,OAAOR,aAAa;AAC3B,QAAIS,UAAUD;AACd,WAAOC,QAAQC,WAAW/B,MAAAA,KAAW8B,YAAY9B,QAAQ;AACrD,UAAI;AACA,YAAIgC,YAAYF,OAAAA,EAASG,WAAW,GAAG;AACnCC,oBAAUJ,OAAAA;AACVA,oBAAUF,QAAQE,OAAAA;QACtB,OAAO;AACH;QACJ;MACJ,QAAQ;AACJ;MACJ;IACJ;EACJ;AACJ;AApCS1B;","names":["resolve","basename","dirname","existsSync","readFileSync","rmSync","readdirSync","rmdirSync","resolveSecurity","resolveModifiers","SECURITY_NONE","basename","MANIFEST_FILENAME","generateOpenCollection","roots","options","files","modelMap","buildModelMap","contractRoots","authOpts","auth","defaultScheme","schemes","undefined","randomExamples","includeInternal","push","relativePath","content","generateCollectionRoot","collectionName","generateEnvFile","rootIdx","length","root","folder","meta","slugifyName","deriveFolderName","file","displayName","charAt","toUpperCase","slice","generateFolderFile","subarea","subareaSlug","requestDir","subareaDisplayName","seq","route","routes","op","operations","resolveModifiers","includes","requestName","name","path","fileName","method","sanitizePath","generateRequestFile","trackedPaths","map","f","sort","JSON","stringify","parseManifest","parsed","parse","Array","isArray","every","scheme","lines","yamlString","renderAuthBlock","join","varName","authEnvVarNames","openCollectionPath","pathParams","extractPathParamNames","n","type","findParamType","params","optional","kind","queryParams","query","expandParamSource","e","allParams","p","paramExampleValue","default","headers","headerEntries","h","security","resolveSecurity","SECURITY_NONE","request","bodies","preferredOrder","primary","ct","find","b","contentType","json","typeToExampleValue","bodyType","jsonLine","split","expectedStatus","pickAssertionStatus","responses","assertedResponse","r","statusCode","requiredHeaders","filter","toLowerCase","docs","buildRequestDocs","docLine","success","parts","description","trim","tag","desc","indent","i","in","headerName","Map","model","models","set","resolveModelFields","collected","bases","base","baseModel","get","fields","source","nodes","visibility","node","defaultValue","values","value","random","randomScalarTemplate","item","items","t","members","modelToExampleObject","inner","fieldsToExampleObject","obj","field","replace","result","matchAll","m","basename","test","plugin","name","cacheKey","generateTargets","opRoots","contractRoots","ctx","auth","config","options","base","baseDir","resolve","rootDir","outDir","output","collectionName","basename","cleanupTrackedFiles","files","generateOpenCollection","randomExamples","includeInternal","relativePath","content","emitFile","createBrunoPlugin","JSON","stringify","manifestPath","MANIFEST_FILENAME","existsSync","tracked","parseManifest","readFileSync","removedDirs","Set","rel","abs","rmSync","force","add","dirname","dir","current","startsWith","readdirSync","length","rmdirSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/codegen-bruno.ts"],"sourcesContent":["import { resolve, basename, dirname } from 'node:path';\nimport { existsSync, readFileSync, rmSync, readdirSync, rmdirSync } from 'node:fs';\nimport { generateOpenCollection, MANIFEST_FILENAME, parseManifest } from './codegen-bruno.js';\nimport type { BrunoSecurityScheme } from './codegen-bruno.js';\nimport type { ContractKitPlugin } from '@contractkit/core';\n\n/** Configuration accepted by the Bruno plugin, both via `contractkit.config.json` and `createBrunoPlugin`. */\nexport interface BrunoPluginConfig {\n baseDir?: string;\n output?: string;\n collectionName?: string;\n /**\n * When true (default), example values use Bruno's faker templates\n * (`{{$randomUUID}}`, `{{$randomEmail}}`, etc.) so each send produces\n * fresh data. Set to false for deterministic placeholders.\n */\n randomExamples?: boolean;\n /**\n * Whether to generate request files for operations marked `internal`. Defaults to\n * `true` — Bruno collections are typically used by the team that owns the API and\n * benefit from full coverage. Set to `false` to omit internal ops.\n */\n includeInternal?: boolean;\n}\n\n/** Full plugin options shape read from `ctx.options` — extends {@link BrunoPluginConfig} with the `auth` block. */\nexport interface BrunoPluginOptions extends BrunoPluginConfig {\n auth?: { defaultScheme: string; schemes?: Record<string, BrunoSecurityScheme> };\n}\n\n// ─── Default export: loaded via plugins array, reads config from ctx.options ─\n\nconst plugin: ContractKitPlugin = {\n name: 'bruno',\n cacheKey: 'bruno',\n async generateTargets({ opRoots, contractRoots }, ctx) {\n const { auth, ...config } = ctx.options as BrunoPluginOptions;\n const base = config.baseDir ? resolve(ctx.rootDir, config.baseDir) : ctx.rootDir;\n const outDir = resolve(base, config.output ?? 'bruno-collection');\n const collectionName = config.collectionName ?? basename(ctx.rootDir);\n\n cleanupTrackedFiles(outDir);\n\n const files = generateOpenCollection(opRoots, {\n collectionName,\n contractRoots,\n auth,\n randomExamples: config.randomExamples ?? true,\n includeInternal: config.includeInternal,\n });\n for (const { relativePath, content } of files) {\n ctx.emitFile(resolve(outDir, relativePath), content);\n }\n },\n};\n\nexport default plugin;\n\n// ─── Factory: for programmatic use with explicit config ────────────────────\n\n/**\n * Creates a Bruno plugin instance with explicit configuration, for programmatic use.\n *\n * Prefer the default export when loading via `contractkit.config.json`. Use this\n * factory when constructing the plugin in code (e.g. in tests or custom build scripts).\n *\n * @param config - Plugin configuration (output paths and feature flags).\n * @param rootDir - Absolute path used to resolve relative paths in `config`.\n * @param auth - Optional auth scheme configuration mirroring the `auth` key in plugin options.\n */\nexport function createBrunoPlugin(\n config: BrunoPluginConfig,\n rootDir: string,\n auth?: { defaultScheme: string; schemes?: Record<string, BrunoSecurityScheme> },\n): ContractKitPlugin {\n return {\n name: 'bruno',\n cacheKey: `bruno:${JSON.stringify(config)}`,\n async generateTargets({ opRoots, contractRoots }, ctx) {\n const base = config.baseDir ? resolve(rootDir, config.baseDir) : rootDir;\n const outDir = resolve(base, config.output ?? 'bruno-collection');\n const collectionName = config.collectionName ?? basename(rootDir);\n\n cleanupTrackedFiles(outDir);\n\n const files = generateOpenCollection(opRoots, {\n collectionName,\n contractRoots,\n auth,\n randomExamples: config.randomExamples ?? true,\n });\n for (const { relativePath, content } of files) {\n ctx.emitFile(resolve(outDir, relativePath), content);\n }\n },\n };\n}\n\n/**\n * Delete files this plugin generated on the previous run, leaving anything\n * the user added (custom .bru files, scripts, secrets, etc.) untouched.\n *\n * On first run — or after manual deletion of the manifest — nothing is\n * removed; stale files from prior versions linger until manually cleaned.\n */\nfunction cleanupTrackedFiles(outDir: string): void {\n const manifestPath = resolve(outDir, MANIFEST_FILENAME);\n if (!existsSync(manifestPath)) return;\n\n let tracked: string[];\n try {\n tracked = parseManifest(readFileSync(manifestPath, 'utf-8'));\n } catch {\n return;\n }\n\n const removedDirs = new Set<string>();\n for (const rel of tracked) {\n const abs = resolve(outDir, rel);\n if (existsSync(abs)) {\n rmSync(abs, { force: true });\n removedDirs.add(dirname(abs));\n }\n }\n\n // Walk up from each affected directory and remove it if empty, stopping at outDir.\n for (const dir of removedDirs) {\n let current = dir;\n while (current.startsWith(outDir) && current !== outDir) {\n try {\n if (readdirSync(current).length === 0) {\n rmdirSync(current);\n current = dirname(current);\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n }\n}\n","import type {\n OpRootNode,\n OpRouteNode,\n OpOperationNode,\n OpResponseNode,\n ParamSource,\n ContractTypeNode,\n ContractRootNode,\n ModelNode,\n FieldNode,\n} from '@contractkit/core';\nimport { resolveSecurity, resolveModifiers, SECURITY_NONE } from '@contractkit/core';\nimport { basename } from 'path';\nimport { parse as parseYaml, stringify as stringifyYaml } from 'yaml';\n\n/** A single file produced by the Bruno codegen — a relative output path and its YAML content. */\nexport interface OpenCollectionFile {\n relativePath: string;\n content: string;\n}\n\n/** Manifest filename — tracks which files this plugin previously generated so subsequent runs can clean up only those, leaving any user-added files alone. */\nexport const MANIFEST_FILENAME = '.contractkit-bruno-manifest.json';\n\n/** Subset of a security scheme sufficient for Bruno auth generation (non-HMAC). */\nexport interface BrunoSecurityScheme {\n type: string; // \"http\" | \"apiKey\" | \"oauth2\" | \"openIdConnect\"\n scheme?: string; // \"bearer\" | \"basic\" (when type === \"http\")\n name?: string; // header/query param name (when type === \"apiKey\")\n in?: string; // \"header\" | \"query\" (when type === \"apiKey\")\n}\n\n/** Auth configuration passed to the Bruno codegen; drives collection-level auth and per-operation auth blocks. */\nexport interface BrunoAuthOptions {\n /** Name of the default scheme (from config.security.default) */\n defaultScheme?: string;\n /** Scheme definitions keyed by name (non-HMAC only) */\n schemes?: Record<string, BrunoSecurityScheme>;\n}\n\n/** Options controlling what {@link generateOpenCollection} emits. */\nexport interface OpenCollectionOptions {\n collectionName: string;\n contractRoots?: ContractRootNode[];\n auth?: BrunoAuthOptions;\n /**\n * When true, emit Bruno faker template strings (e.g. `{{$randomUUID}}`,\n * `{{$randomEmail}}`) for compatible scalar types so each send produces\n * fresh data. When false (default), use deterministic placeholders.\n */\n randomExamples?: boolean;\n /**\n * Whether to generate request files for operations marked `internal`. Defaults to\n * `true` — Bruno collections are typically used by the team that owns the API and\n * benefit from full coverage. Set to `false` to omit internal ops.\n */\n includeInternal?: boolean;\n}\n\n/**\n * Generates an OpenCollection (https://spec.opencollection.com/) API collection\n * from a set of operation roots. Produces opencollection.yml, an environment\n * file, and one .yml request file per operation.\n */\nexport function generateOpenCollection(roots: OpRootNode[], options: OpenCollectionOptions): OpenCollectionFile[] {\n const files: OpenCollectionFile[] = [];\n\n const modelMap = buildModelMap(options.contractRoots ?? []);\n const authOpts = options.auth;\n const defaultScheme = authOpts?.defaultScheme ? authOpts.schemes?.[authOpts.defaultScheme] : undefined;\n const randomExamples = options.randomExamples ?? false;\n const includeInternal = options.includeInternal ?? true;\n\n files.push({ relativePath: 'opencollection.yml', content: generateCollectionRoot(options.collectionName, defaultScheme) });\n files.push({ relativePath: 'environments/local.yml', content: generateEnvFile(defaultScheme) });\n // Manifest is appended at the end so it lists every generated path including itself.\n\n for (let rootIdx = 0; rootIdx < roots.length; rootIdx++) {\n const root = roots[rootIdx]!;\n const folder = root.meta['area'] ? slugifyName(root.meta['area']) : deriveFolderName(root.file);\n const displayName = (root.meta['area'] ?? folder).charAt(0).toUpperCase() + (root.meta['area'] ?? folder).slice(1);\n\n files.push({ relativePath: `${folder}/folder.yml`, content: generateFolderFile(displayName, rootIdx + 1) });\n\n const subarea = root.meta['subarea'];\n const subareaSlug = subarea ? slugifyName(subarea) : undefined;\n const requestDir = subareaSlug ? `${folder}/${subareaSlug}` : folder;\n\n if (subareaSlug) {\n const subareaDisplayName = subarea!.charAt(0).toUpperCase() + subarea!.slice(1);\n files.push({ relativePath: `${requestDir}/folder.yml`, content: generateFolderFile(subareaDisplayName, 1) });\n }\n\n let seq = 1;\n for (const route of root.routes) {\n for (const op of route.operations) {\n if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;\n const requestName = op.name ?? route.path;\n const fileName = op.name ? `${slugifyName(op.name)}.yml` : `${op.method}-${sanitizePath(route.path)}.yml`;\n let content = generateRequestFile(route, op, requestName, seq, modelMap, root, defaultScheme, randomExamples);\n const pluginOverride = op.pluginFiles?.['bruno'];\n if (pluginOverride !== undefined) {\n content = mergePluginFile(content, pluginOverride);\n }\n files.push({ relativePath: `${requestDir}/${fileName}`, content });\n seq++;\n }\n }\n }\n\n const trackedPaths = [...files.map(f => f.relativePath), MANIFEST_FILENAME].sort();\n files.push({\n relativePath: MANIFEST_FILENAME,\n content: JSON.stringify({ files: trackedPaths }, null, 2) + '\\n',\n });\n\n return files;\n}\n\n/** 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. */\nexport function parseManifest(content: string): string[] {\n try {\n const parsed = JSON.parse(content);\n if (Array.isArray(parsed?.files) && parsed.files.every((f: unknown) => typeof f === 'string')) {\n return parsed.files as string[];\n }\n } catch {\n // fall through\n }\n return [];\n}\n\n// ─── Plugin file merge ─────────────────────────────────────────────────────\n\nfunction deepMerge(base: unknown, override: unknown): unknown {\n if (\n override !== null &&\n typeof override === 'object' &&\n !Array.isArray(override) &&\n base !== null &&\n typeof base === 'object' &&\n !Array.isArray(base)\n ) {\n const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };\n for (const [key, val] of Object.entries(override as Record<string, unknown>)) {\n result[key] = deepMerge(result[key], val);\n }\n return result;\n }\n return override;\n}\n\n/**\n * Deep-merges a YAML override string into a generated YAML string.\n *\n * Objects are merged recursively; arrays and scalars in the override replace the\n * generated value entirely. If `pluginFileContent` is not a YAML mapping (e.g. it\n * is a scalar or a list), the generated content is returned unchanged.\n *\n * @param generatedYaml - The YAML string produced by the Bruno codegen.\n * @param pluginFileContent - The YAML override string to merge in.\n * @returns The merged YAML string, or `generatedYaml` if the override is not a mapping.\n */\nexport function mergePluginFile(generatedYaml: string, pluginFileContent: string): string {\n const overrideParsed = parseYaml(pluginFileContent);\n if (overrideParsed === null || typeof overrideParsed !== 'object' || Array.isArray(overrideParsed)) {\n return generatedYaml;\n }\n const merged = deepMerge(parseYaml(generatedYaml), overrideParsed);\n return stringifyYaml(merged, { lineWidth: 0 });\n}\n\n// ─── File generators ───────────────────────────────────────────────────────\n\nfunction generateCollectionRoot(name: string, scheme?: BrunoSecurityScheme): string {\n const lines = [`opencollection: \"1.0.0\"`, `info:`, ` name: ${yamlString(name)}`];\n if (scheme) {\n lines.push(``);\n lines.push(`request:`);\n lines.push(...renderAuthBlock(scheme, ' '));\n }\n lines.push(``);\n return lines.join('\\n');\n}\n\nfunction generateEnvFile(scheme?: BrunoSecurityScheme): string {\n const lines = [`name: Local`, `variables:`, ` - name: baseUrl`, ` value: \"http://localhost:3000\"`];\n if (scheme) {\n for (const varName of authEnvVarNames(scheme)) {\n lines.push(` - name: ${varName}`);\n lines.push(` value: \"\"`);\n }\n }\n lines.push(``);\n return lines.join('\\n');\n}\n\nfunction generateFolderFile(name: string, seq: number): string {\n return [`info:`, ` name: ${yamlString(name)}`, ` type: folder`, ` seq: ${seq}`, ``].join('\\n');\n}\n\nfunction generateRequestFile(\n route: OpRouteNode,\n op: OpOperationNode,\n name: string,\n seq: number,\n modelMap: Map<string, ModelNode>,\n root?: OpRootNode,\n defaultScheme?: BrunoSecurityScheme,\n randomExamples = false,\n): string {\n const lines: string[] = [];\n\n lines.push(`info:`);\n lines.push(` name: ${yamlString(name)}`);\n lines.push(` type: http`);\n lines.push(` seq: ${seq}`);\n lines.push(``);\n lines.push(`http:`);\n lines.push(` method: ${op.method.toUpperCase()}`);\n lines.push(` url: ${yamlString(`{{baseUrl}}${openCollectionPath(route.path)}`)}`);\n\n // Params — flat array with type: \"path\" | \"query\". Optional query params are\n // emitted with disabled: true so users opt in before sending.\n const pathParams: Array<ParamEntry & { kind: 'path' | 'query' }> = extractPathParamNames(route.path).map(n => ({\n name: n,\n type: findParamType(route.params, n, modelMap),\n optional: false,\n kind: 'path' as const,\n }));\n const queryParams: Array<ParamEntry & { kind: 'path' | 'query' }> = op.query\n ? expandParamSource(op.query, modelMap).map(e => ({ ...e, kind: 'query' as const }))\n : [];\n const allParams = [...pathParams, ...queryParams];\n\n if (allParams.length > 0) {\n lines.push(` params:`);\n for (const p of allParams) {\n lines.push(` - name: ${p.name}`);\n lines.push(` value: ${paramExampleValue(p.type, p.default, randomExamples)}`);\n lines.push(` type: ${p.kind}`);\n if (p.optional && p.kind === 'query') lines.push(` disabled: true`);\n }\n }\n\n // Headers\n if (op.headers) {\n const headerEntries = expandParamSource(op.headers, modelMap);\n if (headerEntries.length > 0) {\n lines.push(` headers:`);\n for (const h of headerEntries) {\n lines.push(` - name: ${h.name}`);\n lines.push(` value: ${paramExampleValue(h.type, h.default, randomExamples)}`);\n if (h.optional) lines.push(` disabled: true`);\n }\n }\n }\n\n // Auth — inside http block; inherit collection default unless this op is explicitly public\n if (defaultScheme) {\n const security = root ? resolveSecurity(route, op, root) : (op.security ?? route.security);\n if (security === SECURITY_NONE) {\n lines.push(` auth:`);\n lines.push(` type: none`);\n } else {\n lines.push(` auth: inherit`);\n }\n }\n\n // Body — Bruno supports a single body per request, so prefer JSON, then form-urlencoded, then multipart.\n if (op.request && op.request.bodies.length > 0) {\n const preferredOrder: Array<(typeof op.request.bodies)[number]['contentType']> = [\n 'application/json',\n 'application/x-www-form-urlencoded',\n 'multipart/form-data',\n ];\n const primary =\n preferredOrder.map(ct => op.request!.bodies.find(b => b.contentType === ct)).find(b => b !== undefined) ?? op.request.bodies[0]!;\n\n lines.push(` body:`);\n if (primary.contentType === 'multipart/form-data') {\n lines.push(` type: multipart-form`);\n lines.push(` data: []`);\n } else if (primary.contentType === 'application/x-www-form-urlencoded') {\n lines.push(` type: form-urlencoded`);\n lines.push(` data: []`);\n } else {\n const json = JSON.stringify(typeToExampleValue(primary.bodyType, modelMap, randomExamples), null, 2);\n lines.push(` type: json`);\n lines.push(` data: |`);\n for (const jsonLine of json.split('\\n')) {\n lines.push(` ${jsonLine}`);\n }\n }\n }\n\n // runtime.assertions — auto-generate a status-code check and presence checks for required response headers.\n const expectedStatus = pickAssertionStatus(op.responses);\n const assertedResponse = op.responses.find(r => r.statusCode === expectedStatus);\n const requiredHeaders = (assertedResponse?.headers ?? []).filter(h => !h.optional);\n if (expectedStatus !== undefined) {\n lines.push(``);\n lines.push(`runtime:`);\n lines.push(` assertions:`);\n lines.push(` - expression: res.status`);\n lines.push(` operator: eq`);\n // Always quote — the OpenCollection schema types `value` as a string,\n // so we must keep \"200\" from being parsed as YAML number 200.\n lines.push(` value: \"${expectedStatus}\"`);\n for (const h of requiredHeaders) {\n lines.push(` - expression: res.headers[\"${h.name.toLowerCase()}\"]`);\n lines.push(` operator: isDefined`);\n lines.push(` value: \"\"`);\n }\n }\n\n // docs — combine route- and operation-level descriptions plus the declared response-header summary.\n const docs = buildRequestDocs(route, op, assertedResponse);\n if (docs) {\n lines.push(``);\n lines.push(`docs: |-`);\n for (const docLine of docs.split('\\n')) {\n lines.push(` ${docLine}`);\n }\n }\n\n lines.push(``);\n return lines.join('\\n');\n}\n\n/** 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. */\nfunction pickAssertionStatus(responses: OpResponseNode[]): number | undefined {\n const success = responses.find(r => r.statusCode >= 200 && r.statusCode < 300);\n return success?.statusCode ?? responses[0]?.statusCode;\n}\n\n/** Build a markdown docs block from route- and operation-level descriptions, plus declared response-header summary. */\nfunction buildRequestDocs(route: OpRouteNode, op: OpOperationNode, assertedResponse?: OpResponseNode): string | undefined {\n const parts: string[] = [];\n if (route.description) parts.push(route.description.trim());\n if (op.description) parts.push(op.description.trim());\n const headers = assertedResponse?.headers ?? [];\n if (headers.length > 0) {\n const lines = ['**Response headers**', ''];\n for (const h of headers) {\n const tag = h.optional ? 'optional' : 'required';\n const desc = h.description ? ` — ${h.description}` : '';\n lines.push(`- \\`${h.name}\\` (${tag})${desc}`);\n }\n parts.push(lines.join('\\n'));\n }\n return parts.length > 0 ? parts.join('\\n\\n') : undefined;\n}\n\n// ─── Auth helpers ──────────────────────────────────────────────────────────\n\n/** Generate the YAML lines for an auth block (flat, per spec), indented by `indent`. */\nfunction renderAuthBlock(scheme: BrunoSecurityScheme, indent: string): string[] {\n const i = indent;\n if (scheme.type === 'http' && scheme.scheme === 'bearer') {\n return [`${i}auth:`, `${i} type: bearer`, `${i} token: \"{{token}}\"`];\n }\n if (scheme.type === 'http' && scheme.scheme === 'basic') {\n return [`${i}auth:`, `${i} type: basic`, `${i} username: \"{{username}}\"`, `${i} password: \"{{password}}\"`];\n }\n if (scheme.type === 'apiKey' && scheme.in === 'header') {\n const headerName = scheme.name ?? 'X-Api-Key';\n return [`${i}auth:`, `${i} type: apikey`, `${i} key: ${headerName}`, `${i} value: \"{{apiKey}}\"`, `${i} placement: header`];\n }\n return [];\n}\n\n/** Return the environment variable names needed for a given auth scheme. */\nfunction authEnvVarNames(scheme: BrunoSecurityScheme): string[] {\n if (scheme.type === 'http' && scheme.scheme === 'bearer') return ['token'];\n if (scheme.type === 'http' && scheme.scheme === 'basic') return ['username', 'password'];\n if (scheme.type === 'apiKey') return ['apiKey'];\n return [];\n}\n\n// ─── Model registry ────────────────────────────────────────────────────────\n\nfunction buildModelMap(contractRoots: ContractRootNode[]): Map<string, ModelNode> {\n const map = new Map<string, ModelNode>();\n for (const root of contractRoots) {\n for (const model of root.models) {\n map.set(model.name, model);\n }\n }\n return map;\n}\n\n/** Resolve all fields for a model, including inherited base fields (bases first, in declaration order). */\nfunction resolveModelFields(model: ModelNode, modelMap: Map<string, ModelNode>): FieldNode[] {\n const collected: FieldNode[] = [];\n if (model.bases) {\n for (const base of model.bases) {\n const baseModel = modelMap.get(base);\n if (baseModel) collected.push(...resolveModelFields(baseModel, modelMap));\n }\n }\n return [...collected, ...model.fields];\n}\n\n// ─── Param helpers ─────────────────────────────────────────────────────────\n\ninterface ParamEntry {\n name: string;\n type: ContractTypeNode | undefined;\n default?: string | number | boolean;\n optional: boolean;\n}\n\n/** Expand a ParamSource into a flat list of named entries with their types. */\nfunction expandParamSource(source: ParamSource, modelMap: Map<string, ModelNode>): ParamEntry[] {\n if (source.kind === 'params') {\n return source.nodes.map(n => ({ name: n.name, type: n.type, default: n.default, optional: n.optional }));\n }\n if (source.kind === 'ref') {\n const model = modelMap.get(source.name);\n if (model) {\n return resolveModelFields(model, modelMap)\n .filter(f => f.visibility !== 'readonly')\n .map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));\n }\n // Fallback: single placeholder entry\n const name = source.name.charAt(0).toLowerCase() + source.name.slice(1);\n return [{ name, type: undefined, optional: false }];\n }\n // kind === 'type': if it's an inline object, expand its fields\n if (source.node.kind === 'inlineObject') {\n return source.node.fields.map(f => ({ name: f.name, type: f.type, default: f.default, optional: f.optional }));\n }\n return [];\n}\n\n/** Look up a named path param's type from route.params. */\nfunction findParamType(source: ParamSource | undefined, name: string, modelMap: Map<string, ModelNode>): ContractTypeNode | undefined {\n if (!source) return undefined;\n if (source.kind === 'params') return source.nodes.find(n => n.name === name)?.type;\n if (source.kind === 'ref') {\n const model = modelMap.get(source.name);\n if (model) return resolveModelFields(model, modelMap).find(f => f.name === name)?.type;\n }\n if (source.kind === 'type' && source.node.kind === 'inlineObject') {\n return source.node.fields.find(f => f.name === name)?.type;\n }\n return undefined;\n}\n\n/** Return a YAML-quoted example value string for a param, preferring a default value when provided. */\nfunction paramExampleValue(type: ContractTypeNode | undefined, defaultValue?: string | number | boolean, randomExamples = false): string {\n if (defaultValue !== undefined) return `\"${defaultValue}\"`;\n if (!type) return '\"\"';\n if (type.kind === 'enum') return type.values.length > 0 ? `\"${type.values[0]}\"` : '\"\"';\n if (type.kind === 'literal') return `\"${type.value}\"`;\n if (type.kind !== 'scalar') return '\"\"';\n if (randomExamples) {\n const random = randomScalarTemplate(type.name);\n if (random !== undefined) return `\"${random}\"`;\n }\n switch (type.name) {\n case 'uuid':\n return '\"00000000-0000-0000-0000-000000000000\"';\n case 'email':\n return '\"user@example.com\"';\n case 'url':\n return '\"https://example.com\"';\n case 'number':\n case 'int':\n case 'bigint':\n return '\"0\"';\n case 'boolean':\n return '\"true\"';\n case 'date':\n return '\"2024-01-01\"';\n case 'time':\n return '\"00:00:00\"';\n case 'datetime':\n return '\"2024-01-01T00:00:00Z\"';\n case 'duration':\n return '\"PT1H\"';\n default:\n return '\"\"';\n }\n}\n\n/** Bruno faker template for a scalar type, or undefined when no clean equivalent exists (date, time, duration, raw string). */\nfunction randomScalarTemplate(name: string): string | undefined {\n switch (name) {\n case 'uuid':\n return '{{$randomUUID}}';\n case 'email':\n return '{{$randomEmail}}';\n case 'url':\n return '{{$randomUrl}}';\n case 'number':\n case 'int':\n case 'bigint':\n return '{{$randomInt}}';\n case 'boolean':\n return '{{$randomBoolean}}';\n case 'datetime':\n return '{{$isoTimestamp}}';\n default:\n return undefined;\n }\n}\n\n// ─── Body helpers ──────────────────────────────────────────────────────────\n\n/**\n * Recursively build an example JSON value from a ContractTypeNode.\n *\n * When `randomExamples` is true we substitute Bruno faker templates only for\n * scalars whose JSON representation is a string (uuid/email/url/datetime).\n * Numbers and booleans stay deterministic — embedding `{{$randomInt}}` as a\n * bare JSON number would require sentinel-stripping the surrounding quotes,\n * and the body skeleton is meant as a starting point users edit anyway.\n */\nfunction typeToExampleValue(type: ContractTypeNode, modelMap: Map<string, ModelNode>, randomExamples = false): unknown {\n switch (type.kind) {\n case 'scalar':\n switch (type.name) {\n case 'string':\n return '';\n case 'email':\n return randomExamples ? '{{$randomEmail}}' : 'user@example.com';\n case 'url':\n return randomExamples ? '{{$randomUrl}}' : 'https://example.com';\n case 'uuid':\n return randomExamples ? '{{$randomUUID}}' : '00000000-0000-0000-0000-000000000000';\n case 'number':\n case 'int':\n case 'bigint':\n return 0;\n case 'boolean':\n return true;\n case 'date':\n return '2024-01-01';\n case 'time':\n return '00:00:00';\n case 'datetime':\n return randomExamples ? '{{$isoTimestamp}}' : '2024-01-01T00:00:00Z';\n case 'duration':\n return 'PT1H';\n case 'null':\n return null;\n default:\n return null;\n }\n case 'enum':\n return type.values[0] ?? '';\n case 'literal':\n return type.value;\n case 'array':\n return [typeToExampleValue(type.item, modelMap, randomExamples)];\n case 'tuple':\n return type.items.map(t => typeToExampleValue(t, modelMap, randomExamples));\n case 'record':\n return {};\n case 'union':\n return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;\n case 'discriminatedUnion':\n return type.members.length > 0 ? typeToExampleValue(type.members[0]!, modelMap, randomExamples) : null;\n case 'intersection':\n return {};\n case 'ref': {\n const model = modelMap.get(type.name);\n if (!model) return {};\n // Type alias — recurse into the aliased type\n if (model.type) return typeToExampleValue(model.type, modelMap, randomExamples);\n return modelToExampleObject(model, modelMap, randomExamples);\n }\n case 'lazy':\n return typeToExampleValue(type.inner, modelMap, randomExamples);\n case 'inlineObject':\n return fieldsToExampleObject(type.fields, modelMap, randomExamples);\n default:\n return null;\n }\n}\n\n/** Build an example object from a ModelNode's fields (including inherited base fields). */\nfunction modelToExampleObject(model: ModelNode, modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {\n return fieldsToExampleObject(resolveModelFields(model, modelMap), modelMap, randomExamples);\n}\n\n/** Build an example object from a list of FieldNodes. Excludes readonly fields; uses defaults when available; omits optional fields that have no default so they don't appear in the JSON output. */\nfunction fieldsToExampleObject(fields: FieldNode[], modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {\n const obj: Record<string, unknown> = {};\n for (const field of fields) {\n if (field.visibility === 'readonly') continue;\n if (field.default !== undefined) {\n obj[field.name] = field.default;\n } else if (!field.optional) {\n obj[field.name] = typeToExampleValue(field.type, modelMap, randomExamples);\n }\n }\n return obj;\n}\n\n// ─── Path helpers ──────────────────────────────────────────────────────────\n\n/** Convert /users/{id}/posts → /users/:id/posts (Bruno path parameter syntax) */\nfunction openCollectionPath(path: string): string {\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, ':$1');\n}\n\n/** Convert \"Create an Offer\" → create-an-offer (for .yml file names) */\nexport function slugifyName(name: string): string {\n const result = name\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return result || 'request';\n}\n\n/** Convert /users/{id}/posts → users-id-posts (for .yml file names) */\nexport function sanitizePath(path: string): string {\n const result = path\n .replace(/^\\//, '')\n .replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, '$1')\n .replace(/\\//g, '-')\n .replace(/[^a-zA-Z0-9-]/g, '')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n return result || 'root';\n}\n\n/** Extract param names from a URL template, e.g. /users/{id} → ['id'] */\nfunction extractPathParamNames(path: string): string[] {\n return [...path.matchAll(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g)].map(m => m[1]!);\n}\n\n/** Derive folder name from op file path, e.g. src/users.op → users */\nfunction deriveFolderName(file: string): string {\n return basename(file).replace(/\\.(op|ck)$/, '');\n}\n\n/**\n * Wrap a string in YAML double quotes if it contains characters that require quoting\n * (flow indicators, colons, braces, etc.).\n */\nfunction yamlString(value: string): string {\n if (/[:{}[\\],&*#?|<>=!%@`\"']/.test(value) || /^\\s|\\s$/.test(value)) {\n return `\"${value.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n }\n return value;\n}\n"],"mappings":";;;;AAAA,SAASA,SAASC,YAAAA,WAAUC,eAAe;AAC3C,SAASC,YAAYC,cAAcC,QAAQC,aAAaC,iBAAiB;;;ACUzE,SAASC,iBAAiBC,kBAAkBC,qBAAqB;AACjE,SAASC,gBAAgB;AACzB,SAASC,SAASC,WAAWC,aAAaC,qBAAqB;AASxD,IAAMC,oBAAoB;AA0C1B,SAASC,uBAAuBC,OAAqBC,SAA8B;AACtF,QAAMC,QAA8B,CAAA;AAEpC,QAAMC,WAAWC,cAAcH,QAAQI,iBAAiB,CAAA,CAAE;AAC1D,QAAMC,WAAWL,QAAQM;AACzB,QAAMC,gBAAgBF,UAAUE,gBAAgBF,SAASG,UAAUH,SAASE,aAAa,IAAIE;AAC7F,QAAMC,iBAAiBV,QAAQU,kBAAkB;AACjD,QAAMC,kBAAkBX,QAAQW,mBAAmB;AAEnDV,QAAMW,KAAK;IAAEC,cAAc;IAAsBC,SAASC,uBAAuBf,QAAQgB,gBAAgBT,aAAAA;EAAe,CAAA;AACxHN,QAAMW,KAAK;IAAEC,cAAc;IAA0BC,SAASG,gBAAgBV,aAAAA;EAAe,CAAA;AAG7F,WAASW,UAAU,GAAGA,UAAUnB,MAAMoB,QAAQD,WAAW;AACrD,UAAME,OAAOrB,MAAMmB,OAAAA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Ac,gBAAgBb,OAAOa,kBAAkB;MAC7C,CAAA;AACA,iBAAW,EAAEE,cAAcC,QAAO,KAAML,OAAO;AAC3Cb,YAAImB,SAASb,QAAQE,QAAQS,YAAAA,GAAeC,OAAAA;MAChD;IACJ;EACJ;AACJ;AA1BgBE;AAmChB,SAASR,oBAAoBJ,QAAc;AACvC,QAAMe,eAAejB,QAAQE,QAAQgB,iBAAAA;AACrC,MAAI,CAACC,WAAWF,YAAAA,EAAe;AAE/B,MAAIG;AACJ,MAAI;AACAA,cAAUC,cAAcC,aAAaL,cAAc,OAAA,CAAA;EACvD,QAAQ;AACJ;EACJ;AAEA,QAAMM,cAAc,oBAAIC,IAAAA;AACxB,aAAWC,OAAOL,SAAS;AACvB,UAAMM,MAAM1B,QAAQE,QAAQuB,GAAAA;AAC5B,QAAIN,WAAWO,GAAAA,GAAM;AACjBC,aAAOD,KAAK;QAAEE,OAAO;MAAK,CAAA;AAC1BL,kBAAYM,IAAIC,QAAQJ,GAAAA,CAAAA;IAC5B;EACJ;AAGA,aAAWK,OAAOR,aAAa;AAC3B,QAAIS,UAAUD;AACd,WAAOC,QAAQC,WAAW/B,MAAAA,KAAW8B,YAAY9B,QAAQ;AACrD,UAAI;AACA,YAAIgC,YAAYF,OAAAA,EAASG,WAAW,GAAG;AACnCC,oBAAUJ,OAAAA;AACVA,oBAAUF,QAAQE,OAAAA;QACtB,OAAO;AACH;QACJ;MACJ,QAAQ;AACJ;MACJ;IACJ;EACJ;AACJ;AApCS1B;","names":["resolve","basename","dirname","existsSync","readFileSync","rmSync","readdirSync","rmdirSync","resolveSecurity","resolveModifiers","SECURITY_NONE","basename","parse","parseYaml","stringify","stringifyYaml","MANIFEST_FILENAME","generateOpenCollection","roots","options","files","modelMap","buildModelMap","contractRoots","authOpts","auth","defaultScheme","schemes","undefined","randomExamples","includeInternal","push","relativePath","content","generateCollectionRoot","collectionName","generateEnvFile","rootIdx","length","root","folder","meta","slugifyName","deriveFolderName","file","displayName","charAt","toUpperCase","slice","generateFolderFile","subarea","subareaSlug","requestDir","subareaDisplayName","seq","route","routes","op","operations","resolveModifiers","includes","requestName","name","path","fileName","method","sanitizePath","generateRequestFile","pluginOverride","pluginFiles","mergePluginFile","trackedPaths","map","f","sort","JSON","stringify","parseManifest","parsed","parse","Array","isArray","every","deepMerge","base","override","result","key","val","Object","entries","generatedYaml","pluginFileContent","overrideParsed","parseYaml","merged","stringifyYaml","lineWidth","scheme","lines","yamlString","renderAuthBlock","join","varName","authEnvVarNames","openCollectionPath","pathParams","extractPathParamNames","n","type","findParamType","params","optional","kind","queryParams","query","expandParamSource","e","allParams","p","paramExampleValue","default","headers","headerEntries","h","security","resolveSecurity","SECURITY_NONE","request","bodies","preferredOrder","primary","ct","find","b","contentType","json","typeToExampleValue","bodyType","jsonLine","split","expectedStatus","pickAssertionStatus","responses","assertedResponse","r","statusCode","requiredHeaders","filter","toLowerCase","docs","buildRequestDocs","docLine","success","parts","description","trim","tag","desc","indent","i","in","headerName","Map","model","models","set","resolveModelFields","collected","bases","baseModel","get","fields","source","nodes","visibility","node","defaultValue","values","value","random","randomScalarTemplate","item","items","t","members","modelToExampleObject","inner","fieldsToExampleObject","obj","field","replace","matchAll","m","basename","test","plugin","name","cacheKey","generateTargets","opRoots","contractRoots","ctx","auth","config","options","base","baseDir","resolve","rootDir","outDir","output","collectionName","basename","cleanupTrackedFiles","files","generateOpenCollection","randomExamples","includeInternal","relativePath","content","emitFile","createBrunoPlugin","JSON","stringify","manifestPath","MANIFEST_FILENAME","existsSync","tracked","parseManifest","readFileSync","removedDirs","Set","rel","abs","rmSync","force","add","dirname","dir","current","startsWith","readdirSync","length","rmdirSync"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@contractkit/plugin-bruno",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "ContractKit built-in plugin: Bruno REST collection generation",
|
|
5
5
|
"author": {
|
|
6
6
|
"name": "Marooned Software",
|
|
@@ -26,7 +26,8 @@
|
|
|
26
26
|
".": "./dist/index.js"
|
|
27
27
|
},
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"
|
|
29
|
+
"yaml": "^2.8.3",
|
|
30
|
+
"@contractkit/core": "0.13.0"
|
|
30
31
|
},
|
|
31
32
|
"devDependencies": {
|
|
32
33
|
"@repo/config-eslint": "0.3.1",
|
package/src/codegen-bruno.ts
CHANGED
|
@@ -11,7 +11,9 @@ import type {
|
|
|
11
11
|
} from '@contractkit/core';
|
|
12
12
|
import { resolveSecurity, resolveModifiers, SECURITY_NONE } from '@contractkit/core';
|
|
13
13
|
import { basename } from 'path';
|
|
14
|
+
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
|
|
14
15
|
|
|
16
|
+
/** A single file produced by the Bruno codegen — a relative output path and its YAML content. */
|
|
15
17
|
export interface OpenCollectionFile {
|
|
16
18
|
relativePath: string;
|
|
17
19
|
content: string;
|
|
@@ -28,6 +30,7 @@ export interface BrunoSecurityScheme {
|
|
|
28
30
|
in?: string; // "header" | "query" (when type === "apiKey")
|
|
29
31
|
}
|
|
30
32
|
|
|
33
|
+
/** Auth configuration passed to the Bruno codegen; drives collection-level auth and per-operation auth blocks. */
|
|
31
34
|
export interface BrunoAuthOptions {
|
|
32
35
|
/** Name of the default scheme (from config.security.default) */
|
|
33
36
|
defaultScheme?: string;
|
|
@@ -35,6 +38,7 @@ export interface BrunoAuthOptions {
|
|
|
35
38
|
schemes?: Record<string, BrunoSecurityScheme>;
|
|
36
39
|
}
|
|
37
40
|
|
|
41
|
+
/** Options controlling what {@link generateOpenCollection} emits. */
|
|
38
42
|
export interface OpenCollectionOptions {
|
|
39
43
|
collectionName: string;
|
|
40
44
|
contractRoots?: ContractRootNode[];
|
|
@@ -93,10 +97,12 @@ export function generateOpenCollection(roots: OpRootNode[], options: OpenCollect
|
|
|
93
97
|
if (!includeInternal && resolveModifiers(route, op).includes('internal')) continue;
|
|
94
98
|
const requestName = op.name ?? route.path;
|
|
95
99
|
const fileName = op.name ? `${slugifyName(op.name)}.yml` : `${op.method}-${sanitizePath(route.path)}.yml`;
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
+
let content = generateRequestFile(route, op, requestName, seq, modelMap, root, defaultScheme, randomExamples);
|
|
101
|
+
const pluginOverride = op.pluginFiles?.['bruno'];
|
|
102
|
+
if (pluginOverride !== undefined) {
|
|
103
|
+
content = mergePluginFile(content, pluginOverride);
|
|
104
|
+
}
|
|
105
|
+
files.push({ relativePath: `${requestDir}/${fileName}`, content });
|
|
100
106
|
seq++;
|
|
101
107
|
}
|
|
102
108
|
}
|
|
@@ -124,6 +130,46 @@ export function parseManifest(content: string): string[] {
|
|
|
124
130
|
return [];
|
|
125
131
|
}
|
|
126
132
|
|
|
133
|
+
// ─── Plugin file merge ─────────────────────────────────────────────────────
|
|
134
|
+
|
|
135
|
+
function deepMerge(base: unknown, override: unknown): unknown {
|
|
136
|
+
if (
|
|
137
|
+
override !== null &&
|
|
138
|
+
typeof override === 'object' &&
|
|
139
|
+
!Array.isArray(override) &&
|
|
140
|
+
base !== null &&
|
|
141
|
+
typeof base === 'object' &&
|
|
142
|
+
!Array.isArray(base)
|
|
143
|
+
) {
|
|
144
|
+
const result: Record<string, unknown> = { ...(base as Record<string, unknown>) };
|
|
145
|
+
for (const [key, val] of Object.entries(override as Record<string, unknown>)) {
|
|
146
|
+
result[key] = deepMerge(result[key], val);
|
|
147
|
+
}
|
|
148
|
+
return result;
|
|
149
|
+
}
|
|
150
|
+
return override;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Deep-merges a YAML override string into a generated YAML string.
|
|
155
|
+
*
|
|
156
|
+
* Objects are merged recursively; arrays and scalars in the override replace the
|
|
157
|
+
* generated value entirely. If `pluginFileContent` is not a YAML mapping (e.g. it
|
|
158
|
+
* is a scalar or a list), the generated content is returned unchanged.
|
|
159
|
+
*
|
|
160
|
+
* @param generatedYaml - The YAML string produced by the Bruno codegen.
|
|
161
|
+
* @param pluginFileContent - The YAML override string to merge in.
|
|
162
|
+
* @returns The merged YAML string, or `generatedYaml` if the override is not a mapping.
|
|
163
|
+
*/
|
|
164
|
+
export function mergePluginFile(generatedYaml: string, pluginFileContent: string): string {
|
|
165
|
+
const overrideParsed = parseYaml(pluginFileContent);
|
|
166
|
+
if (overrideParsed === null || typeof overrideParsed !== 'object' || Array.isArray(overrideParsed)) {
|
|
167
|
+
return generatedYaml;
|
|
168
|
+
}
|
|
169
|
+
const merged = deepMerge(parseYaml(generatedYaml), overrideParsed);
|
|
170
|
+
return stringifyYaml(merged, { lineWidth: 0 });
|
|
171
|
+
}
|
|
172
|
+
|
|
127
173
|
// ─── File generators ───────────────────────────────────────────────────────
|
|
128
174
|
|
|
129
175
|
function generateCollectionRoot(name: string, scheme?: BrunoSecurityScheme): string {
|
|
@@ -540,16 +586,14 @@ function modelToExampleObject(model: ModelNode, modelMap: Map<string, ModelNode>
|
|
|
540
586
|
return fieldsToExampleObject(resolveModelFields(model, modelMap), modelMap, randomExamples);
|
|
541
587
|
}
|
|
542
588
|
|
|
543
|
-
/** Build an example object from a list of FieldNodes. Excludes readonly; uses defaults when available
|
|
589
|
+
/** Build an example object from a list of FieldNodes. Excludes readonly fields; uses defaults when available; omits optional fields that have no default so they don't appear in the JSON output. */
|
|
544
590
|
function fieldsToExampleObject(fields: FieldNode[], modelMap: Map<string, ModelNode>, randomExamples = false): Record<string, unknown> {
|
|
545
591
|
const obj: Record<string, unknown> = {};
|
|
546
592
|
for (const field of fields) {
|
|
547
593
|
if (field.visibility === 'readonly') continue;
|
|
548
594
|
if (field.default !== undefined) {
|
|
549
595
|
obj[field.name] = field.default;
|
|
550
|
-
} else if (field.optional) {
|
|
551
|
-
obj[field.name] = null;
|
|
552
|
-
} else {
|
|
596
|
+
} else if (!field.optional) {
|
|
553
597
|
obj[field.name] = typeToExampleValue(field.type, modelMap, randomExamples);
|
|
554
598
|
}
|
|
555
599
|
}
|
package/src/index.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { generateOpenCollection, MANIFEST_FILENAME, parseManifest } from './code
|
|
|
4
4
|
import type { BrunoSecurityScheme } from './codegen-bruno.js';
|
|
5
5
|
import type { ContractKitPlugin } from '@contractkit/core';
|
|
6
6
|
|
|
7
|
+
/** Configuration accepted by the Bruno plugin, both via `contractkit.config.json` and `createBrunoPlugin`. */
|
|
7
8
|
export interface BrunoPluginConfig {
|
|
8
9
|
baseDir?: string;
|
|
9
10
|
output?: string;
|
|
@@ -22,6 +23,7 @@ export interface BrunoPluginConfig {
|
|
|
22
23
|
includeInternal?: boolean;
|
|
23
24
|
}
|
|
24
25
|
|
|
26
|
+
/** Full plugin options shape read from `ctx.options` — extends {@link BrunoPluginConfig} with the `auth` block. */
|
|
25
27
|
export interface BrunoPluginOptions extends BrunoPluginConfig {
|
|
26
28
|
auth?: { defaultScheme: string; schemes?: Record<string, BrunoSecurityScheme> };
|
|
27
29
|
}
|
|
@@ -56,6 +58,16 @@ export default plugin;
|
|
|
56
58
|
|
|
57
59
|
// ─── Factory: for programmatic use with explicit config ────────────────────
|
|
58
60
|
|
|
61
|
+
/**
|
|
62
|
+
* Creates a Bruno plugin instance with explicit configuration, for programmatic use.
|
|
63
|
+
*
|
|
64
|
+
* Prefer the default export when loading via `contractkit.config.json`. Use this
|
|
65
|
+
* factory when constructing the plugin in code (e.g. in tests or custom build scripts).
|
|
66
|
+
*
|
|
67
|
+
* @param config - Plugin configuration (output paths and feature flags).
|
|
68
|
+
* @param rootDir - Absolute path used to resolve relative paths in `config`.
|
|
69
|
+
* @param auth - Optional auth scheme configuration mirroring the `auth` key in plugin options.
|
|
70
|
+
*/
|
|
59
71
|
export function createBrunoPlugin(
|
|
60
72
|
config: BrunoPluginConfig,
|
|
61
73
|
rootDir: string,
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, it, expect } from 'vitest';
|
|
2
|
-
import { generateOpenCollection, sanitizePath, MANIFEST_FILENAME, parseManifest } from '../src/codegen-bruno.js';
|
|
2
|
+
import { generateOpenCollection, sanitizePath, MANIFEST_FILENAME, parseManifest, mergePluginFile } from '../src/codegen-bruno.js';
|
|
3
3
|
import {
|
|
4
4
|
opRoot,
|
|
5
5
|
opRoute,
|
|
@@ -483,7 +483,7 @@ describe('generateOpenCollection', () => {
|
|
|
483
483
|
expect(yml!.content).toContain('"name": ""');
|
|
484
484
|
});
|
|
485
485
|
|
|
486
|
-
it('
|
|
486
|
+
it('omits optional fields with no default from body', () => {
|
|
487
487
|
const userModel = model('CreateUserInput', [
|
|
488
488
|
field('name', scalarType('string')),
|
|
489
489
|
field('nickname', scalarType('string'), { optional: true }),
|
|
@@ -495,7 +495,7 @@ describe('generateOpenCollection', () => {
|
|
|
495
495
|
const files = generateOpenCollection([root], { collectionName: 'API', contractRoots: [contractRoot([userModel])] });
|
|
496
496
|
const yml = files.find(f => f.relativePath === 'users/post-users.yml');
|
|
497
497
|
expect(yml!.content).toContain('"name": ""');
|
|
498
|
-
expect(yml!.content).toContain('"nickname"
|
|
498
|
+
expect(yml!.content).not.toContain('"nickname"');
|
|
499
499
|
});
|
|
500
500
|
|
|
501
501
|
it('expands inherited fields from base model in ref body', () => {
|
|
@@ -1006,3 +1006,153 @@ describe('sanitizePath', () => {
|
|
|
1006
1006
|
expect(sanitizePath('/users//posts')).toBe('users-posts');
|
|
1007
1007
|
});
|
|
1008
1008
|
});
|
|
1009
|
+
|
|
1010
|
+
describe('plugin file merges', () => {
|
|
1011
|
+
function getRequestFile(files: ReturnType<typeof generateOpenCollection>): { relativePath: string; content: string } {
|
|
1012
|
+
const f = files.find(f => !['opencollection.yml', 'environments/local.yml', MANIFEST_FILENAME].includes(f.relativePath) && !f.relativePath.endsWith('folder.yml'));
|
|
1013
|
+
if (!f) throw new Error('no request file found');
|
|
1014
|
+
return f;
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
it('deep-merges object override into generated request file', () => {
|
|
1018
|
+
const root = opRoot([
|
|
1019
|
+
opRoute('/users', [
|
|
1020
|
+
opOperation('get', {
|
|
1021
|
+
responses: [opResponse(200, 'User')],
|
|
1022
|
+
pluginFiles: { bruno: 'runtime:\n script:\n req: |\n console.log("pre");\n' },
|
|
1023
|
+
}),
|
|
1024
|
+
]),
|
|
1025
|
+
]);
|
|
1026
|
+
const files = generateOpenCollection([root], { collectionName: 'API' });
|
|
1027
|
+
const req = getRequestFile(files);
|
|
1028
|
+
// injected key from override
|
|
1029
|
+
expect(req.content).toContain('script:');
|
|
1030
|
+
expect(req.content).toContain('console.log("pre")');
|
|
1031
|
+
// generated key survives (assertions from the 200 response)
|
|
1032
|
+
expect(req.content).toContain('assertions:');
|
|
1033
|
+
});
|
|
1034
|
+
|
|
1035
|
+
it('replaces arrays in override rather than appending', () => {
|
|
1036
|
+
const root = opRoot([
|
|
1037
|
+
opRoute('/users', [
|
|
1038
|
+
opOperation('get', {
|
|
1039
|
+
responses: [opResponse(200)],
|
|
1040
|
+
pluginFiles: {
|
|
1041
|
+
bruno: [
|
|
1042
|
+
'runtime:',
|
|
1043
|
+
' assertions:',
|
|
1044
|
+
' - expression: res.status',
|
|
1045
|
+
' operator: eq',
|
|
1046
|
+
' value: "200"',
|
|
1047
|
+
' - expression: res.headers["x-request-id"]',
|
|
1048
|
+
' operator: isDefined',
|
|
1049
|
+
' value: ""',
|
|
1050
|
+
].join('\n'),
|
|
1051
|
+
},
|
|
1052
|
+
}),
|
|
1053
|
+
]),
|
|
1054
|
+
]);
|
|
1055
|
+
const files = generateOpenCollection([root], { collectionName: 'API' });
|
|
1056
|
+
const req = getRequestFile(files);
|
|
1057
|
+
// Count assertion blocks — should be exactly 2 (override replaces, not appends)
|
|
1058
|
+
const matches = req.content.match(/operator:/g);
|
|
1059
|
+
expect(matches).toHaveLength(2);
|
|
1060
|
+
});
|
|
1061
|
+
|
|
1062
|
+
it('preserves sibling keys not touched by override', () => {
|
|
1063
|
+
const root = opRoot([
|
|
1064
|
+
opRoute('/users', [
|
|
1065
|
+
opOperation('get', {
|
|
1066
|
+
responses: [opResponse(200)],
|
|
1067
|
+
pluginFiles: { bruno: 'runtime:\n script:\n req: |\n // pre\n' },
|
|
1068
|
+
}),
|
|
1069
|
+
]),
|
|
1070
|
+
]);
|
|
1071
|
+
const files = generateOpenCollection([root], { collectionName: 'API' });
|
|
1072
|
+
const req = getRequestFile(files);
|
|
1073
|
+
// Original http block must still be present
|
|
1074
|
+
expect(req.content).toContain('method: GET');
|
|
1075
|
+
expect(req.content).toContain('url:');
|
|
1076
|
+
});
|
|
1077
|
+
|
|
1078
|
+
it('leaves generated content unchanged when pluginFiles is absent', () => {
|
|
1079
|
+
const withoutOverride = opRoot([opRoute('/users', [opOperation('get', { responses: [opResponse(200)] })])]);
|
|
1080
|
+
const withOverride = opRoot([
|
|
1081
|
+
opRoute('/users', [
|
|
1082
|
+
opOperation('get', {
|
|
1083
|
+
responses: [opResponse(200)],
|
|
1084
|
+
pluginFiles: {},
|
|
1085
|
+
}),
|
|
1086
|
+
]),
|
|
1087
|
+
]);
|
|
1088
|
+
const filesWithout = generateOpenCollection([withoutOverride], { collectionName: 'API' });
|
|
1089
|
+
const filesWith = generateOpenCollection([withOverride], { collectionName: 'API' });
|
|
1090
|
+
expect(getRequestFile(filesWithout).content).toBe(getRequestFile(filesWith).content);
|
|
1091
|
+
});
|
|
1092
|
+
|
|
1093
|
+
it('ignores a malformed (non-mapping) plugin file and returns generated content unchanged', () => {
|
|
1094
|
+
const withoutOverride = opRoot([opRoute('/users', [opOperation('get', { responses: [opResponse(200)] })])]);
|
|
1095
|
+
const withBadOverride = opRoot([
|
|
1096
|
+
opRoute('/users', [
|
|
1097
|
+
opOperation('get', {
|
|
1098
|
+
responses: [opResponse(200)],
|
|
1099
|
+
pluginFiles: { bruno: 'just a scalar string' },
|
|
1100
|
+
}),
|
|
1101
|
+
]),
|
|
1102
|
+
]);
|
|
1103
|
+
const filesWithout = generateOpenCollection([withoutOverride], { collectionName: 'API' });
|
|
1104
|
+
const filesWith = generateOpenCollection([withBadOverride], { collectionName: 'API' });
|
|
1105
|
+
expect(getRequestFile(filesWithout).content).toBe(getRequestFile(filesWith).content);
|
|
1106
|
+
});
|
|
1107
|
+
|
|
1108
|
+
it('scalar override value replaces generated value', () => {
|
|
1109
|
+
const root = opRoot([
|
|
1110
|
+
opRoute('/users', [
|
|
1111
|
+
opOperation('get', {
|
|
1112
|
+
pluginFiles: { bruno: 'info:\n name: Custom Name\n' },
|
|
1113
|
+
}),
|
|
1114
|
+
]),
|
|
1115
|
+
]);
|
|
1116
|
+
const files = generateOpenCollection([root], { collectionName: 'API' });
|
|
1117
|
+
const req = getRequestFile(files);
|
|
1118
|
+
expect(req.content).toContain('name: Custom Name');
|
|
1119
|
+
});
|
|
1120
|
+
});
|
|
1121
|
+
|
|
1122
|
+
describe('mergePluginFile', () => {
|
|
1123
|
+
it('merges override object keys into generated YAML', () => {
|
|
1124
|
+
const base = 'info:\n name: Original\n type: http\n';
|
|
1125
|
+
const override = 'info:\n name: Overridden\n';
|
|
1126
|
+
const result = mergePluginFile(base, override);
|
|
1127
|
+
expect(result).toContain('name: Overridden');
|
|
1128
|
+
expect(result).toContain('type: http');
|
|
1129
|
+
});
|
|
1130
|
+
|
|
1131
|
+
it('replaces arrays in the override rather than appending', () => {
|
|
1132
|
+
const base = 'runtime:\n assertions:\n - expression: res.status\n operator: eq\n value: "200"\n';
|
|
1133
|
+
const override = 'runtime:\n assertions:\n - expression: res.status\n operator: eq\n value: "201"\n - expression: res.status\n operator: eq\n value: "202"\n';
|
|
1134
|
+
const result = mergePluginFile(base, override);
|
|
1135
|
+
const matches = result.match(/operator:/g);
|
|
1136
|
+
expect(matches).toHaveLength(2);
|
|
1137
|
+
expect(result).not.toContain('"200"');
|
|
1138
|
+
});
|
|
1139
|
+
|
|
1140
|
+
it('returns generated YAML unchanged when override is a scalar', () => {
|
|
1141
|
+
const base = 'info:\n name: Original\n';
|
|
1142
|
+
expect(mergePluginFile(base, 'just a scalar')).toBe(base);
|
|
1143
|
+
});
|
|
1144
|
+
|
|
1145
|
+
it('returns generated YAML unchanged when override is an array', () => {
|
|
1146
|
+
const base = 'info:\n name: Original\n';
|
|
1147
|
+
expect(mergePluginFile(base, '- a\n- b\n')).toBe(base);
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
it('adds keys from override that are absent in the generated YAML', () => {
|
|
1151
|
+
const base = 'http:\n method: GET\n';
|
|
1152
|
+
const override = 'runtime:\n script:\n req: |\n console.log("hi");\n';
|
|
1153
|
+
const result = mergePluginFile(base, override);
|
|
1154
|
+
expect(result).toContain('method: GET');
|
|
1155
|
+
expect(result).toContain('script:');
|
|
1156
|
+
});
|
|
1157
|
+
});
|
|
1158
|
+
|
package/.turbo/turbo-build.log
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
> @contractkit/plugin-bruno@0.9.0 build /Users/robert/projects/contractkit/packages/plugin-bruno
|
|
3
|
-
> tsup src/index.ts --format esm --sourcemap --dts && tsc --emitDeclarationOnly --declaration
|
|
4
|
-
|
|
5
|
-
CLI Building entry: src/index.ts
|
|
6
|
-
CLI Using tsconfig: tsconfig.json
|
|
7
|
-
CLI tsup v8.5.1
|
|
8
|
-
CLI Target: esnext
|
|
9
|
-
ESM Build start
|
|
10
|
-
ESM dist/index.js 19.94 KB
|
|
11
|
-
ESM dist/index.js.map 46.49 KB
|
|
12
|
-
ESM ⚡️ Build success in 69ms
|
|
13
|
-
DTS Build start
|
|
14
|
-
DTS ⚡️ Build success in 594ms
|
|
15
|
-
DTS dist/index.d.ts 1.37 KB
|
package/.turbo/turbo-test.log
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
|
|
2
|
-
> @contractkit/plugin-bruno@0.9.0 test /Users/robert/projects/contractkit/packages/plugin-bruno
|
|
3
|
-
> vitest run
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
[1m[30m[46m RUN [49m[39m[22m [36mv4.1.5 [39m[90m/Users/robert/projects/contractkit/packages/plugin-bruno[39m
|
|
7
|
-
|
|
8
|
-
[32m✓[39m tests/codegen-bruno.test.ts [2m([22m[2m85 tests[22m[2m)[22m[32m 9[2mms[22m[39m
|
|
9
|
-
|
|
10
|
-
[2m Test Files [22m [1m[32m1 passed[39m[22m[90m (1)[39m
|
|
11
|
-
[2m Tests [22m [1m[32m85 passed[39m[22m[90m (85)[39m
|
|
12
|
-
[2m Start at [22m 08:51:33
|
|
13
|
-
[2m Duration [22m 414ms[2m (transform 136ms, setup 0ms, import 255ms, tests 9ms, environment 0ms)[22m
|
|
14
|
-
|