import { ast } from '@kubb/ast' import { type Config, memoryStorage, type Plugin } from '@kubb/core' import { addGenerator, defineExtension, type TemplateContext } from '@kubb/kit' import { createMockedAdapter } from '@kubb/core/mocks' import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises' import { tmpdir } from 'node:os' import path from 'node:path' import { describe, expect, it } from 'vitest' import { createGenerationStore, generate, hashOf, listDisk, type GenerationStore, type SourceFiles } from './generations.ts' function sourceFiles(files: Record): SourceFiles { const storage = memoryStorage() for (const [path, content] of Object.entries(files)) void storage.writeItem(`/project/${path}`, content) return { storage, root: '/project', paths: new Set(Object.keys(files)) } } async function addRun({ store, jobId, files }: { store: GenerationStore; jobId: string; files: Record }) { const output = await store.keep({ jobId, files: sourceFiles(files), maxSetMb: 1 }) await store.add({ jobId, output }) } describe('createGenerationStore', () => { it('keeps the name of a ref schema but not the copy of its target', async () => { const pet = ast.factory.createSchema({ type: 'object', name: 'Pet', properties: [] }) const ref = ast.factory.createSchema({ type: 'ref', name: 'Pet', ref: '#/components/schemas/Pet', schema: pet }) const input = ast.factory.createInput({ schemas: [pet, ast.factory.createSchema({ type: 'array', name: 'Pets', items: [ref] })] }) const store = createGenerationStore({ storage: memoryStorage(), maxCount: 4, maxMb: 10 }) await store.keepInput({ jobId: 'job-1', maxSetMb: 1, input }) const kept = await store.readInput('job-1') expect(kept?.schemas[1]).toMatchObject({ type: 'array', items: [{ type: 'ref', name: 'Pet', ref: '#/components/schemas/Pet' }] }) expect(JSON.stringify(kept)).not.toContain('"schema":') }) it('counts a kept input toward the size limit and drops it with its job', async () => { const store = createGenerationStore({ storage: memoryStorage(), maxCount: 4, maxMb: 100 / (1024 * 1024) }) const inputBytes = await store.keepInput({ maxSetMb: 1, jobId: 'job-1', input: ast.factory.createInput({ meta: { description: 'x'.repeat(200) } }), }) const output = await store.keep({ jobId: 'job-1', files: sourceFiles({ 'a.ts': 'one' }), maxSetMb: 1 }) await store.add({ jobId: 'job-1', output, inputBytes }) await addRun({ store, jobId: 'job-2', files: { 'b.ts': 'two' } }) expect(await store.get('job-1')).toBeUndefined() await expect(store.readInput('job-1')).resolves.toBeUndefined() }) it('reads a generation back by its job id only, including after a restart', async () => { const storage = memoryStorage() await addRun({ store: createGenerationStore({ storage, maxCount: 4, maxMb: 10 }), jobId: 'job-1', files: { 'a.ts': 'one' } }) const restarted = createGenerationStore({ storage, maxCount: 4, maxMb: 10 }) const generation = await restarted.get('job-1') expect(await restarted.get('job-2')).toBeUndefined() expect(generation?.output.hashes['a.ts']).toMatch(/^[0-9a-f]{16}$/) await expect(restarted.read({ generation: generation!, paths: ['a.ts', 'b.ts'] })).resolves.toStrictEqual({ files: { 'a.ts': 'one' } }) }) it('hashes the exact stored bytes, including leading and trailing whitespace', async () => { const store = createGenerationStore({ storage: memoryStorage(), maxCount: 4, maxMb: 10 }) const output = await store.keep({ jobId: 'job-1', files: sourceFiles({ 'a.ts': '\nexport const a = 1' }), maxSetMb: 1 }) const disk = await store.keep({ jobId: 'job-2', files: sourceFiles({ 'a.ts': 'export const a = 1\n' }), maxSetMb: 1 }) expect(output.hashes['a.ts']).toBe(hashOf('\nexport const a = 1')) expect(output.hashes['a.ts']).not.toBe(disk.hashes['a.ts']) }) it('pages through a file split on any line ending until nextCursor is null', async () => { const store = createGenerationStore({ storage: memoryStorage(), maxCount: 4, maxMb: 10 }) await addRun({ store, jobId: 'job-1', files: { 'a.ts': 'l0\r\nl1\rl2\nl3\nl4' } }) const generation = (await store.get('job-1'))! await expect(store.read({ generation, paths: ['a.ts'], limit: 2 })).resolves.toStrictEqual({ files: { 'a.ts': 'l0\nl1' }, pages: { 'a.ts': { nextCursor: 2, totalLines: 5 } }, }) await expect(store.read({ generation, paths: ['a.ts'], cursor: 4, limit: 10 })).resolves.toStrictEqual({ files: { 'a.ts': 'l4' }, pages: { 'a.ts': { nextCursor: null, totalLines: 5 } }, }) await expect(store.read({ generation, paths: ['a.ts'], cursor: 9, limit: 2 })).resolves.toStrictEqual({ files: { 'a.ts': '' }, pages: { 'a.ts': { nextCursor: null, totalLines: 5 } }, }) }) it('keeps both of two generations added at the same time', async () => { const store = createGenerationStore({ storage: memoryStorage(), maxCount: 8, maxMb: 10 }) const [first, second] = await Promise.all(['job-1', 'job-2'].map((jobId) => store.keep({ jobId, files: sourceFiles({ 'a.ts': jobId }), maxSetMb: 1 }))) await Promise.all([store.add({ jobId: 'job-1', output: first! }), store.add({ jobId: 'job-2', output: second! })]) expect((await store.get('job-1'))?.jobId).toBe('job-1') expect((await store.get('job-2'))?.jobId).toBe('job-2') }) it('keeps the index whole when an add lands while keepInitial reuses an entry', async () => { const base = memoryStorage() let onEmpty: (() => void) | undefined const storage = { ...base, async empty(prefix?: string) { const callback = onEmpty onEmpty = undefined callback?.() await base.empty(prefix) }, } const store = createGenerationStore({ storage, maxCount: 1, maxMb: 10 }) const files = sourceFiles({ 'a.ts': 'same' }) const first = await store.keepInitial(files) const other = await store.keep({ jobId: 'job-b', files: sourceFiles({ 'b.ts': 'other' }), maxSetMb: 1 }) let added: Promise | undefined // The reuse drops its candidate copy. An initial add that evicts the match starts right then. onEmpty = () => { added = store.add({ jobId: 'job-b', output: other, initial: true }) } const reused = await store.keepInitial(files) await added expect(reused.jobId).toBe(first.jobId) // The later add wins, and the index still points at files that exist. expect((await store.get('job-b'))?.jobId).toBe('job-b') expect((await storage.readKeys()).some((key) => key.endsWith('b.ts'))).toBe(true) }) it('keeps an entry an add committed while a slower index read was still waiting', async () => { const base = memoryStorage() const slow = Promise.withResolvers() let first = true const storage = { ...base, async readItem(key: string) { // The first index read returns what was on disk before the add, but only after the add committed. const value = await base.readItem(key) if (key.endsWith('generations.json') && first) { first = false await slow.promise } return value }, } const store = createGenerationStore({ storage, maxCount: 8, maxMb: 10 }) const output = await store.keep({ jobId: 'job-1', files: sourceFiles({ 'a.ts': 'one' }), maxSetMb: 1 }) const reading = store.get('job-1') await store.add({ jobId: 'job-1', output }) slow.resolve() expect((await reading)?.jobId).toBe('job-1') expect((await store.get('job-1'))?.jobId).toBe('job-1') }) it('drops the oldest past the count, and their files with them', async () => { const storage = memoryStorage() const store = createGenerationStore({ storage, maxCount: 2, maxMb: 10 }) for (const jobId of ['job-1', 'job-2', 'job-3']) await addRun({ store, jobId, files: { 'a.ts': jobId } }) expect(await store.get('job-1')).toBeUndefined() expect((await store.get('job-3'))?.jobId).toBe('job-3') expect((await storage.readKeys()).filter((key) => key.endsWith('a.ts'))).toHaveLength(2) }) }) describe('generate', () => { // Records where the build places each schema file. function makeConfig(name: string, placed: Array): Config { const types = defineExtension({ kind: 'plugin', meta: { name: 'types' }, setup(options) { addGenerator({ name: 'types', schema(node: ast.SchemaNode, gctx: TemplateContext) { placed.push( gctx.getResolver('types').file({ name: node.name!, extname: '.ts', root: gctx.root, output: { path: 'types', mode: 'directory' } }).path, ) return null }, }) return options }, })({ output: { path: 'types' } }) as unknown as Plugin const schemas = [ast.factory.createSchema({ type: 'string', name: 'Name' }), ast.factory.createSchema({ type: 'string', name })] return { root: '/project', input: './spec.json', output: { path: `./gen/${name}`, clean: true }, shared: { path: './gen/common' }, parsers: [], reporters: [], adapter: createMockedAdapter({ parse: async () => ast.factory.createInput({ schemas }) }), plugins: [types], storage: memoryStorage(), } } it('places a schema the other entries of the config file define too under shared.path, and keeps what they wrote there', async () => { const placed: Array = [] const animals = makeConfig('Animal', placed) const fruits = makeConfig('Fruit', []) await animals.storage.writeItem('/project/gen/common/types/fruit.ts', 'kept') await generate({ configs: [animals, fruits], allowExec: false }) expect(placed).toStrictEqual(['/project/gen/common/types/name.ts', '/project/gen/Animal/types/animal.ts']) expect(await animals.storage.readItem('/project/gen/common/types/fruit.ts')).toBe('kept') }) }) describe('generate code index input positions', () => { it('places pointers in an input file inside the project, but not in one behind a symlink that leads outside it', async () => { const root = await mkdtemp(path.join(tmpdir(), 'kubb-index-input-')) const outside = await mkdtemp(path.join(tmpdir(), 'kubb-index-outside-')) try { await writeFile(path.join(root, 'spec.yaml'), 'openapi: 3.1.0\n') await writeFile(path.join(outside, 'spec.yaml'), 'secret: true\n') await symlink(outside, path.join(root, 'linked'), 'dir') const operations = [ast.factory.createOperation({ operationId: 'getPet', method: 'GET', path: '/pet', pointer: '#/paths/~1pet/get' })] const pet = defineExtension({ kind: 'plugin', meta: { name: 'pet' }, hooks: {} })() const config = (input: string): Config => ({ root, input, output: { path: './gen' }, parsers: [], reporters: [], adapter: Object.assign(createMockedAdapter({ parse: async () => ast.factory.createInput({ operations }) }), { locate: () => ({ start: 0, end: 1 }) }), plugins: [pet], storage: memoryStorage(), }) const inside = await generate({ configs: [config('./spec.yaml')], allowExec: false, codeIndex: true }) const linked = await generate({ configs: [config('./linked/spec.yaml')], allowExec: false, codeIndex: true }) expect(inside.codeIndex?.inputPositions?.path).toBe('spec.yaml') expect(linked.codeIndex?.inputPositions).toBeUndefined() } finally { await rm(root, { recursive: true, force: true }) await rm(outside, { recursive: true, force: true }) } }) }) describe('listDisk', () => { it('lists an output folder named with two leading dots, and nothing outside the root', async () => { const root = await mkdtemp(path.join(tmpdir(), 'kubb-list-disk-')) try { await mkdir(path.join(root, '..cache')) await writeFile(path.join(root, '..cache', 'pet.ts'), 'export {}') expect((await listDisk({ root, outputPath: '..cache', maxFiles: 10 }))?.paths).toStrictEqual(new Set(['..cache/pet.ts'])) expect(await listDisk({ root, outputPath: '..', maxFiles: 10 })).toBeUndefined() expect(await listDisk({ root, outputPath: '.', maxFiles: 10 })).toBeUndefined() } finally { await rm(root, { recursive: true, force: true }) } }) })