npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@alt-stack/zod-asyncapi

v1.1.3

Published

Convert AsyncAPI schemas to Zod schemas with TypeScript code generation

Downloads

538

Readme

zod-asyncapi

Convert AsyncAPI schemas to Zod schemas with TypeScript code generation.

Features

  • Converts AsyncAPI 3.x schemas to Zod validation schemas
  • Generates TypeScript code with Zod schemas and inferred types
  • Handles complex types: objects, arrays, unions (oneOf), intersections (allOf)
  • Supports custom string formats via registry system
  • Generates Topics lookup object for easy message schema access
  • Supports nullable schemas, enums, validation constraints, and more

Installation

pnpm add @alt-stack/zod-asyncapi
# or
npm install @alt-stack/zod-asyncapi
# or
yarn add @alt-stack/zod-asyncapi

CLI Usage

Generate TypeScript types directly from the command line:

npx zod-asyncapi <input> [options]

Options

| Option | Description | |--------|-------------| | -o, --output <file> | Output file path (default: generated-types.ts) | | -r, --registry <file> | Registry file that registers custom schemas | | -i, --include <file> | TypeScript file to include at top of generated output | | -h, --help | Show help message |

Basic CLI Example

# Generate from local file
npx zod-asyncapi asyncapi.json

# Generate from URL
npx zod-asyncapi http://localhost:3000/asyncapi.json

# Specify output file
npx zod-asyncapi asyncapi.json -o src/kafka-types.ts

Custom Schemas with CLI

For custom type mappings (e.g., using Luxon DateTime for iso-date format), create a registry file and an include file:

registry.ts - Registers format-to-schema mappings:

import { z } from "zod";
import { registerZodSchemaToAsyncApiSchema } from "@alt-stack/zod-asyncapi";

// Register DateTime schema for iso-date and iso-date-time formats
const dateTimeSchema = z.string();
registerZodSchemaToAsyncApiSchema(dateTimeSchema, {
  schemaExportedVariableName: "DateTimeSchema",
  type: "string",
  formats: ["iso-date", "iso-date-time"],
});

custom-schemas.ts - Included in generated output:

import { DateTime } from "luxon";

export const DateTimeSchema = z
  .string()
  .transform((v) => DateTime.fromISO(v));

Run the CLI:

npx zod-asyncapi asyncapi.json \
  -r ./registry.ts \
  -i ./custom-schemas.ts \
  -o src/kafka-types.ts

The generated output will include your custom schemas and use DateTimeSchema for any fields with format: "iso-date" or format: "iso-date-time".

Programmatic Usage

Basic Example

import { asyncApiToZodTsCode } from "@alt-stack/zod-asyncapi";

const asyncApiSpec = {
  asyncapi: "3.0.0",
  info: { title: "My API", version: "1.0.0" },
  channels: {
    userEvents: {
      address: "user-events",
      messages: {
        UserCreated: { $ref: "#/components/messages/UserCreated" },
      },
    },
  },
  components: {
    messages: {
      UserCreated: {
        payload: { $ref: "#/components/schemas/User" },
      },
    },
    schemas: {
      User: {
        type: "object",
        properties: {
          id: { type: "string", format: "uuid" },
          name: { type: "string" },
          email: { type: "string", format: "email" },
        },
        required: ["id", "name", "email"],
      },
    },
  },
};

const generatedCode = asyncApiToZodTsCode(asyncApiSpec);
console.log(generatedCode);

Generated output:

/**
 * This file was automatically generated from AsyncAPI schema
 * Do not manually edit this file
 */

import { z } from 'zod';

// Component Schemas
export const UserSchema = z.object({
  id: z.string().uuid(),
  name: z.string(),
  email: z.string().email(),
});
export type User = z.infer<typeof UserSchema>;

// Topic Message Schemas
export const UserEventsMessageSchema = UserSchema;
export type UserEventsMessage = z.infer<typeof UserEventsMessageSchema>;

// Topics Object
export const Topics = {
  'user-events': UserEventsMessageSchema
} as const;

export type TopicName = keyof typeof Topics;
export type MessageType<T extends TopicName> = z.infer<typeof Topics[T]>;

Custom String Formats

Register custom Zod schemas for AsyncAPI string formats:

import {
  registerZodSchemaToAsyncApiSchema,
  asyncApiToZodTsCode,
} from "@alt-stack/zod-asyncapi";
import { z } from "zod";

// Register a custom UUID schema
const uuidSchema = z.string().uuid();
registerZodSchemaToAsyncApiSchema(uuidSchema, {
  schemaExportedVariableName: "uuidSchema",
  type: "string",
  format: "uuid",
});

// Now AsyncAPI schemas with format: "uuid" will use your custom schema
const asyncApiSpec = {
  asyncapi: "3.0.0",
  info: { title: "My API", version: "1.0.0" },
  components: {
    schemas: {
      Event: {
        type: "object",
        properties: {
          id: { type: "string", format: "uuid" },
        },
      },
    },
  },
};

const code = asyncApiToZodTsCode(asyncApiSpec, [
  'import { uuidSchema } from "./custom-schemas";',
]);

Supported String Formats

The following string formats are supported out of the box:

  • color-hex
  • date
  • date-time
  • email
  • iso-date
  • iso-date-time
  • objectid
  • uri
  • url
  • uuid

API Reference

asyncApiToZodTsCode(asyncapi, customImportLines?)

Converts an AsyncAPI specification to TypeScript code containing Zod schemas.

Parameters:

  • asyncapi: AsyncAPI specification object
  • customImportLines: Optional array of custom import statements to include

Returns: string - Generated TypeScript code

convertSchemaToZodString(schema)

Converts a single AsyncAPI/JSON schema to a Zod expression string.

Parameters:

  • schema: AsyncAPI schema object

Returns: string - Zod expression as a string (e.g., "z.string()")

registerZodSchemaToAsyncApiSchema(schema, registration)

Registers a Zod schema with its AsyncAPI representation for custom string formats.

Parameters:

  • schema: Zod schema instance
  • registration: Registration object describing the AsyncAPI type/format

clearZodSchemaToAsyncApiSchemaRegistry()

Clear all registered schemas in the global registry.

Supported AsyncAPI Schema Features

  • ✅ Basic types: string, number, integer, boolean
  • ✅ Objects with properties and required
  • ✅ Arrays with items
  • ✅ Unions (oneOf)
  • ✅ Intersections (allOf)
  • ✅ Nullable schemas
  • ✅ Enums
  • ✅ String formats (email, date, uuid, etc.)
  • ✅ Validation constraints (minLength, maxLength, pattern, minimum, maximum, etc.)
  • ✅ Schema references ($ref)
  • ✅ Additional properties
  • ✅ Topics lookup object for message schemas

Development

# Run tests
pnpm test

# Type check
pnpm check-types