import { ast } from '@kubb/ast' import { type Adapter, Hookable, type KubbHooks, type Parser } from '@kubb/core' import { describe, expect, it } from 'vitest' import { type CodeIndexer, createCodeIndexer } from './codeIndex.ts' const { createContent, createFile, createInput, createOperation, createResponse, createSchema, createSource, createText } = ast.factory const input = createInput({ schemas: [ { ...createSchema({ type: 'object', name: 'Tag' }), pointer: '#/components/schemas/Tag' }, { ...createSchema({ type: 'object', name: 'Pet', properties: [ast.factory.createProperty({ name: 'tag', schema: createSchema({ type: 'ref', name: 'Tag' }), required: false })], }), pointer: '#/components/schemas/Pet', }, ], operations: [ { ...createOperation({ operationId: 'getPetById', method: 'GET', path: '/pet/{petId}', responses: [ createResponse({ statusCode: '200', content: [createContent({ contentType: 'application/json', schema: createSchema({ type: 'ref', name: 'Pet' }) })], }), ], }), pointer: '#/paths/~1pet~1{petId}/get', }, { ...createOperation({ operationId: 'logout', method: 'GET', path: '/user/logout' }), pointer: '#/paths/~1user~1logout/get' }, ], meta: { title: 'Pets' }, }) // A stand-in for a parser's `find`: it finds ` =` after `type`, so any parser shape works here. const parsers = [ { extNames: ['.ts'], find: (text: string) => [...text.matchAll(/^export type (\w+) =/gm)].map((match) => ({ name: match[1]!, offset: match.index + 'export type '.length })), } as unknown as Parser, ] const petText = ['/** Generated */', '', '/**', ' * type Pet in a comment', ' */', 'export type Pet = { id: number }'].join('\n') const petFile = (path = 'src/gen/Pet.ts') => createFile({ baseName: 'Pet.ts', path, sources: [{ ...createSource({ name: 'Pet', nodes: [createText('')] }), pointer: '#/components/schemas/Pet' }], imports: [], exports: [], }) /** Runs an indexer the way a build does: the build starts, then Kubb writes each file. */ async function index( files: Array<{ file: ReturnType; source: string }>, { placeDeclarations = true, withParsers = parsers, inputFile, }: { placeDeclarations?: boolean; withParsers?: Array; inputFile?: Parameters[0]['inputFile'] } = {}, ) { const hooks = new Hookable() const indexer = createCodeIndexer({ hooks, placeDeclarations, relativePath: (root, filePath) => filePath.replace(`${root}/`, '') }) await hooks.callHook('kubb:build:start', { config: { root: '/project', parsers: withParsers } } as unknown as KubbHooks['kubb:build:start'][0]) for (const { file, source } of files) await hooks.callHook('kubb:file:processed', { file, source } as KubbHooks['kubb:file:processed'][0]) indexer.close() return indexer.build({ input, inputFile }) } const petFiles = () => [ { file: petFile('/project/src/gen/Pet.ts'), source: petText }, // A file without pointers, such as a barrel, is not indexed. { file: createFile({ baseName: 'index.ts', path: '/project/src/gen/index.ts', sources: [createSource({ nodes: [createText('')] })], imports: [], exports: [], }), source: "export * from './Pet'", }, ] describe('CodeIndexer', async () => { it('links each declaration to its file and line, and lists the schemas each key references directly', async () => { const codeIndex = await index(petFiles()) expect(codeIndex.declarations).toEqual([{ name: 'Pet', pointer: '#/components/schemas/Pet', path: 'src/gen/Pet.ts', line: 6, column: 13 }]) expect(codeIndex.operations).toEqual([ { pointer: '#/paths/~1pet~1{petId}/get', operationId: 'getPetById', method: 'GET', path: '/pet/{petId}' }, { pointer: '#/paths/~1user~1logout/get', operationId: 'logout', method: 'GET', path: '/user/logout' }, ]) // Only direct references: the operation names `Pet`, and `Pet` names `Tag`. expect(codeIndex.refs).toEqual({ '#/paths/~1pet~1{petId}/get': ['#/components/schemas/Pet'], '#/paths/~1user~1logout/get': [], '#/components/schemas/Pet': ['#/components/schemas/Tag'], '#/components/schemas/Tag': [], }) }) it('places each pointer in the input with the adapter', async () => { const text = ['components:', ' schemas:', ' Pet:', ' type: object'].join('\n') const adapter = { locate: (source: string, location: { pointer: string }) => { if (location.pointer !== '#/components/schemas/Pet') return undefined const start = source.indexOf('Pet:') return { start, end: start + 3 } }, } as unknown as Adapter const codeIndex = await index(petFiles(), { inputFile: { adapter, text, path: 'petStore.yaml' } }) expect(codeIndex.inputPositions).toEqual({ path: 'petStore.yaml', positions: { '#/components/schemas/Pet': { line: 3, column: 5 } } }) }) it('asks the adapter for a key under an operation as an operation', async () => { const file = createFile({ baseName: 'Pet.ts', path: 'src/gen/Pet.ts', sources: [ { ...createSource({ name: 'GetPetByIdPathParams', nodes: [createText('')] }), pointer: '#/paths/~1pet~1{petId}/get/parameters/0' }, { ...createSource({ name: 'Legacy', nodes: [createText('')] }), pointer: '#/definitions/Legacy' }, ], imports: [], exports: [], }) const kinds: Record = {} const adapter = { locate: (_source: string, location: { kind: string; pointer: string }) => { kinds[location.pointer] = location.kind return undefined }, } as unknown as Adapter await index([{ file, source: '' }], { inputFile: { adapter, text: '', path: 'petStore.yaml' } }) expect(kinds['#/paths/~1pet~1{petId}/get/parameters/0']).toBe('operation') expect(kinds['#/definitions/Legacy']).toBe('schema') }) it('has no input positions when the adapter cannot place pointers', async () => { const codeIndex = await index(petFiles(), { inputFile: { adapter: undefined, text: '', path: 'petStore.yaml' } }) expect(codeIndex.inputPositions).toBeUndefined() }) it('counts positions in the written text when the printed text starts with whitespace', async () => { const [declaration] = (await index([{ file: petFile(), source: '\n\nexport type Pet = number' }])).declarations // The storage writes `export type Pet = number`, so `Pet` is on line 1. expect(declaration).toMatchObject({ line: 1, column: 13 }) }) it('keeps a declaration without a position when no parser claims the file', async () => { const json = createFile({ baseName: 'pet.json', path: 'src/gen/pet.json', sources: [{ ...createSource({ name: 'Pet', nodes: [createText('')] }), pointer: '#/components/schemas/Pet' }], imports: [], exports: [], }) expect((await index([{ file: json, source: '{ "Pet": {} }' }])).declarations).toEqual([ { name: 'Pet', pointer: '#/components/schemas/Pet', path: 'src/gen/pet.json' }, ]) }) it('places no declaration when the parser of the file has no find', async () => { const { declarations } = await index(petFiles(), { withParsers: [{ extNames: ['.ts'] } as unknown as Parser] }) expect(declarations).toEqual([{ name: 'Pet', pointer: '#/components/schemas/Pet', path: 'src/gen/Pet.ts' }]) }) it('leaves out positions when the written files were rewritten after printing', async () => { expect((await index(petFiles(), { placeDeclarations: false })).declarations).toEqual([ { name: 'Pet', pointer: '#/components/schemas/Pet', path: 'src/gen/Pet.ts' }, ]) }) })