Aller au contenu principal

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