Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

fortify-schema

Nehonix-Team755GNU Affero General Public License v31.1.5TypeScript support: included

The Future of TypeScript Validation. 20+ operators, perfect type inference, and enterprise-grade performance.

schema, validation, conditional-validation, advanced-validation, typescript, type-safe, interface, runtime-validation, schema-validation, data-validation, input-validation, form-validation, api-validation, json-schema, type-inference, compile-time-safety, zod-alternative, joi-alternative, yup-alternative, ajv-alternative, typescript-first, type-checking, parse, parser, serialization, deserialization, constraints, strict-typing, runtime-types, interface-like, schema-builder, validation-library, type-validation, object-validation, array-validation, string-validation, number-validation, email-validation, url-validation, date-validation, uuid-validation, phone-validation, pattern-validation, regex-validation, union-types, literal-types, optional-fields, required-fields, nested-objects, nested-validation, conditional-logic, business-rules, dynamic-validation, context-aware, field-dependencies, schema-composition, schema-transformation, schema-merging, pick-omit, partial-required, type-coercion, loose-mode, strict-mode, error-handling, validation-errors, safe-parsing, try-catch, api-schema, rest-api, graphql, json-api, form-schema, configuration, config-validation, environment-variables, env-validation, database-schema, model-validation, dto, data-transfer-object, request-validation, response-validation, middleware, express, fastify, koa, node, nehonix, typescript, javascript, fortifyjs, nodejs, backend, frontend, fullstack, react, vue, angular, next, nuxt, svelte, web-development, developer-experience, dx, clean-code, maintainable, readable, intuitive, simple, powerful, lightweight, performant, tree-shakable, bundle-size, zero-dependencies, enterprise, production-ready, battle-tested, reliable, robust, scalable

readme

Fortify Schema

npm version TypeScript Build Status Bundle Size VS Code Extension

Fortify Schema Logo

Modern TypeScript Validation with Interface-Native Syntax

Fortify Schema brings TypeScript interface syntax to runtime validation, providing developers with a familiar and powerful way to define schemas. Built for teams who want validation that feels natural to TypeScript developers while offering advanced features like conditional validation and superior IDE integration.

Key Features

  • Interface-native syntax - Define schemas using TypeScript interface-like syntax
  • Advanced conditional validation - Express complex business logic with intuitive operators
  • Perfect TypeScript integration - Full type inference and compile-time safety
  • Enhanced VS Code support - Dedicated extension with syntax highlighting and IntelliSense
  • High performance - Optimized validation with minimal bundle impact

🚀 VS Code Extension

Enhanced development experience with syntax highlighting, autocomplete, and validation

VS Code Extension Preview

Install the VS Code Extension

Quick Installation

# Download and install the latest version
curl -L https://sdk.nehonix.space/pkgs/mods/vscode/latest/fortify-schema.vsix -o fortify-schema.vsix
code --install-extension fortify-schema.vsix

Marketplace

  • Search for "Fortify Schema" in the VS Code Extensions marketplace

Uninstalling Cleanly

  • The extension now automatically offers to clean up themes and settings when uninstalled
  • For manual cleanup, use Command Palette: Fortify: Cleanup Themes and Settings
  • Cleanup guide for existing users

Extension Features

  • 🎨 Syntax Highlighting: Beautiful syntax highlighting for conditional validation
  • 🔍 IntelliSense: Smart autocomplete for field types and constraints
  • ⚡ Real-time Validation: Instant feedback on schema syntax
  • 📖 Hover Documentation: Detailed help text for operators and syntax
  • 🔧 Error Detection: Catch syntax errors before runtime
  • 🎯 Conditional Logic Highlighting: Clear visual distinction for conditional validation syntax
  • 🚫 @fortify-ignore: Suppress validation warnings with special comments
  • 🧹 Clean Uninstall: Automatic cleanup of themes and settings

⚠️ Important: Extension Cleanup

If you've previously uninstalled the extension, you may have leftover settings in your VSCode configuration. We've fixed this issue, but existing users need to clean up manually:

Quick Cleanup (Windows)

# Download and run our cleanup script
curl -L http://sdk.nehonix.space/scripts/cleanup-vscode-simple.ps1 -o cleanup.ps1
powershell -ExecutionPolicy Bypass -File cleanup.ps1

Manual Cleanup

  1. Open VSCode settings: Ctrl+Shift+P → "Preferences: Open Settings (JSON)"
  2. Remove any lines containing fortify (case-insensitive)
  3. Save and restart VSCode

What Gets Cleaned

  • ✅ All *.fortify.* semantic token rules (18+ items)
  • fortify.colorTheme configuration setting
  • ✅ Preserves your other custom VSCode settings

Future uninstalls will be clean automatically! 🎉

Documentation

Resource Description
Complete Documentation Full documentation with organized sections
Conditional Validation Guide Comprehensive guide to conditional validation
Quick Reference Cheat sheet for common patterns
Field Types Reference Complete guide to all available types
Examples Real-world examples and use cases
Migration Guide Migration from Zod, Joi, and Yup
VSCode Cleanup Guide ⚠️ Clean up leftover extension settings

Why Choose Fortify Schema?

Interface-Native Syntax

Traditional validation libraries use method chaining, which can feel verbose and disconnected from TypeScript's type system. Fortify Schema uses syntax that mirrors TypeScript interfaces:

Traditional Approach (Zod):

import { z } from "zod";

const UserSchema = z.object({
  id: z.number().int().positive(),
  email: z.string().email(),
  name: z.string().min(2).max(50),
  age: z.number().int().min(18).max(120).optional(),
  tags: z.array(z.string()).min(1).max(10).optional(),
  status: z.enum(["active", "inactive", "pending"]),
  role: z.literal("admin"),
});

Fortify Schema Approach:

import { Interface } from "fortify-schema";

const UserSchema = Interface({
  id: "positive",
  email: "email",
  name: "string(2,50)",
  age: "int(18,120)?",
  tags: "string[](1,10)?",
  status: "active|inactive|pending",
  role: "admin",
});

Comparison with Zod

Feature Zod Fortify Schema
Syntax Style Method chaining Interface-native
Learning Curve New API to learn Familiar TypeScript syntax
Conditional Validation Complex refinements Native conditional operators
IDE Support Good Enhanced with VS Code extension
Bundle Size Established Optimized and tree-shakable
TypeScript Integration Excellent Perfect with literal types

Both libraries are excellent choices. Zod is battle-tested with a large ecosystem, while Fortify Schema offers a more TypeScript-native approach with advanced conditional validation.

Advanced Conditional Validation

Express complex business logic naturally:

const UserSchema = Interface({
  role: "admin|user|guest",
  accountType: "free|premium|enterprise",

  // Conditional validation with beautiful VS Code highlighting
  permissions: "when role=admin *? string[] : string[]?",
  maxProjects: "when accountType=free *? int(1,3) : int(1,)",
  paymentMethod: "when accountType!=free *? string : string?",

  // Multiple condition types
  seniorDiscount: "when age>=65 *? number(0,50) : number?",
  adminFeatures: "when role.in(admin,moderator) *? string[] : string[]?",
});

Perfect TypeScript Integration

const result = UserSchema.safeParse(userData);

if (result.success) {
  // Perfect type inference - no manual type definitions needed
  result.data.status; // "active" | "inactive" | "pending"
  result.data.role; // "admin"
  result.data.age; // number | undefined
}

Installation

npm install fortify-schema

VS Code Extension (Recommended):

curl -L https://sdk.nehonix.space/pkgs/mods/vscode/latest/fortify-schema.vsix -o fortify-schema.vsix
code --install-extension fortify-schema.vsix

Requirements:

  • TypeScript 4.5+
  • Node.js 14+
  • VS Code (recommended for enhanced experience)

Quick Start

Basic Schema Definition

import { Interface } from "fortify-schema";

const UserSchema = Interface({
  id: "number",
  email: "email",
  name: "string",
  age: "number?", // Optional field
  isActive: "boolean",
  tags: "string[]?", // Optional array
  status: "active|inactive|pending", // Union types
  role: "user", // Literal value
});

Data Validation

// Safe validation (recommended)
const result = UserSchema.safeParse(userData);

if (result.success) {
  console.log("✅ Valid user:", result.data);
  // result.data is perfectly typed
} else {
  console.log("❌ Validation errors:", result.errors);
}

// For unknown data sources
const unknownResult = UserSchema.safeParseUnknown(apiResponse);

Schema Transformation

import { Mod } from "fortify-schema";

// Create schema variations
const PublicUserSchema = Mod.omit(UserSchema, ["password"]);
const PartialUserSchema = Mod.partial(UserSchema);
const ExtendedSchema = Mod.extend(UserSchema, {
  createdAt: "date",
  lastLogin: "date?",
});

Core Concepts

Field Types

// Basic types
{
  name: "string",           // String validation
  age: "number",            // Number validation
  active: "boolean",        // Boolean validation
  created: "date",          // Date validation
}

// Optional fields
{
  name: "string",           // Required
  bio: "string?",           // Optional
  tags: "string[]?",        // Optional array
}

// Validation formats
{
  email: "email",           // Email format
  website: "url",           // URL format
  id: "uuid",               // UUID format
  phone: "phone",           // Phone number
}

// Arrays
{
  tags: "string[]",         // Array of strings
  scores: "number[]",       // Array of numbers
  emails: "email[]",        // Array of emails
}

Constraints

// String constraints
{
  username: "string(3,20)",        // 3-20 characters
  password: "string(8,)",          // Minimum 8 characters
  bio: "string(,500)?",            // Max 500 characters, optional
  slug: "string(/^[a-z0-9-]+$/)",  // Pattern validation
}

// Number constraints
{
  age: "number(18,120)",           // Range 18-120
  score: "number(0,100)",          // Score 0-100
  price: "number(0.01,999.99)",    // Price with precision
}

// Array constraints
{
  tags: "string[](1,10)",          // 1-10 items
  scores: "number[](3,5)",         // Exactly 3-5 items
  emails: "email[](,20)",          // Max 20 emails
}

Conditional Validation

Fortify Schema provides three approaches to conditional validation:

{
  role: "admin|user|guest",

  // Crystal clear conditional syntax
  permissions: "when role=admin *? string[] : string[]?",
  maxProjects: "when accountType=free *? int(1,3) : int(1,)",
  paymentMethod: "when accountType!=free *? string : string?",
}

2. Parentheses Syntax

{
  role: "admin|user|guest",
  permissions: "when(role=admin) then(string[]) else(string[]?)",
  maxProjects: "when(accountType=free) then(int(1,3)) else(int(1,))",
}

3. Import-based Syntax

import { When } from 'fortify-schema';

{
  role: "admin|user|guest",
  permissions: When.field("role").is("admin").then("string[]").else("string[]?"),
  maxProjects: When.field("accountType").is("free").then("int(1,3)").else("int(1,)"),
}

Condition Operators

Comparison Operators:

  • = - Equal: "when role=admin *? ..."
  • != - Not equal: "when status!=pending *? ..."
  • >, >=, <, <= - Numeric comparison: "when age>=18 *? ..."

Pattern Operators:

  • ~ - Regex match: "when email~^admin *? ..."
  • !~ - Negative regex: "when email!~@temp *? ..."

Existence Operators:

  • .exists - Field exists: "when email.exists *? ..."
  • .!exists - Field doesn't exist: "when email.!exists *? ..."

Array Operators:

  • .in(a,b,c) - Value in array: "when role.in(admin,mod) *? ..."
  • .!in(a,b,c) - Value not in array: "when role.!in(guest) *? ..."

String Operators:

  • .startsWith(value) - String starts with
  • .endsWith(value) - String ends with
  • .contains(value) - String contains
  • .!contains(value) - String doesn't contain

Advanced Features

Schema Transformation with Mod

import { Mod } from "fortify-schema";

const UserSchema = Interface({
  id: "number",
  name: "string",
  email: "email",
  password: "string",
  createdAt: "date",
});

// Transform schemas
const PublicSchema = Mod.pick(UserSchema, ["id", "name", "email"]);
const SafeSchema = Mod.omit(UserSchema, ["password"]);
const PartialSchema = Mod.partial(UserSchema);
const ExtendedSchema = Mod.extend(UserSchema, {
  lastLogin: "date?",
  isVerified: "boolean",
});

// Combine schemas
const ProfileSchema = Interface({ bio: "string?", avatar: "url?" });
const CompleteSchema = Mod.merge(UserSchema, ProfileSchema);

Validation Modes

// Strict mode (default) - exact type matching
const result = UserSchema.safeParse(data);

// Loose mode - type coercion
const looseResult = UserSchema.loose().safeParse({
  id: "123", // Converted to number
  active: "true", // Converted to boolean
});

// Strict object mode - no extra properties
const strictResult = UserSchema.strict().safeParse(data);

Advanced Type Definitions

import { Make } from 'fortify-schema';

const schema = Interface({
  // Explicit constants
  version: Make.const("1.0"),
  status: Make.const(200),

  // Union types
  priority: Make.union("low", "medium", "high"),
  role: Make.unionOptional("user", "admin", "moderator"),
});

Real-World Examples

User Management System

const UserSchema = Interface({
  // Core identification
  id: "uuid",
  email: "email",
  username: "string(3,20)",

  // Security
  password: "string(8,)",
  role: "user|moderator|admin",
  status: "active|inactive|suspended",

  // Profile information
  profile: {
    firstName: "string(1,50)",
    lastName: "string(1,50)",
    avatar: "url?",
    bio: "string(,500)?",
    dateOfBirth: "date?",
  },

  // Conditional validation
  permissions: "when role.in(admin,moderator) *? string[] : string[]?",
  maxProjects: "when role=admin *? int(1,) : int(1,10)",

  // Metadata
  createdAt: "date",
  lastLogin: "date?",
  preferences: {
    theme: "light|dark|auto",
    notifications: "boolean",
    language: "string(/^[a-z]{2}$/)",
  },
});

API Response Schema

const APIResponseSchema = Interface({
  // Response metadata
  version: "2.0",
  timestamp: "date",
  requestId: "uuid",

  // Status information
  status: "success|error|partial",
  statusCode: "number(100,599)",

  // Dynamic content
  data: "any?",
  errors: "string[]?",
  warnings: "string[]?",

  // Pagination
  pagination: {
    page: "number(1,)",
    limit: "number(1,100)",
    total: "number(0,)",
    hasMore: "boolean"
  }?,

  // Environment context
  meta: {
    environment: "development|staging|production",
    region: "string(/^[a-z]{2}-[a-z]+-\\d$/)",
    cached: "boolean?",
    ttl: "number(0,)?"
  }
});

Migration from Zod

Migrating from Zod to Fortify Schema is straightforward:

Basic Schema Migration

// Zod
const zodSchema = z.object({
  name: z.string().min(2).max(50),
  age: z.number().int().positive().optional(),
  email: z.string().email(),
  role: z.enum(["user", "admin"]),
});

// Fortify Schema
const fortifySchema = Interface({
  name: "string(2,50)",
  age: "positive?",
  email: "email",
  role: "user|admin",
});

Complex Validation Migration

// Zod with refinements
const zodSchema = z.object({
  role: z.enum(["admin", "user"]),
  permissions: z.array(z.string()).optional(),
}).refine(
  (data) => data.role === "admin" ? data.permissions !== undefined : true,
  { message: "Admin users must have permissions" }
);

// Fortify Schema with conditional validation
const fortifySchema = Interface({
  role: "admin|user",
  permissions: "when role=admin *? string[] : string[]?",
});

Key Differences

  1. Syntax: Interface-native vs method chaining
  2. Conditional Logic: Built-in vs refinements
  3. Type Inference: Literal types vs general unions
  4. IDE Support: Enhanced with VS Code extension

Performance

Bundle Size Optimization

// Import only what you need
import { Interface } from "fortify-schema"; // Core only
import { Interface, Make } from "fortify-schema"; // + Union types
import { Interface, Make, Mod } from "fortify-schema"; // + Transformations

// Tree-shakable extensions
import { When, Smart, Live } from "fortify-schema";

Validation Performance

  • Optimized algorithms for fast validation
  • Efficient parsing with detailed error messages
  • Minimal runtime overhead with type inference
  • Caching system for repeated validations

API Reference

Core Functions

// Schema creation
Interface(definition: SchemaDefinition): Schema<T>

// Type utilities
Make.const(value)                    // Literal constant
Make.union(...values)                // Union type
Make.unionOptional(...values)        // Optional union

// Schema transformation
Mod.merge(schema1, schema2)          // Combine schemas
Mod.pick(schema, keys)               // Select fields
Mod.omit(schema, keys)               // Remove fields
Mod.partial(schema)                  // Make optional
Mod.required(schema)                 // Make required
Mod.extend(schema, definition)       // Add fields

Schema Methods

schema.parse(data)                   // Parse with exceptions
schema.safeParse(data)               // Safe parse
schema.safeParseUnknown(data)        // Parse unknown data
schema.loose()                       // Enable type coercion
schema.strict()                      // Prevent extra properties

Conditional Validation

// Advanced syntax
"when condition *? then : else"

// Import-based
When.field("role").is("admin").then("string[]").else("string[]?")
When.custom((data) => data.age >= 18).then("string").else("string?")

Production Ready & Battle-Tested

Fortify Schema is production-ready with proven reliability:

  • ✅ API Stability: Guaranteed stable APIs with semantic versioning
  • ✅ Performance: 265,000+ validations/second with sub-millisecond latency
  • ✅ Real-World Usage: Production case studies from enterprise deployments
  • ✅ Quality Assurance: 95%+ test coverage with comprehensive edge case validation
  • ✅ Enterprise Support: Long-term support and migration assistance available

Ready for production? See our Production Deployment Guide.


Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

git clone https://github.com/Nehonix-Team/fortify-schema.git
cd fortify-schema
npm install
npm test
npm run build

Support


License

MIT © Nehonix Team


Built with precision and care by the Nehonix Team

changelog

Changelog

All notable changes to Fortify Schema are documented in this file, following the Keep a Changelog format and adhering to Semantic Versioning.

[Unreleased]

Added

  • Conditional Validation: Enhanced support for conditional fields with full TypeScript inference.
    • *? syntax: "when role=admin *? string[] : string[]?"
    • Parentheses syntax: "when(role=admin) then(string[]) else(string[]?)"
    • Import-based syntax: When.field("role").is("admin").then("string[]").else("string[]?")
    • Provides compile-time type checking and runtime validation.
    • Supports IDE autocompletion and error detection.
  • Schema Transformation Utilities: Introduced Mod module for schema manipulation.
    • Mod.merge(): Combine multiple schemas.
    • Mod.pick(): Select specific fields.
    • Mod.omit(): Remove specific fields.
    • Mod.partial(): Make all fields optional.
    • Mod.required(): Make all fields required.
    • Mod.extend(): Add fields to existing schemas.
  • Extension System: Added modular extensions with TypeScript support.
    • Smart: Generates schemas from sample data or types.
    • When: Supports advanced conditional validation.
    • Live: Enables real-time validation for dynamic data.
    • Docs: Generates schema documentation automatically.
    • Extensions: Provides unified access to extension features.
    • Quick: Offers shortcuts for common extension tasks.
    • TypeScriptGenerator: Creates TypeScript types from schemas.
  • Value Creation: Renamed SchemaHelpers to Make for clarity.
    • Make.const(): Defines exact constant values.
    • Make.union(): Creates union types with precise inference.
  • Strict Validation: Enabled by default for precise type enforcement.
  • Documentation: Overhauled for clarity and accessibility.

Fixed

  • Regex Pattern Validation: Resolved issue with regex pattern validation.
  • Optional Field Type Inference: Improved TypeScript inference for optional fields.
  • Constraint Parsing: Enhanced reliability of constraint parsing logic.

Changed

  • API Naming: Renamed SchemaHelpers to Make for improved developer experience.
  • Documentation Structure: Reorganized for better navigation and discoverability.
  • Type System: Strengthened type inference for seamless TypeScript integration.

Performance

  • Optimized validation performance for faster processing.
  • Maintained minimal bundle size despite new features.
  • Improved tree-shaking for better build optimization.

[1.0.0] - 2025-06-14/2025-06-13

Added

  • Interface-based Schema Definition: TypeScript-like syntax for schema creation.
  • Basic Field Types: Support for string, number, boolean, date, and array validation.
  • Format Validation: Includes email, URL, UUID, and phone number formats.
  • Constraint System: Supports length, range, and size constraints.
  • Array Validation: Validates arrays with size constraints.
  • Union Types: Allows multiple values with type safety.
  • Validation Methods: Includes parse(), safeParse(), and safeParseUnknown().
  • Error Handling: Provides detailed error messages and warnings.
  • Loose Mode: Optional type coercion for external data.
  • Documentation: Includes getting started guide and basic examples.

Features

  • TypeScript-first design with zero dependencies.
  • Small, tree-shakable bundle size.
  • Precise type inference for robust type safety.
  • Intuitive API for ease of use.

Migration Notes

From Pre-1.0 to 1.0+

For users upgrading from pre-release versions:

  1. Update Imports

    // Old
    import { Interface, SchemaHelpers } from 'fortify-schema';
    
    // New
    import { Interface, Make, Mod } from 'fortify-schema';
  2. Update Helper Usage

    // Old
    status: SchemaHelpers.union("active", "inactive"),
    role: SchemaHelpers.const("admin")
    
    // New
    status: Make.union("active", "inactive"),
    role: Make.const("admin")
  3. Use Transformation Utilities

    const PublicSchema = Mod.omit(UserSchema, ["password"]);
    const PartialSchema = Mod.partial(UserSchema);

Breaking Changes

  • Renamed SchemaHelpers to Make (use find/replace).
  • Requires TypeScript 4.5+ for enhanced type inference.
  • Default validation is stricter; use .loose() for previous behavior.

Roadmap

Upcoming Features

  • Async Validation: Support for asynchronous validation rules.
  • Internationalization: Multi-language error messages.
  • Plugin System: Extensible validation plugins.
  • Performance Monitoring: Built-in metrics for validation performance.
  • Custom Error Formatting: Flexible error message customization.

Long-term Goals

  • Runtime Schema Generation: Generate schemas from TypeScript types.
  • Advanced Introspection: Tools for schema analysis and documentation.
  • IDE Extensions: Enhanced IDE support for schema development.
  • Framework Integrations: Native support for popular frameworks.

Contributing

Contributions are welcome! See the Contributing Guide for details.

License

MIT License - see LICENSE for details.