/** * vapor-chamber - Standard Schema validator plugin. * * Schema-library agnostic. Works with any schema lib implementing * [Standard Schema v1](https://standardschema.dev/): Zod, Valibot, * ArkType, Effect Schema, etc. The plugin only depends on the * `~standard` interop shape - no schema lib is bundled. * * @example with Zod * import { z } from 'zod'; * import { validateSchemas } from 'vapor-chamber/standard-schema'; * * bus.use(validateSchemas({ * cartAdd: z.object({ id: z.number(), qty: z.number().min(1) }), * orderCreate: z.object({ items: z.array(z.any()).min(1) }), * })); * * @example with Valibot * import * as v from 'valibot'; * * bus.use(validateSchemas({ * cartAdd: v.object({ id: v.number(), qty: v.pipe(v.number(), v.minValue(1)) }), * })); * * @example with ArkType * import { type } from 'arktype'; * * bus.use(validateSchemas({ * cartAdd: type({ id: 'number', 'qty?': 'number>0' }), * })); * * Validation runs against `cmd.target` by default. Switch to `payload`, * `both`, or a custom selector via the `field` option. */ import type { Command, CommandResult, PluginParts } from './command-bus'; import { _report } from './report'; import { _errResult, _failures } from './command-bus'; // The plugin's own failures; its declared name is their owner (docs/contract.md 5). const schemaFail = _failures('validateSchemas'); // --------------------------------------------------------------------------- // Standard Schema v1 - minimal interop types. // We don't `import` from any schema lib; we duck-type via the `~standard` // property that all conforming libs expose. // --------------------------------------------------------------------------- export interface StandardSchemaV1 { readonly '~standard': { readonly version: 1; readonly vendor: string; readonly validate: ( value: unknown, ) => | StandardSchemaV1Result | Promise>; readonly types?: { readonly input: Input; readonly output: Output }; }; } export type StandardSchemaV1Result = | { readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray }; export interface StandardSchemaV1Issue { readonly message: string; readonly path?: ReadonlyArray; } // --------------------------------------------------------------------------- // Plugin // --------------------------------------------------------------------------- export type SchemaValidatorOptions = { /** * Which field on the Command to validate. Default: `'target'`. * - `'target'` - validate `cmd.target` * - `'payload'` - validate `cmd.payload` * - `'both'` - validate `{ target, payload }` as a single object * - `(cmd) => unknown` - extract a custom value from `cmd` */ field?: 'target' | 'payload' | 'both' | ((cmd: Command) => unknown); /** * What to do on validation failure: * - `'reject'` (default) - return `{ ok: false, error }`, a `validateSchemas:invalid:payload` BusError, * without invoking the handler * - `'warn'` - report a `validateSchemas:invalid:payload` warning and continue to the handler * * In both modes the handler gets the command as dispatched: the schema's * output (a coerced or defaulted value) is never written back * (tests/plugins-schema.test.ts). To use that output, validate before * dispatching and dispatch the output. */ onInvalid?: 'reject' | 'warn'; }; function describe(issues: ReadonlyArray): string { return issues .map((issue) => { if (!issue.path || issue.path.length === 0) return issue.message; const path = issue.path .map((p) => (typeof p === 'object' && p !== null ? String((p as { key: PropertyKey }).key) : String(p))) .join('.'); return `${path}: ${issue.message}`; }) .join('; '); } function pickValue(cmd: Command, field: SchemaValidatorOptions['field']): unknown { if (typeof field === 'function') return field(cmd); if (field === 'payload') return cmd.payload; if (field === 'both') return { target: cmd.target, payload: cmd.payload }; return cmd.target; } /** * Own entries into a Map, once at plugin creation. * * An action name is a string from outside, so looking it up on a plain object * (see ../dict) would find inherited members: for `toString` the inherited * FUNCTION is not `undefined`, and reading `fn['~standard'].validate` would * throw a TypeError out of `bus.dispatch()`, breaking the contract that * dispatch always returns a CommandResult. A Map has no chain to walk. */ function compileSchemas( schemas: Record, ): Map { return new Map(Object.entries(schemas)); } function rejectResult(action: string, message: string): CommandResult { return _errResult(schemaFail('invalid:payload', `Validation failed for "${action}": ${message}`, { action })); } /** * Sync schema validator plugin. Use with `createCommandBus()`. * * If any of your schemas are async (return a Promise from `~standard.validate`), * use {@link validateSchemasAsync} on `createAsyncCommandBus()` instead. */ export function validateSchemas( schemas: Record, options: SchemaValidatorOptions = {}, ): PluginParts { const { field = 'target', onInvalid = 'reject' } = options; const compiled = compileSchemas(schemas); return { id: 'validateSchemas', validate(action) { const schema = compiled.get(action); return schema && ((cmd) => { const result = schema['~standard'].validate(pickValue(cmd, field)); // A sync bus can't await - if a schema returns a Promise, we treat // that as a configuration error and fail the dispatch loudly. if (typeof (result as Promise).then === 'function') { return rejectResult( cmd.action, 'validateSchemas received an async schema on a sync bus. Use validateSchemasAsync on createAsyncCommandBus.', ); } return verdict(cmd.action, result as StandardSchemaV1Result, onInvalid); }); }, }; } /** * Async variant - supports schemas whose `validate` returns a Promise. * Use with `createAsyncCommandBus()`. */ export function validateSchemasAsync( schemas: Record, options: SchemaValidatorOptions = {}, ): PluginParts { const { field = 'target', onInvalid = 'reject' } = options; const compiled = compileSchemas(schemas); return { id: 'validateSchemas', validate(action) { const schema = compiled.get(action); return schema && (async (cmd) => verdict(cmd.action, await schema['~standard'].validate(pickValue(cmd, field)), onInvalid)); }, }; } /** A schema's result as the rule's answer: a refusal, a warning, or undefined. */ function verdict(action: string, r: StandardSchemaV1Result, onInvalid: SchemaValidatorOptions['onInvalid']): CommandResult | undefined { if (r.issues === undefined) return undefined; const message = describe(r.issues); if (onInvalid !== 'warn') return rejectResult(action, message); _report('warn', 'validateSchemas:invalid:payload', `Validation failed for "${action}": ${message}`, undefined, { action }); return undefined; }