@power-plant/schema 0.0.3 → 0.0.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/codegen.cjs +77 -1
- package/dist/codegen.mjs +78 -1
- package/dist/codegen.mjs.map +1 -0
- package/dist/{constants-u7ovYS9e.d.cts → constants-lihlIQu7.d.cts} +2 -2
- package/dist/{constants-u7ovYS9e.d.cts.map → constants-lihlIQu7.d.cts.map} +1 -1
- package/dist/{constants-u7ovYS9e.d.mts → constants-lihlIQu7.d.mts} +2 -2
- package/dist/constants-lihlIQu7.d.mts.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.d.cts +1 -1
- package/dist/constants.d.mts +1 -1
- package/dist/constants.mjs +1 -1
- package/dist/extract.cjs +1 -1
- package/dist/extract.d.cts +4 -12
- package/dist/extract.d.cts.map +1 -1
- package/dist/extract.d.mts +4 -12
- package/dist/extract.mjs +1 -1
- package/dist/helpers.cjs +1 -1
- package/dist/helpers.d.cts +8 -8
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.mts +8 -8
- package/dist/helpers.mjs +2 -1
- package/dist/helpers.mjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.mts +5 -5
- package/dist/index.mjs +1 -1
- package/dist/metadata.cjs +1 -1
- package/dist/metadata.d.cts +2 -65
- package/dist/metadata.d.cts.map +1 -1
- package/dist/metadata.d.mts +2 -65
- package/dist/metadata.mjs +2 -1
- package/dist/metadata.mjs.map +1 -0
- package/dist/type-checks.d.cts +5 -5
- package/dist/type-checks.d.cts.map +1 -1
- package/dist/type-checks.d.mts +5 -5
- package/dist/types.d.cts +12 -165
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +12 -165
- package/package.json +15 -15
- package/dist/constants-u7ovYS9e.d.mts.map +0 -1
- package/dist/metadata-CsY3HrP2.cjs +0 -77
- package/dist/metadata-DIEpQjbq.mjs +0 -78
- package/dist/metadata-DIEpQjbq.mjs.map +0 -1
package/dist/codegen.cjs
CHANGED
|
@@ -1 +1,77 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./type-checks.cjs"),t=require("./metadata.cjs"),n=require("./helpers.cjs");let r=require("@stryke/type-checks"),i=require("@stryke/type-checks/is-set-string"),a=require("@stryke/convert/to-bool"),o=require("@stryke/string-format/camel-case"),s=require("@stryke/string-format/list"),c=require("@stryke/type-checks/is-boolean"),l=require("@stryke/type-checks/is-null"),u=require("@stryke/type-checks/is-number"),d=require("@stryke/type-checks/is-undefined");function f(e,t){return(0,d.isUndefined)(e)?`undefined`:(0,l.isNull)(e)?`null`:t===`boolean`||(0,c.isBoolean)(e)?String((0,a.toBool)(e)):t===`number`||(0,u.isNumber)(e)?Number.parseFloat(String(e)).toLocaleString(void 0,{maximumFractionDigits:20}):t===`integer`?Number.parseInt(String(e)).toLocaleString():t===`string`||t===`object`||t===`array`?JSON.stringify(e):String(e)}function p(r){if(!r)return`unknown`;if(typeof r==`boolean`)return r?`unknown`:`never`;if(e.isJsonSchemaObject(r)&&(0,i.isSetString)(r.name))return r.name;let a=r;if((0,i.isSetString)(a.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(a.$ref)?.[1]??a.$ref;if(e.isJsonSchemaLiteral(r)&&!(0,d.isUndefined)(r.const))return JSON.stringify((0,i.isSetString)(r.const)?r.const.replaceAll(/^['"`]|['"`]$/g,``):r.const);let o=t.getPrimarySchemaType(r);if(o)return o===`integer`||o===`number`?`number`:o;if(a.type===`array`&&Array.isArray(a.enum))return a.enum.map(e=>JSON.stringify(e)).join(` | `);if(a.const!==void 0)return JSON.stringify(a.const);if(a.type===`array`||a.items)return`${p(Array.isArray(a.items)?a.items[0]:a.items)}[]`;if(a.type===`object`||a.properties||a.additionalProperties){if(e.isJsonSchema(a.additionalProperties))return`{ [key: string]: ${p(a.additionalProperties)} }`;if(e.isJsonSchemaObject(a)){let e=a.required??[];return`{ ${n.getPropertiesList(a).map(t=>{let r=!e.includes(t.name)||n.isSchemaNullable(t)?`${e.includes(t.name)?``:`?`}${n.isSchemaNullable(t)?` | null`:``}`:``;return`${t.name}${r}: ${p(t)}`}).join(`;
|
|
2
|
+
`)} }`}}return a.oneOf||a.anyOf?(a.oneOf??a.anyOf??[]).map(e=>p(e)).join(` | `):a.allOf?`object`:`unknown`}function m(e){return(0,l.isNull)(e)?`null`:(0,c.isBoolean)(e)?`boolean`:(0,r.isInteger)(e)?`integer`:(0,u.isNumber)(e)?`number`:(0,r.isString)(e)?`string`:(0,r.isObject)(e)?`object`:Array.isArray(e)?`array`:void 0}function h(e){return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(e)?.[1]}function g(e){let t=e.replace(/[^\w$]/gu,`_`);return`parse_${/^\d/u.test(t)?`_${t}`:t}`}function _(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function v(e,t){return`${e} + ${JSON.stringify(t)}`}function y(a,c={}){let l=a,u=typeof l==`boolean`?{}:{...l.definitions,...l.$defs},d={};function f(e){let t=d[e]??0;return d[e]=t+1,`${e}${t>0?`${t}`:``}`}function m(e,t,r,a,s=`errors`){if(typeof e==`boolean`)return e?[`${a} = ${t};`]:[`${s}.push({ path: ${r}, failure: "No value is allowed at this location" });`,`${a} = ${t};`];if((0,i.isSetString)(e.$ref)){let n=h(e.$ref);return n&&n in u?[`${a} = ${g(n)}(${t}, ${r}, ${s});`]:[`${a} = ${t};`]}let l=f(e.name?`${(0,o.camelCase)(e.name)}Value`:`value`),d=f(e.name?`${(0,o.camelCase)(e.name)}Path`:`path`),p=[`const ${l} = ${t};`,`const ${d} = ${r};`];return!c.ignoreDefaults&&e.default!==void 0?(p.push(`if (${l} === undefined${e.type===`string`?` || ${l} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${l})`:``}) {`,` ${a} = ${JSON.stringify(e.default)};`,`} else {`),n.isSchemaNullable(e)?(p.push(` if (${l} === null) {`,` ${a} = null;`,` } else {`),p.push(...y(e,l,d,a,s)),p.push(` }`)):p.push(...y(e,l,d,a,s)),p.push(`}`),p):(p.push(`if (${l} === undefined) {`,` ${s}.push({ path: ${d}, failure: "A value is required" });`,` ${a} = ${l};`,`} else {`),n.isSchemaNullable(e)?(p.push(` if (${l} === null) {`,` ${a} = null;`,` } else {`),p.push(...y(e,l,d,a,s)),p.push(` }`)):p.push(...y(e,l,d,a,s)),p.push(`}`),p)}function y(e,r,i,a,c){let l=[];if(e.const!==void 0){let t=JSON.stringify(e.const);return l.push(`if (${e.type===`string`?r:`JSON.stringify(${r})`} !== ${t}) { ${c}.push({ path: ${i}, failure: "Expected the constant value " + ${t} }); }`,`${a} = ${t};`),l}if(Array.isArray(e.enum)){let t=JSON.stringify(e.enum);return l.push(`if (!${t}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${r}))) { ${c}.push({ path: ${i}, failure: \`Expected one of: ${(0,s.list)(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${r})}\` }); }`,`${a} = ${r};`),l}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let t=e.oneOf??e.anyOf??[],n=f(e.name?`${(0,o.camelCase)(e.name)}Matched`:`matched`);l.push(`let ${n} = false;`);for(let s of t){let t=f(e.name?`${(0,o.camelCase)(e.name)}BranchErrors`:`branchErrors`),c=f(e.name?`${(0,o.camelCase)(e.name)}BranchResult`:`branchResult`);l.push(`if (!${n}) {`),l.push(` const ${t}: { path: string; failure: string }[] = [];`,` let ${c};`),l.push(...m(s,r,i,c,t)),l.push(` if (${t}.length === 0) {`,` ${a} = ${c};`,` ${n} = true;`,` }`,`}`)}return l.push(`if (!${n}) {`,` ${c}.push({ path: ${i}, failure: \`The provided value \${JSON.stringify(${r})} does not match the allowed schemas\` });`,` ${a} = ${r};`,`}`),l}if(Array.isArray(e.allOf)){let{allOf:t,...o}=e,s=n.merge(o,...t);return l.push(...m(s,r,i,a,c)),l}let u=_(e);switch(t.getPrimarySchemaType(e)??u.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:l.push(...b(e,r,i,a,c));break;case`array`:l.push(...x(e,r,i,a,c));break;case`string`:l.push(`if (typeof ${r} === "string") {`,` ${a} = ${r};`,`} else if (typeof ${r} === "number" || typeof ${r} === "boolean") {`,` ${a} = String(${r});`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a string value" });`,` ${a} = ${r};`,`}`);break;case`integer`:l.push(`if (typeof ${r} === "number" && Number.isInteger(${r})) {`,` ${a} = ${r};`,`} else if (typeof ${r} === "string" && ${r}.trim() !== "" && Number.isInteger(Number(${r}))) {`,` ${a} = Number(${r});`,`} else if (typeof ${r} === "boolean") {`,` ${a} = ${r} ? 1 : 0;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected an integer value" });`,` ${a} = ${r};`,`}`);break;case`number`:l.push(`if (typeof ${r} === "number") {`,` ${a} = ${r};`,`} else if (typeof ${r} === "string" && ${r}.trim() !== "" && !Number.isNaN(Number(${r}))) {`,` ${a} = Number(${r});`,`} else if (typeof ${r} === "boolean") {`,` ${a} = ${r} ? 1 : 0;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a number value" });`,` ${a} = ${r};`,`}`);break;case`boolean`:l.push(`if (typeof ${r} === "boolean") {`,` ${a} = ${r};`,`} else if ((typeof ${r} === "string" && (${r}.toLowerCase() === "true" || ${r}.toLowerCase() === "t" || ${r}.toLowerCase() === "yes" || ${r}.toLowerCase() === "y" || (!Number.isNaN(Number.parseInt(${r})) && Number.parseInt(${r}) > 0))) || (typeof ${r} === "number" && ${r} > 0)) {`,` ${a} = true;`,`} else if ((typeof ${r} === "string" && (${r}.toLowerCase() === "false" || ${r}.toLowerCase() === "f" || ${r}.toLowerCase() === "no" || ${r}.toLowerCase() === "n" || (!Number.isNaN(Number.parseInt(${r})) && Number.parseInt(${r}) <= 0))) || (typeof ${r} === "number" && ${r} <= 0)) {`,` ${a} = false;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a boolean value" });`,` ${a} = ${r};`,`}`);break;case`null`:l.push(`if (${r} === null) {`,` ${a} = null;`,`} else {`,` ${c}.push({ path: ${i}, failure: "Expected a null value" });`,` ${a} = ${r};`,`}`);break;case void 0:default:l.push(`${a} = ${r};`);break}return l}function b(t,i,a,s,c){let l=p(t),u=[`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) {`,` ${c}.push({ path: ${a}, failure: "Expected an object value" });`,` ${s} = ${i};`,`} else {`],d=f(l||t.name?`${(0,o.camelCase)(l||t.name)}Schema`:`schema`);if(u.push(`const ${d} = {} as Record<string, any>`),e.isJsonSchemaObject(t)){let s=new Set;for(let l of n.getPropertiesList(t)){s.add(l.name);let t;(0,r.isSetArray)(l.alias)?(t=`(${l.alias.map(e=>`${i}[${JSON.stringify(e)}]`).join(` ${e.isJsonSchemaString(l)?`||`:`??`} `)} ${e.isJsonSchemaString(l)?`||`:`??`} ${i}[${JSON.stringify(l.name)}])`,l.alias.forEach(e=>s.add(e))):t=`${i}[${JSON.stringify(l.name)}]`;let n=v(a,`.${l.name}`),p=f(l.name?`${(0,o.camelCase)(l.name)}Property`:`property`),h=l.default===void 0?l.required?`${c}.push({ path: ${n}, failure: "Required property is missing" });`:``:`${d}[${JSON.stringify(l.name)}] = ${JSON.stringify(l.default)};`;u.push(` if (${t} !== undefined) {`,` let ${p};`),u.push(...m(l,t,n,p,c)),u.push(`${d}[${JSON.stringify(l.name)}] = ${p};`),h?u.push(`} else { ${h} }`):u.push(`}`)}let p=t.additionalProperties;if(e.isJsonSchema(p)){let e=f(l||t.name?`${(0,o.camelCase)(l||t.name)}AdditionalProperties`:`additionalProperties`);u.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...s])}.includes(key)) { continue; }`,` let ${e};`),u.push(...m(p,`${i}[key]`,`${a} + "." + key`,e,c)),u.push(`${d}[key] = ${e};`,`}`)}else p!==!1&&u.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...s])}.includes(key)) { continue; }`,` ${d}[key] = ${i}[key];`,`}`)}return u.push(`${s} = ${d};`,`}`),u}function x(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],s=f(e.name?`${(0,o.camelCase)(e.name)}Array`:`array`);a.push(`const ${s}: unknown[] = [];`);let c=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(c){let o=Array.isArray(e.items)?void 0:e.items;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),c.forEach((e,t)=>{a.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),a.push(...m(e,`item`,v(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),o?(a.push(`else {`),a.push(...m(o,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${s}.push(itemResult);`,` }`,` ${r} = ${s};`,`}`),a}let l=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(...m(l,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(` ${s}.push(itemResult);`,` }`,` ${r} = ${s};`,`}`),a}return`/**
|
|
3
|
+
* Parser error constructor function.
|
|
4
|
+
*/
|
|
5
|
+
function ParserError(path, failure) {
|
|
6
|
+
this.path = path;
|
|
7
|
+
this.failure = failure;
|
|
8
|
+
this.name = "ParserError";
|
|
9
|
+
this.message = path + ": " + failure;
|
|
10
|
+
}
|
|
11
|
+
ParserError.prototype = Object.create(Error.prototype);
|
|
12
|
+
ParserError.prototype.constructor = ParserError;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Represents a parser error with path and failure message.
|
|
16
|
+
*/
|
|
17
|
+
export class ParserError extends Error {
|
|
18
|
+
constructor(
|
|
19
|
+
public path: string,
|
|
20
|
+
public failure: string
|
|
21
|
+
) {
|
|
22
|
+
super(\`\${path}: \${failure}\`);
|
|
23
|
+
this.name = "ParserError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
${Object.entries(u).map(([e,t])=>`function ${g(e)}(inputValue, inputPath, errors) {
|
|
28
|
+
let result;
|
|
29
|
+
${m(t,`inputValue`,`inputPath`,`result`,`errors`).join(`
|
|
30
|
+
`)}
|
|
31
|
+
|
|
32
|
+
return result;
|
|
33
|
+
}`).join(`
|
|
34
|
+
|
|
35
|
+
`)}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Safely parses an input value into the type described by the JSON Schema, returning an array of validation errors when the value cannot be converted into a valid result.
|
|
39
|
+
*
|
|
40
|
+
* @remarks
|
|
41
|
+
* The parser applies default values for missing properties, coerces primitive values to the declared type, and returns an array of validation errors when the value cannot be converted into a valid result.
|
|
42
|
+
*
|
|
43
|
+
* @param value - The input value to parse.
|
|
44
|
+
* @returns The parsed value conforming to the schema or an array of validation errors.
|
|
45
|
+
*/
|
|
46
|
+
export function parseSafe(inputValue) {
|
|
47
|
+
const errors = [];
|
|
48
|
+
|
|
49
|
+
let result;
|
|
50
|
+
${m(a,`inputValue`,`"$"`,`result`,`errors`).join(`
|
|
51
|
+
`)}
|
|
52
|
+
|
|
53
|
+
if (errors.length > 0) {
|
|
54
|
+
return errors;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parses an input value into the type described by the JSON Schema, throwing an error if the value cannot be converted into a valid result.
|
|
62
|
+
*
|
|
63
|
+
* @remarks
|
|
64
|
+
* The parser applies default values for missing properties, coerces primitive values to the declared type, and throws an error when the value cannot be converted into a valid result.
|
|
65
|
+
*
|
|
66
|
+
* @param value - The input value to parse.
|
|
67
|
+
* @returns The parsed value conforming to the schema.
|
|
68
|
+
* @throws {Error} When the input value cannot be parsed into a valid result according to the schema.
|
|
69
|
+
*/
|
|
70
|
+
export function parse(inputValue) {
|
|
71
|
+
const result = parseSafe(inputValue);
|
|
72
|
+
if (Array.isArray(result) && result.length > 0 && result.every(error => "path" in error && typeof error.path === "string" && error.path && "failure" in error && typeof error.failure === "string" && error.failure)) {
|
|
73
|
+
throw new Error(\`The following validation errors occurred while parsing the input value: \\n\${Object.entries(result.reduce((acc, error) => ((acc[error.path] ??= []).push(error.failure), acc), {})).map(([path, failures]) => \`\${path.replace(/^\\$\\./, "") ? \`\${path.replace(/^\\$\\./, "")}: \\n\` : ""}\${failures.map(failure => \` - \${failure}\`).join("\\n")}\`).join("\\n")}\`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return result;
|
|
77
|
+
}`}exports.generateParserCode=y,exports.getJsonSchemaType=m,exports.stringifyType=p,exports.stringifyValue=f;
|
package/dist/codegen.mjs
CHANGED
|
@@ -1 +1,78 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isJsonSchema as e,isJsonSchemaLiteral as t,isJsonSchemaObject as n,isJsonSchemaString as r}from"./type-checks.mjs";import{getPrimarySchemaType as i}from"./metadata.mjs";import{getPropertiesList as a,isSchemaNullable as o,merge as s}from"./helpers.mjs";import{isInteger as c,isObject as l,isSetArray as u,isString as d}from"@stryke/type-checks";import{isSetString as f}from"@stryke/type-checks/is-set-string";import{toBool as p}from"@stryke/convert/to-bool";import{camelCase as m}from"@stryke/string-format/camel-case";import{list as h}from"@stryke/string-format/list";import{isBoolean as g}from"@stryke/type-checks/is-boolean";import{isNull as _}from"@stryke/type-checks/is-null";import{isNumber as v}from"@stryke/type-checks/is-number";import{isUndefined as y}from"@stryke/type-checks/is-undefined";function b(e,t){return y(e)?`undefined`:_(e)?`null`:t===`boolean`||g(e)?String(p(e)):t===`number`||v(e)?Number.parseFloat(String(e)).toLocaleString(void 0,{maximumFractionDigits:20}):t===`integer`?Number.parseInt(String(e)).toLocaleString():t===`string`||t===`object`||t===`array`?JSON.stringify(e):String(e)}function x(r){if(!r)return`unknown`;if(typeof r==`boolean`)return r?`unknown`:`never`;if(n(r)&&f(r.name))return r.name;let s=r;if(f(s.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(s.$ref)?.[1]??s.$ref;if(t(r)&&!y(r.const))return JSON.stringify(f(r.const)?r.const.replaceAll(/^['"`]|['"`]$/g,``):r.const);let c=i(r);if(c)return c===`integer`||c===`number`?`number`:c;if(s.type===`array`&&Array.isArray(s.enum))return s.enum.map(e=>JSON.stringify(e)).join(` | `);if(s.const!==void 0)return JSON.stringify(s.const);if(s.type===`array`||s.items)return`${x(Array.isArray(s.items)?s.items[0]:s.items)}[]`;if(s.type===`object`||s.properties||s.additionalProperties){if(e(s.additionalProperties))return`{ [key: string]: ${x(s.additionalProperties)} }`;if(n(s)){let e=s.required??[];return`{ ${a(s).map(t=>{let n=!e.includes(t.name)||o(t)?`${e.includes(t.name)?``:`?`}${o(t)?` | null`:``}`:``;return`${t.name}${n}: ${x(t)}`}).join(`;
|
|
2
|
+
`)} }`}}return s.oneOf||s.anyOf?(s.oneOf??s.anyOf??[]).map(e=>x(e)).join(` | `):s.allOf?`object`:`unknown`}function S(e){return _(e)?`null`:g(e)?`boolean`:c(e)?`integer`:v(e)?`number`:d(e)?`string`:l(e)?`object`:Array.isArray(e)?`array`:void 0}function C(e){return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(e)?.[1]}function w(e){let t=e.replace(/[^\w$]/gu,`_`);return`parse_${/^\d/u.test(t)?`_${t}`:t}`}function T(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function E(e,t){return`${e} + ${JSON.stringify(t)}`}function D(t,c={}){let l=t,d=typeof l==`boolean`?{}:{...l.definitions,...l.$defs},p={};function g(e){let t=p[e]??0;return p[e]=t+1,`${e}${t>0?`${t}`:``}`}function _(e,t,n,r,i=`errors`){if(typeof e==`boolean`)return e?[`${r} = ${t};`]:[`${i}.push({ path: ${n}, failure: "No value is allowed at this location" });`,`${r} = ${t};`];if(f(e.$ref)){let a=C(e.$ref);return a&&a in d?[`${r} = ${w(a)}(${t}, ${n}, ${i});`]:[`${r} = ${t};`]}let a=g(e.name?`${m(e.name)}Value`:`value`),s=g(e.name?`${m(e.name)}Path`:`path`),l=[`const ${a} = ${t};`,`const ${s} = ${n};`];return!c.ignoreDefaults&&e.default!==void 0?(l.push(`if (${a} === undefined${e.type===`string`?` || ${a} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${a})`:``}) {`,` ${r} = ${JSON.stringify(e.default)};`,`} else {`),o(e)?(l.push(` if (${a} === null) {`,` ${r} = null;`,` } else {`),l.push(...v(e,a,s,r,i)),l.push(` }`)):l.push(...v(e,a,s,r,i)),l.push(`}`),l):(l.push(`if (${a} === undefined) {`,` ${i}.push({ path: ${s}, failure: "A value is required" });`,` ${r} = ${a};`,`} else {`),o(e)?(l.push(` if (${a} === null) {`,` ${r} = null;`,` } else {`),l.push(...v(e,a,s,r,i)),l.push(` }`)):l.push(...v(e,a,s,r,i)),l.push(`}`),l)}function v(e,t,n,r,a){let o=[];if(e.const!==void 0){let i=JSON.stringify(e.const);return o.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${i}) { ${a}.push({ path: ${n}, failure: "Expected the constant value " + ${i} }); }`,`${r} = ${i};`),o}if(Array.isArray(e.enum)){let i=JSON.stringify(e.enum);return o.push(`if (!${i}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${a}.push({ path: ${n}, failure: \`Expected one of: ${h(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),o}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let i=e.oneOf??e.anyOf??[],s=g(e.name?`${m(e.name)}Matched`:`matched`);o.push(`let ${s} = false;`);for(let a of i){let i=g(e.name?`${m(e.name)}BranchErrors`:`branchErrors`),c=g(e.name?`${m(e.name)}BranchResult`:`branchResult`);o.push(`if (!${s}) {`),o.push(` const ${i}: { path: string; failure: string }[] = [];`,` let ${c};`),o.push(..._(a,t,n,c,i)),o.push(` if (${i}.length === 0) {`,` ${r} = ${c};`,` ${s} = true;`,` }`,`}`)}return o.push(`if (!${s}) {`,` ${a}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),o}if(Array.isArray(e.allOf)){let{allOf:i,...c}=e,l=s(c,...i);return o.push(..._(l,t,n,r,a)),o}let c=T(e);switch(i(e)??c.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:o.push(...y(e,t,n,r,a));break;case`array`:o.push(...b(e,t,n,r,a));break;case`string`:o.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:o.push(`if (typeof ${t} === "number" && Number.isInteger(${t})) {`,` ${r} = ${t};`,`} else if (typeof ${t} === "string" && ${t}.trim() !== "" && Number.isInteger(Number(${t}))) {`,` ${r} = Number(${t});`,`} else if (typeof ${t} === "boolean") {`,` ${r} = ${t} ? 1 : 0;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:o.push(`if (typeof ${t} === "number") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "string" && ${t}.trim() !== "" && !Number.isNaN(Number(${t}))) {`,` ${r} = Number(${t});`,`} else if (typeof ${t} === "boolean") {`,` ${r} = ${t} ? 1 : 0;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:o.push(`if (typeof ${t} === "boolean") {`,` ${r} = ${t};`,`} else if ((typeof ${t} === "string" && (${t}.toLowerCase() === "true" || ${t}.toLowerCase() === "t" || ${t}.toLowerCase() === "yes" || ${t}.toLowerCase() === "y" || (!Number.isNaN(Number.parseInt(${t})) && Number.parseInt(${t}) > 0))) || (typeof ${t} === "number" && ${t} > 0)) {`,` ${r} = true;`,`} else if ((typeof ${t} === "string" && (${t}.toLowerCase() === "false" || ${t}.toLowerCase() === "f" || ${t}.toLowerCase() === "no" || ${t}.toLowerCase() === "n" || (!Number.isNaN(Number.parseInt(${t})) && Number.parseInt(${t}) <= 0))) || (typeof ${t} === "number" && ${t} <= 0)) {`,` ${r} = false;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:o.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${a}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:o.push(`${r} = ${t};`);break}return o}function y(t,i,o,s,c){let l=x(t),d=[`if (typeof ${i} !== "object" || ${i} === null || Array.isArray(${i})) {`,` ${c}.push({ path: ${o}, failure: "Expected an object value" });`,` ${s} = ${i};`,`} else {`],f=g(l||t.name?`${m(l||t.name)}Schema`:`schema`);if(d.push(`const ${f} = {} as Record<string, any>`),n(t)){let n=new Set;for(let e of a(t)){n.add(e.name);let t;u(e.alias)?(t=`(${e.alias.map(e=>`${i}[${JSON.stringify(e)}]`).join(` ${r(e)?`||`:`??`} `)} ${r(e)?`||`:`??`} ${i}[${JSON.stringify(e.name)}])`,e.alias.forEach(e=>n.add(e))):t=`${i}[${JSON.stringify(e.name)}]`;let a=E(o,`.${e.name}`),s=g(e.name?`${m(e.name)}Property`:`property`),l=e.default===void 0?e.required?`${c}.push({ path: ${a}, failure: "Required property is missing" });`:``:`${f}[${JSON.stringify(e.name)}] = ${JSON.stringify(e.default)};`;d.push(` if (${t} !== undefined) {`,` let ${s};`),d.push(..._(e,t,a,s,c)),d.push(`${f}[${JSON.stringify(e.name)}] = ${s};`),l?d.push(`} else { ${l} }`):d.push(`}`)}let s=t.additionalProperties;if(e(s)){let e=g(l||t.name?`${m(l||t.name)}AdditionalProperties`:`additionalProperties`);d.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...n])}.includes(key)) { continue; }`,` let ${e};`),d.push(..._(s,`${i}[key]`,`${o} + "." + key`,e,c)),d.push(`${f}[key] = ${e};`,`}`)}else s!==!1&&d.push(` for (const key of Object.keys(${i})) {`,` if (${JSON.stringify([...n])}.includes(key)) { continue; }`,` ${f}[key] = ${i}[key];`,`}`)}return d.push(`${s} = ${f};`,`}`),d}function b(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=g(e.name?`${m(e.name)}Array`:`array`);a.push(`const ${o}: unknown[] = [];`);let s=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(s){let c=Array.isArray(e.items)?void 0:e.items;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),s.forEach((e,t)=>{a.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),a.push(..._(e,`item`,E(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),c?(a.push(`else {`),a.push(..._(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let c=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(..._(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}return`/**
|
|
3
|
+
* Parser error constructor function.
|
|
4
|
+
*/
|
|
5
|
+
function ParserError(path, failure) {
|
|
6
|
+
this.path = path;
|
|
7
|
+
this.failure = failure;
|
|
8
|
+
this.name = "ParserError";
|
|
9
|
+
this.message = path + ": " + failure;
|
|
10
|
+
}
|
|
11
|
+
ParserError.prototype = Object.create(Error.prototype);
|
|
12
|
+
ParserError.prototype.constructor = ParserError;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Represents a parser error with path and failure message.
|
|
16
|
+
*/
|
|
17
|
+
export class ParserError extends Error {
|
|
18
|
+
constructor(
|
|
19
|
+
public path: string,
|
|
20
|
+
public failure: string
|
|
21
|
+
) {
|
|
22
|
+
super(\`\${path}: \${failure}\`);
|
|
23
|
+
this.name = "ParserError";
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
${Object.entries(d).map(([e,t])=>`function ${w(e)}(inputValue, inputPath, errors) {
|
|
28
|
+
let result;
|
|
29
|
+
${_(t,`inputValue`,`inputPath`,`result`,`errors`).join(`
|
|
30
|
+
`)}
|
|
31
|
+
|
|
32
|
+
return result;
|
|
33
|
+
}`).join(`
|
|
34
|
+
|
|
35
|
+
`)}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Safely parses an input value into the type described by the JSON Schema, returning an array of validation errors when the value cannot be converted into a valid result.
|
|
39
|
+
*
|
|
40
|
+
* @remarks
|
|
41
|
+
* The parser applies default values for missing properties, coerces primitive values to the declared type, and returns an array of validation errors when the value cannot be converted into a valid result.
|
|
42
|
+
*
|
|
43
|
+
* @param value - The input value to parse.
|
|
44
|
+
* @returns The parsed value conforming to the schema or an array of validation errors.
|
|
45
|
+
*/
|
|
46
|
+
export function parseSafe(inputValue) {
|
|
47
|
+
const errors = [];
|
|
48
|
+
|
|
49
|
+
let result;
|
|
50
|
+
${_(t,`inputValue`,`"$"`,`result`,`errors`).join(`
|
|
51
|
+
`)}
|
|
52
|
+
|
|
53
|
+
if (errors.length > 0) {
|
|
54
|
+
return errors;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return result;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Parses an input value into the type described by the JSON Schema, throwing an error if the value cannot be converted into a valid result.
|
|
62
|
+
*
|
|
63
|
+
* @remarks
|
|
64
|
+
* The parser applies default values for missing properties, coerces primitive values to the declared type, and throws an error when the value cannot be converted into a valid result.
|
|
65
|
+
*
|
|
66
|
+
* @param value - The input value to parse.
|
|
67
|
+
* @returns The parsed value conforming to the schema.
|
|
68
|
+
* @throws {Error} When the input value cannot be parsed into a valid result according to the schema.
|
|
69
|
+
*/
|
|
70
|
+
export function parse(inputValue) {
|
|
71
|
+
const result = parseSafe(inputValue);
|
|
72
|
+
if (Array.isArray(result) && result.length > 0 && result.every(error => "path" in error && typeof error.path === "string" && error.path && "failure" in error && typeof error.failure === "string" && error.failure)) {
|
|
73
|
+
throw new Error(\`The following validation errors occurred while parsing the input value: \\n\${Object.entries(result.reduce((acc, error) => ((acc[error.path] ??= []).push(error.failure), acc), {})).map(([path, failures]) => \`\${path.replace(/^\\$\\./, "") ? \`\${path.replace(/^\\$\\./, "")}: \\n\` : ""}\${failures.map(failure => \` - \${failure}\`).join("\\n")}\`).join("\\n")}\`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return result;
|
|
77
|
+
}`}export{D as generateParserCode,S as getJsonSchemaType,x as stringifyType,b as stringifyValue};
|
|
78
|
+
//# sourceMappingURL=codegen.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codegen.mjs","names":[],"sources":[],"mappings":""}
|
|
@@ -10,7 +10,7 @@ declare const JsonSchemaTypeNames: {
|
|
|
10
10
|
};
|
|
11
11
|
declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "integer", "boolean", "null"];
|
|
12
12
|
declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
|
|
13
|
-
declare const JSON_SCHEMA_METADATA_KEYS: ("$id" | "$schema" | "$vocabulary" | "$comment" | "$anchor" | "$defs" | "$dynamicRef" | "$dynamicAnchor" | "name" | "version" | "
|
|
13
|
+
declare const JSON_SCHEMA_METADATA_KEYS: ("$id" | "$schema" | "$vocabulary" | "$comment" | "$anchor" | "$defs" | "$dynamicRef" | "$dynamicAnchor" | "name" | "version" | "title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
|
|
14
14
|
/**
|
|
15
15
|
* Keywords whose values are a flat record of named JSON Schema fragments.
|
|
16
16
|
* Each child schema is merged recursively with its counterpart.
|
|
@@ -28,4 +28,4 @@ declare const SCHEMA_SINGLE_KEYWORDS: Set<string>;
|
|
|
28
28
|
declare const SCHEMA_ARRAY_CONCAT_KEYWORDS: Set<string>;
|
|
29
29
|
//#endregion
|
|
30
30
|
export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
|
|
31
|
-
//# sourceMappingURL=constants-
|
|
31
|
+
//# sourceMappingURL=constants-lihlIQu7.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants-
|
|
1
|
+
{"version":3,"file":"constants-lihlIQu7.d.cts","names":[],"sources":["../src/constants.ts"],"mappings":";cAoBa,mBAAA;EAAA;;;;;;;;cAUA,2BAAA;AAAA,cAQA,iBAAA;AAAA,cAMA,yBAAA;;;AAdb;;cA4Ca,sBAAA,EAAsB,GAAA;;AAtCzB;AAEV;;cAgDa,sBAAA,EAAsB,GAAA;;AA5CzB;AAEV;;cA2Da,4BAAA,EAA4B,GAAA"}
|
|
@@ -10,7 +10,7 @@ declare const JsonSchemaTypeNames: {
|
|
|
10
10
|
};
|
|
11
11
|
declare const JSON_SCHEMA_PRIMITIVE_TYPES: readonly ["string", "number", "integer", "boolean", "null"];
|
|
12
12
|
declare const JSON_SCHEMA_TYPES: readonly ["string", "number", "integer", "boolean", "null", "array", "object"];
|
|
13
|
-
declare const JSON_SCHEMA_METADATA_KEYS: ("$id" | "$schema" | "$vocabulary" | "$comment" | "$anchor" | "$defs" | "$dynamicRef" | "$dynamicAnchor" | "name" | "version" | "
|
|
13
|
+
declare const JSON_SCHEMA_METADATA_KEYS: ("$id" | "$schema" | "$vocabulary" | "$comment" | "$anchor" | "$defs" | "$dynamicRef" | "$dynamicAnchor" | "name" | "version" | "title" | "description" | "docs" | "examples" | "alias" | "tags" | "deprecated" | "hidden" | "ignore" | "internal" | "runtime" | "readOnly" | "writeOnly")[];
|
|
14
14
|
/**
|
|
15
15
|
* Keywords whose values are a flat record of named JSON Schema fragments.
|
|
16
16
|
* Each child schema is merged recursively with its counterpart.
|
|
@@ -28,4 +28,4 @@ declare const SCHEMA_SINGLE_KEYWORDS: Set<string>;
|
|
|
28
28
|
declare const SCHEMA_ARRAY_CONCAT_KEYWORDS: Set<string>;
|
|
29
29
|
//#endregion
|
|
30
30
|
export { SCHEMA_ARRAY_CONCAT_KEYWORDS as a, JsonSchemaTypeNames as i, JSON_SCHEMA_PRIMITIVE_TYPES as n, SCHEMA_RECORD_KEYWORDS as o, JSON_SCHEMA_TYPES as r, SCHEMA_SINGLE_KEYWORDS as s, JSON_SCHEMA_METADATA_KEYS as t };
|
|
31
|
-
//# sourceMappingURL=constants-
|
|
31
|
+
//# sourceMappingURL=constants-lihlIQu7.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants-lihlIQu7.d.mts","names":[],"sources":["../src/constants.ts"],"mappings":""}
|
package/dist/constants.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},t=[e.STRING,e.NUMBER,e.INTEGER,e.BOOLEAN,e.NULL],n=[...t,e.ARRAY,e.OBJECT],r=[`$id`,`$schema`,`$vocabulary`,`$comment`,`$anchor`,`$defs`,`$dynamicRef`,`$dynamicAnchor`,`alias`,`deprecated`,`description`,`
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},t=[e.STRING,e.NUMBER,e.INTEGER,e.BOOLEAN,e.NULL],n=[...t,e.ARRAY,e.OBJECT],r=[`$id`,`$schema`,`$vocabulary`,`$comment`,`$anchor`,`$defs`,`$dynamicRef`,`$dynamicAnchor`,`alias`,`deprecated`,`description`,`title`,`docs`,`examples`,`hidden`,`ignore`,`internal`,`name`,`readOnly`,`runtime`,`tags`,`version`,`writeOnly`],i=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`]),a=new Set([`if`,`then`,`else`,`not`,`contains`,`items`,`additionalProperties`,`unevaluatedProperties`,`propertyNames`,`unevaluatedItems`]),o=new Set([`allOf`,`anyOf`,`oneOf`]);exports.JSON_SCHEMA_METADATA_KEYS=r,exports.JSON_SCHEMA_PRIMITIVE_TYPES=t,exports.JSON_SCHEMA_TYPES=n,exports.JsonSchemaTypeNames=e,exports.SCHEMA_ARRAY_CONCAT_KEYWORDS=o,exports.SCHEMA_RECORD_KEYWORDS=i,exports.SCHEMA_SINGLE_KEYWORDS=a;
|
package/dist/constants.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-
|
|
1
|
+
import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-lihlIQu7.cjs";
|
|
2
2
|
export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS };
|
package/dist/constants.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-
|
|
1
|
+
import { a as SCHEMA_ARRAY_CONCAT_KEYWORDS, i as JsonSchemaTypeNames, n as JSON_SCHEMA_PRIMITIVE_TYPES, o as SCHEMA_RECORD_KEYWORDS, r as JSON_SCHEMA_TYPES, s as SCHEMA_SINGLE_KEYWORDS, t as JSON_SCHEMA_METADATA_KEYS } from "./constants-lihlIQu7.mjs";
|
|
2
2
|
export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS };
|
package/dist/constants.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},t=[e.STRING,e.NUMBER,e.INTEGER,e.BOOLEAN,e.NULL],n=[...t,e.ARRAY,e.OBJECT],r=[`$id`,`$schema`,`$vocabulary`,`$comment`,`$anchor`,`$defs`,`$dynamicRef`,`$dynamicAnchor`,`alias`,`deprecated`,`description`,`
|
|
1
|
+
const e={STRING:`string`,NUMBER:`number`,INTEGER:`integer`,BOOLEAN:`boolean`,NULL:`null`,OBJECT:`object`,ARRAY:`array`},t=[e.STRING,e.NUMBER,e.INTEGER,e.BOOLEAN,e.NULL],n=[...t,e.ARRAY,e.OBJECT],r=[`$id`,`$schema`,`$vocabulary`,`$comment`,`$anchor`,`$defs`,`$dynamicRef`,`$dynamicAnchor`,`alias`,`deprecated`,`description`,`title`,`docs`,`examples`,`hidden`,`ignore`,`internal`,`name`,`readOnly`,`runtime`,`tags`,`version`,`writeOnly`],i=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`]),a=new Set([`if`,`then`,`else`,`not`,`contains`,`items`,`additionalProperties`,`unevaluatedProperties`,`propertyNames`,`unevaluatedItems`]),o=new Set([`allOf`,`anyOf`,`oneOf`]);export{r as JSON_SCHEMA_METADATA_KEYS,t as JSON_SCHEMA_PRIMITIVE_TYPES,n as JSON_SCHEMA_TYPES,e as JsonSchemaTypeNames,o as SCHEMA_ARRAY_CONCAT_KEYWORDS,i as SCHEMA_RECORD_KEYWORDS,a as SCHEMA_SINGLE_KEYWORDS};
|
|
2
2
|
//# sourceMappingURL=constants.mjs.map
|
package/dist/extract.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./metadata-CsY3HrP2.cjs"),t=require("./type-checks.cjs");let n=require("@stryke/type-checks"),r=require("@stryke/type-checks/is-set-object"),i=require("@stryke/string-format/list"),a=require("@stryke/path/find"),o=require("@stryke/resolve/constants"),s=require("@stryke/convert/extract-file-reference"),c=require("@stryke/hash"),l=require("@stryke/helpers/deep-clone"),u=require("@stryke/json"),d=require("@stryke/resolve/load"),f=require("@stryke/zod"),p=require("@valibot/to-json-schema"),m=require("ts-json-schema-generator/dist/factory/generator.js");const h=`https://power-plant.invalid/`;function g(e){return!(0,r.isSetObject)(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e?!1:Object.keys(e).every(e=>e===`schema`||e===`meta`)}function _(e){return g(e)?{input:e.schema,meta:(0,n.isSetString)(e.meta)?{description:e.meta}:e.meta}:{input:e}}function v(e){return e.endsWith(`#`)?e.slice(0,-1):e}function y(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function b(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function x(e){return e.length===0?``:`/${e.map(e=>b(e)).join(`/`)}`}function S(e,t){try{return v(new URL(e,t).toString())}catch{return v(e)}}function C(e,t,i,a,o){if(!(0,r.isSetObject)(e))return;let s=e,c=x(t),l=(0,n.isSetString)(s.$id)?S(s.$id,i):i,u=y(l);if(a.set(l,c),a.set(u,c),(0,n.isSetString)(s.$anchor)&&a.set(`${u}#${s.$anchor}`,c),(0,n.isSetString)(s.$dynamicAnchor)){let e=`${u}#${s.$dynamicAnchor}`;a.set(e,c),o.set(e,`#${s.$dynamicAnchor}`)}for(let[e,n]of Object.entries(s)){if(Array.isArray(n)){n.forEach((n,r)=>{C(n,[...t,e,String(r)],l,a,o)});continue}C(n,[...t,e],l,a,o)}}function w(e,t,i,a,o){if(!(0,r.isSetObject)(e))return;let s=e,c=(0,n.isSetString)(s.$id)?S(s.$id,i):i;if((0,n.isSetString)(s.$ref)){let e=S(s.$ref,c),t=a.get(e)??a.get(y(e));t!==void 0&&(s.$ref=t.length>0?`#${t}`:`#`)}if((0,n.isSetString)(s.$dynamicRef)){let e=S(s.$dynamicRef,c),t=o.get(e);if(t)s.$dynamicRef=t;else{let t=a.get(e)??a.get(y(e));t!==void 0&&(s.$dynamicRef=t.length>0?`#${t}`:`#`)}}for(let[e,n]of Object.entries(s)){if(Array.isArray(n)){n.forEach((n,r)=>{w(n,[...t,e,String(r)],c,a,o)});continue}w(n,[...t,e],c,a,o)}}function T(e){if(!(0,r.isSetObject)(e))return e;let t=(0,l.deepClone)(e),i=(0,n.isSetString)(t.$id)?S(t.$id,h):h,a=new Map,o=new Map;return C(t,[],i,a,o),w(t,[],i,a,o),t}function E(e){if(t.isUntypedSchema(e))return k(e);if((0,r.isSetObject)(e)){if(t.isUntypedInput(e))return A(e);let n=e;if(`$schema`in n&&t.isUntypedSchema(n.$schema))return k(n.$schema)}return e}function D(e){return Array.isArray(e)?e.map(e=>E(e)):e}function O(e){return(0,p.toJsonSchema)(e,{target:`draft-2020-12`})}function k(e){let t=e,i={};for(let[e,a]of Object.entries(t))if(!(e===`tsType`||e===`markdownType`||e===`tags`||e===`args`||e===`resolve`)){if(e===`id`&&(0,n.isSetString)(a)){i.$id=a;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!(0,r.isSetObject)(a)){i[e]=a;continue}i[e]=Object.fromEntries(Object.entries(a).map(([e,t])=>[e,E(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){i[e]=E(a);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){i[e]=D(a);continue}i[e]=a}return i}function A(e){let n=e,i=t.isUntypedSchema(n.$schema)?k(n.$schema):{},a={};for(let[e,i]of Object.entries(n)){if(e.startsWith(`$`)||!(0,r.isSetObject)(i))continue;if(t.isUntypedInput(i)){a[e]=A(i);continue}let n=i;if(`$schema`in n&&t.isUntypedSchema(n.$schema)){a[e]=k(n.$schema);continue}t.isUntypedSchema(i)&&(a[e]=k(i))}if(!t.isJsonSchemaObject(i))throw Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);let o={...(0,r.isSetObject)(i.properties)?i.properties:{},...a};return{...i,type:i.type??`object`,...Object.keys(o).length>0?{properties:o}:{}}}function j(e,i){let{input:a}=_(i);if(t.isSchemaWithSource(a)||t.isSchema(a))return(0,c.murmurhash)({variant:e,input:a.schema});if((0,n.isSetString)(a)||typeof a==`boolean`)return(0,c.murmurhash)({variant:e,input:a});if((0,r.isSetObject)(a)){if((0,f.isZod3Type)(a))return(0,c.murmurhash)({variant:e,input:a._def});if((0,u.isStandardJsonSchema)(a))return(0,c.murmurhash)({variant:e,input:a[`~standard`]});if(t.isJsonSchema(a))return(0,c.murmurhash)({variant:e,input:a});if(t.isValibotSchema(a))return(0,c.murmurhash)({variant:e,input:O(a)});if(t.isUntypedInput(a))return(0,c.murmurhash)({variant:e,input:A(a)});if(t.isUntypedSchema(a))return(0,c.murmurhash)({variant:e,input:k(a)})}throw Error(`Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, or a reflected Deepkit Type object.`)}function M(e){if((0,r.isSetObject)(e)){if((0,f.isZod3Type)(e))return(0,f.extractJsonSchema)(e,{target:`draft-2020-12`});if(t.isUntypedInputStrict(e))return A(e);if(t.isUntypedSchemaStrict(e))return k(e);if((0,u.isStandardJsonSchema)(e))return e[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(t.isValibotSchema(e))return O(e);if(t.isJsonSchema(e))return e}}function N(e){if((0,r.isSetObject)(e)){if((0,f.isZod3Type)(e))return`zod3`;if(t.isUntypedInputStrict(e)||t.isUntypedSchemaStrict(e))return`untyped`;if((0,u.isStandardJsonSchema)(e))return`standard-schema`;if(t.isJsonSchema(e))return`json-schema`;if(t.isValibotSchema(e))return`valibot`}throw Error(`Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, a reflected Deepkit Type object, or an Untyped schema.`)}function P(e){let{input:r}=_(e);return t.isSchemaWithSource(r)||t.isSchema(r)?r.variant:(0,n.isSetString)(r)||t.isFileReference(r)?`file-reference`:N(r)}async function F(e,n){if(t.isSchemaWithSource(e))return e.schema;let r=n??N(e),i;if((r===`zod3`||r===`json-schema`||r===`standard-schema`||r===`untyped`||r===`valibot`)&&(i=M(e)),i)return T(i);throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, an untyped schema, or a reflected Deepkit Type object.`)}function I(e,t){if(e===`zod3`)return{hash:j(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:j(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:j(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:j(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:j(e,t),variant:`valibot`,schema:t};throw Error(`Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`)}async function L(e,t={}){let n=(0,s.extractFileReference)(e);if(!n)throw Error(`Failed to extract a file reference from the provided input. The input must be a string or an object with a "file" property that specifies the file path and optional export name.`);let r=n.export??`*`;try{return(0,m.createGenerator)({path:n.file,type:r,expose:`export`,jsDoc:`extended`,...t}).createSchema(r)}catch(e){throw Error(`Failed to generate a JSON schema for "${n.file}" using the type "${r}". Error: ${e.message}`)}}function R(t,n){let r=t.schema,i=t.meta??{};return i.name=e.u(r,i,n?.name),i.version=e.d(r,i,n?.version),i.id=e.c(r,i),i.displayName=e.o(r,i,n?.displayName),i.description=e.a(`A schema that describes the shape of the {displayName} specification.`,t.schema,i,n?.description),i.examples=e.s(t.schema,i,n?.examples),i.links=e.l(t.schema,i,n?.links),n?.deprecated&&(i.deprecated=n?.deprecated),n?.usage&&(i.usage=n?.usage),n?.tags&&(i.tags=n?.tags),i}async function z(e,n={}){let{input:r,meta:c}=_(e);if(t.isSchemaWithSource(r))return{...r,meta:R(r,c)};if(t.isSchema(r))return{...r,meta:R(r,c),source:{hash:j(`json-schema`,r.schema),variant:`json-schema`,schema:r.schema}};let l,u=c,f=P(r),p=j(f,r);if(f===`file-reference`){let e=(0,s.extractFileReference)(r);if(!e)throw Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(r)}". Please ensure that the input is correctly formatted as a file reference (e.g. "./schema.ts#MySchema") and that the file exists at the specified path.`);let c=(0,a.findFileExtensionSafe)(e.file);if(c&&!o.VALID_OBJECT_SOURCE_EXTENSIONS.includes(c))throw Error(`The provided schema file input "${e.file}" has an invalid file extension (.${c}). Please ensure that the file has one of the following extensions: ${(0,i.list)(o.VALID_OBJECT_SOURCE_EXTENSIONS,{conjunction:`or`})}.`);let f=await(0,d.loadSafe)(r,n);f??=await L(r,n);let{input:p,meta:m}=_(f);u?m&&(u={...m,...u}):u=m,l=t.isSchemaWithSource(p)?p.source:t.isSchema(p)?{hash:j(`json-schema`,p.schema),variant:`json-schema`,schema:p.schema}:I(N(p),p)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(f))l=I(f,r);else throw Error(`Invalid schema definition input "${f}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);let m={variant:f,source:l,schema:await F(l.schema,l.variant),hash:p,meta:{}};return m.meta=R(m,u),m}async function B(e,n={}){let r=_(e),i=r.input;if(t.isSchemaWithSource(i)||t.isSchemaOf(i))return{...i,meta:R(i,r.meta)};let a=await z(e,n);if(a.meta=R(a,r.meta),!a?.schema)throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);return a}exports.bundleReferences=T,exports.extract=B,exports.extractHash=j,exports.extractJsonSchema=M,exports.extractResolvedVariant=N,exports.extractSchema=F,exports.extractSchemaMeta=R,exports.extractSchemaWithSource=z,exports.extractSource=I,exports.extractTSType=L,exports.extractVariant=P;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./type-checks.cjs");let t=require("@stryke/type-checks"),n=require("@stryke/type-checks/is-set-object"),r=require("@stryke/string-format/list"),i=require("@stryke/path/find"),a=require("@stryke/resolve/constants"),o=require("@stryke/convert/extract-file-reference"),s=require("@stryke/hash"),c=require("@stryke/helpers/deep-clone"),l=require("@stryke/json"),u=require("@stryke/resolve/load"),d=require("@stryke/zod"),f=require("@valibot/to-json-schema"),p=require("ts-json-schema-generator/dist/factory/generator.js");const m=`https://power-plant.invalid/`;function h(e){return!(!(0,n.isSetObject)(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e)}function g(e){return h(e)?e.schema:e}function _(e){return e.endsWith(`#`)?e.slice(0,-1):e}function v(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function y(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function b(e){return e.length===0?``:`/${e.map(e=>y(e)).join(`/`)}`}function x(e,t){try{return _(new URL(e,t).toString())}catch{return _(e)}}function S(e,r,i,a,o){if(!(0,n.isSetObject)(e))return;let s=e,c=b(r),l=(0,t.isSetString)(s.$id)?x(s.$id,i):i,u=v(l);if(a.set(l,c),a.set(u,c),(0,t.isSetString)(s.$anchor)&&a.set(`${u}#${s.$anchor}`,c),(0,t.isSetString)(s.$dynamicAnchor)){let e=`${u}#${s.$dynamicAnchor}`;a.set(e,c),o.set(e,`#${s.$dynamicAnchor}`)}for(let[e,t]of Object.entries(s)){if(Array.isArray(t)){t.forEach((t,n)=>{S(t,[...r,e,String(n)],l,a,o)});continue}S(t,[...r,e],l,a,o)}}function C(e,r,i,a,o){if(!(0,n.isSetObject)(e))return;let s=e,c=(0,t.isSetString)(s.$id)?x(s.$id,i):i;if((0,t.isSetString)(s.$ref)){let e=x(s.$ref,c),t=a.get(e)??a.get(v(e));t!==void 0&&(s.$ref=t.length>0?`#${t}`:`#`)}if((0,t.isSetString)(s.$dynamicRef)){let e=x(s.$dynamicRef,c),t=o.get(e);if(t)s.$dynamicRef=t;else{let t=a.get(e)??a.get(v(e));t!==void 0&&(s.$dynamicRef=t.length>0?`#${t}`:`#`)}}for(let[e,t]of Object.entries(s)){if(Array.isArray(t)){t.forEach((t,n)=>{C(t,[...r,e,String(n)],c,a,o)});continue}C(t,[...r,e],c,a,o)}}function w(e){if(!(0,n.isSetObject)(e))return e;let r=(0,c.deepClone)(e),i=(0,t.isSetString)(r.$id)?x(r.$id,m):m,a=new Map,o=new Map;return S(r,[],i,a,o),C(r,[],i,a,o),r}function T(t){if(e.isUntypedSchema(t))return O(t);if((0,n.isSetObject)(t)){if(e.isUntypedInput(t))return k(t);let n=t;if(`$schema`in n&&e.isUntypedSchema(n.$schema))return O(n.$schema)}return t}function E(e){return Array.isArray(e)?e.map(e=>T(e)):e}function D(e){return(0,f.toJsonSchema)(e,{target:`draft-2020-12`})}function O(e){let r=e,i={};for(let[e,a]of Object.entries(r))if(!(e===`tsType`||e===`markdownType`||e===`tags`||e===`args`||e===`resolve`)){if(e===`id`&&(0,t.isSetString)(a)){i.$id=a;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!(0,n.isSetObject)(a)){i[e]=a;continue}i[e]=Object.fromEntries(Object.entries(a).map(([e,t])=>[e,T(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){i[e]=T(a);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){i[e]=E(a);continue}i[e]=a}return i}function k(t){let r=t,i=e.isUntypedSchema(r.$schema)?O(r.$schema):{},a={};for(let[t,i]of Object.entries(r)){if(t.startsWith(`$`)||!(0,n.isSetObject)(i))continue;if(e.isUntypedInput(i)){a[t]=k(i);continue}let r=i;if(`$schema`in r&&e.isUntypedSchema(r.$schema)){a[t]=O(r.$schema);continue}e.isUntypedSchema(i)&&(a[t]=O(i))}if(!e.isJsonSchemaObject(i))throw Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);let o={...(0,n.isSetObject)(i.properties)?i.properties:{},...a};return{...i,type:i.type??`object`,...Object.keys(o).length>0?{properties:o}:{}}}function A(r,i){let a=g(i);if(e.isSchemaWithSource(a)||e.isSchema(a))return(0,s.murmurhash)({variant:r,input:a.schema});if((0,t.isSetString)(a)||typeof a==`boolean`)return(0,s.murmurhash)({variant:r,input:a});if((0,n.isSetObject)(a)){if((0,d.isZod3Type)(a))return(0,s.murmurhash)({variant:r,input:a._def});if((0,l.isStandardJsonSchema)(a))return(0,s.murmurhash)({variant:r,input:a[`~standard`]});if(e.isJsonSchema(a))return(0,s.murmurhash)({variant:r,input:a});if(e.isValibotSchema(a))return(0,s.murmurhash)({variant:r,input:D(a)});if(e.isUntypedInput(a))return(0,s.murmurhash)({variant:r,input:k(a)});if(e.isUntypedSchema(a))return(0,s.murmurhash)({variant:r,input:O(a)})}throw Error(`Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, or a reflected Deepkit Type object.`)}function j(t){if((0,n.isSetObject)(t)){if((0,d.isZod3Type)(t))return(0,d.extractJsonSchema)(t,{target:`draft-2020-12`});if(e.isUntypedInputStrict(t))return k(t);if(e.isUntypedSchemaStrict(t))return O(t);if((0,l.isStandardJsonSchema)(t))return t[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(e.isValibotSchema(t))return D(t);if(e.isJsonSchema(t))return t}}function M(t){if((0,n.isSetObject)(t)){if((0,d.isZod3Type)(t))return`zod3`;if(e.isUntypedInputStrict(t)||e.isUntypedSchemaStrict(t))return`untyped`;if((0,l.isStandardJsonSchema)(t))return`standard-schema`;if(e.isJsonSchema(t))return`json-schema`;if(e.isValibotSchema(t))return`valibot`}throw Error(`Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, a reflected Deepkit Type object, or an Untyped schema.`)}function N(n){let r=g(n);return e.isSchemaWithSource(r)||e.isSchema(r)?r.variant:(0,t.isSetString)(r)||e.isFileReference(r)?`file-reference`:M(r)}async function P(t,n){if(e.isSchemaWithSource(t))return t.schema;let r=n??M(t),i;if((r===`zod3`||r===`json-schema`||r===`standard-schema`||r===`untyped`||r===`valibot`)&&(i=j(t)),i)return w(i);throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, an untyped schema, or a reflected Deepkit Type object.`)}function F(e,t){if(e===`zod3`)return{hash:A(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:A(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:A(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:A(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:A(e,t),variant:`valibot`,schema:t};throw Error(`Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`)}async function I(e,t={}){let n=(0,o.extractFileReference)(e);if(!n)throw Error(`Failed to extract a file reference from the provided input. The input must be a string or an object with a "file" property that specifies the file path and optional export name.`);let r=n.export??`*`;try{return(0,p.createGenerator)({path:n.file,type:r,expose:`export`,jsDoc:`extended`,...t}).createSchema(r)}catch(e){throw Error(`Failed to generate a JSON schema for "${n.file}" using the type "${r}". Error: ${e.message}`)}}async function L(t,n={}){let s=g(t);if(e.isSchemaWithSource(s))return s;if(e.isSchema(s))return{...s,source:{hash:A(`json-schema`,s.schema),variant:`json-schema`,schema:s.schema}};let c,l=N(s),d=A(l,s);if(l===`file-reference`){let t=(0,o.extractFileReference)(s);if(!t)throw Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(s)}". Please ensure that the input is correctly formatted as a file reference (e.g. "./schema.ts#MySchema") and that the file exists at the specified path.`);let l=(0,i.findFileExtensionSafe)(t.file);if(l&&!a.VALID_OBJECT_SOURCE_EXTENSIONS.includes(l))throw Error(`The provided schema file input "${t.file}" has an invalid file extension (.${l}). Please ensure that the file has one of the following extensions: ${(0,r.list)(a.VALID_OBJECT_SOURCE_EXTENSIONS,{conjunction:`or`})}.`);let d=await(0,u.loadSafe)(s,n);d??=await I(s,n);let f=g(d);c=e.isSchemaWithSource(f)?f.source:e.isSchema(f)?{hash:A(`json-schema`,f.schema),variant:`json-schema`,schema:f.schema}:F(M(f),f)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(l))c=F(l,s);else throw Error(`Invalid schema definition input "${l}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);return{variant:l,source:c,schema:await P(c.schema,c.variant),hash:d}}async function R(t,n={}){let r=g(t);if(e.isSchemaWithSource(r)||e.isSchemaOf(r))return r;let i=await L(t,n);if(!i?.schema)throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);return i}exports.bundleReferences=w,exports.extract=R,exports.extractHash=A,exports.extractJsonSchema=j,exports.extractResolvedVariant=M,exports.extractSchema=P,exports.extractSchemaWithSource=L,exports.extractSource=F,exports.extractTSType=I,exports.extractVariant=N;
|
package/dist/extract.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ExtractedSchemaEnvelope, InferExtractOptions, JsonSchema, SchemaEnvelopeOf, SchemaInput, SchemaInputVariant, SchemaSource, SchemaSourceInput, SchemaSourceVariant } from "./types.cjs";
|
|
2
2
|
import { InferLoadOptions } from "@stryke/resolve/types";
|
|
3
3
|
import { FileReferenceInput } from "@stryke/types";
|
|
4
4
|
|
|
@@ -62,14 +62,6 @@ declare function extractSource(variant: SchemaSourceVariant, input: SchemaSource
|
|
|
62
62
|
* @returns A promise that resolves to the generated JSON Schema.
|
|
63
63
|
*/
|
|
64
64
|
declare function extractTSType(input: FileReferenceInput, options?: InferLoadOptions<typeof input>): Promise<JsonSchema>;
|
|
65
|
-
/**
|
|
66
|
-
* Extracts and normalizes {@link SchemaMeta | schema metadata} from a given {@link SchemaMetaInput}. This function ensures that the metadata is in a consistent format, converting version numbers to strings and filtering out any invalid or empty tags.
|
|
67
|
-
*
|
|
68
|
-
* @param schema - The schema from which to extract metadata.
|
|
69
|
-
* @param input - The schema metadata input to extract and normalize.
|
|
70
|
-
* @returns The normalized schema metadata.
|
|
71
|
-
*/
|
|
72
|
-
declare function extractSchemaMeta<TSpec = any>(schema: SchemaOf<TSpec>, input?: SchemaMetaInput<TSpec>): SchemaMeta<TSpec>;
|
|
73
65
|
/**
|
|
74
66
|
* Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
|
|
75
67
|
*
|
|
@@ -103,7 +95,7 @@ declare function extractSchemaMeta<TSpec = any>(schema: SchemaOf<TSpec>, input?:
|
|
|
103
95
|
* @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
|
|
104
96
|
* @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
|
|
105
97
|
*/
|
|
106
|
-
declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: InferExtractOptions<typeof input>): Promise<
|
|
98
|
+
declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: InferExtractOptions<typeof input>): Promise<ExtractedSchemaEnvelope<TSpec>>;
|
|
107
99
|
/**
|
|
108
100
|
* Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
|
|
109
101
|
*
|
|
@@ -137,7 +129,7 @@ declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, option
|
|
|
137
129
|
* @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
|
|
138
130
|
* @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
|
|
139
131
|
*/
|
|
140
|
-
declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: InferExtractOptions<typeof input>): Promise<
|
|
132
|
+
declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: InferExtractOptions<typeof input>): Promise<SchemaEnvelopeOf<TSpec>>;
|
|
141
133
|
//#endregion
|
|
142
|
-
export { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema,
|
|
134
|
+
export { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaWithSource, extractSource, extractTSType, extractVariant };
|
|
143
135
|
//# sourceMappingURL=extract.d.cts.map
|
package/dist/extract.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;AAmQA;;;;iBAAgB,gBAAA,CAAiB,MAAA,EAAQ,UAAA,GAAa,UAAU;;;;iBAgMhD,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EAAO,WAAW;AAFpB;;;;;;AAAA,iBAkDgB,iBAAA,CAAkB,MAAA,YAAkB,UAAU;;;AAhD1C;AAgDpB;;;;iBAoCgB,sBAAA,CACd,KAAA,EAAO,iBAAA,GACN,mBAAmB;AAFtB;;;;;;AAAA,iBA4BgB,cAAA,CAAe,KAAA,EAAO,WAAA,GAAc,kBAAkB;;AA1BhD;AA0BtB;;;;;;iBAsBsB,aAAA,CACpB,KAAA,EAAO,iBAAA,EACP,OAAA,GAAU,kBAAA,GACT,OAAA,CAAQ,UAAA;;AAzB2D;AAsBtE;;;;;;iBAsCgB,aAAA,CACd,OAAA,EAAS,mBAAA,EACT,KAAA,EAAO,iBAAA,GACN,YAAA;;;;;;;;iBA6CmB,aAAA,CACpB,KAAA,EAAO,kBAAA,EACP,OAAA,GAAS,gBAAA,QAAwB,KAAA,IAChC,OAAA,CAAQ,UAAA;;AAtFU;AAmCrB;;;;;;;;;;;;;;AAGe;AA6Cf;;;;;;;;;;;;;;;;iBAiEsB,uBAAA,cACpB,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,mBAAA,QAA2B,KAAA,IACnC,OAAA,CAAQ,uBAAA,CAAwB,KAAA;;AAjEd;AA8DrB;;;;;;;;;;;;;;;;;;;;;AAGwC;AAsIxC;;;;;;;;;iBAAsB,OAAA,cACpB,KAAA,EAAO,WAAA,CAAY,KAAA,GACnB,OAAA,GAAS,mBAAA,QAA2B,KAAA,IACnC,OAAA,CAAQ,gBAAA,CAAiB,KAAA"}
|
package/dist/extract.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { ExtractedSchemaEnvelope, InferExtractOptions, JsonSchema, SchemaEnvelopeOf, SchemaInput, SchemaInputVariant, SchemaSource, SchemaSourceInput, SchemaSourceVariant } from "./types.mjs";
|
|
2
2
|
import { InferLoadOptions } from "@stryke/resolve/types";
|
|
3
3
|
import { FileReferenceInput } from "@stryke/types";
|
|
4
4
|
|
|
@@ -62,14 +62,6 @@ declare function extractSource(variant: SchemaSourceVariant, input: SchemaSource
|
|
|
62
62
|
* @returns A promise that resolves to the generated JSON Schema.
|
|
63
63
|
*/
|
|
64
64
|
declare function extractTSType(input: FileReferenceInput, options?: InferLoadOptions<typeof input>): Promise<JsonSchema>;
|
|
65
|
-
/**
|
|
66
|
-
* Extracts and normalizes {@link SchemaMeta | schema metadata} from a given {@link SchemaMetaInput}. This function ensures that the metadata is in a consistent format, converting version numbers to strings and filtering out any invalid or empty tags.
|
|
67
|
-
*
|
|
68
|
-
* @param schema - The schema from which to extract metadata.
|
|
69
|
-
* @param input - The schema metadata input to extract and normalize.
|
|
70
|
-
* @returns The normalized schema metadata.
|
|
71
|
-
*/
|
|
72
|
-
declare function extractSchemaMeta<TSpec = any>(schema: SchemaOf<TSpec>, input?: SchemaMetaInput<TSpec>): SchemaMeta<TSpec>;
|
|
73
65
|
/**
|
|
74
66
|
* Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
|
|
75
67
|
*
|
|
@@ -103,7 +95,7 @@ declare function extractSchemaMeta<TSpec = any>(schema: SchemaOf<TSpec>, input?:
|
|
|
103
95
|
* @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
|
|
104
96
|
* @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
|
|
105
97
|
*/
|
|
106
|
-
declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: InferExtractOptions<typeof input>): Promise<
|
|
98
|
+
declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: InferExtractOptions<typeof input>): Promise<ExtractedSchemaEnvelope<TSpec>>;
|
|
107
99
|
/**
|
|
108
100
|
* Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a {@link FileReferenceInput} to an exported TypeScript type definition or any of the previous options. If the input is a {@link FileReferenceInput} (e.g. a file path with an export), the source code will be bundled with [esbuild](esbuild.github.io) using [ts-json-schema-generator](https://github.com/vega/ts-json-schema-generator) to obtain the actual schema definition before extraction.
|
|
109
101
|
*
|
|
@@ -137,7 +129,7 @@ declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, option
|
|
|
137
129
|
* @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
|
|
138
130
|
* @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.
|
|
139
131
|
*/
|
|
140
|
-
declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: InferExtractOptions<typeof input>): Promise<
|
|
132
|
+
declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: InferExtractOptions<typeof input>): Promise<SchemaEnvelopeOf<TSpec>>;
|
|
141
133
|
//#endregion
|
|
142
|
-
export { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema,
|
|
134
|
+
export { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaWithSource, extractSource, extractTSType, extractVariant };
|
|
143
135
|
//# sourceMappingURL=extract.d.mts.map
|
package/dist/extract.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{isFileReference as e,isJsonSchema as t,isJsonSchemaObject as n,isSchema as r,isSchemaOf as i,isSchemaWithSource as a,isUntypedInput as o,isUntypedInputStrict as s,isUntypedSchema as c,isUntypedSchemaStrict as l,isValibotSchema as u}from"./type-checks.mjs";import{
|
|
1
|
+
import{isFileReference as e,isJsonSchema as t,isJsonSchemaObject as n,isSchema as r,isSchemaOf as i,isSchemaWithSource as a,isUntypedInput as o,isUntypedInputStrict as s,isUntypedSchema as c,isUntypedSchemaStrict as l,isValibotSchema as u}from"./type-checks.mjs";import{isSetString as d}from"@stryke/type-checks";import{isSetObject as f}from"@stryke/type-checks/is-set-object";import{list as p}from"@stryke/string-format/list";import{findFileExtensionSafe as m}from"@stryke/path/find";import{VALID_OBJECT_SOURCE_EXTENSIONS as h}from"@stryke/resolve/constants";import{extractFileReference as g}from"@stryke/convert/extract-file-reference";import{murmurhash as _}from"@stryke/hash";import{deepClone as v}from"@stryke/helpers/deep-clone";import{isStandardJsonSchema as y}from"@stryke/json";import{loadSafe as b}from"@stryke/resolve/load";import{extractJsonSchema as x,isZod3Type as S}from"@stryke/zod";import{toJsonSchema as C}from"@valibot/to-json-schema";import{createGenerator as w}from"ts-json-schema-generator/dist/factory/generator.js";const T=`https://power-plant.invalid/`;function E(e){return!(!f(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e)}function D(e){return E(e)?e.schema:e}function O(e){return e.endsWith(`#`)?e.slice(0,-1):e}function k(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function A(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function j(e){return e.length===0?``:`/${e.map(e=>A(e)).join(`/`)}`}function M(e,t){try{return O(new URL(e,t).toString())}catch{return O(e)}}function N(e,t,n,r,i){if(!f(e))return;let a=e,o=j(t),s=d(a.$id)?M(a.$id,n):n,c=k(s);if(r.set(s,o),r.set(c,o),d(a.$anchor)&&r.set(`${c}#${a.$anchor}`,o),d(a.$dynamicAnchor)){let e=`${c}#${a.$dynamicAnchor}`;r.set(e,o),i.set(e,`#${a.$dynamicAnchor}`)}for(let[e,n]of Object.entries(a)){if(Array.isArray(n)){n.forEach((n,a)=>{N(n,[...t,e,String(a)],s,r,i)});continue}N(n,[...t,e],s,r,i)}}function P(e,t,n,r,i){if(!f(e))return;let a=e,o=d(a.$id)?M(a.$id,n):n;if(d(a.$ref)){let e=M(a.$ref,o),t=r.get(e)??r.get(k(e));t!==void 0&&(a.$ref=t.length>0?`#${t}`:`#`)}if(d(a.$dynamicRef)){let e=M(a.$dynamicRef,o),t=i.get(e);if(t)a.$dynamicRef=t;else{let t=r.get(e)??r.get(k(e));t!==void 0&&(a.$dynamicRef=t.length>0?`#${t}`:`#`)}}for(let[e,n]of Object.entries(a)){if(Array.isArray(n)){n.forEach((n,a)=>{P(n,[...t,e,String(a)],o,r,i)});continue}P(n,[...t,e],o,r,i)}}function F(e){if(!f(e))return e;let t=v(e),n=d(t.$id)?M(t.$id,T):T,r=new Map,i=new Map;return N(t,[],n,r,i),P(t,[],n,r,i),t}function I(e){if(c(e))return z(e);if(f(e)){if(o(e))return B(e);let t=e;if(`$schema`in t&&c(t.$schema))return z(t.$schema)}return e}function L(e){return Array.isArray(e)?e.map(e=>I(e)):e}function R(e){return C(e,{target:`draft-2020-12`})}function z(e){let t=e,n={};for(let[e,r]of Object.entries(t))if(!(e===`tsType`||e===`markdownType`||e===`tags`||e===`args`||e===`resolve`)){if(e===`id`&&d(r)){n.$id=r;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!f(r)){n[e]=r;continue}n[e]=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,I(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){n[e]=I(r);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){n[e]=L(r);continue}n[e]=r}return n}function B(e){let t=e,r=c(t.$schema)?z(t.$schema):{},i={};for(let[e,n]of Object.entries(t)){if(e.startsWith(`$`)||!f(n))continue;if(o(n)){i[e]=B(n);continue}let t=n;if(`$schema`in t&&c(t.$schema)){i[e]=z(t.$schema);continue}c(n)&&(i[e]=z(n))}if(!n(r))throw Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);let a={...f(r.properties)?r.properties:{},...i};return{...r,type:r.type??`object`,...Object.keys(a).length>0?{properties:a}:{}}}function V(e,n){let i=D(n);if(a(i)||r(i))return _({variant:e,input:i.schema});if(d(i)||typeof i==`boolean`)return _({variant:e,input:i});if(f(i)){if(S(i))return _({variant:e,input:i._def});if(y(i))return _({variant:e,input:i[`~standard`]});if(t(i))return _({variant:e,input:i});if(u(i))return _({variant:e,input:R(i)});if(o(i))return _({variant:e,input:B(i)});if(c(i))return _({variant:e,input:z(i)})}throw Error(`Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, or a reflected Deepkit Type object.`)}function H(e){if(f(e)){if(S(e))return x(e,{target:`draft-2020-12`});if(s(e))return B(e);if(l(e))return z(e);if(y(e))return e[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(u(e))return R(e);if(t(e))return e}}function U(e){if(f(e)){if(S(e))return`zod3`;if(s(e)||l(e))return`untyped`;if(y(e))return`standard-schema`;if(t(e))return`json-schema`;if(u(e))return`valibot`}throw Error(`Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, a reflected Deepkit Type object, or an Untyped schema.`)}function W(t){let n=D(t);return a(n)||r(n)?n.variant:d(n)||e(n)?`file-reference`:U(n)}async function G(e,t){if(a(e))return e.schema;let n=t??U(e),r;if((n===`zod3`||n===`json-schema`||n===`standard-schema`||n===`untyped`||n===`valibot`)&&(r=H(e)),r)return F(r);throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a Valibot BaseSchema, an untyped schema, or a reflected Deepkit Type object.`)}function K(e,t){if(e===`zod3`)return{hash:V(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:V(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:V(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:V(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:V(e,t),variant:`valibot`,schema:t};throw Error(`Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`)}async function q(e,t={}){let n=g(e);if(!n)throw Error(`Failed to extract a file reference from the provided input. The input must be a string or an object with a "file" property that specifies the file path and optional export name.`);let r=n.export??`*`;try{return w({path:n.file,type:r,expose:`export`,jsDoc:`extended`,...t}).createSchema(r)}catch(e){throw Error(`Failed to generate a JSON schema for "${n.file}" using the type "${r}". Error: ${e.message}`)}}async function J(e,t={}){let n=D(e);if(a(n))return n;if(r(n))return{...n,source:{hash:V(`json-schema`,n.schema),variant:`json-schema`,schema:n.schema}};let i,o=W(n),s=V(o,n);if(o===`file-reference`){let e=g(n);if(!e)throw Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(n)}". Please ensure that the input is correctly formatted as a file reference (e.g. "./schema.ts#MySchema") and that the file exists at the specified path.`);let o=m(e.file);if(o&&!h.includes(o))throw Error(`The provided schema file input "${e.file}" has an invalid file extension (.${o}). Please ensure that the file has one of the following extensions: ${p(h,{conjunction:`or`})}.`);let s=await b(n,t);s??=await q(n,t);let c=D(s);i=a(c)?c.source:r(c)?{hash:V(`json-schema`,c.schema),variant:`json-schema`,schema:c.schema}:K(U(c),c)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(o))i=K(o,n);else throw Error(`Invalid schema definition input "${o}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);return{variant:o,source:i,schema:await G(i.schema,i.variant),hash:s}}async function Y(e,t={}){let n=D(e);if(a(n)||i(n))return n;let r=await J(e,t);if(!r?.schema)throw Error(`Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Valibot schema, any Standard JSON Schema type, a plain JSON Schema object, an untyped schema, or a reflected Deepkit Type object.`);return r}export{F as bundleReferences,Y as extract,V as extractHash,H as extractJsonSchema,U as extractResolvedVariant,G as extractSchema,J as extractSchemaWithSource,K as extractSource,q as extractTSType,W as extractVariant};
|
|
2
2
|
//# sourceMappingURL=extract.mjs.map
|
package/dist/helpers.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require("./constants.cjs"),l=require("./type-checks.cjs"),u=require("./metadata.cjs");let d=require("@stryke/type-checks"),f=require("@stryke/helpers/get-unique"),p=require("@stryke/path/find"),m=require("@stryke/resolve/constants"),h=require("defu");h=s(h,1);function g(e){let t=l.isSchema(e)?e.schema:e;if(!l.isJsonSchema(t))throw TypeError(`The provided input is not a valid JSON Schema`);return t}function _(e){let t=g(e);if(!l.isJsonSchemaObject(t))throw TypeError(`The provided input is not a valid JSON Schema object`);return t}function v(e){let t=_(e);return(0,d.isSetObject)(t.properties)?Object.entries(t.properties).reduce((e,[n,r])=>(r.name=n,r.required=!E(t,n),r.default=t.default?.[n]??r.default,e[n]=r,e),{}):{}}function y(e){return Object.values(v(e))}function b(e,t){let n=_(e);if(!(0,d.isSetObject)(n.properties))throw TypeError(`The provided schema does not have any properties`);let r=n.properties[t];if(!r)throw TypeError(`The provided schema does not have a property named "${t}"`);return{...r,name:t,required:!E(n,t),default:n.default?.[t]??r?.default}}function x(e,t,n){let r=_(e);r.properties??={},r.required??=[],n.name=t,r.properties[t]=n,r.required.includes(t)||r.required.push(t),r.required.length===0&&delete r.required}function S(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(e===`required`)n[e]=(0,f.getUnique)([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);else if(c.SCHEMA_RECORD_KEYWORDS.has(e)&&(0,d.isSetObject)(t)&&(0,d.isSetObject)(r)){let i={...t};for(let[e,t]of Object.entries(r)){let n=i[e];i[e]=l.isJsonSchema(n)&&l.isJsonSchema(t)?S(n,t):t}n[e]=i}else c.SCHEMA_ARRAY_CONCAT_KEYWORDS.has(e)&&Array.isArray(t)&&Array.isArray(r)?n[e]=[...t,...r]:c.SCHEMA_SINGLE_KEYWORDS.has(e)&&l.isJsonSchema(t)&&l.isJsonSchema(r)?n[e]=S(t,r):n[e]=r}return n}function C(...e){let t=e.map(e=>g(e));return t.length===0?{}:t.reduce((e,t)=>{let n=e.type,r=t.type;return n&&r&&n!==r?t:S(e,t)})}function w(e,t){return(0,h.default)(e,Object.fromEntries(c.JSON_SCHEMA_METADATA_KEYS.filter(e=>t[e]!==void 0).map(e=>[e,t[e]])))}function T(e){return(0,d.isSetObject)(e)?e.nullable===!0?!0:u.readSchemaTypes(e).includes(`null`):!1}function E(e,t){if(!e.properties?.[t])throw Error(`The property "${t}" does not exist in the parent schema.`);return!(e.required??[]).includes(t)}function D(e){return m.VALID_OBJECT_SOURCE_EXTENSIONS.includes((0,p.findFileExtensionSafe)(e))}exports.addProperty=x,exports.getJsonSchema=g,exports.getJsonSchemaObject=_,exports.getProperties=v,exports.getPropertiesList=y,exports.getProperty=b,exports.isPropertyOptional=E,exports.isSchemaNullable=T,exports.isValidSchemaInputFile=D,exports.merge=C,exports.mergeMetadata=w;
|
package/dist/helpers.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaObject, JsonSchemaOf,
|
|
1
|
+
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaObject, JsonSchemaOf, SchemaEnvelope } from "./types.cjs";
|
|
2
2
|
|
|
3
3
|
//#region src/helpers.d.ts
|
|
4
4
|
type GetPropertyResult = JsonSchema & {
|
|
@@ -16,7 +16,7 @@ type GetPropertyResult = JsonSchema & {
|
|
|
16
16
|
* @returns The JSON Schema object.
|
|
17
17
|
* @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
|
|
18
18
|
*/
|
|
19
|
-
declare function getJsonSchema(input:
|
|
19
|
+
declare function getJsonSchema(input: SchemaEnvelope | JsonSchema): JsonSchema;
|
|
20
20
|
/**
|
|
21
21
|
* Retrieves the JSON Schema in Object form from a Schema wrapper or returns the input if it's already a JSON Schema.
|
|
22
22
|
*
|
|
@@ -27,7 +27,7 @@ declare function getJsonSchema(input: Schema | JsonSchema): JsonSchema;
|
|
|
27
27
|
* @returns The JSON Schema object.
|
|
28
28
|
* @throws Will throw a TypeError if the input is neither a valid Schema wrapper nor a valid JSON Schema object.
|
|
29
29
|
*/
|
|
30
|
-
declare function getJsonSchemaObject(input:
|
|
30
|
+
declare function getJsonSchemaObject(input: SchemaEnvelope | JsonSchema): JsonSchemaObject;
|
|
31
31
|
/**
|
|
32
32
|
* Extracts object properties from a JSON Schema object form.
|
|
33
33
|
*
|
|
@@ -37,7 +37,7 @@ declare function getJsonSchemaObject(input: Schema | JsonSchema): JsonSchemaObje
|
|
|
37
37
|
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
38
38
|
* @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
|
|
39
39
|
*/
|
|
40
|
-
declare function getProperties(obj:
|
|
40
|
+
declare function getProperties(obj: SchemaEnvelope | JsonSchemaObject): Record<string, GetPropertyResult>;
|
|
41
41
|
/**
|
|
42
42
|
* Returns object properties as an array.
|
|
43
43
|
*
|
|
@@ -47,7 +47,7 @@ declare function getProperties(obj: Schema | JsonSchemaObject): Record<string, G
|
|
|
47
47
|
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
48
48
|
* @returns An array of JSON Schema fragments representing the properties, each including metadata.
|
|
49
49
|
*/
|
|
50
|
-
declare function getPropertiesList(obj:
|
|
50
|
+
declare function getPropertiesList(obj: SchemaEnvelope | JsonSchemaObject): GetPropertyResult[];
|
|
51
51
|
/**
|
|
52
52
|
* Extracts object properties from a JSON Schema object form.
|
|
53
53
|
*
|
|
@@ -57,7 +57,7 @@ declare function getPropertiesList(obj: Schema | JsonSchemaObject): GetPropertyR
|
|
|
57
57
|
* @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
|
|
58
58
|
* @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
|
|
59
59
|
*/
|
|
60
|
-
declare function getProperty<TSchema extends JsonSchemaObject>(obj:
|
|
60
|
+
declare function getProperty<TSchema extends JsonSchemaObject>(obj: SchemaEnvelope<TSchema> | TSchema, name: keyof TSchema["properties"] & string): GetPropertyResult;
|
|
61
61
|
/**
|
|
62
62
|
* Adds a property to a JSON Schema object form.
|
|
63
63
|
*
|
|
@@ -69,7 +69,7 @@ declare function getProperty<TSchema extends JsonSchemaObject>(obj: Schema<TSche
|
|
|
69
69
|
* @param property - The JSON Schema fragment representing the property's schema, including metadata.
|
|
70
70
|
* @throws Will throw an error if the provided schema is not an object form.
|
|
71
71
|
*/
|
|
72
|
-
declare function addProperty(obj:
|
|
72
|
+
declare function addProperty(obj: SchemaEnvelope | JsonSchemaObject, name: string, property: JsonSchema): void;
|
|
73
73
|
/**
|
|
74
74
|
* Merges multiple JSON Schemas into one.
|
|
75
75
|
*
|
|
@@ -89,7 +89,7 @@ declare function addProperty(obj: Schema | JsonSchemaObject, name: string, prope
|
|
|
89
89
|
* @param schemas - An array of JSON Schemas or Schema wrappers to merge.
|
|
90
90
|
* @returns A new JSON Schema that is the result of merging all input schemas.
|
|
91
91
|
*/
|
|
92
|
-
declare function merge(...schemas: (JsonSchema |
|
|
92
|
+
declare function merge(...schemas: (JsonSchema | SchemaEnvelope)[]): JsonSchema;
|
|
93
93
|
/**
|
|
94
94
|
* Merges metadata into a JSON Schema fragment.
|
|
95
95
|
*
|
package/dist/helpers.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;KAwCY,iBAAA,GAAoB,UAAU;EACxC,IAAA;EACA,QAAA;EACA,OAAA;AAAA;;;;;;;AAAO;AAaT;;;iBAAgB,aAAA,CAAc,KAAA,EAAO,
|
|
1
|
+
{"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;KAwCY,iBAAA,GAAoB,UAAU;EACxC,IAAA;EACA,QAAA;EACA,OAAA;AAAA;;;;;;;AAAO;AAaT;;;iBAAgB,aAAA,CAAc,KAAA,EAAO,cAAA,GAAiB,UAAA,GAAa,UAAA;;;;;;;;;;AAAU;iBAmB7D,mBAAA,CACd,KAAA,EAAO,cAAA,GAAiB,UAAA,GACvB,gBAAA;;;;;;;;;;iBAkBa,aAAA,CACd,GAAA,EAAK,cAAA,GAAiB,gBAAA,GACrB,MAAA,SAAe,iBAAA;;;AApBC;AAkBnB;;;;;;iBA+BgB,iBAAA,CAAkB,GAAA,EAAK,cAAA,GAAiB,gBAAA,GAAgB,iBAAA;;;;;;;;;AA7BrC;iBA0CnB,WAAA,iBAA4B,gBAAA,EAC1C,GAAA,EAAK,cAAA,CAAe,OAAA,IAAW,OAAA,EAC/B,IAAA,QAAY,OAAA,0BACX,iBAAA;;;;;;;;;;;;iBAgCa,WAAA,CACd,GAAA,EAAK,cAAA,GAAiB,gBAAA,EACtB,IAAA,UACA,QAAA,EAAU,UAAA;AAnD4D;AAaxE;;;;;;;;;;;;;;;;;;AAbwE,iBA4JxD,KAAA,IAAS,OAAA,GAAU,UAAA,GAAa,cAAA,MAAoB,UAAA;;;AA5IhD;AAgCpB;;;;;;;iBAyIgB,aAAA,QACd,MAAA,EAAQ,YAAA,CAAa,KAAA,GACrB,QAAA,EAAU,0BAAA,GACT,YAAA,CAAa,KAAA;;;;;;;;AAzIM;AAyGtB;iBAoDgB,gBAAA,CAAiB,MAAmB,GAAV,UAAU;;;;;;;;;;;iBAsBpC,kBAAA,CACd,MAAA,EAAQ,gBAAgB,EACxB,YAAA;AA5E4E;AA6B9E;;;;;AA7B8E,iBA6F9D,sBAAA,CAAuB,QAAgB"}
|