Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
"homepage": "https://github.com/sinclairzx81/typebox-codegen#readme",
"devDependencies": {
"@sinclair/hammer": "^0.17.2",
"@types/inquirer": "^9.0.7",
"@types/node": "^18.15.11",
"@types/prettier": "^2.7.2"
},
Expand Down
44 changes: 39 additions & 5 deletions src/model/model-to-json-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ import * as Types from '@sinclair/typebox'
// ModelToJsonSchema
// --------------------------------------------------------------------------
export namespace ModelToJsonSchema {
interface JsonSchemaOptions {
format?: 'js' | 'json'
}

function Any(schema: Types.TAny): Types.TSchema {
return schema
}
Expand Down Expand Up @@ -155,13 +159,43 @@ export namespace ModelToJsonSchema {
if (Types.TypeGuard.IsVoid(schema)) return Void(schema)
return UnsupportedType(schema)
}
export function Generate(model: TypeBoxModel): string {
const buffer: string[] = []

interface Formatter {
push(type: Types.TSchema, schema: Types.TSchema): void
finalize(): string
}
class JsFormatter implements Formatter {
buffer: string[] = []

push(type: Types.TSchema, schema: Types.TSchema) {
const encode = JSON.stringify(schema, null, 2)
this.buffer.push(`export const ${type.$id} = ${encode}`)
}
finalize() {
return Formatter.Format(this.buffer.join('\n'))
}
}

class JsonFormatter implements Formatter {
objs: Record<string, any> = {}

push(type: Types.TSchema, schema: Types.TSchema) {
if (type.$id !== undefined) this.objs[type.$id] = schema
}
finalize(): string {
return JSON.stringify(this.objs, null, 2)
}
}

export function Generate(model: TypeBoxModel, options?: JsonSchemaOptions): string {
const format = options?.format ?? 'js'
const formatter = format === 'js' ? new JsFormatter() : new JsonFormatter()

for (const type of model.types.filter((type) => Types.TypeGuard.IsSchema(type))) {
const schema = Visit(type)
const encode = JSON.stringify(schema, null, 2)
buffer.push(`export const ${type.$id} = ${encode}`)
formatter.push(type, schema)
}
return Formatter.Format(buffer.join('\n'))

return formatter.finalize()
}
}
26 changes: 21 additions & 5 deletions src/model/model-to-valibot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ export namespace ModelToValibot {
}
function Literal(schema: Types.TLiteral) {
// prettier-ignore
return typeof schema.const === `string`
? Type(`v.literal`, `'${schema.const}'`, [])
return typeof schema.const === `string`
? Type(`v.literal`, `'${schema.const}'`, [])
: Type(`v.literal`, `${schema.const}`, [])
}
function Never(schema: Types.TNever) {
Expand All @@ -99,6 +99,21 @@ export namespace ModelToValibot {
const constraints: string[] = []
if (IsDefined<number>(schema.maxLength)) constraints.push(`v.maxLength(${schema.maxLength})`)
if (IsDefined<number>(schema.minLength)) constraints.push(`v.minLength(${schema.minLength})`)
if (IsDefined<string>(schema.format)) {
switch (schema.format) {
case 'date':
constraints.push(`v.isoDate()`)
break
case 'date-time':
constraints.push(`v.isoTimestamp()`)
break
case 'uuid':
constraints.push(`v.uuid()`)
break
default:
throw new Error(`Unsupported format: ${schema.format}`)
}
}
return Type(`v.string`, null, constraints)
}
function Number(schema: Types.TNumber) {
Expand Down Expand Up @@ -128,7 +143,8 @@ export namespace ModelToValibot {
if (key === `^(0|[1-9][0-9]*)$`) {
return UnsupportedType(schema)
} else {
return Type(`v.record`, type, [])
const keyType = key === '^(.*)$' ? Type('v.string', null, []) : Type('v.string', null, [`v.regex(/${key}/)`])
return Type(`v.record`, [keyType, type].join(', '), [])
}
}
throw Error(`Unreachable`)
Expand All @@ -146,8 +162,8 @@ export namespace ModelToValibot {
return Type(`v.tuple`, `[${items}]`, [])
}
function TemplateLiteral(schema: Types.TTemplateLiteral) {
const constaint = Type(`v.regex`, `/${schema.pattern}/`, [])
return Type(`v.string`, null, [constaint])
const constraint = Type(`v.regex`, `/${schema.pattern}/`, [])
return Type(`v.string`, null, [constraint])
}
function UInt8Array(schema: Types.TUint8Array): string {
return UnsupportedType(schema)
Expand Down