Skip to main content

compile()

compile<T>(schema, options?): CompiledValidator<T>

Experimental

Compiles a schema into an optimized validator function using JIT compilation.

The JIT compiler generates JavaScript code at runtime using new Function(), which is then executed by the V8 engine with full optimization. This results in validators that are significantly faster than the interpreted V3 validators.

Performanceโ€‹

Typical performance improvements over V3 non-compiled validators:

  • Simple objects (3 props): ~1.4x faster
  • Complex objects (nested): ~4x faster
  • Large arrays (500+ items): ~4x faster
  • Unions: ~1.3-2x faster

Cachingโ€‹

Compiled validators are cached using a WeakMap keyed by schema reference. This means calling compile(schema) multiple times with the same schema returns the same compiled validator without re-compilation.


CSP Limitationsโ€‹

The JIT compiler uses new Function() which is blocked in environments with strict Content Security Policy (missing 'unsafe-eval'). In such cases, the compiler automatically falls back to the original V3 validator. Check validator.isFallback to detect this scenario.


Refinementsโ€‹

Schemas with refinements (custom validation functions) are supported but cannot be fully inlined. Refinements are called as external functions, which introduces some overhead compared to pure type validation.


Type Parametersโ€‹

T: Tโ€‹

The type that the schema validates


Parametersโ€‹

schema: Schema<T>โ€‹

The schema to compile

options?: CompileOptionsโ€‹

Compilation options


Returns: CompiledValidator<T>โ€‹

A compiled validator function


Examplesโ€‹

import { object, string, number, compile } from "@kanon";

const userSchema = object({ name: string(), age: number() });
const validate = compile(userSchema);

validate({ name: "John", age: 30 }); // true
validate({ name: 123, age: 30 }); // "Property 'name': Expected string"
const validate = compile(schema, { debug: true });
console.log(validate.source);
// Output:
// if (typeof value !== "object" || value === null) {
// return "Expected object";
// }
// var v_0 = value.name;
// if (typeof v_0 !== "string") {
// return "Property 'name': Expected string";
// }
// ...
const validate = compile(schema);
if (validate.isFallback) {
console.warn("JIT compilation not available, using V3 fallback");
}
const tagsSchema = array(string());
const validate = compile(tagsSchema);

validate(["a", "b", "c"]); // true
validate(["a", 123, "c"]); // "Index 1: Expected string"
const idSchema = unionOf(string(), number());
const validate = compile(idSchema);

validate("abc"); // true
validate(123); // true
validate(true); // "Expected string or number"

Sinceโ€‹

2.0.0

CompileOptionsโ€‹

Interface

Experimental

Options for the compile function.


Exampleโ€‹

// Default compilation (cached, no debug)
const validate = compile(schema);

// Debug mode - includes source code
const debugValidate = compile(schema, { debug: true });
console.log(debugValidate.source);

// Disable caching (useful for testing)
const uncachedValidate = compile(schema, { noCache: true });

// Force fallback (useful for testing CSP scenarios)
const fallbackValidate = compile(schema, { forceFallback: true });

Sinceโ€‹

2.0.0


Propertiesโ€‹

debug?: booleanโ€‹

Experimental

Enable debug mode to include source code in the result. When true, the compiled validator will have a source property containing the generated JavaScript code.

noCache?: booleanโ€‹

Experimental

Disable caching for this compilation. By default, compiled validators are cached using a WeakMap. Set to true to always generate a new validator.

Defaultโ€‹

false

forceFallback?: booleanโ€‹

Experimental

Force fallback to V3 validator (for testing). When true, the JIT compiler will skip compilation and return the original V3 validator with isFallback: true.

Defaultโ€‹

false

CompiledValidator()<T>โ€‹

Interface

Compiled validator with metadata.


Sinceโ€‹

2.0.0


Extendsโ€‹


Type Parametersโ€‹

T: Tโ€‹

The type being validated

CompiledValidator(value): ValidatorResult<T>

Experimental


Parametersโ€‹

value: unknownโ€‹


Returns: ValidatorResult<T>โ€‹


Propertiesโ€‹

source?: stringโ€‹

Experimental

Generated source code (only in debug mode)

isFallback?: booleanโ€‹

Experimental

Whether this is a fallback to V3 non-compiled validator

CompiledValidatorFn()<T>โ€‹

Type

CompiledValidatorFn<T> = (value) => ValidatorResult<T>

Experimental

Compiled validator function type.

A compiled validator is a function that validates a value and returns either true for valid values, a string error message for invalid values, or a coerced result object.


Type Parametersโ€‹

T: Tโ€‹

The type being validated


Parametersโ€‹

value: unknownโ€‹


Returns: ValidatorResult<T>โ€‹


Sinceโ€‹

2.0.0

isJITAvailable()โ€‹

Function

isJITAvailable(): boolean

Experimental

Checks if JIT compilation is available in the current environment.

JIT compilation requires new Function() to be available, which may be blocked by Content Security Policy (CSP) in some environments.

Use this function to check availability before deciding whether to use JIT compilation or fall back to alternative strategies.


Returns: booleanโ€‹

true if new Function() is supported, false otherwise


Exampleโ€‹

import { isJITAvailable, compile } from "@kanon";

if (isJITAvailable()) {
const validate = compile(schema);
// Use JIT-compiled validator
} else {
// Use V3 non-compiled validator
const validate = schema.validator;
}

Sinceโ€‹

2.0.0

clearCache()โ€‹

Function

clearCache(): void

Experimental

Clears the global validator cache.

The JIT compiler caches compiled validators using a WeakMap keyed by schema reference. This function clears all cached validators, forcing re-compilation on the next compile() call.

Useful for:

  • Testing scenarios where you need fresh compilations
  • Memory management in long-running applications
  • Debugging compilation issues

Returns: voidโ€‹


Exampleโ€‹

import { compile, clearCache } from "@kanon";

const validate1 = compile(schema);
const validate2 = compile(schema);
console.log(validate1 === validate2); // true (cached)

clearCache();

const validate3 = compile(schema);
console.log(validate1 === validate3); // false (re-compiled)

Sinceโ€‹

2.0.0