UNPKG

xsschema

Version:

extra-small, Standard Schema-based alternative to typeschema.

63 lines (57 loc) 2.99 kB
const jsonSchema = (schema) => schema; const strictJsonSchema = (schema) => ({ ...schema, additionalProperties: false, properties: schema.properties != null ? Object.fromEntries( Object.entries(schema.properties).map(([k, v]) => [ k, v != null && typeof v === "object" && "type" in v && v.type === "object" ? strictJsonSchema(v) : v ]) ) : schema.properties }); const missingDependenciesUrl = "https://xsai.js.org/docs/packages-top/xsschema#missing-dependencies"; const tryImport = async (result, name) => { try { return await result; } catch { throw new Error(`xsschema: Missing dependencies "${name}". see ${missingDependenciesUrl}`); } }; const getToJsonSchemaFn = async (vendor) => { switch (vendor) { case "arktype": return import('./arktype-C-GObzDh.js').then(async ({ getToJsonSchemaFn: getToJsonSchemaFn2 }) => getToJsonSchemaFn2()); case "effect": return import('./effect--zg3C1LQ.js').then(async ({ getToJsonSchemaFn: getToJsonSchemaFn2 }) => getToJsonSchemaFn2()); case "sury": return import('./sury-s6Akl-oc.js').then(async ({ getToJsonSchemaFn: getToJsonSchemaFn2 }) => getToJsonSchemaFn2()); case "valibot": return import('./valibot-DBCeetIe.js').then(async ({ getToJsonSchemaFn: getToJsonSchemaFn2 }) => getToJsonSchemaFn2()); case "zod": return import('./zod-Bw_60DVU.js').then(async ({ getToJsonSchemaFn: getToJsonSchemaFn2 }) => getToJsonSchemaFn2()); default: throw new Error(`xsschema: Unsupported schema vendor "${vendor}". see https://xsai.js.org/docs/packages-top/xsschema#unsupported-schema-vendor`); } }; const toJsonSchema = async (schema) => getToJsonSchemaFn(schema["~standard"].vendor).then(async (toJsonSchema2) => toJsonSchema2(schema)); const ToJsonSchemaVendors = /* @__PURE__ */ new Map(); const initToJsonSchemaSyncVendor = async (vendor) => getToJsonSchemaFn(vendor).then((fn) => ToJsonSchemaVendors.set(vendor, fn)); const toJsonSchemaSync = (schema) => { const { vendor } = schema["~standard"]; const toJsonSchema = ToJsonSchemaVendors.get(vendor); if (!toJsonSchema) throw new Error(`xsschema: Unregistered or unsupported schema vendor "${vendor}". Make sure to register the vendor using "await initToJsonSchemaSyncVendor('${vendor}')" before calling toJsonSchemaSync.`); const result = toJsonSchema(schema); if (result instanceof Promise) throw new Error("xsschema: Function returns a Promise. you need to use toJsonSchema instead of toJsonSchemaSync."); return result; }; const validate = async (schema, input) => { let result = schema["~standard"].validate(input); if (result instanceof Promise) result = await result; if (result.issues) throw new Error(JSON.stringify(result.issues, null, 2)); return result.value; }; export { toJsonSchema as a, toJsonSchemaSync as b, initToJsonSchemaSyncVendor as i, jsonSchema as j, missingDependenciesUrl as m, strictJsonSchema as s, tryImport as t, validate as v };