#validation #generate-typescript #type #type-validator

app bagsakan

A Rust-based utility to generate typescript validator functions from typescript type definitions

8 releases

0.1.9 Aug 10, 2025
0.1.8 Aug 2, 2025
0.1.6 Jul 31, 2025

#782 in Command line utilities

MIT license

84KB
1.5K SLoC

Rust 1.5K SLoC // 0.1% comments TypeScript 251 SLoC // 0.1% comments JavaScript 132 SLoC // 0.1% comments Shell 7 SLoC // 0.2% comments

bagsakan

This is a rust project to implement optimal validation functions based on TypeScript types.

It uses the very fast oxidation compile libraries which are written in rust and highly optimised to parse TypeScript files and resolve imports.

Unlike similar projects it does not require hooking into the TypeScript compiler via ts-patch.

Installation

Using npm/pnpm/yarn

# npm
npm install -D bagsakan

# pnpm
pnpm add -D bagsakan

# yarn
yarn add -D bagsakan

Manual Installation

Download the appropriate binary for your platform from the releases page.

Usage

Basic Usage

Scan for validator function calls and generate validators:

# Using npx/pnpm exec
npx bagsakan
pnpm exec bagsakan

# Or if installed globally
bagsakan

Add Command

Add a validator for a specific interface without scanning for validator calls:

# Add a validator for the User interface
bagsakan add User

# Add a validator for ProductDetails interface
bagsakan add ProductDetails

The add command will:

  • Search for the specified interface in your source files
  • Generate a validator function for it
  • Insert it into your validators file in alphabetical order
  • Preserve any existing validators in the file

This is useful when:

  • You want to add validators incrementally
  • You're adding validators for interfaces that aren't used yet
  • You want to generate validators without having to write validator function calls first

Overview

Unlike other projects that need to use a transformer via ts-patch, this code statically generates one file containing validators which can be viewed by the user and stored in the repo. The file containing the validator functions must be recreated if any interfaces are changed or new interface validators are added to the code.

This project has a toml configuration file which looks like this (the following shows the defaults):

validatorPattern = "validate%(type)"
sourceFiles = "src/**/*.ts"
validatorFile = "src/validators.ts"
useJsExtensions = false
followExternalImports = true
excludePackages = []
conditions = []

Configuration Options

  • validatorPattern: Pattern for validator function names where %(type) matches [a-z][A-Z]+ and identifies which interface is being validated
  • sourceFiles: Glob pattern for TypeScript files to scan for validator function calls
  • validatorFile: Output path for the generated validator functions
  • useJsExtensions: If true, imports in the generated file will end with .js (useful for ESM projects)
  • followExternalImports: If true, bagsakan will follow imports to external packages to find interface definitions
  • excludePackages: Array of package names to exclude when following imports (useful for resolving conflicts)
  • conditions: Export conditions to use when resolving package.json exports (e.g., ["dev"], ["production"])

How it works

  1. Uses oxc-parser to parse all TypeScript files that match sourceFiles
  2. Finds function calls that match validatorPattern where %(type) identifies the interface name
  3. Follows imports (including to external packages) to find the interface definitions
  4. Generates validator functions with runtime type checking for each interface
  5. Stores all generated functions in the validatorFile

Resolving Interface Conflicts with excludePackages

When multiple packages export interfaces with the same name, you can use excludePackages to ensure the correct interface is used:

# If both 'api-types' and 'legacy-types' packages export a 'User' interface,
# but you want to use the one from 'api-types':
excludePackages = ["legacy-types"]

This is particularly useful in monorepos or projects with multiple type packages where interface names might collide.

Example

Basic Setup

Given a TypeScript file src/api.ts:

import { User, Order } from 'shared-types'
import { Product } from '@company/product-types'

export function handleRequest(data: unknown) {
  if (!validateUser(data.user)) {
    throw new Error('Invalid user')
  }
  if (!validateOrder(data.order)) {
    throw new Error('Invalid order')
  }
  // ... handle request
}

Without a bagsakan.toml in the current directory (using default options), running bagsakan will generate src/validators.ts:

// THIS FILE IS AUTO-GENERATED BY BAGSAKAN
// DO NOT EDIT THIS FILE MANUALLY
// To regenerate, run: bagsakan

import type { Order, User } from 'shared-types'

export function validateOrder(value: unknown): value is Order {
  if (typeof value !== 'object' || value === null) {
    return false
  }

  const obj = value as Order
  // ... property validations
  return true
}

export function validateUser(value: unknown): value is User {
  if (typeof value !== 'object' || value === null) {
    return false
  }

  const obj = value as User
  // ... property validations
  return true
}

Advanced Configuration for Monorepos

For projects using export conditions and symlinked packages:

validatorPattern = "validate%(type)"
sourceFiles = "src/**/*.ts"
validatorFile = "src/validators.ts"
useJsExtensions = true
followExternalImports = true
conditions = ["dev"]  # Use 'dev' export condition from package.json
excludePackages = ["@legacy/types"]  # Exclude legacy type definitions

This configuration is useful when:

  • Your monorepo uses export conditions in package.json
  • You have multiple versions of type packages
  • You need to exclude certain packages to avoid conflicts

Dependencies

~21MB
~376K SLoC