import { describe, expect, test } from 'vitest' import { extractSingleJsonSchema, v } from 'suretype' import { schemaParser } from './parser.js' import { Type } from 'typebox' describe('schemaParser', () => { test('it parses args to json-schema', async () => { let done: () => void = () => void 0 const promise = new Promise((r) => { done = r }) const args = v.object({ name: v.string(), age: v.number(), }) const result = schemaParser( { args: args, }, (errors) => { throw new Error(JSON.stringify(errors)) }, ) expect(result.jsonSchema.args).toEqual( extractSingleJsonSchema(args)?.schema, ) done() await promise await promise }) test('it parses args and generates a validator function', async () => { let done: () => void = () => void 0 const promise = new Promise((r) => { done = r }) const args = v.object({ name: v.string(), age: v.number().required(), }) const result = schemaParser( { args: args, }, (errors) => { throw new Error(JSON.stringify(errors)) }, ) expect( result.validation.args?.({ name: 'John', age: 30, })?.errors, ).toBeUndefined() expect( result.validation.args?.({ name: { name: '' }, age: 'poop', })?.errors, ).toBeDefined() expect( result.validation.args?.({ name: { name: '' }, age: 'poop', })?.errors?.length, ).toEqual(2) done() await promise }) test('it parses data to json-schema', async () => { let done: () => void = () => void 0 const promise = new Promise((r) => { done = r }) const data = v.object({ name: v.string(), age: v.number(), }) const result = schemaParser( { data: data, }, (errors) => { throw new Error(JSON.stringify(errors)) }, ) expect(result.jsonSchema.data).toEqual( extractSingleJsonSchema(data)?.schema, ) done() await promise }) test('it throws a meaningful error to the dev', async () => { schemaParser( // invalid args schema { args: { test: Type.String() } }, (errors) => { expect(errors.args).toMatch(/Error extracting json schema schema.args/) }, ) schemaParser( // invalid data schema { data: 'string value' }, (errors) => { expect(errors.data).toMatch(/Error extracting json schema schema.data/) }, ) }) test('it parses multiple schemas correct', async () => { const schema = schemaParser( { args: Type.Object({ a: Type.String() }), data: Type.Object({ b: Type.Null() }), }, (error) => { throw new Error(JSON.stringify(error)) }, ) const schema2= schemaParser( { args: Type.Object({ c: Type.String() }), data: Type.Object({ d: Type.Number() }), }, (error) => { throw new Error(JSON.stringify(error)) }, ) expect(schema.validation.args?.({}).errors?.[0]?.message).toMatch(/must have required property 'a'/) expect(schema2.validation.args?.({ c: 'test' }) ).toMatchObject({}) expect(schema.validation.args?.({}).errors?.[0]?.message).toMatch(/must have required property 'a'/) }) })