@magnaboy/kotlin-typescript
v0.0.1
Published
Generate kotlinx.serialization Kotlin models from Zod schemas.
Readme
@magnaboy/kotlin-typescript
Generate Kotlin models from Zod 4 schemas. Output targets kotlinx.serialization and is deterministic so generated
files can be checked in CI.
Install
npm i -D @magnaboy/kotlin-typescript zodRequires Node 25+, Zod 4, and ESM.
Generate models
import path from 'node:path';
import { z, type ZodType } from 'zod';
import {
emitEnum,
emitSchemaDataClass,
runGenerator
} from '@magnaboy/kotlin-typescript';
const ZRole = z.enum(['viewer', 'moderator']);
const ZUser = z.object({
id: z.number().int(),
display_name: z.string(),
role: ZRole
});
const named = new Map<ZodType, string>([[ZRole, 'Role']]);
runGenerator({
packageName: 'com.example.api',
sourceScript: 'scripts/generate-models.ts',
outPath: path.resolve('android/GeneratedModels.kt'),
blocks: [emitEnum('Role', ZRole), emitSchemaDataClass('User', ZUser, named)]
});Run the script with --check to verify that its output is current without writing it.
Compatibility profiles
The default behavior follows schema defaults: a required Zod collection remains a required Kotlin constructor argument. CX-style client models can instead default required collections to empty:
import { createKotlinEmitter } from '@magnaboy/kotlin-typescript';
const kotlin = createKotlinEmitter({
intType: 'Long',
numberType: 'Double',
requiredCollectionDefaults: 'empty'
});
const model = kotlin.emitSchemaDataClass('Response', schema, named);CX Live producer models can select their wire types and optional-list convention:
const kotlin = createKotlinEmitter({
producer: true,
intType: 'Int',
numberType: 'Float'
});The stateless extractFields() and emitSchemaDataClass() functions accept the same options directly. Flat unions,
sealed interfaces, serial names, inherited data classes, omitted fields, overrides, and named schema references are
also supported.
Unsupported schemas
Unnamed objects, unions, and unsupported Zod types become JsonElement by default. Set
unsupportedSchema: 'error' while defining an emitter to make those mappings fail fast. The package uses Zod's
schema definition metadata internally and is tested against Zod 4.3 and 4.4, the versions used by the CX repositories.
