|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// Pins the self-consistency gate on the generated OpenAPI document (#5168). |
| 4 | +// |
| 5 | +// The defect: every contract schema is wrapped in `lazySchema()`, whose Proxy |
| 6 | +// target is `function lazyZod() {}`. The collector in `build-openapi.ts` led |
| 7 | +// its guard with `typeof schema === 'object'`, so all nine short-circuited and |
| 8 | +// `components.schemas` shipped as `{}` — while the hand-written `$ref` |
| 9 | +// literals in `paths` were emitted regardless, leaving six dangling refs |
| 10 | +// across every CRUD request/response body in the published |
| 11 | +// `GET /api/v1/openapi.json`. |
| 12 | +// |
| 13 | +// Nothing went red. `gen:openapi` is one of the two generators with no gate at |
| 14 | +// all, so the breakage was visible three ways (empty components, dangling |
| 15 | +// refs, a literal `Components: 0` on the console) and asserted by nothing. |
| 16 | +// |
| 17 | +// These tests therefore cover BOTH halves, and the second half is the one that |
| 18 | +// prevents recurrence: |
| 19 | +// |
| 20 | +// 1. the pure assertions, against synthetic documents; |
| 21 | +// 2. the REAL `build-openapi.ts`, run as a subprocess — green on the shipped |
| 22 | +// source, and red again under each of the two ways this can break. That |
| 23 | +// second group is the reverse verification: a gate that has never been |
| 24 | +// observed failing is not known to be a gate. |
| 25 | +// |
| 26 | +// ── Why a sandbox for the subprocess group ──────────────────────────────── |
| 27 | +// The script resolves its output dir from its own `__dirname` (`../json-schema` |
| 28 | +// -> the package's real, gitignored artifact) and a concurrent |
| 29 | +// `pnpm --filter @objectstack/spec build` under `turbo run test` writes that |
| 30 | +// same file. Running the mutated copies in place would be both destructive and |
| 31 | +// flaky, so each variant is written into a temp tree that COPIES `scripts/` and |
| 32 | +// symlinks the read-only inputs (`src/`, `node_modules/`, `package.json`) — |
| 33 | +// the same discipline `build-schemas-check-mode.test.ts` uses, and for the same |
| 34 | +// reason: no test-only seam is added to the gate, because a seam is a place |
| 35 | +// where the gate can differ from what CI runs. |
| 36 | + |
| 37 | +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; |
| 38 | +import { spawnSync } from 'node:child_process'; |
| 39 | +import fs from 'node:fs'; |
| 40 | +import os from 'node:os'; |
| 41 | +import path from 'node:path'; |
| 42 | +import { |
| 43 | + findDanglingRefs, |
| 44 | + assertRefsResolve, |
| 45 | + assertNoDegradedSchemas, |
| 46 | +} from './lib/openapi-self-consistency'; |
| 47 | + |
| 48 | +const PKG_ROOT = path.resolve(__dirname, '..'); |
| 49 | + |
| 50 | +describe('findDanglingRefs', () => { |
| 51 | + it('reports nothing for a document whose refs all resolve', () => { |
| 52 | + const doc = { |
| 53 | + paths: { |
| 54 | + '/api/{object}': { |
| 55 | + get: { responses: { '200': { schema: { $ref: '#/components/schemas/ApiError' } } } }, |
| 56 | + }, |
| 57 | + }, |
| 58 | + components: { schemas: { ApiError: { type: 'object' } } }, |
| 59 | + }; |
| 60 | + expect(findDanglingRefs(doc)).toEqual([]); |
| 61 | + }); |
| 62 | + |
| 63 | + it('reports the #5168 shape: refs present, components.schemas empty', () => { |
| 64 | + const doc = { |
| 65 | + paths: { |
| 66 | + '/api/{object}': { |
| 67 | + get: { responses: { '200': { schema: { $ref: '#/components/schemas/ListRecordResponse' } } } }, |
| 68 | + }, |
| 69 | + }, |
| 70 | + components: { schemas: {} }, |
| 71 | + }; |
| 72 | + const dangling = findDanglingRefs(doc); |
| 73 | + expect(dangling).toHaveLength(1); |
| 74 | + expect(dangling[0].ref).toBe('#/components/schemas/ListRecordResponse'); |
| 75 | + // The location is what makes the failure actionable. |
| 76 | + expect(dangling[0].at).toContain('/api/{object}'); |
| 77 | + }); |
| 78 | + |
| 79 | + it('finds refs nested inside arrays', () => { |
| 80 | + const doc = { |
| 81 | + paths: { '/x': { get: { anyOf: [{ $ref: '#/components/schemas/Gone' }] } } }, |
| 82 | + components: { schemas: {} }, |
| 83 | + }; |
| 84 | + expect(findDanglingRefs(doc).map((d) => d.ref)).toEqual(['#/components/schemas/Gone']); |
| 85 | + }); |
| 86 | + |
| 87 | + it('resolves by JSON pointer, so a future non-components ref is covered too', () => { |
| 88 | + const ok = { $defs: { Node: { type: 'string' } }, a: { $ref: '#/$defs/Node' } }; |
| 89 | + expect(findDanglingRefs(ok)).toEqual([]); |
| 90 | + const bad = { $defs: {}, a: { $ref: '#/$defs/Node' } }; |
| 91 | + expect(findDanglingRefs(bad).map((d) => d.ref)).toEqual(['#/$defs/Node']); |
| 92 | + }); |
| 93 | + |
| 94 | + it('ignores external refs rather than guessing about them', () => { |
| 95 | + const doc = { a: { $ref: 'https://example.com/schema.json#/Thing' }, components: { schemas: {} } }; |
| 96 | + expect(findDanglingRefs(doc)).toEqual([]); |
| 97 | + }); |
| 98 | + |
| 99 | + it('unescapes JSON-pointer ~1 and ~0 segments', () => { |
| 100 | + const doc = { paths: { '/api/x': { ok: true } }, a: { $ref: '#/paths/~1api~1x' } }; |
| 101 | + expect(findDanglingRefs(doc)).toEqual([]); |
| 102 | + }); |
| 103 | + |
| 104 | + it('terminates on a cyclic document instead of hanging the build', () => { |
| 105 | + const doc: Record<string, unknown> = { components: { schemas: {} } }; |
| 106 | + doc.self = doc; |
| 107 | + expect(() => findDanglingRefs(doc)).not.toThrow(); |
| 108 | + }); |
| 109 | +}); |
| 110 | + |
| 111 | +describe('assertRefsResolve', () => { |
| 112 | + it('passes a coherent document', () => { |
| 113 | + const doc = { a: { $ref: '#/components/schemas/X' }, components: { schemas: { X: {} } } }; |
| 114 | + expect(() => assertRefsResolve(doc)).not.toThrow(); |
| 115 | + }); |
| 116 | + |
| 117 | + it('throws naming the offender and the (empty) defined set', () => { |
| 118 | + const doc = { a: { $ref: '#/components/schemas/X' }, components: { schemas: {} } }; |
| 119 | + expect(() => assertRefsResolve(doc)).toThrow(/unresolvable \$ref/); |
| 120 | + expect(() => assertRefsResolve(doc)).toThrow(/#\/components\/schemas\/X/); |
| 121 | + expect(() => assertRefsResolve(doc)).toThrow(/<none>/); |
| 122 | + }); |
| 123 | +}); |
| 124 | + |
| 125 | +describe('assertNoDegradedSchemas', () => { |
| 126 | + it('passes when every declared name was emitted', () => { |
| 127 | + expect(() => assertNoDegradedSchemas(['A', 'B'], { A: {}, B: {} }, [])).not.toThrow(); |
| 128 | + }); |
| 129 | + |
| 130 | + it('throws on a silently skipped schema — the #5168 root cause', () => { |
| 131 | + expect(() => assertNoDegradedSchemas(['A', 'B'], { A: {} }, [])).toThrow( |
| 132 | + /not emitted at all \(1\): B/, |
| 133 | + ); |
| 134 | + }); |
| 135 | + |
| 136 | + it('throws on a placeholder-converted schema rather than publishing it', () => { |
| 137 | + expect(() => assertNoDegradedSchemas(['A'], { A: {} }, ['A'])).toThrow( |
| 138 | + /converted to a placeholder \(1\): A/, |
| 139 | + ); |
| 140 | + }); |
| 141 | +}); |
| 142 | + |
| 143 | +// ───────────────────────────────────────────────────────────────────────── |
| 144 | +// The real generator, as a subprocess. |
| 145 | +// ───────────────────────────────────────────────────────────────────────── |
| 146 | + |
| 147 | +let sandbox: string; |
| 148 | + |
| 149 | +/** Run a (possibly mutated) copy of `build-openapi.ts` in an isolated tree. */ |
| 150 | +function runGenerator(mutate?: (src: string) => string): { status: number; output: string } { |
| 151 | + const dir = fs.mkdtempSync(path.join(sandbox, 'gen-')); |
| 152 | + fs.cpSync(path.join(PKG_ROOT, 'scripts'), path.join(dir, 'scripts'), { recursive: true }); |
| 153 | + for (const entry of ['src', 'node_modules', 'package.json']) { |
| 154 | + fs.symlinkSync(path.join(PKG_ROOT, entry), path.join(dir, entry)); |
| 155 | + } |
| 156 | + |
| 157 | + const scriptPath = path.join(dir, 'scripts', 'build-openapi.ts'); |
| 158 | + if (mutate) { |
| 159 | + const original = fs.readFileSync(scriptPath, 'utf-8'); |
| 160 | + const mutated = mutate(original); |
| 161 | + expect(mutated, 'mutation must actually change the source').not.toBe(original); |
| 162 | + fs.writeFileSync(scriptPath, mutated); |
| 163 | + } |
| 164 | + |
| 165 | + const res = spawnSync('npx', ['tsx', scriptPath], { |
| 166 | + cwd: dir, |
| 167 | + encoding: 'utf-8', |
| 168 | + env: { ...process.env, NODE_OPTIONS: '--max-old-space-size=4096' }, |
| 169 | + }); |
| 170 | + return { status: res.status ?? -1, output: `${res.stdout ?? ''}${res.stderr ?? ''}` }; |
| 171 | +} |
| 172 | + |
| 173 | +describe('build-openapi.ts end to end', () => { |
| 174 | + beforeAll(() => { |
| 175 | + sandbox = fs.mkdtempSync(path.join(os.tmpdir(), 'os-openapi-5168-')); |
| 176 | + }); |
| 177 | + afterAll(() => { |
| 178 | + fs.rmSync(sandbox, { recursive: true, force: true }); |
| 179 | + }); |
| 180 | + |
| 181 | + it('emits all nine components WITHOUT OS_EAGER_SCHEMAS (#5168 regression pin)', () => { |
| 182 | + const { status, output } = runGenerator(); |
| 183 | + expect(output).toContain('Components: 9'); |
| 184 | + // The exact symptom string from the issue, which nobody was asserting. |
| 185 | + expect(output).not.toContain('Components: 0'); |
| 186 | + expect(status).toBe(0); |
| 187 | + }); |
| 188 | + |
| 189 | + it('writes a document in which every $ref resolves', () => { |
| 190 | + const { status } = runGenerator(); |
| 191 | + expect(status).toBe(0); |
| 192 | + // Re-read the artifact the run just produced and check it independently of |
| 193 | + // the generator's own gate. |
| 194 | + const dirs = fs |
| 195 | + .readdirSync(sandbox) |
| 196 | + .map((d) => path.join(sandbox, d, 'json-schema', 'openapi.json')) |
| 197 | + .filter((p) => fs.existsSync(p)); |
| 198 | + const doc = JSON.parse(fs.readFileSync(dirs[dirs.length - 1], 'utf-8')); |
| 199 | + expect(Object.keys(doc.components.schemas)).toHaveLength(9); |
| 200 | + expect(findDanglingRefs(doc)).toEqual([]); |
| 201 | + }); |
| 202 | + |
| 203 | + // ── Reverse verification ──────────────────────────────────────────────── |
| 204 | + // Predicted direction for BOTH: RED (non-zero exit). These are not |
| 205 | + // decoration — before #5168 the generator exited 0 on a document with six |
| 206 | + // dangling refs, so "the gate can fail" is the claim under test. |
| 207 | + |
| 208 | + it('goes RED when the lazySchema Proxy is rejected again (the original bug)', () => { |
| 209 | + const { status, output } = runGenerator((src) => |
| 210 | + src.replace( |
| 211 | + "!!schema && (typeof schema === 'object' || typeof schema === 'function') && '_zod' in schema", |
| 212 | + "!!schema && typeof schema === 'object' && '_zod' in schema", |
| 213 | + ), |
| 214 | + ); |
| 215 | + expect(status).not.toBe(0); |
| 216 | + expect(output).toMatch(/not emitted at all \(9\)/); |
| 217 | + expect(output).toContain('ApiError'); |
| 218 | + }); |
| 219 | + |
| 220 | + it('goes RED when a $ref points at a schema that does not exist', () => { |
| 221 | + const { status, output } = runGenerator((src) => |
| 222 | + src.replace(/#\/components\/schemas\/ApiError'/g, "#/components/schemas/ApiErrorTypo'"), |
| 223 | + ); |
| 224 | + expect(status).not.toBe(0); |
| 225 | + expect(output).toMatch(/unresolvable \$ref/); |
| 226 | + expect(output).toContain('#/components/schemas/ApiErrorTypo'); |
| 227 | + }); |
| 228 | + |
| 229 | + it('refuses to WRITE the artifact when the document is inconsistent', () => { |
| 230 | + const dirsBefore = new Set(fs.readdirSync(sandbox)); |
| 231 | + runGenerator((src) => |
| 232 | + src.replace(/#\/components\/schemas\/ApiError'/g, "#/components/schemas/ApiErrorTypo'"), |
| 233 | + ); |
| 234 | + const newDir = fs.readdirSync(sandbox).find((d) => !dirsBefore.has(d))!; |
| 235 | + // The gate runs before the write, so no half-broken document is published. |
| 236 | + expect(fs.existsSync(path.join(sandbox, newDir, 'json-schema', 'openapi.json'))).toBe(false); |
| 237 | + }); |
| 238 | +}); |
0 commit comments