### Install SchemaShield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Install the SchemaShield library using npm or bun. This is the first step before importing and using the SchemaShield class in your project. ```bash bun add schema-shield ``` -------------------------------- ### Quick Start: Compile and Validate JSON Schema Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Demonstrates the basic usage of SchemaShield to compile a JSON Schema and then use the compiled validator to check JSON data. It shows successful validation and an example of a validation failure. ```javascript import { SchemaShield } from "schema-shield"; const validator = new SchemaShield().compile({ type: "object", properties: { name: { type: "string" }, age: { type: "number" } } }); validator({ name: "John", age: 30 }); // { valid: true, data: { name: "John", age: 30 } } validator({ name: "John", age: "30" }); // { valid: false, error: ValidationError } ``` -------------------------------- ### Install SchemaShield Package Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md This command installs the SchemaShield package using npm. Ensure you have Node.js and npm installed on your system. ```bash npm install schema-shield ``` -------------------------------- ### Install SchemaShield using npm or bun Source: https://github.com/masquerade-circus/schema-shield/blob/main/llms.txt This snippet shows how to install the SchemaShield library using either npm or bun package managers. ```bash npm install schema-shield # or bun add schema-shield ``` -------------------------------- ### Complex Custom Keyword using Instance in SchemaShield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Provides an advanced example of adding a custom keyword to SchemaShield where the keyword's validation logic can access the entire instance being validated. ```javascript import { SchemaShield } from "schema-shield"; const schemaShield = new SchemaShield(); schemaShield.addKeyword({ keyword: "dependsOn", type: "string", validate: (schema, data, context) => { if (typeof schema !== "string") { throw new Error("Invalid schema for dependsOn keyword"); } // 'context.instance' refers to the entire object being validated return context.instance[schema] !== undefined; } }); const validator = schemaShield.compile({ type: "object", properties: { role: { type: "string", enum: ["admin", "user"] }, permissions: { type: "string", dependsOn: "role" } // permissions should exist if role is present } }); console.log(validator({ role: "admin", permissions: "read-write" })); // { valid: true, data: { role: 'admin', permissions: 'read-write' } } console.log(validator({ role: "user" })); // 'permissions' is missing, but dependsOn checks if 'role' exists, which it does. // { valid: true, data: { role: 'user' } } // Example where dependsOn might fail if the schema was different, e.g., checking for a specific value // For this specific 'dependsOn' implementation, it only checks for existence of the key named in schema. // A more complex example would involve checking the value of the depended-upon key. ``` -------------------------------- ### SchemaShield for Serverless/Edge: Compile Once Source: https://github.com/masquerade-circus/schema-shield/blob/main/llms.txt Illustrates how to use SchemaShield in serverless or edge environments by compiling the validator once at the module level for optimal performance during cold starts. It includes a handler function for Vercel Edge or Cloudflare Workers. ```javascript // Compile at module level - runs once at cold start const validateRequest = new SchemaShield().compile({ type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email" } }, required: ["name", "email"] }); // Vercel Edge / Cloudflare Worker handler export default function handler(request) { const result = validateRequest(request.body); if (!result.valid) { return new Response(JSON.stringify({ error: result.error.message }), { status: 400, headers: { "Content-Type": "application/json" } }); } return new Response(JSON.stringify(result.data), { status: 200 }); } ``` -------------------------------- ### Get Full Error Tree with getTree() Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Demonstrates how to obtain the complete error chain as a nested ErrorTree object using the `getTree()` method on a validation error. This is useful for deep inspection of validation failures. ```javascript import { SchemaShield } from "schema-shield"; const schemaShield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { description: { type: "string" }, shouldLoadDb: { type: "boolean" }, enableNetConnectFor: { type: "array", items: { type: "string" } }, params: { type: "object", additionalProperties: { type: "object", properties: { description: { type: "string" }, default: { type: "string" } }, required: ["description"] } }, run: { type: "string" } } }; const validator = schemaShield.compile(schema); const invalidData = { description: "Say hello to the bot.", shouldLoadDb: false, enableNetConnectFor: [], params: { color: { type: "string", // description: "The color of the text", // Missing description on purpose default: "red" } }, run: "run" }; const validationResult = validator(invalidData); if (validationResult.valid) { console.log("Data is valid:", validationResult.data); } else { console.error("Validation error:", validationResult.error.message); // "Property is invalid" // Get the full error chain as a tree const errorTree = validationResult.error.getTree(); console.error(errorTree); /* { message: "Property is invalid", keyword: "properties", item: "params", schemaPath: "#/properties/params", instancePath: "#/params", data: { color: { type: "string", default: "red" } }, cause: { message: "Additional properties are invalid", keyword: "additionalProperties", item: "color", schemaPath: "#/properties/params/additionalProperties", instancePath: "#/params/color", data: { type: "string", default: "red" }, cause: { message: "Required property is missing", keyword: "required", item: "description", schemaPath: "#/properties/params/additionalProperties/required", instancePath: "#/params/color/description", data: undefined } } } */ } ``` -------------------------------- ### Serverless and Edge Runtime Validation with SchemaShield in JavaScript Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Shows how to use SchemaShield in serverless and edge environments like Vercel Edge or Cloudflare Workers. Validators are compiled at module level for efficiency, and the handler function processes incoming requests, performing validation before returning a response. This approach minimizes cold start overhead and ensures CSP compliance. ```javascript import { SchemaShield } from "schema-shield"; // Compile validators at module level (runs once at cold start) const validateCreateUser = new SchemaShield().compile({ type: "object", properties: { name: { type: "string", minLength: 1, maxLength: 100 }, email: { type: "string", format: "email" }, password: { type: "string", minLength: 8 } }, required: ["name", "email", "password"], additionalProperties: false }); const validateUpdateUser = new SchemaShield().compile({ type: "object", properties: { name: { type: "string", minLength: 1, maxLength: 100 }, email: { type: "string", format: "email" } }, additionalProperties: false, minProperties: 1 }); // Vercel Edge / Cloudflare Worker handler export default async function handler(request) { const body = await request.json(); const validator = request.method === "POST" ? validateCreateUser : validateUpdateUser; const result = validator(body); if (!result.valid) { return new Response( JSON.stringify({ error: "Validation failed", details: result.error }), { status: 400, headers: { "Content-Type": "application/json" } } ); } // Process validated data return new Response( JSON.stringify({ success: true, data: result.data }), { status: 200, headers: { "Content-Type": "application/json" } } ); } export const config = { runtime: "edge" }; ``` -------------------------------- ### Custom Object Validation with SchemaShield in JavaScript Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Demonstrates how to use SchemaShield to validate custom JavaScript objects, including class instances. It shows how to add custom types and keywords to handle complex validation logic, such as checking if an employee has the required skills for a project. The example includes defining custom classes, registering them with SchemaShield, creating a custom validation keyword, compiling a schema, and performing validation. ```javascript import { SchemaShield, ValidationError } from "schema-shield"; const schemaShield = new SchemaShield({ failFast: false }); // Custom classes class Project { constructor(name, requiredSkills) { this.name = name; this.requiredSkills = requiredSkills; } } class Employee { constructor(name, skills) { this.name = name; this.skills = skills; } hasSkillsForProject(project) { return project.requiredSkills.every((skill) => this.skills.includes(skill)); } } // Add custom types to the instance schemaShield.addType("project", (data) => data instanceof Project); schemaShield.addType("employee", (data) => data instanceof Employee); schemaShield.addKeyword( "requiresQualifiedEmployee", (schema, data, defineError, instance) => { const { assignment, project, employee } = data; const stringTypeValidator = instance.getType("string"); const projectTypeValidator = instance.getType("project"); const employeeTypeValidator = instance.getType("employee"); if (!stringTypeValidator(assignment)) { return defineError("Assignment must be a string", { item: "assignment", data: assignment }); } if (!projectTypeValidator(project)) { return defineError("Project must be a Project instance", { item: "project", data: project }); } if (!employeeTypeValidator(employee)) { return defineError("Employee must be an Employee instance", { item: "employee", data: employee }); } if (schema.requiresQualifiedEmployee) { if (!employee.hasSkillsForProject(project)) { return defineError( "Employee does not meet the project's requirements", { data: { assignment, project, employee } } ); } } } ); // Create and compile the schema const schema = { type: "object", properties: { assignment: {}, // Empty schema because we will validate it with the custom keyword project: {}, // Empty schema because we will validate it with the custom keyword employee: {} // Empty schema because we will validate it with the custom keyword }, required: ["assignment", "project", "employee"], requiresQualifiedEmployee: true }; const validator = schemaShield.compile(schema); // Create some data to validate const employee1 = new Employee("Employee 1", ["A", "B", "C"]); const project1 = new Project("Project 1", ["A", "B"]); const dataToValidate = { assignment: "Assignment 1 for Project 1", project: project1, employee: employee1 }; // Validate the data const validationResult = validator(dataToValidate); if (validationResult.valid) { console.log("Assignment is valid:", validationResult.data); } else { console.error("Validation error:", validationResult.error.message); } ``` -------------------------------- ### SchemaShield Built-in Formats Validation Example (JavaScript) Source: https://context7.com/masquerade-circus/schema-shield/llms.txt This JavaScript code snippet demonstrates how to use SchemaShield to validate various built-in string formats within a JSON schema. It imports SchemaShield, creates an instance, defines a schema with properties for different formats (date, time, email, hostname, IP addresses, URIs, UUIDs, JSON Pointers, regex), and compiles the schema for validation. No external dependencies are required beyond the SchemaShield library itself. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield(); const schema = { type: "object", properties: { // Date & Time formats date: { type: "string", format: "date" }, // "2024-01-15" time: { type: "string", format: "time" }, // "14:30:00Z" dateTime: { type: "string", format: "date-time" }, // "2024-01-15T14:30:00Z" duration: { type: "string", format: "duration" }, // "P3Y6M4DT12H30M5S" // Email formats email: { type: "string", format: "email" }, // "user@example.com" idnEmail: { type: "string", format: "idn-email" }, // "user@exämple.com" // Hostname formats hostname: { type: "string", format: "hostname" }, // "example.com" idnHostname: { type: "string", format: "idn-hostname" }, // "exämple.com" // IP Address formats ipv4: { type: "string", format: "ipv4" }, // "192.168.1.1" ipv6: { type: "string", format: "ipv6" }, // "2001:0db8:85a3::8a2e:0370:7334" // Resource Identifier formats uri: { type: "string", format: "uri" }, // "https://example.com/path" uriRef: { type: "string", format: "uri-reference" },// "/path/to/resource" uriTemplate: { type: "string", format: "uri-template" }, // "/users/{id}" iri: { type: "string", format: "iri" }, // "https://exämple.com/páth" iriRef: { type: "string", format: "iri-reference" },// "/páth/to/resource" // UUID format uuid: { type: "string", format: "uuid" }, // "550e8400-e29b-41d4-a716-446655440000" // JSON Pointer formats jsonPointer: { type: "string", format: "json-pointer" }, // "/foo/bar/0" relJsonPointer: { type: "string", format: "relative-json-pointer" }, // "1/foo" // Regex format regex: { type: "string", format: "regex" } // "^[a-z]+$" } }; const validate = shield.compile(schema); ``` -------------------------------- ### CSP-Compliant Validation Example Source: https://github.com/masquerade-circus/schema-shield/blob/main/llms.txt Demonstrates how SchemaShield can be used in strict Content Security Policy (CSP) environments due to its lack of code generation. ```APIDOC ## CSP-Compliant Validation ### Description SchemaShield is designed to work in strict CSP environments because it avoids dynamic code generation like `eval()` or `new Function()`. ### Example ```javascript // No eval(), no new Function() - CSP-safe const validator = new SchemaShield().compile({ type: "object", properties: { name: { type: "string" } } }); // This works in strict CSP policies const result = validator({ name: "John" }); // result will be { valid: true, data: { name: 'John' } } ``` ``` -------------------------------- ### Get Error Paths with Schema Shield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Demonstrates how to use the getPath() method on a ValidationError object to retrieve the JSON Pointer paths to the error location in both the schema and the data. This is useful for pinpointing validation failures. ```javascript import { SchemaShield } from "schema-shield"; const schemaShield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { description: { type: "string" }, shouldLoadDb: { type: "boolean" }, enableNetConnectFor: { type: "array", items: { type: "string" } }, params: { type: "object", additionalProperties: { type: "object", properties: { description: { type: "string" }, default: { type: "string" } }, required: ["description"] } }, run: { type: "string" } } }; const validator = schemaShield.compile(schema); const invalidData = { description: "Say hello to the bot.", shouldLoadDb: false, enableNetConnectFor: [], params: { color: { type: "string", // description: "The color of the text", // Missing description on purpose default: "red" } }, run: "run" }; const validationResult = validator(invalidData); if (validationResult.valid) { console.log("Data is valid:", validationResult.data); } else { console.error("Validation error:", validationResult.error.message); // "Property is invalid" // Get the paths to the error location in the schema and in the data const errorPaths = validationResult.error.getPath(); console.error("Schema path:", errorPaths.schemaPath); // "#/properties/params/additionalProperties/required" console.error("Instance path:", errorPaths.instancePath); // "#/params/color/description" } ``` -------------------------------- ### Get Root Error Cause with getCause() Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Illustrates how to retrieve the immediate root cause of a validation error using the `getCause()` method. This method returns a ValidationError instance, providing access to its message, paths, data, schema, and keyword. ```javascript import { SchemaShield } from "schema-shield"; const schemaShield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { description: { type: "string" }, shouldLoadDb: { type: "boolean" }, enableNetConnectFor: { type: "array", items: { type: "string" } }, params: { type: "object", additionalProperties: { type: "object", properties: { description: { type: "string" }, default: { type: "string" } }, required: ["description"] } }, run: { type: "string" } } }; const validator = schemaShield.compile(schema); const invalidData = { description: "Say hello to the bot.", shouldLoadDb: false, enableNetConnectFor: [], params: { color: { type: "string", // description: "The color of the text", // Missing description on purpose default: "red" } }, run: "run" }; const validationResult = validator(invalidData); if (validationResult.valid) { console.log("Data is valid:", validationResult.data); } else { console.error("Validation error:", validationResult.error.message); // "Property is invalid" // Get the root cause of the error const errorCause = validationResult.error.getCause(); console.error("Root cause:", errorCause.message); // "Required property is missing" console.error("Schema path:", errorCause.schemaPath); // "#/properties/params/additionalProperties/required" console.error("Instance path:", errorCause.instancePath); // "#/params/color/description" console.error("Error data:", errorCause.data); // undefined console.error("Error schema:", errorCause.schema); // ["description"] console.error("Error keyword:", errorCause.keyword); // "required" } ``` -------------------------------- ### Initialize SchemaShield Class Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Demonstrates how to create a new SchemaShield instance with various configuration options. You can enable immutability or switch to detailed error reporting. ```javascript import { SchemaShield } from "schema-shield"; // Default: mutable data, fail-fast mode (lightweight error sentinel) const shield = new SchemaShield(); // Immutable mode: creates deep copy of input data before validation const immutableShield = new SchemaShield({ immutable: true }); // Detailed errors mode: returns full ValidationError instances const detailedShield = new SchemaShield({ failFast: false }); // Combined: immutable data with detailed error reporting const strictShield = new SchemaShield({ immutable: true, failFast: false }); ``` -------------------------------- ### Instantiate SchemaShield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Create an instance of the SchemaShield class. You can optionally configure it with `immutable` and `failFast` options to control validation behavior and performance. ```javascript const schemaShield = new SchemaShield(); // With options: // const schemaShield = new SchemaShield({ // immutable: true, // failFast: false // }); ``` -------------------------------- ### Getting the Full Error Tree (JavaScript) Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Shows how to obtain the complete error tree for a validation failure in SchemaShield. This provides a detailed, hierarchical view of all validation issues encountered. ```javascript console.log(JSON.stringify(result.error.getTree(), null, 2)); // { // message: "Property is invalid", // keyword: "properties", // item: "user", // schemaPath: "#/properties/user", // instancePath: "#/user", // cause: { // message: "Property is invalid", // keyword: "properties", // item: "email", // schemaPath: "#/properties/user/properties/email", // instancePath: "#/user/email", // cause: { // message: "Value does not match the format", // keyword: "format", // schemaPath: "#/properties/user/properties/email/format", // instancePath: "#/user/email" // } // } // } ``` -------------------------------- ### Run SchemaShield Tests Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Provides commands to run the tests for the SchemaShield library. These tests ensure compliance with the JSON Schema Test Suite, guaranteeing reliability and accuracy. Two commands are offered: a standard test command and one for development environments. ```bash npm test ``` ```bash npm run test:dev ``` -------------------------------- ### String Validation with SchemaShield Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Demonstrates string validation using keywords like minLength, maxLength, pattern, and format (email, uri, date, date-time, ipv4, uuid, duration). Requires the 'schema-shield' package. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { username: { type: "string", minLength: 3, maxLength: 20, pattern: "^[a-zA-Z][a-zA-Z0-9_]*$" }, email: { type: "string", format: "email" }, website: { type: "string", format: "uri" }, birthDate: { type: "string", format: "date" }, createdAt: { type: "string", format: "date-time" }, ipAddress: { type: "string", format: "ipv4" }, userId: { type: "string", format: "uuid" }, duration: { type: "string", format: "duration" } } }; const validate = shield.compile(schema); const result = validate({ username: "john_doe", email: "john@example.com", website: "https://example.com", birthDate: "1990-05-15", createdAt: "2024-01-15T10:30:00Z", ipAddress: "192.168.1.1", userId: "550e8400-e29b-41d4-a716-446655440000", duration: "P3Y6M4DT12H30M5S" }); console.log(result.valid); // true ``` -------------------------------- ### Conditional Schema Selection with if/then/else in SchemaShield Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Demonstrates how to use 'if', 'then', and 'else' keywords to conditionally apply schema rules based on data validation. This is useful for creating schemas that adapt to different data structures. Requires the 'schema-shield' library. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { type: { type: "string", enum: ["person", "company"] }, name: { type: "string" } }, required: ["type", "name"], if: { properties: { type: { const: "person" } } }, then: { properties: { firstName: { type: "string" }, lastName: { type: "string" }, age: { type: "integer", minimum: 0 } }, required: ["firstName", "lastName"] }, else: { properties: { companyName: { type: "string" }, taxId: { type: "string", pattern: "^[0-9]{9}$" } }, required: ["companyName", "taxId"] } }; const validate = shield.compile(schema); // Person type - must have firstName, lastName const person = validate({ type: "person", name: "John Doe", firstName: "John", lastName: "Doe", age: 30 }); console.log(person.valid); // true // Company type - must have companyName, taxId const company = validate({ type: "company", name: "Acme Corp", companyName: "Acme Corporation", taxId: "123456789" }); console.log(company.valid); // true ``` -------------------------------- ### Adding Custom Types to SchemaShield (JavaScript) Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Shows how to extend SchemaShield's capabilities by adding custom validation types. This example defines a 'positiveInt' type to validate that a number is an integer and greater than zero. ```javascript const shield = new SchemaShield({ failFast: false }); shield.addType("positiveInt", (value) => typeof value === "number" && Number.isInteger(value) && value > 0 ); const validator = shield.compile({ type: "object", properties: { count: { type: "positiveInt" } } }); ``` -------------------------------- ### Getting the Root Cause of a Validation Error (JavaScript) Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Demonstrates how to access the root cause of a validation error in SchemaShield. This helps in understanding the primary reason for a validation failure, especially when dealing with nested errors. ```javascript console.log(result.error.getCause().message); // "Value does not match the format" ``` -------------------------------- ### Add Custom Format to SchemaShield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Demonstrates how to add a custom format validator to SchemaShield. This involves defining a validation function and registering it with a unique name. The example shows adding an 'ssn' format to validate U.S. Social Security Numbers. ```javascript import { SchemaShield } from "schema-shield"; const schemaShield = new SchemaShield({ failFast: false }); // Custom format 'ssn' validator function const ssnValidator = (data) => { const ssnPattern = /^(?!000|.+0{4})(?:\d{9}|\d{3}-\d{2}-\d{4})$/; return typeof data === "string" && ssnPattern.test(data); }; // Adding the custom format 'ssn' schemaShield.addFormat("ssn", ssnValidator); const schema = { type: "object", properties: { name: { type: "string" }, ssn: { type: "string", format: "ssn" } } }; const validator = schemaShield.compile(schema); const validData = { name: "John Doe", ssn: "123-45-6789" }; const validationResult = validator(validData); if (validationResult.valid) { console.log("Data is valid:", validationResult.data); } else { console.error("Validation error:", validationResult.error.getCause().message); } ``` -------------------------------- ### Combinator Validation with SchemaShield (allOf, anyOf, oneOf, not) Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Shows how to use combinator keywords (allOf, anyOf, oneOf, not) for complex schema composition and boolean logic. Requires the 'schema-shield' package. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield({ failFast: false }); // allOf: must match ALL schemas const allOfSchema = { allOf: [ { type: "object", properties: { name: { type: "string" } }, required: ["name"] }, { type: "object", properties: { age: { type: "number" } }, required: ["age"] } ] }; const validateAllOf = shield.compile(allOfSchema); console.log(validateAllOf({ name: "John", age: 30 }).valid); // true console.log(validateAllOf({ name: "John" }).valid); // false // anyOf: must match AT LEAST ONE schema const anyOfSchema = { anyOf: [ { type: "string" }, { type: "number" }, { type: "null" } ] }; const validateAnyOf = shield.compile(anyOfSchema); console.log(validateAnyOf("hello").valid); // true console.log(validateAnyOf(42).valid); // true console.log(validateAnyOf(null).valid); // true console.log(validateAnyOf([]).valid); // false // oneOf: must match EXACTLY ONE schema const oneOfSchema = { oneOf: [ { type: "integer", multipleOf: 2 }, { type: "integer", multipleOf: 3 } ] }; const validateOneOf = shield.compile(oneOfSchema); console.log(validateOneOf(4).valid); // true (only multiple of 2) console.log(validateOneOf(9).valid); // true (only multiple of 3) console.log(validateOneOf(6).valid); // false (multiple of both) // not: must NOT match the schema const notSchema = { not: { type: "string" } }; const validateNot = shield.compile(notSchema); console.log(validateNot(42).valid); // true console.log(validateNot("hello").valid); // false ``` -------------------------------- ### Custom Type Validators in SchemaShield (JavaScript) Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Shows how to add custom validation types to SchemaShield, enabling checks beyond standard JSON Schema types. Examples include validating instances of JavaScript `Date` objects and custom classes. ```javascript schemaShield.addType("date-class", (data) => data instanceof Date); // or use your custom classes, functions or references class CustomDate extends Date {} schemaShield.addType("custom-date-class", (data) => data instanceof CustomDate); ``` -------------------------------- ### Number Validation with SchemaShield Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Illustrates number and integer validation using keywords like minimum, maximum, exclusiveMinimum, exclusiveMaximum, and multipleOf. Requires the 'schema-shield' package. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { age: { type: "integer", minimum: 0, maximum: 150 }, price: { type: "number", minimum: 0, exclusiveMaximum: 1000000 }, rating: { type: "number", minimum: 0, maximum: 5, multipleOf: 0.5 }, temperature: { type: "number", exclusiveMinimum: -273.15 // Absolute zero }, quantity: { type: "integer", multipleOf: 5 } } }; const validate = shield.compile(schema); const result = validate({ age: 25, price: 99.99, rating: 4.5, temperature: 20, quantity: 15 }); console.log(result.valid); // true // Invalid values console.log(validate({ age: -1 }).valid); // false console.log(validate({ rating: 4.3 }).valid); // false (not multiple of 0.5) console.log(validate({ quantity: 17 }).valid); // false (not multiple of 5) ``` -------------------------------- ### Getting Error Path with JSON Pointers (JavaScript) Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Explains how to retrieve the specific path to an error within a validated schema using JSON Pointers. This is crucial for pinpointing validation failures in complex data structures. ```javascript if (!result.valid) { console.log(result.error.getPath()); // { schemaPath: "#/properties/user/properties/email/format", // instancePath: "#/user/email" } } ``` -------------------------------- ### Basic Schema Validation with SchemaShield (JavaScript) Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Illustrates basic schema validation using SchemaShield. It shows how to compile a schema and then use the compiled validator to check data objects for validity, including handling both valid and invalid cases. ```javascript import { SchemaShield } from "schema-shield"; const validator = new SchemaShield().compile({ type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email" }, age: { type: "number", minimum: 0 } }, required: ["name", "email"] }); // Valid data validator({ name: "John", email: "john@example.com", age: 30 }); // { valid: true, data: {...} } // Invalid data validator({ name: "John", email: "invalid" }); // { valid: false, error: ValidationError } ``` -------------------------------- ### SchemaShield Interpreter Architecture Example Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Illustrates the internal compilation of a JSON schema into a flat-loop validator function. SchemaShield compiles schemas into a tree of validator functions at compile-time, resolving references once and then processing data in a non-recursive loop. ```javascript // This schema gets compiled into a function tree const schema = { type: "object", properties: { user: { type: "object", properties: { name: { type: "string" }}}) } }; // Internally becomes a flat function: function validate(data) { if (typeof data !== "object") return error; if (data.user) validate_user(data.user); } ``` -------------------------------- ### Applying Default Values in SchemaShield Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Demonstrates how SchemaShield automatically applies default values to missing required properties in the input data. This simplifies data handling by ensuring expected fields are present. Requires the 'schema-shield' library. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield(); const schema = { type: "object", properties: { name: { type: "string" }, role: { type: "string", default: "user" }, settings: { type: "object", default: { notifications: true, theme: "light" } }, tags: { type: "array", default: [] } }, required: ["name", "role", "settings", "tags"] }; const validate = shield.compile(schema); // Defaults are applied for missing required properties const result = validate({ name: "Alice" }); console.log(result.data); // { // name: "Alice", // role: "user", // settings: { notifications: true, theme: "light" }, // tags: [] // } console.log(result.valid); // true ``` -------------------------------- ### SchemaShield Performance Optimization Tips Source: https://github.com/masquerade-circus/schema-shield/blob/main/llms.txt Provides guidance on optimizing SchemaShield performance by structuring schemas with flat layouts rather than deep nesting of allOf/anyOf keywords. It contrasts a fast schema with a slower, deeply nested one. ```javascript // Best: Flat structure const fastSchema = { type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email" } } }; // Slower: Deeply nested allOf/anyOf const slowSchema = { allOf: [ { allOf: [{ allOf: [...] }]} ] }; // Better: Flatten your schema const betterSchema = { type: "object", properties: { /* ... */ } }; ``` -------------------------------- ### Basic SchemaShield Usage: Compile and Validate Source: https://github.com/masquerade-circus/schema-shield/blob/main/llms.txt Demonstrates the basic usage of SchemaShield by compiling a JSON schema and then using the compiled validator to check data. It shows the expected output for both valid and invalid data. ```javascript import { SchemaShield } from "schema-shield"; const validator = new SchemaShield().compile({ type: "object", properties: { name: { type: "string" }, email: { type: "string", format: "email" } }, required: ["name"] }); validator({ name: "John", email: "john@example.com" }); // { valid: true, data: { name: "John", email: "john@example.com" } } validator({ email: "invalid" }); // { valid: false, error: ValidationError } ``` -------------------------------- ### Schema References ($ref and $id) for Reuse in SchemaShield Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Explains how to use '$ref' for internal schema references, enabling schema reuse and recursive structures, and '$id' to define named anchors. This promotes modularity and maintainability. Requires the 'schema-shield' library. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield({ failFast: false }); // Using $ref with definitions const schema = { $id: "https://example.com/schemas/tree", type: "object", definitions: { node: { type: "object", properties: { value: { type: "string" }, children: { type: "array", items: { $ref: "#/definitions/node" } } }, required: ["value"] }, address: { type: "object", properties: { street: { type: "string" }, city: { type: "string" }, country: { type: "string" } }, required: ["street", "city"] } }, properties: { root: { $ref: "#/definitions/node" }, billingAddress: { $ref: "#/definitions/address" }, shippingAddress: { $ref: "#/definitions/address" } } }; const validate = shield.compile(schema); const result = validate({ root: { value: "root", children: [ { value: "child1", children: [] }, { value: "child2", children: [ { value: "grandchild", children: [] } ]} ] }, billingAddress: { street: "123 Main St", city: "Boston" }, shippingAddress: { street: "456 Oak Ave", city: "Cambridge" } }); console.log(result.valid); // true ``` -------------------------------- ### Enable Immutable Mode in SchemaShield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Demonstrates how to enable immutable mode when initializing SchemaShield. This mode ensures that the input data is not modified during validation by creating a deep copy. It is useful for preserving original data integrity but may have performance implications or issues with complex object cloning. ```javascript const schemaShield = new SchemaShield({ immutable: true }); ``` -------------------------------- ### Migrating Remote $ref to Local Schema Reference Source: https://github.com/masquerade-circus/schema-shield/blob/main/SKILL.md Demonstrates how to migrate from using remote HTTP/HTTPS references in JSON schemas to local, bundled references. This is a security best practice to prevent SSRF and ensure deterministic validation. ```javascript // Instead of: // { "$ref": "https://example.com/schema.json" } // Do this: // 1. Download the schema at build time // 2. Bundle it locally import localSchema from "./schemas/schema.json"; // 3. Reference it // { "$ref": "#/definitions/User" } // In the same file, define: // { "definitions": { "User": { ... } } } ``` -------------------------------- ### SchemaShield Constructor Options Source: https://github.com/masquerade-circus/schema-shield/blob/main/llms.txt Details the options available when constructing a SchemaShield instance, specifically `immutable` to prevent input data modification and `failFast` to control error reporting behavior. ```javascript new SchemaShield({ immutable?: boolean, failFast?: boolean }) ``` -------------------------------- ### Add Custom Types, Formats, and Keywords Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Extend SchemaShield's validation capabilities by adding custom types, formats, or keywords. This allows for more specific and complex validation rules tailored to your data. ```javascript schemaShield.addType("customType", (data) => { // Custom type validation logic }); schemaShield.addFormat("customFormat", (data) => { // Custom format validation logic }); schemaShield.addKeyword( "customKeyword", (schema, data, defineError, instance) => { // Custom keyword validation logic } ); ``` -------------------------------- ### Adding Custom Format Validation in SchemaShield Source: https://github.com/masquerade-circus/schema-shield/blob/main/README.md Shows how to define and add custom formats to SchemaShield, enabling validation against specific string patterns or rules beyond standard JSON Schema formats. ```javascript import { SchemaShield } from "schema-shield"; const schemaShield = new SchemaShield(); schemaShield.addFormat({ name: "custom-email", validate: (value) => /^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/.test(value) }); const validator = schemaShield.compile({ type: "object", properties: { email: { type: "string", format: "custom-email" } } }); console.log(validator({ email: "test@example.com" })); // { valid: true, data: { email: 'test@example.com' } } console.log(validator({ email: "invalid-email" })); // { valid: false, error: ValidationError } ``` -------------------------------- ### Object Validation Keywords in JavaScript with Schema Shield Source: https://context7.com/masquerade-circus/schema-shield/llms.txt Illustrates how to use various keywords for validating JSON objects, including properties, required fields, additional properties, pattern properties, property names, min/max properties, and dependencies. Supports fail-fast behavior. ```javascript import { SchemaShield } from "schema-shield"; const shield = new SchemaShield({ failFast: false }); const schema = { type: "object", properties: { id: { type: "integer" }, name: { type: "string", minLength: 1 }, email: { type: "string", format: "email" }, role: { type: "string", enum: ["admin", "user", "guest"] }, metadata: { type: "object", additionalProperties: { type: "string" } } }, required: ["id", "name", "email"], additionalProperties: false, minProperties: 3, maxProperties: 10, propertyNames: { pattern: "^[a-zA-Z_][a-zA-Z0-9_]*$" }, dependencies: { role: ["id"] // if "role" is present, "id" must also be present } }; const validate = shield.compile(schema); // Valid object const result = validate({ id: 1, name: "Alice", email: "alice@example.com", role: "admin", metadata: { key: "value" } }); console.log(result.valid); // true // Pattern properties example const patternSchema = { type: "object", patternProperties: { "^S_" : { type: "string" }, "^N_" : { type: "number" } }, additionalProperties: false }; const validatePattern = shield.compile(patternSchema); console.log(validatePattern({ S_name: "test", N_count: 42 }).valid); // true ```