由 Devika 出售

Joi is a powerful schema description language and data validator for JavaScript, enabling developers to define, validate, and sanitize complex data structures with expressive, chainable APIs.
joi is a schema description language and data validator for JavaScript and TypeScript. It provides a fluent API for defining the shape and constraints of data structures, then validating values against those schemas synchronously or asynchronously. Typical buyers are Node.js/TypeScript backend teams building APIs, CLI tools, or configuration validators.
types/ - Per-type schema implementations (string, number, boolean, array, object, date, binary, alternatives, link, symbol, function, any)annotate.js - Annotates validation error positions within complex valuesbase.js - Core Base class from which all schema types inherit; hosts all common validation methodscache.js - LRU-style validation result caching layercommon.js - Shared constants, default preferences, and utility symbolscompile.js - Compiles raw values (literals, regex, references) into schema nodeserrors.js - Error class and message formatting/renderingextend.js - Extension API for defining custom schema typesindex.d.ts - TypeScript declarations for the full public APIindex.js - Package entry point; assembles and exports the root joi objectmanifest.js - Serialises schemas to plain-object descriptions and rebuilds themmessages.js - Default and custom error message templatesmodify.js - Structural modification helpers (ID tracking for $_modify)ref.js - Reference resolution (Joi.ref, Joi.in, context/global refs)schemas.js - Internal meta-schemas for validating joi options themselvesstate.js - Tracks validation position (path, ancestors) during a passtemplate.js - Template-literal engine used inside error messagestrace.js - Optional tracing/debug instrumentationvalidator.js - Synchronous (entry) and async (entryAsync) validation runnersvalues.js - Set-like container used for allow() / valid() / invalid() value lists启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This JavaScript cli / script completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 da81226da8edf613…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
npm install @hapi/address @hapi/formula @hapi/hoek @hapi/pinpoint @hapi/tlds @hapi/topo @standard-schema/spec
No native build steps, pod installs, or binary linking required. All dependencies are pure JavaScript.
source/ directory into your project, e.g. src/vendor/joi/.// instead of: import Joi from 'joi'
import Joi from '../vendor/joi/index.js';
tsconfig.json:
{
"compilerOptions": {
"paths": {
"joi": ["./src/vendor/joi/index.d.ts"]
}
}
}
joi to ./src/vendor/joi/index.js.Buffer availability is detected at runtime; binary type is registered only when Buffer exists (Node.js and most bundlers).root (the default export from index.js)import Joi from './src/vendor/joi/index.js';
// Type factories
const schema = Joi.string().min(3).max(30).required();
const num = Joi.number().integer().min(0);
const obj = Joi.object({ name: Joi.string(), age: Joi.number() });
The root object exposes one factory method per registered type (string, number, boolean, array, object, date, binary, alternatives, link, symbol, function, any) plus aliases alt, bool, func. Call a factory with no arguments (except alternatives, link, object which accept optional arguments) to obtain a schema instance.
root.validate / schema.validateconst { error, value } = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
password: Joi.string().pattern(/^[a-zA-Z0-9]{8,30}$/).required(),
}).validate({ username: 'abc', password: 'secret99' });
if (error) throw error;
console.log(value); // { username: 'abc', password: 'secret99' }
Synchronous validation entry point (backed by validator.js entry). Returns { value, error?, warning?, artifacts? }. Use when no external async rules are present.
root.validateAsync / schema.validateAsyncconst result = await Joi.string().email().validateAsync('user@example.com', {
warnings: true,
});
console.log(result); // 'user@example.com'
Async validation entry point (backed by validator.js entryAsync). Required when the schema contains .external() rules. Throws on validation failure by default; pass { abortEarly: false } in preferences to collect all errors.
root.extendimport Joi from './src/vendor/joi/index.js';
const CustomJoi = Joi.extend((joi) => ({
type: 'positiveNumber',
base: joi.number(),
messages: { 'positiveNumber.base': '{{#label}} must be positive' },
validate(value, helpers) {
if (value <= 0) return { value, errors: helpers.error('positiveNumber.base') };
},
}));
const schema = CustomJoi.positiveNumber().required();
const { error } = schema.validate(-1);
Creates a new joi instance with additional custom types merged in. The extension descriptor matches the shape validated internally by extend.js. Does not mutate the original root.
Parse and validate a JSON body before processing. All errors are collected in one pass and returned as a 400 response.
import express, { Request, Response } from 'express';
import Joi from './src/vendor/joi/index.js';
const app = express();
app.use(express.json());
const createUserSchema = Joi.object({
username: Joi.string().alphanum().min(3).max(30).required(),
email: Joi.string().email().required(),
age: Joi.number().integer().min(0).max(120),
}).options({ abortEarly: false });
app.post('/users', (req: Request, res: Response) => {
const { error, value } = createUserSchema.validate(req.body);
if (error) {
return res.status(400).json({ errors: error.details.map(d => d.message) });
}
// value is fully typed and safe to use
res.status(201).json({ created: value.username });
});
Use .external() when validation requires a database call.
import Joi from './src/vendor/joi/index.js';
async function isUsernameAvailable(username: string): Promise<boolean> {
// simulate DB check
return username !== 'taken';
}
const schema = Joi.object({
username: Joi.string()
.min(3)
.external(async (value, helpers) => {
const available = await isUsernameAvailable(value);
if (!available) throw helpers.error('any.invalid');
return value;
}),
password: Joi.string().min(8).required(),
});
try {
const value = await schema.validateAsync({ username: 'alice', password: 'hunter22' });
console.log('Valid:', value);
} catch (err) {
console.error('Invalid:', (err as Error).message);
}
Serialise a schema to a plain object for storage or transport, then rebuild it.
import Joi from './src/vendor/joi/index.js';
const original = Joi.object({
name: Joi.string().min(1).required(),
score: Joi.number().min(0).max(100).default(0),
});
// Serialise
const description = original.describe();
console.log(JSON.stringify(description, null, 2));
// Rebuild (requires the same joi root that produced the description)
const rebuilt = Joi.build(description);
const { error, value } = rebuilt.validate({ name: 'Alice' });
console.log(value); // { name: 'Alice', score: 0 }
index.js - Assembles the root API object, registers all built-in types, applies aliases, and exports extend, compile, build, assert, attempt, ref, in, isRef, isSchema, valid, invalid, override, and defaults.index.d.ts - TypeScript ambient declarations covering all root methods, schema interfaces, and option types; import this as the type source.base.js - internals.Base class: all schema methods (validate, validateAsync, allow, valid, invalid, required, optional, default, label, rule, when, describe, etc.) live here.validator.js - Synchronous entry and async entryAsync functions that run the actual validation walk; also handles externals, warnings, artifacts, and debug output.manifest.js - describe (schema → plain object) and build (plain object → schema) for serialisation round-trips.errors.js - ValidationError class, details formatter, and message renderer using template engine.compile.js - Converts literals, arrays, regex, and references into proper schema nodes during chained calls.extend.js - Validates and merges extension descriptors into a new joi root.ref.js - Ref class and Manager; resolves Joi.ref('field'), Joi.ref('/global'), and Joi.in('list') during validation.template.js - Lightweight template engine ({#label}, {#limit}, etc.) used in error message strings.common.js - Default preference object, preferences() merge, shared symbols, and small utilities.cache.js - Optional schema-level result cache; activated via .cache() on a schema.messages.js - Default English error message templates and decompile helper for manifest.modify.js - Ids class tracks schema node IDs for structural modifications ($_modify, $_mapLabels).state.js - State class passed through the validation walk, tracking current path and ancestor values.trace.js - Optional debugging hooks; no-ops in production builds unless activated.values.js - Values set used by allow(), valid(), invalid(); handles reference members correctly.schemas.js - Internal joi schemas that validate joi's own option objects (preferences, extensions).annotate.js - Annotates a raw value object with error markers for human-readable error output.types/ - One file per type; each exports a class extending Base with type-specific rules and coercions.index.js uses require(); if your project is pure ESM, wrap with a dynamic import() or use an interop shim — do not add "type": "module" to the vendor directory.validateAsync required for external rules: calling synchronous validate() on a schema with .external() throws "Schema with external rules must use validateAsync()" — always use validateAsync in that case.abortEarly defaults to true: only the first error is returned by default; pass { abortEarly: false } to collect all errors.binary type absent in browser: the binary type is registered only when Buffer is defined; polyfill Buffer or avoid Joi.binary() in browser/edge environments.@hapi/hoek version pin: joi 18.x requires @hapi/hoek 11.x; mismatched versions cause runtime errors on assert/clone calls — check node_modules/@hapi/hoek/package.json.schema.required() modifies schema in place — always reassign: schema = schema.required().I have dropped the joi validation library source into `src/vendor/joi/` in my project.
The integration guide is in `USAGE.md` (next to this prompt).
The upstream package is `user@example.com`.
Please integrate joi into my project by:
1. Reading `USAGE.md` and `src/vendor/joi/index.js` to understand available exports.
2. Adding an alias in my bundler/tsconfig so `import Joi from 'joi'` resolves to `src/vendor/joi/index.js`.
3. Installing the required runtime dependencies listed in `USAGE.md`.
4. Creating a `src/validation/` directory with:
- `schemas.ts` — joi schemas for my existing domain types (ask me to list them).
- `middleware.ts` — an Express middleware that validates `req.body` against a passed schema.
5. Showing me how to use `validateAsync` for any schema that calls an external database check.
6. Using only exports visible in `src/vendor/joi/index.js` — do not invent API surface.
Walk me through each step with code snippets and explanations.
joi is released under the BSD-3-Clause license (see source/LICENSE if present, or the upstream repository). Upstream package: joi on npm — authored and maintained by the hapi.js team. Documentation and API reference: joi.dev.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费