@power-plant/schema 0.0.2 → 0.0.3
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/README.md +221 -1
- package/dist/codegen.cjs +1 -77
- package/dist/codegen.mjs +1 -78
- package/dist/{constants-Cx9_Shfk.d.cts → constants-u7ovYS9e.d.cts} +3 -4
- package/dist/constants-u7ovYS9e.d.cts.map +1 -0
- package/dist/{constants-Cx9_Shfk.d.mts → constants-u7ovYS9e.d.mts} +3 -4
- package/dist/constants-u7ovYS9e.d.mts.map +1 -0
- package/dist/constants.cjs +1 -1
- package/dist/constants.d.cts +2 -2
- package/dist/constants.d.mts +2 -2
- package/dist/constants.mjs +1 -1
- package/dist/extract.cjs +1 -1
- package/dist/extract.d.cts +22 -9
- package/dist/extract.d.cts.map +1 -1
- package/dist/extract.d.mts +22 -9
- package/dist/extract.mjs +2 -1
- package/dist/extract.mjs.map +1 -0
- package/dist/helpers.cjs +1 -1
- package/dist/helpers.d.cts +14 -3
- package/dist/helpers.d.cts.map +1 -1
- package/dist/helpers.d.mts +14 -3
- package/dist/helpers.mjs +1 -2
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +7 -10
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +7 -10
- package/dist/index.mjs +1 -1
- package/dist/metadata-CsY3HrP2.cjs +77 -0
- package/dist/metadata-DIEpQjbq.mjs +78 -0
- package/dist/metadata-DIEpQjbq.mjs.map +1 -0
- package/dist/metadata.cjs +1 -1
- package/dist/metadata.d.cts +65 -2
- package/dist/metadata.d.cts.map +1 -1
- package/dist/metadata.d.mts +65 -2
- package/dist/metadata.mjs +1 -2
- package/dist/type-checks.cjs +1 -1
- package/dist/type-checks.d.cts +10 -3
- package/dist/type-checks.d.cts.map +1 -1
- package/dist/type-checks.d.mts +10 -3
- package/dist/type-checks.mjs +1 -1
- package/dist/types.d.cts +206 -37
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +206 -37
- package/package.json +19 -64
- package/dist/bundle.cjs +0 -1
- package/dist/bundle.d.cts +0 -18
- package/dist/bundle.d.cts.map +0 -1
- package/dist/bundle.d.mts +0 -18
- package/dist/bundle.d.mts.map +0 -1
- package/dist/bundle.mjs +0 -2
- package/dist/bundle.mjs.map +0 -1
- package/dist/codegen.mjs.map +0 -1
- package/dist/constants-Cx9_Shfk.d.cts.map +0 -1
- package/dist/constants-Cx9_Shfk.d.mts.map +0 -1
- package/dist/helpers.mjs.map +0 -1
- package/dist/metadata.mjs.map +0 -1
- package/dist/persistence-B9pzElsC.mjs +0 -2
- package/dist/persistence-B9pzElsC.mjs.map +0 -1
- package/dist/persistence-CLni2zCP.cjs +0 -1
- package/dist/persistence.cjs +0 -1
- package/dist/persistence.d.cts +0 -58
- package/dist/persistence.d.cts.map +0 -1
- package/dist/persistence.d.mts +0 -58
- package/dist/persistence.d.mts.map +0 -1
- package/dist/persistence.mjs +0 -1
- package/dist/resolve.cjs +0 -1
- package/dist/resolve.d.cts +0 -45
- package/dist/resolve.d.cts.map +0 -1
- package/dist/resolve.d.mts +0 -45
- package/dist/resolve.d.mts.map +0 -1
- package/dist/resolve.mjs +0 -2
- package/dist/resolve.mjs.map +0 -1
package/dist/extract.d.mts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { ExtractedSchema, InferExtractOptions, JsonSchema, SchemaInput, SchemaInputVariant, SchemaMeta, SchemaMetaInput, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant } from "./types.mjs";
|
|
2
|
+
import { InferLoadOptions } from "@stryke/resolve/types";
|
|
3
|
+
import { FileReferenceInput } from "@stryke/types";
|
|
3
4
|
|
|
4
5
|
//#region src/extract.d.ts
|
|
5
6
|
/**
|
|
@@ -53,6 +54,22 @@ declare function extractSchema(input: SchemaSourceInput, variant?: SchemaInputVa
|
|
|
53
54
|
* @throws Will throw an error if the provided variant is unsupported.
|
|
54
55
|
*/
|
|
55
56
|
declare function extractSource(variant: SchemaSourceVariant, input: SchemaSourceInput): SchemaSource;
|
|
57
|
+
/**
|
|
58
|
+
* Resolves a type definition to a JSON Schema. This function passes the provided file reference to ts-json-schema-generator, using the referenced export name as the target type when one is provided.
|
|
59
|
+
*
|
|
60
|
+
* @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.
|
|
61
|
+
* @param options - Optional overrides reserved for API compatibility.
|
|
62
|
+
* @returns A promise that resolves to the generated JSON Schema.
|
|
63
|
+
*/
|
|
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>;
|
|
56
73
|
/**
|
|
57
74
|
* 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.
|
|
58
75
|
*
|
|
@@ -86,11 +103,7 @@ declare function extractSource(variant: SchemaSourceVariant, input: SchemaSource
|
|
|
86
103
|
* @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
|
|
87
104
|
* @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.
|
|
88
105
|
*/
|
|
89
|
-
declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?:
|
|
90
|
-
type ExtractOptions = BundleOptions & {
|
|
91
|
-
cachePath?: string;
|
|
92
|
-
skipCache?: boolean;
|
|
93
|
-
};
|
|
106
|
+
declare function extractSchemaWithSource<TSpec = any>(input: SchemaInput, options?: InferExtractOptions<typeof input>): Promise<ExtractedSchema<TSpec>>;
|
|
94
107
|
/**
|
|
95
108
|
* 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.
|
|
96
109
|
*
|
|
@@ -124,7 +137,7 @@ type ExtractOptions = BundleOptions & {
|
|
|
124
137
|
* @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
|
|
125
138
|
* @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.
|
|
126
139
|
*/
|
|
127
|
-
declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?:
|
|
140
|
+
declare function extract<TSpec = any>(input: SchemaInput<TSpec>, options?: InferExtractOptions<typeof input>): Promise<SchemaOf<TSpec>>;
|
|
128
141
|
//#endregion
|
|
129
|
-
export {
|
|
142
|
+
export { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaMeta, extractSchemaWithSource, extractSource, extractTSType, extractVariant };
|
|
130
143
|
//# sourceMappingURL=extract.d.mts.map
|
package/dist/extract.mjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
import"./type-checks.mjs";import{c as
|
|
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{a as d,c as f,d as p,l as ee,o as m,s as h,u as g}from"./metadata-DIEpQjbq.mjs";import{isSetString as _}from"@stryke/type-checks";import{isSetObject as v}from"@stryke/type-checks/is-set-object";import{list as y}from"@stryke/string-format/list";import{findFileExtensionSafe as b}from"@stryke/path/find";import{VALID_OBJECT_SOURCE_EXTENSIONS as x}from"@stryke/resolve/constants";import{extractFileReference as S}from"@stryke/convert/extract-file-reference";import{murmurhash as C}from"@stryke/hash";import{deepClone as w}from"@stryke/helpers/deep-clone";import{isStandardJsonSchema as T}from"@stryke/json";import{loadSafe as te}from"@stryke/resolve/load";import{extractJsonSchema as ne,isZod3Type as E}from"@stryke/zod";import{toJsonSchema as D}from"@valibot/to-json-schema";import{createGenerator as O}from"ts-json-schema-generator/dist/factory/generator.js";const k=`https://power-plant.invalid/`;function A(e){return!v(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e?!1:Object.keys(e).every(e=>e===`schema`||e===`meta`)}function j(e){return A(e)?{input:e.schema,meta:_(e.meta)?{description:e.meta}:e.meta}:{input:e}}function M(e){return e.endsWith(`#`)?e.slice(0,-1):e}function N(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function P(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function F(e){return e.length===0?``:`/${e.map(e=>P(e)).join(`/`)}`}function I(e,t){try{return M(new URL(e,t).toString())}catch{return M(e)}}function L(e,t,n,r,i){if(!v(e))return;let a=e,o=F(t),s=_(a.$id)?I(a.$id,n):n,c=N(s);if(r.set(s,o),r.set(c,o),_(a.$anchor)&&r.set(`${c}#${a.$anchor}`,o),_(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)=>{L(n,[...t,e,String(a)],s,r,i)});continue}L(n,[...t,e],s,r,i)}}function R(e,t,n,r,i){if(!v(e))return;let a=e,o=_(a.$id)?I(a.$id,n):n;if(_(a.$ref)){let e=I(a.$ref,o),t=r.get(e)??r.get(N(e));t!==void 0&&(a.$ref=t.length>0?`#${t}`:`#`)}if(_(a.$dynamicRef)){let e=I(a.$dynamicRef,o),t=i.get(e);if(t)a.$dynamicRef=t;else{let t=r.get(e)??r.get(N(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)=>{R(n,[...t,e,String(a)],o,r,i)});continue}R(n,[...t,e],o,r,i)}}function z(e){if(!v(e))return e;let t=w(e),n=_(t.$id)?I(t.$id,k):k,r=new Map,i=new Map;return L(t,[],n,r,i),R(t,[],n,r,i),t}function B(e){if(c(e))return U(e);if(v(e)){if(o(e))return W(e);let t=e;if(`$schema`in t&&c(t.$schema))return U(t.$schema)}return e}function V(e){return Array.isArray(e)?e.map(e=>B(e)):e}function H(e){return D(e,{target:`draft-2020-12`})}function U(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`&&_(r)){n.$id=r;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!v(r)){n[e]=r;continue}n[e]=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,B(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){n[e]=B(r);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){n[e]=V(r);continue}n[e]=r}return n}function W(e){let t=e,r=c(t.$schema)?U(t.$schema):{},i={};for(let[e,n]of Object.entries(t)){if(e.startsWith(`$`)||!v(n))continue;if(o(n)){i[e]=W(n);continue}let t=n;if(`$schema`in t&&c(t.$schema)){i[e]=U(t.$schema);continue}c(n)&&(i[e]=U(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={...v(r.properties)?r.properties:{},...i};return{...r,type:r.type??`object`,...Object.keys(a).length>0?{properties:a}:{}}}function G(e,n){let{input:i}=j(n);if(a(i)||r(i))return C({variant:e,input:i.schema});if(_(i)||typeof i==`boolean`)return C({variant:e,input:i});if(v(i)){if(E(i))return C({variant:e,input:i._def});if(T(i))return C({variant:e,input:i[`~standard`]});if(t(i))return C({variant:e,input:i});if(u(i))return C({variant:e,input:H(i)});if(o(i))return C({variant:e,input:W(i)});if(c(i))return C({variant:e,input:U(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 K(e){if(v(e)){if(E(e))return ne(e,{target:`draft-2020-12`});if(s(e))return W(e);if(l(e))return U(e);if(T(e))return e[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(u(e))return H(e);if(t(e))return e}}function q(e){if(v(e)){if(E(e))return`zod3`;if(s(e)||l(e))return`untyped`;if(T(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 J(t){let{input:n}=j(t);return a(n)||r(n)?n.variant:_(n)||e(n)?`file-reference`:q(n)}async function Y(e,t){if(a(e))return e.schema;let n=t??q(e),r;if((n===`zod3`||n===`json-schema`||n===`standard-schema`||n===`untyped`||n===`valibot`)&&(r=K(e)),r)return z(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 X(e,t){if(e===`zod3`)return{hash:G(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:G(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:G(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:G(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:G(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 Z(e,t={}){let n=S(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 O({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 Q(e,t){let n=e.schema,r=e.meta??{};return r.name=g(n,r,t?.name),r.version=p(n,r,t?.version),r.id=f(n,r),r.displayName=m(n,r,t?.displayName),r.description=d(`A schema that describes the shape of the {displayName} specification.`,e.schema,r,t?.description),r.examples=h(e.schema,r,t?.examples),r.links=ee(e.schema,r,t?.links),t?.deprecated&&(r.deprecated=t?.deprecated),t?.usage&&(r.usage=t?.usage),t?.tags&&(r.tags=t?.tags),r}async function $(e,t={}){let{input:n,meta:i}=j(e);if(a(n))return{...n,meta:Q(n,i)};if(r(n))return{...n,meta:Q(n,i),source:{hash:G(`json-schema`,n.schema),variant:`json-schema`,schema:n.schema}};let o,s=i,c=J(n),l=G(c,n);if(c===`file-reference`){let e=S(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 i=b(e.file);if(i&&!x.includes(i))throw Error(`The provided schema file input "${e.file}" has an invalid file extension (.${i}). Please ensure that the file has one of the following extensions: ${y(x,{conjunction:`or`})}.`);let c=await te(n,t);c??=await Z(n,t);let{input:l,meta:u}=j(c);s?u&&(s={...u,...s}):s=u,o=a(l)?l.source:r(l)?{hash:G(`json-schema`,l.schema),variant:`json-schema`,schema:l.schema}:X(q(l),l)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(c))o=X(c,n);else throw Error(`Invalid schema definition input "${c}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);let u={variant:c,source:o,schema:await Y(o.schema,o.variant),hash:l,meta:{}};return u.meta=Q(u,s),u}async function re(e,t={}){let n=j(e),r=n.input;if(a(r)||i(r))return{...r,meta:Q(r,n.meta)};let o=await $(e,t);if(o.meta=Q(o,n.meta),!o?.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 o}export{z as bundleReferences,re as extract,G as extractHash,K as extractJsonSchema,q as extractResolvedVariant,Y as extractSchema,Q as extractSchemaMeta,$ as extractSchemaWithSource,X as extractSource,Z as extractTSType,J as extractVariant};
|
|
2
|
+
//# sourceMappingURL=extract.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extract.mjs","names":[],"sources":[],"mappings":""}
|
package/dist/helpers.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./metadata-CsY3HrP2.cjs");exports.addProperty=e.g,exports.getJsonSchema=e._,exports.getJsonSchemaObject=e.v,exports.getProperties=e.y,exports.getPropertiesList=e.b,exports.getProperty=e.x,exports.isPropertyOptional=e.S,exports.isSchemaNullable=e.C,exports.isValidSchemaInputFile=e.w,exports.merge=e.T,exports.mergeMetadata=e.E;
|
package/dist/helpers.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { JsonSchema, JsonSchemaObject, Schema } from "./types.cjs";
|
|
1
|
+
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaObject, JsonSchemaOf, Schema } from "./types.cjs";
|
|
2
2
|
|
|
3
3
|
//#region src/helpers.d.ts
|
|
4
4
|
type GetPropertyResult = JsonSchema & {
|
|
@@ -84,12 +84,23 @@ declare function addProperty(obj: Schema | JsonSchemaObject, name: string, prope
|
|
|
84
84
|
* - Composition arrays (`allOf`, `anyOf`, `oneOf`) are concatenated.
|
|
85
85
|
* - Single-schema keywords (`if`, `then`, `else`, `not`, `items`, etc.)
|
|
86
86
|
* are merged recursively when both sides define them.
|
|
87
|
-
* - `required` arrays are
|
|
87
|
+
* - `required` arrays are union'ed and deduplicated.
|
|
88
88
|
*
|
|
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
92
|
declare function merge(...schemas: (JsonSchema | Schema)[]): JsonSchema;
|
|
93
|
+
/**
|
|
94
|
+
* Merges metadata into a JSON Schema fragment.
|
|
95
|
+
*
|
|
96
|
+
* @remarks
|
|
97
|
+
* This function takes a JSON Schema fragment and a metadata object, and merges the metadata into the schema. Only the keys defined in {@link JSON_SCHEMA_METADATA_KEYS} are considered for merging. The resulting schema will include the original schema properties along with the provided metadata.
|
|
98
|
+
*
|
|
99
|
+
* @param schema - The JSON Schema fragment to merge metadata into.
|
|
100
|
+
* @param metadata - The metadata to merge into the schema.
|
|
101
|
+
* @returns A new JSON Schema fragment that includes the merged metadata.
|
|
102
|
+
*/
|
|
103
|
+
declare function mergeMetadata<TSpec>(schema: JsonSchemaOf<TSpec>, metadata: JsonSchemaMetadataKeywords): JsonSchemaOf<TSpec>;
|
|
93
104
|
/**
|
|
94
105
|
* Returns whether a JSON Schema fragment accepts `null`.
|
|
95
106
|
*
|
|
@@ -119,5 +130,5 @@ declare function isPropertyOptional(parent: JsonSchemaObject, propertyName: stri
|
|
|
119
130
|
*/
|
|
120
131
|
declare function isValidSchemaInputFile(fileName: string): boolean;
|
|
121
132
|
//#endregion
|
|
122
|
-
export { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge };
|
|
133
|
+
export { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge, mergeMetadata };
|
|
123
134
|
//# sourceMappingURL=helpers.d.cts.map
|
package/dist/helpers.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;
|
|
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,MAAA,GAAS,UAAA,GAAa,UAAA;;;;;;;;;;AAAU;iBAmBrD,mBAAA,CACd,KAAA,EAAO,MAAA,GAAS,UAAA,GACf,gBAAA;;;;;;;;;;iBAkBa,aAAA,CACd,GAAA,EAAK,MAAA,GAAS,gBAAA,GACb,MAAA,SAAe,iBAAA;;;AApBC;AAkBnB;;;;;;iBA+BgB,iBAAA,CAAkB,GAAA,EAAK,MAAA,GAAS,gBAAA,GAAgB,iBAAA;;;;;;;;;AA7B7B;iBA0CnB,WAAA,iBAA4B,gBAAA,EAC1C,GAAA,EAAK,MAAA,CAAO,OAAA,IAAW,OAAA,EACvB,IAAA,QAAY,OAAA,0BACX,iBAAA;;;;;;;;;;;;iBAgCa,WAAA,CACd,GAAA,EAAK,MAAA,GAAS,gBAAA,EACd,IAAA,UACA,QAAA,EAAU,UAAA;AAnDoD;AAahE;;;;;;;;;;;;;;;;;;AAbgE,iBA4JhD,KAAA,IAAS,OAAA,GAAU,UAAA,GAAa,MAAA,MAAY,UAAA;;;AA5IxC;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;AA5EoE;AA6BtE;;;;;AA7BsE,iBA6FtD,sBAAA,CAAuB,QAAgB"}
|
package/dist/helpers.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { JsonSchema, JsonSchemaObject, Schema } from "./types.mjs";
|
|
1
|
+
import { JsonSchema, JsonSchemaMetadataKeywords, JsonSchemaObject, JsonSchemaOf, Schema } from "./types.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/helpers.d.ts
|
|
4
4
|
type GetPropertyResult = JsonSchema & {
|
|
@@ -84,12 +84,23 @@ declare function addProperty(obj: Schema | JsonSchemaObject, name: string, prope
|
|
|
84
84
|
* - Composition arrays (`allOf`, `anyOf`, `oneOf`) are concatenated.
|
|
85
85
|
* - Single-schema keywords (`if`, `then`, `else`, `not`, `items`, etc.)
|
|
86
86
|
* are merged recursively when both sides define them.
|
|
87
|
-
* - `required` arrays are
|
|
87
|
+
* - `required` arrays are union'ed and deduplicated.
|
|
88
88
|
*
|
|
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
92
|
declare function merge(...schemas: (JsonSchema | Schema)[]): JsonSchema;
|
|
93
|
+
/**
|
|
94
|
+
* Merges metadata into a JSON Schema fragment.
|
|
95
|
+
*
|
|
96
|
+
* @remarks
|
|
97
|
+
* This function takes a JSON Schema fragment and a metadata object, and merges the metadata into the schema. Only the keys defined in {@link JSON_SCHEMA_METADATA_KEYS} are considered for merging. The resulting schema will include the original schema properties along with the provided metadata.
|
|
98
|
+
*
|
|
99
|
+
* @param schema - The JSON Schema fragment to merge metadata into.
|
|
100
|
+
* @param metadata - The metadata to merge into the schema.
|
|
101
|
+
* @returns A new JSON Schema fragment that includes the merged metadata.
|
|
102
|
+
*/
|
|
103
|
+
declare function mergeMetadata<TSpec>(schema: JsonSchemaOf<TSpec>, metadata: JsonSchemaMetadataKeywords): JsonSchemaOf<TSpec>;
|
|
93
104
|
/**
|
|
94
105
|
* Returns whether a JSON Schema fragment accepts `null`.
|
|
95
106
|
*
|
|
@@ -119,5 +130,5 @@ declare function isPropertyOptional(parent: JsonSchemaObject, propertyName: stri
|
|
|
119
130
|
*/
|
|
120
131
|
declare function isValidSchemaInputFile(fileName: string): boolean;
|
|
121
132
|
//#endregion
|
|
122
|
-
export { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge };
|
|
133
|
+
export { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge, mergeMetadata };
|
|
123
134
|
//# sourceMappingURL=helpers.d.mts.map
|
package/dist/helpers.mjs
CHANGED
|
@@ -1,2 +1 @@
|
|
|
1
|
-
import{
|
|
2
|
-
//# sourceMappingURL=helpers.mjs.map
|
|
1
|
+
import{C as e,E as t,S as n,T as r,_ as i,b as a,g as o,v as s,w as c,x as l,y as u}from"./metadata-DIEpQjbq.mjs";export{o as addProperty,i as getJsonSchema,s as getJsonSchemaObject,u as getProperties,a as getPropertiesList,l as getProperty,n as isPropertyOptional,e as isSchemaNullable,c as isValidSchemaInputFile,r as merge,t as mergeMetadata};
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`})
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./metadata-CsY3HrP2.cjs");require("./types.cjs");const t=require("./constants.cjs"),n=require("./type-checks.cjs"),r=require("./extract.cjs");exports.JSON_SCHEMA_METADATA_KEYS=t.JSON_SCHEMA_METADATA_KEYS,exports.JSON_SCHEMA_PRIMITIVE_TYPES=t.JSON_SCHEMA_PRIMITIVE_TYPES,exports.JSON_SCHEMA_TYPES=t.JSON_SCHEMA_TYPES,exports.JsonSchemaTypeNames=t.JsonSchemaTypeNames,exports.SCHEMA_ARRAY_CONCAT_KEYWORDS=t.SCHEMA_ARRAY_CONCAT_KEYWORDS,exports.SCHEMA_RECORD_KEYWORDS=t.SCHEMA_RECORD_KEYWORDS,exports.SCHEMA_SINGLE_KEYWORDS=t.SCHEMA_SINGLE_KEYWORDS,exports.addProperty=e.g,exports.applyJsonSchemaMetadata=e.t,exports.bundleReferences=r.bundleReferences,exports.extract=r.extract,exports.extractHash=r.extractHash,exports.extractJsonSchema=r.extractJsonSchema,exports.extractResolvedVariant=r.extractResolvedVariant,exports.extractSchema=r.extractSchema,exports.extractSchemaMeta=r.extractSchemaMeta,exports.extractSchemaWithSource=r.extractSchemaWithSource,exports.extractSource=r.extractSource,exports.extractTSType=r.extractTSType,exports.extractVariant=r.extractVariant,exports.formatMetaVersion=e.n,exports.generateParserCode=e.f,exports.getJsonSchema=e._,exports.getJsonSchemaObject=e.v,exports.getJsonSchemaType=e.p,exports.getPrimarySchemaType=e.r,exports.getProperties=e.y,exports.getPropertiesList=e.b,exports.getProperty=e.x,exports.isFileReference=n.isFileReference,exports.isJsonSchema=n.isJsonSchema,exports.isJsonSchemaAllOf=n.isJsonSchemaAllOf,exports.isJsonSchemaAny=n.isJsonSchemaAny,exports.isJsonSchemaAnyOf=n.isJsonSchemaAnyOf,exports.isJsonSchemaArray=n.isJsonSchemaArray,exports.isJsonSchemaBigint=n.isJsonSchemaBigint,exports.isJsonSchemaBoolean=n.isJsonSchemaBoolean,exports.isJsonSchemaDate=n.isJsonSchemaDate,exports.isJsonSchemaDecimal=n.isJsonSchemaDecimal,exports.isJsonSchemaEnum=n.isJsonSchemaEnum,exports.isJsonSchemaInteger=n.isJsonSchemaInteger,exports.isJsonSchemaKeywords=n.isJsonSchemaKeywords,exports.isJsonSchemaLiteral=n.isJsonSchemaLiteral,exports.isJsonSchemaMap=n.isJsonSchemaMap,exports.isJsonSchemaNativeEnum=n.isJsonSchemaNativeEnum,exports.isJsonSchemaNever=n.isJsonSchemaNever,exports.isJsonSchemaNull=n.isJsonSchemaNull,exports.isJsonSchemaNullable=n.isJsonSchemaNullable,exports.isJsonSchemaNumber=n.isJsonSchemaNumber,exports.isJsonSchemaObject=n.isJsonSchemaObject,exports.isJsonSchemaPrimitiveType=n.isJsonSchemaPrimitiveType,exports.isJsonSchemaPrimitiveUnion=n.isJsonSchemaPrimitiveUnion,exports.isJsonSchemaRecord=n.isJsonSchemaRecord,exports.isJsonSchemaRef=n.isJsonSchemaRef,exports.isJsonSchemaSet=n.isJsonSchemaSet,exports.isJsonSchemaString=n.isJsonSchemaString,exports.isJsonSchemaTuple=n.isJsonSchemaTuple,exports.isJsonSchemaType=n.isJsonSchemaType,exports.isJsonSchemaUndefined=n.isJsonSchemaUndefined,exports.isJsonSchemaUnion=n.isJsonSchemaUnion,exports.isJsonSchemaUnknown=n.isJsonSchemaUnknown,exports.isNullOnlyJsonSchema=n.isNullOnlyJsonSchema,exports.isPropertyOptional=e.S,exports.isSchema=n.isSchema,exports.isSchemaNullable=e.C,exports.isSchemaObject=n.isSchemaObject,exports.isSchemaOf=n.isSchemaOf,exports.isSchemaWithSource=n.isSchemaWithSource,exports.isStandardSchema=n.isStandardSchema,exports.isUntypedInput=n.isUntypedInput,exports.isUntypedInputStrict=n.isUntypedInputStrict,exports.isUntypedSchema=n.isUntypedSchema,exports.isUntypedSchemaStrict=n.isUntypedSchemaStrict,exports.isValibotSchema=n.isValibotSchema,exports.isValidSchemaInputFile=e.w,exports.merge=e.T,exports.mergeMetadata=e.E,exports.readSchemaTypes=e.i,exports.resolveMetaDescription=e.a,exports.resolveMetaDisplayName=e.o,exports.resolveMetaExample=e.s,exports.resolveMetaId=e.c,exports.resolveMetaLinks=e.l,exports.resolveMetaName=e.u,exports.resolveMetaVersion=e.d,exports.stringifyType=e.m,exports.stringifyValue=e.h;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { BaseSchemaSource, ExtractedSchema, JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBigint, JsonSchemaBoolean, JsonSchemaConditionalKeywords, JsonSchemaDate, JsonSchemaDecimal, JsonSchemaDecimalFormat, JsonSchemaEnum, JsonSchemaInteger, JsonSchemaIntegerFormat, JsonSchemaKeywords, JsonSchemaLike, JsonSchemaLiteral, JsonSchemaLogicKeywords, JsonSchemaMap, JsonSchemaMetadataKeywords, JsonSchemaNativeEnum, JsonSchemaNever, JsonSchemaNull, JsonSchemaNullable, JsonSchemaNumber, JsonSchemaNumberFormat, JsonSchemaObject, JsonSchemaOf, JsonSchemaPrimitiveType, JsonSchemaPrimitiveUnion, JsonSchemaRecord, JsonSchemaRecordPropertyNames, JsonSchemaRef, JsonSchemaSchemaSource, JsonSchemaSet, JsonSchemaString, JsonSchemaStringFormat, JsonSchemaTuple, JsonSchemaType, JsonSchemaUndefined, JsonSchemaUnion, JsonSchemaUnknown, Schema, SchemaInput, SchemaInputVariant, SchemaInputWithMeta, SchemaMeta, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant, SpecOf, StandardSchemaSchemaSource, UntypedInputObject, UntypedSchema, UntypedSchemaSource, ValibotSchema, ValibotSchemaSource, Zod3SchemaSource } from "./types.cjs";
|
|
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-u7ovYS9e.cjs";
|
|
2
|
+
import { BaseSchemaSource, ExtractedSchema, InferExtractOptions, JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBigint, JsonSchemaBoolean, JsonSchemaConditionalKeywords, JsonSchemaDate, JsonSchemaDecimal, JsonSchemaDecimalFormat, JsonSchemaEnum, JsonSchemaInteger, JsonSchemaIntegerFormat, JsonSchemaKeywords, JsonSchemaLike, JsonSchemaLiteral, JsonSchemaLogicKeywords, JsonSchemaMap, JsonSchemaMetadataKeywords, JsonSchemaNativeEnum, JsonSchemaNever, JsonSchemaNull, JsonSchemaNullable, JsonSchemaNumber, JsonSchemaNumberFormat, JsonSchemaObject, JsonSchemaOf, JsonSchemaPrimitiveType, JsonSchemaPrimitiveUnion, JsonSchemaRecord, JsonSchemaRecordPropertyNames, JsonSchemaRef, JsonSchemaSchemaSource, JsonSchemaSet, JsonSchemaString, JsonSchemaStringFormat, JsonSchemaTuple, JsonSchemaType, JsonSchemaUndefined, JsonSchemaUnion, JsonSchemaUnknown, Meta, MetaDeprecated, MetaInput, MetaLink, MetaValue, Schema, SchemaInput, SchemaInputVariant, SchemaInputWithMeta, SchemaMeta, SchemaMetaExample, SchemaMetaInput, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant, SpecOf, StandardSchemaSchemaSource, UntypedInputObject, UntypedSchema, UntypedSchemaSource, ValibotSchema, ValibotSchemaSource, Zod3SchemaSource } from "./types.cjs";
|
|
4
3
|
import { GenerateParserCodeOptions, generateParserCode, getJsonSchemaType, stringifyType, stringifyValue } from "./codegen.cjs";
|
|
5
|
-
import {
|
|
6
|
-
import { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge } from "./helpers.cjs";
|
|
7
|
-
import { applyJsonSchemaMetadata, getPrimarySchemaType, readSchemaTypes } from "./metadata.cjs";
|
|
8
|
-
import {
|
|
9
|
-
import { ResolveOptions, resolve, resolveModule, resolveSafe, resolveTSType } from "./resolve.cjs";
|
|
10
|
-
import { isFileReference, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isSchema, isSchemaObject, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema } from "./type-checks.cjs";
|
|
4
|
+
import { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaMeta, extractSchemaWithSource, extractSource, extractTSType, extractVariant } from "./extract.cjs";
|
|
5
|
+
import { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge, mergeMetadata } from "./helpers.cjs";
|
|
6
|
+
import { applyJsonSchemaMetadata, formatMetaVersion, getPrimarySchemaType, readSchemaTypes, resolveMetaDescription, resolveMetaDisplayName, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaVersion } from "./metadata.cjs";
|
|
7
|
+
import { isFileReference, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isSchema, isSchemaObject, isSchemaOf, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema } from "./type-checks.cjs";
|
|
11
8
|
|
|
12
9
|
//#region src/index.d.ts
|
|
13
10
|
declare module "zod" {
|
|
@@ -33,5 +30,5 @@ declare module "zod" {
|
|
|
33
30
|
}
|
|
34
31
|
}
|
|
35
32
|
//#endregion
|
|
36
|
-
export { BaseSchemaSource,
|
|
33
|
+
export { BaseSchemaSource, ExtractedSchema, GenerateParserCodeOptions, GetPropertyResult, InferExtractOptions, JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBigint, JsonSchemaBoolean, JsonSchemaConditionalKeywords, JsonSchemaDate, JsonSchemaDecimal, JsonSchemaDecimalFormat, JsonSchemaEnum, JsonSchemaInteger, JsonSchemaIntegerFormat, JsonSchemaKeywords, JsonSchemaLike, JsonSchemaLiteral, JsonSchemaLogicKeywords, JsonSchemaMap, JsonSchemaMetadataKeywords, JsonSchemaNativeEnum, JsonSchemaNever, JsonSchemaNull, JsonSchemaNullable, JsonSchemaNumber, JsonSchemaNumberFormat, JsonSchemaObject, JsonSchemaOf, JsonSchemaPrimitiveType, JsonSchemaPrimitiveUnion, JsonSchemaRecord, JsonSchemaRecordPropertyNames, JsonSchemaRef, JsonSchemaSchemaSource, JsonSchemaSet, JsonSchemaString, JsonSchemaStringFormat, JsonSchemaTuple, JsonSchemaType, JsonSchemaTypeNames, JsonSchemaUndefined, JsonSchemaUnion, JsonSchemaUnknown, Meta, MetaDeprecated, MetaInput, MetaLink, MetaValue, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS, Schema, SchemaInput, SchemaInputVariant, SchemaInputWithMeta, SchemaMeta, SchemaMetaExample, SchemaMetaInput, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant, SpecOf, StandardSchemaSchemaSource, UntypedInputObject, UntypedSchema, UntypedSchemaSource, ValibotSchema, ValibotSchemaSource, Zod3SchemaSource, addProperty, applyJsonSchemaMetadata, bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaMeta, extractSchemaWithSource, extractSource, extractTSType, extractVariant, formatMetaVersion, generateParserCode, getJsonSchema, getJsonSchemaObject, getJsonSchemaType, getPrimarySchemaType, getProperties, getPropertiesList, getProperty, isFileReference, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isPropertyOptional, isSchema, isSchemaNullable, isSchemaObject, isSchemaOf, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema, isValidSchemaInputFile, merge, mergeMetadata, readSchemaTypes, resolveMetaDescription, resolveMetaDisplayName, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaVersion, stringifyType, stringifyValue };
|
|
37
34
|
//# sourceMappingURL=index.d.cts.map
|
package/dist/index.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;YAmBY,UAAA;IACR,EAAA;IACA,KAAA;IACA,WAAA;IACA,IAAA;IACA,KAAA;IACA,IAAA;IACA,UAAA;IACA,MAAA;IACA,MAAA;IACA,QAAA;IACA,OAAA;IACA,QAAA;IACA,QAAA;IACA,SAAA;IACA,eAAA;IACA,gBAAA;IACA,aAAA;IAAA,CACC,OAAA;EAAA;AAAA"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,13 +1,10 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { BaseSchemaSource, ExtractedSchema, JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBigint, JsonSchemaBoolean, JsonSchemaConditionalKeywords, JsonSchemaDate, JsonSchemaDecimal, JsonSchemaDecimalFormat, JsonSchemaEnum, JsonSchemaInteger, JsonSchemaIntegerFormat, JsonSchemaKeywords, JsonSchemaLike, JsonSchemaLiteral, JsonSchemaLogicKeywords, JsonSchemaMap, JsonSchemaMetadataKeywords, JsonSchemaNativeEnum, JsonSchemaNever, JsonSchemaNull, JsonSchemaNullable, JsonSchemaNumber, JsonSchemaNumberFormat, JsonSchemaObject, JsonSchemaOf, JsonSchemaPrimitiveType, JsonSchemaPrimitiveUnion, JsonSchemaRecord, JsonSchemaRecordPropertyNames, JsonSchemaRef, JsonSchemaSchemaSource, JsonSchemaSet, JsonSchemaString, JsonSchemaStringFormat, JsonSchemaTuple, JsonSchemaType, JsonSchemaUndefined, JsonSchemaUnion, JsonSchemaUnknown, Schema, SchemaInput, SchemaInputVariant, SchemaInputWithMeta, SchemaMeta, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant, SpecOf, StandardSchemaSchemaSource, UntypedInputObject, UntypedSchema, UntypedSchemaSource, ValibotSchema, ValibotSchemaSource, Zod3SchemaSource } from "./types.mjs";
|
|
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-u7ovYS9e.mjs";
|
|
2
|
+
import { BaseSchemaSource, ExtractedSchema, InferExtractOptions, JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBigint, JsonSchemaBoolean, JsonSchemaConditionalKeywords, JsonSchemaDate, JsonSchemaDecimal, JsonSchemaDecimalFormat, JsonSchemaEnum, JsonSchemaInteger, JsonSchemaIntegerFormat, JsonSchemaKeywords, JsonSchemaLike, JsonSchemaLiteral, JsonSchemaLogicKeywords, JsonSchemaMap, JsonSchemaMetadataKeywords, JsonSchemaNativeEnum, JsonSchemaNever, JsonSchemaNull, JsonSchemaNullable, JsonSchemaNumber, JsonSchemaNumberFormat, JsonSchemaObject, JsonSchemaOf, JsonSchemaPrimitiveType, JsonSchemaPrimitiveUnion, JsonSchemaRecord, JsonSchemaRecordPropertyNames, JsonSchemaRef, JsonSchemaSchemaSource, JsonSchemaSet, JsonSchemaString, JsonSchemaStringFormat, JsonSchemaTuple, JsonSchemaType, JsonSchemaUndefined, JsonSchemaUnion, JsonSchemaUnknown, Meta, MetaDeprecated, MetaInput, MetaLink, MetaValue, Schema, SchemaInput, SchemaInputVariant, SchemaInputWithMeta, SchemaMeta, SchemaMetaExample, SchemaMetaInput, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant, SpecOf, StandardSchemaSchemaSource, UntypedInputObject, UntypedSchema, UntypedSchemaSource, ValibotSchema, ValibotSchemaSource, Zod3SchemaSource } from "./types.mjs";
|
|
4
3
|
import { GenerateParserCodeOptions, generateParserCode, getJsonSchemaType, stringifyType, stringifyValue } from "./codegen.mjs";
|
|
5
|
-
import {
|
|
6
|
-
import { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge } from "./helpers.mjs";
|
|
7
|
-
import { applyJsonSchemaMetadata, getPrimarySchemaType, readSchemaTypes } from "./metadata.mjs";
|
|
8
|
-
import {
|
|
9
|
-
import { ResolveOptions, resolve, resolveModule, resolveSafe, resolveTSType } from "./resolve.mjs";
|
|
10
|
-
import { isFileReference, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isSchema, isSchemaObject, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema } from "./type-checks.mjs";
|
|
4
|
+
import { bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaMeta, extractSchemaWithSource, extractSource, extractTSType, extractVariant } from "./extract.mjs";
|
|
5
|
+
import { GetPropertyResult, addProperty, getJsonSchema, getJsonSchemaObject, getProperties, getPropertiesList, getProperty, isPropertyOptional, isSchemaNullable, isValidSchemaInputFile, merge, mergeMetadata } from "./helpers.mjs";
|
|
6
|
+
import { applyJsonSchemaMetadata, formatMetaVersion, getPrimarySchemaType, readSchemaTypes, resolveMetaDescription, resolveMetaDisplayName, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaVersion } from "./metadata.mjs";
|
|
7
|
+
import { isFileReference, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isSchema, isSchemaObject, isSchemaOf, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema } from "./type-checks.mjs";
|
|
11
8
|
|
|
12
9
|
//#region src/index.d.ts
|
|
13
10
|
declare module "zod" {
|
|
@@ -33,5 +30,5 @@ declare module "zod" {
|
|
|
33
30
|
}
|
|
34
31
|
}
|
|
35
32
|
//#endregion
|
|
36
|
-
export { BaseSchemaSource,
|
|
33
|
+
export { BaseSchemaSource, ExtractedSchema, GenerateParserCodeOptions, GetPropertyResult, InferExtractOptions, JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchema, JsonSchemaAllOf, JsonSchemaAny, JsonSchemaAnyOf, JsonSchemaArray, JsonSchemaBigint, JsonSchemaBoolean, JsonSchemaConditionalKeywords, JsonSchemaDate, JsonSchemaDecimal, JsonSchemaDecimalFormat, JsonSchemaEnum, JsonSchemaInteger, JsonSchemaIntegerFormat, JsonSchemaKeywords, JsonSchemaLike, JsonSchemaLiteral, JsonSchemaLogicKeywords, JsonSchemaMap, JsonSchemaMetadataKeywords, JsonSchemaNativeEnum, JsonSchemaNever, JsonSchemaNull, JsonSchemaNullable, JsonSchemaNumber, JsonSchemaNumberFormat, JsonSchemaObject, JsonSchemaOf, JsonSchemaPrimitiveType, JsonSchemaPrimitiveUnion, JsonSchemaRecord, JsonSchemaRecordPropertyNames, JsonSchemaRef, JsonSchemaSchemaSource, JsonSchemaSet, JsonSchemaString, JsonSchemaStringFormat, JsonSchemaTuple, JsonSchemaType, JsonSchemaTypeNames, JsonSchemaUndefined, JsonSchemaUnion, JsonSchemaUnknown, Meta, MetaDeprecated, MetaInput, MetaLink, MetaValue, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS, Schema, SchemaInput, SchemaInputVariant, SchemaInputWithMeta, SchemaMeta, SchemaMetaExample, SchemaMetaInput, SchemaOf, SchemaSource, SchemaSourceInput, SchemaSourceVariant, SpecOf, StandardSchemaSchemaSource, UntypedInputObject, UntypedSchema, UntypedSchemaSource, ValibotSchema, ValibotSchemaSource, Zod3SchemaSource, addProperty, applyJsonSchemaMetadata, bundleReferences, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaMeta, extractSchemaWithSource, extractSource, extractTSType, extractVariant, formatMetaVersion, generateParserCode, getJsonSchema, getJsonSchemaObject, getJsonSchemaType, getPrimarySchemaType, getProperties, getPropertiesList, getProperty, isFileReference, isJsonSchema, isJsonSchemaAllOf, isJsonSchemaAny, isJsonSchemaAnyOf, isJsonSchemaArray, isJsonSchemaBigint, isJsonSchemaBoolean, isJsonSchemaDate, isJsonSchemaDecimal, isJsonSchemaEnum, isJsonSchemaInteger, isJsonSchemaKeywords, isJsonSchemaLiteral, isJsonSchemaMap, isJsonSchemaNativeEnum, isJsonSchemaNever, isJsonSchemaNull, isJsonSchemaNullable, isJsonSchemaNumber, isJsonSchemaObject, isJsonSchemaPrimitiveType, isJsonSchemaPrimitiveUnion, isJsonSchemaRecord, isJsonSchemaRef, isJsonSchemaSet, isJsonSchemaString, isJsonSchemaTuple, isJsonSchemaType, isJsonSchemaUndefined, isJsonSchemaUnion, isJsonSchemaUnknown, isNullOnlyJsonSchema, isPropertyOptional, isSchema, isSchemaNullable, isSchemaObject, isSchemaOf, isSchemaWithSource, isStandardSchema, isUntypedInput, isUntypedInputStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema, isValidSchemaInputFile, merge, mergeMetadata, readSchemaTypes, resolveMetaDescription, resolveMetaDisplayName, resolveMetaExample, resolveMetaId, resolveMetaLinks, resolveMetaName, resolveMetaVersion, stringifyType, stringifyValue };
|
|
37
34
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import"./types.mjs";import{JSON_SCHEMA_METADATA_KEYS as e,JSON_SCHEMA_PRIMITIVE_TYPES as t,JSON_SCHEMA_TYPES as n,JsonSchemaTypeNames as r,SCHEMA_ARRAY_CONCAT_KEYWORDS as i,SCHEMA_RECORD_KEYWORDS as a,SCHEMA_SINGLE_KEYWORDS as o
|
|
1
|
+
import"./types.mjs";import{JSON_SCHEMA_METADATA_KEYS as e,JSON_SCHEMA_PRIMITIVE_TYPES as t,JSON_SCHEMA_TYPES as n,JsonSchemaTypeNames as r,SCHEMA_ARRAY_CONCAT_KEYWORDS as i,SCHEMA_RECORD_KEYWORDS as a,SCHEMA_SINGLE_KEYWORDS as o}from"./constants.mjs";import{isFileReference as s,isJsonSchema as c,isJsonSchemaAllOf as l,isJsonSchemaAny as u,isJsonSchemaAnyOf as d,isJsonSchemaArray as f,isJsonSchemaBigint as p,isJsonSchemaBoolean as m,isJsonSchemaDate as h,isJsonSchemaDecimal as g,isJsonSchemaEnum as _,isJsonSchemaInteger as v,isJsonSchemaKeywords as y,isJsonSchemaLiteral as b,isJsonSchemaMap as x,isJsonSchemaNativeEnum as S,isJsonSchemaNever as C,isJsonSchemaNull as w,isJsonSchemaNullable as T,isJsonSchemaNumber as E,isJsonSchemaObject as D,isJsonSchemaPrimitiveType as O,isJsonSchemaPrimitiveUnion as k,isJsonSchemaRecord as A,isJsonSchemaRef as j,isJsonSchemaSet as M,isJsonSchemaString as N,isJsonSchemaTuple as P,isJsonSchemaType as F,isJsonSchemaUndefined as I,isJsonSchemaUnion as L,isJsonSchemaUnknown as R,isNullOnlyJsonSchema as z,isSchema as B,isSchemaObject as V,isSchemaOf as H,isSchemaWithSource as U,isStandardSchema as W,isUntypedInput as G,isUntypedInputStrict as K,isUntypedSchema as q,isUntypedSchemaStrict as J,isValibotSchema as Y}from"./type-checks.mjs";import{C as X,E as Z,S as Q,T as $,_ as ee,a as te,b as ne,c as re,d as ie,f as ae,g as oe,h as se,i as ce,l as le,m as ue,n as de,o as fe,p as pe,r as me,s as he,t as ge,u as _e,v as ve,w as ye,x as be,y as xe}from"./metadata-DIEpQjbq.mjs";import{bundleReferences as Se,extract as Ce,extractHash as we,extractJsonSchema as Te,extractResolvedVariant as Ee,extractSchema as De,extractSchemaMeta as Oe,extractSchemaWithSource as ke,extractSource as Ae,extractTSType as je,extractVariant as Me}from"./extract.mjs";export{e as JSON_SCHEMA_METADATA_KEYS,t as JSON_SCHEMA_PRIMITIVE_TYPES,n as JSON_SCHEMA_TYPES,r as JsonSchemaTypeNames,i as SCHEMA_ARRAY_CONCAT_KEYWORDS,a as SCHEMA_RECORD_KEYWORDS,o as SCHEMA_SINGLE_KEYWORDS,oe as addProperty,ge as applyJsonSchemaMetadata,Se as bundleReferences,Ce as extract,we as extractHash,Te as extractJsonSchema,Ee as extractResolvedVariant,De as extractSchema,Oe as extractSchemaMeta,ke as extractSchemaWithSource,Ae as extractSource,je as extractTSType,Me as extractVariant,de as formatMetaVersion,ae as generateParserCode,ee as getJsonSchema,ve as getJsonSchemaObject,pe as getJsonSchemaType,me as getPrimarySchemaType,xe as getProperties,ne as getPropertiesList,be as getProperty,s as isFileReference,c as isJsonSchema,l as isJsonSchemaAllOf,u as isJsonSchemaAny,d as isJsonSchemaAnyOf,f as isJsonSchemaArray,p as isJsonSchemaBigint,m as isJsonSchemaBoolean,h as isJsonSchemaDate,g as isJsonSchemaDecimal,_ as isJsonSchemaEnum,v as isJsonSchemaInteger,y as isJsonSchemaKeywords,b as isJsonSchemaLiteral,x as isJsonSchemaMap,S as isJsonSchemaNativeEnum,C as isJsonSchemaNever,w as isJsonSchemaNull,T as isJsonSchemaNullable,E as isJsonSchemaNumber,D as isJsonSchemaObject,O as isJsonSchemaPrimitiveType,k as isJsonSchemaPrimitiveUnion,A as isJsonSchemaRecord,j as isJsonSchemaRef,M as isJsonSchemaSet,N as isJsonSchemaString,P as isJsonSchemaTuple,F as isJsonSchemaType,I as isJsonSchemaUndefined,L as isJsonSchemaUnion,R as isJsonSchemaUnknown,z as isNullOnlyJsonSchema,Q as isPropertyOptional,B as isSchema,X as isSchemaNullable,V as isSchemaObject,H as isSchemaOf,U as isSchemaWithSource,W as isStandardSchema,G as isUntypedInput,K as isUntypedInputStrict,q as isUntypedSchema,J as isUntypedSchemaStrict,Y as isValibotSchema,ye as isValidSchemaInputFile,$ as merge,Z as mergeMetadata,ce as readSchemaTypes,te as resolveMetaDescription,fe as resolveMetaDisplayName,he as resolveMetaExample,re as resolveMetaId,le as resolveMetaLinks,_e as resolveMetaName,ie as resolveMetaVersion,ue as stringifyType,se as stringifyValue};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
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");let u=require("@stryke/type-checks"),d=require("@stryke/convert/to-array"),f=require("@stryke/date/format"),p=require("@stryke/date/validate"),m=require("@stryke/helpers/get-unique"),h=require("@stryke/string-format/kebab-case"),g=require("@stryke/string-format/title-case"),_=require("@stryke/type-checks/is-date"),v=require("@stryke/type-checks/is-function"),y=require("@stryke/type-checks/is-number"),b=require("@stryke/type-checks/is-set-object"),x=require("@stryke/type-checks/is-set-string"),ee=require("@stryke/unique-id/nanoid"),te=require("@stryke/convert/to-bool"),S=require("@stryke/string-format/camel-case"),C=require("@stryke/string-format/list"),w=require("@stryke/type-checks/is-boolean"),T=require("@stryke/type-checks/is-null"),E=require("@stryke/type-checks/is-undefined"),D=require("@stryke/path/find"),ne=require("@stryke/resolve/constants"),O=require("defu");O=s(O,1);function k(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 A(e){let t=k(e);if(!l.isJsonSchemaObject(t))throw TypeError(`The provided input is not a valid JSON Schema object`);return t}function j(e){let t=A(e);return(0,u.isSetObject)(t.properties)?Object.entries(t.properties).reduce((e,[n,r])=>(r.name=n,r.required=!z(t,n),r.default=t.default?.[n]??r.default,e[n]=r,e),{}):{}}function M(e){return Object.values(j(e))}function N(e,t){let n=A(e);if(!(0,u.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:!z(n,t),default:n.default?.[t]??r?.default}}function P(e,t,n){let r=A(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 F(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];if(e===`required`)n[e]=(0,m.getUnique)([...Array.isArray(t)?t:[],...Array.isArray(r)?r:[]]);else if(c.SCHEMA_RECORD_KEYWORDS.has(e)&&(0,u.isSetObject)(t)&&(0,u.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)?F(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]=F(t,r):n[e]=r}return n}function I(...e){let t=e.map(e=>k(e));return t.length===0?{}:t.reduce((e,t)=>{let n=e.type,r=t.type;return n&&r&&n!==r?t:F(e,t)})}function L(e,t){return(0,O.default)(e,Object.fromEntries(c.JSON_SCHEMA_METADATA_KEYS.filter(e=>t[e]!==void 0).map(e=>[e,t[e]])))}function R(e){return(0,u.isSetObject)(e)?e.nullable===!0?!0:J(e).includes(`null`):!1}function z(e,t){if(!e.properties?.[t])throw Error(`The property "${t}" does not exist in the parent schema.`);return!(e.required??[]).includes(t)}function B(e){return ne.VALID_OBJECT_SOURCE_EXTENSIONS.includes((0,D.findFileExtensionSafe)(e))}function V(e,t){return(0,E.isUndefined)(e)?`undefined`:(0,T.isNull)(e)?`null`:t===`boolean`||(0,w.isBoolean)(e)?String((0,te.toBool)(e)):t===`number`||(0,y.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 H(e){if(!e)return`unknown`;if(typeof e==`boolean`)return e?`unknown`:`never`;if(l.isJsonSchemaObject(e)&&(0,x.isSetString)(e.name))return e.name;let t=e;if((0,x.isSetString)(t.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(t.$ref)?.[1]??t.$ref;if(l.isJsonSchemaLiteral(e)&&!(0,E.isUndefined)(e.const))return JSON.stringify((0,x.isSetString)(e.const)?e.const.replaceAll(/^['"`]|['"`]$/g,``):e.const);let n=Y(e);if(n)return n===`integer`||n===`number`?`number`:n;if(t.type===`array`&&Array.isArray(t.enum))return t.enum.map(e=>JSON.stringify(e)).join(` | `);if(t.const!==void 0)return JSON.stringify(t.const);if(t.type===`array`||t.items)return`${H(Array.isArray(t.items)?t.items[0]:t.items)}[]`;if(t.type===`object`||t.properties||t.additionalProperties){if(l.isJsonSchema(t.additionalProperties))return`{ [key: string]: ${H(t.additionalProperties)} }`;if(l.isJsonSchemaObject(t)){let e=t.required??[];return`{ ${M(t).map(t=>{let n=!e.includes(t.name)||R(t)?`${e.includes(t.name)?``:`?`}${R(t)?` | null`:``}`:``;return`${t.name}${n}: ${H(t)}`}).join(`;
|
|
2
|
+
`)} }`}}return t.oneOf||t.anyOf?(t.oneOf??t.anyOf??[]).map(e=>H(e)).join(` | `):t.allOf?`object`:`unknown`}function U(e){return(0,T.isNull)(e)?`null`:(0,w.isBoolean)(e)?`boolean`:(0,u.isInteger)(e)?`integer`:(0,y.isNumber)(e)?`number`:(0,u.isString)(e)?`string`:(0,u.isObject)(e)?`object`:Array.isArray(e)?`array`:void 0}function W(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 K(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function q(e,t){return`${e} + ${JSON.stringify(t)}`}function re(e,t={}){let n=e,r=typeof n==`boolean`?{}:{...n.definitions,...n.$defs},i={};function a(e){let t=i[e]??0;return i[e]=t+1,`${e}${t>0?`${t}`:``}`}function o(e,n,i,o,c=`errors`){if(typeof e==`boolean`)return e?[`${o} = ${n};`]:[`${c}.push({ path: ${i}, failure: "No value is allowed at this location" });`,`${o} = ${n};`];if((0,x.isSetString)(e.$ref)){let t=W(e.$ref);return t&&t in r?[`${o} = ${G(t)}(${n}, ${i}, ${c});`]:[`${o} = ${n};`]}let l=a(e.name?`${(0,S.camelCase)(e.name)}Value`:`value`),u=a(e.name?`${(0,S.camelCase)(e.name)}Path`:`path`),d=[`const ${l} = ${n};`,`const ${u} = ${i};`];return!t.ignoreDefaults&&e.default!==void 0?(d.push(`if (${l} === undefined${e.type===`string`?` || ${l} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${l})`:``}) {`,` ${o} = ${JSON.stringify(e.default)};`,`} else {`),R(e)?(d.push(` if (${l} === null) {`,` ${o} = null;`,` } else {`),d.push(...s(e,l,u,o,c)),d.push(` }`)):d.push(...s(e,l,u,o,c)),d.push(`}`),d):(d.push(`if (${l} === undefined) {`,` ${c}.push({ path: ${u}, failure: "A value is required" });`,` ${o} = ${l};`,`} else {`),R(e)?(d.push(` if (${l} === null) {`,` ${o} = null;`,` } else {`),d.push(...s(e,l,u,o,c)),d.push(` }`)):d.push(...s(e,l,u,o,c)),d.push(`}`),d)}function s(e,t,n,r,i){let s=[];if(e.const!==void 0){let a=JSON.stringify(e.const);return s.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${a}) { ${i}.push({ path: ${n}, failure: "Expected the constant value " + ${a} }); }`,`${r} = ${a};`),s}if(Array.isArray(e.enum)){let a=JSON.stringify(e.enum);return s.push(`if (!${a}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${i}.push({ path: ${n}, failure: \`Expected one of: ${(0,C.list)(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),s}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let c=e.oneOf??e.anyOf??[],l=a(e.name?`${(0,S.camelCase)(e.name)}Matched`:`matched`);s.push(`let ${l} = false;`);for(let i of c){let c=a(e.name?`${(0,S.camelCase)(e.name)}BranchErrors`:`branchErrors`),u=a(e.name?`${(0,S.camelCase)(e.name)}BranchResult`:`branchResult`);s.push(`if (!${l}) {`),s.push(` const ${c}: { path: string; failure: string }[] = [];`,` let ${u};`),s.push(...o(i,t,n,u,c)),s.push(` if (${c}.length === 0) {`,` ${r} = ${u};`,` ${l} = true;`,` }`,`}`)}return s.push(`if (!${l}) {`,` ${i}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),s}if(Array.isArray(e.allOf)){let{allOf:a,...c}=e,l=I(c,...a);return s.push(...o(l,t,n,r,i)),s}let l=K(e);switch(Y(e)??l.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:s.push(...c(e,t,n,r,i));break;case`array`:s.push(...d(e,t,n,r,i));break;case`string`:s.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:s.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 {`,` ${i}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:s.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:s.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:s.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:s.push(`${r} = ${t};`);break}return s}function c(e,t,n,r,i){let s=H(e),c=[`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an object value" });`,` ${r} = ${t};`,`} else {`],d=a(s||e.name?`${(0,S.camelCase)(s||e.name)}Schema`:`schema`);if(c.push(`const ${d} = {} as Record<string, any>`),l.isJsonSchemaObject(e)){let r=new Set;for(let s of M(e)){r.add(s.name);let e;(0,u.isSetArray)(s.alias)?(e=`(${s.alias.map(e=>`${t}[${JSON.stringify(e)}]`).join(` ${l.isJsonSchemaString(s)?`||`:`??`} `)} ${l.isJsonSchemaString(s)?`||`:`??`} ${t}[${JSON.stringify(s.name)}])`,s.alias.forEach(e=>r.add(e))):e=`${t}[${JSON.stringify(s.name)}]`;let f=q(n,`.${s.name}`),p=a(s.name?`${(0,S.camelCase)(s.name)}Property`:`property`),m=s.default===void 0?s.required?`${i}.push({ path: ${f}, failure: "Required property is missing" });`:``:`${d}[${JSON.stringify(s.name)}] = ${JSON.stringify(s.default)};`;c.push(` if (${e} !== undefined) {`,` let ${p};`),c.push(...o(s,e,f,p,i)),c.push(`${d}[${JSON.stringify(s.name)}] = ${p};`),m?c.push(`} else { ${m} }`):c.push(`}`)}let f=e.additionalProperties;if(l.isJsonSchema(f)){let l=a(s||e.name?`${(0,S.camelCase)(s||e.name)}AdditionalProperties`:`additionalProperties`);c.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` let ${l};`),c.push(...o(f,`${t}[key]`,`${n} + "." + key`,l,i)),c.push(`${d}[key] = ${l};`,`}`)}else f!==!1&&c.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` ${d}[key] = ${t}[key];`,`}`)}return c.push(`${r} = ${d};`,`}`),c}function d(e,t,n,r,i){let s=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],c=a(e.name?`${(0,S.camelCase)(e.name)}Array`:`array`);s.push(`const ${c}: unknown[] = [];`);let l=e.prefixItems??(Array.isArray(e.items)?e.items:void 0);if(l){let a=Array.isArray(e.items)?void 0:e.items;return s.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),l.forEach((e,t)=>{s.push(` ${t===0?`if`:`else if`} (index === ${t}) {`),s.push(...o(e,`item`,q(n,`[${t}]`),`itemResult`,i)),s.push(`}`)}),a?(s.push(`else {`),s.push(...o(a,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),s.push(`}`)):s.push(`else { itemResult = item; }`),s.push(` ${c}.push(itemResult);`,` }`,` ${r} = ${c};`,`}`),s}let u=e.items??!0;return s.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),s.push(...o(u,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),s.push(` ${c}.push(itemResult);`,` }`,` ${r} = ${c};`,`}`),s}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(r).map(([e,t])=>`function ${G(e)}(inputValue, inputPath, errors) {
|
|
28
|
+
let result;
|
|
29
|
+
${o(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
|
+
${o(e,`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
|
+
}`}function ie(e,t){if(!t||!(0,b.isSetObject)(e))return e;let n={...e},r=n;for(let e of c.JSON_SCHEMA_METADATA_KEYS){let n=t[e];n!=null&&(r[e]=n)}return n}function J(e){if(!(0,b.isSetObject)(e))return[];let t=e;return Array.isArray(t.type)?t.type.filter(e=>(0,x.isSetString)(e)):(0,x.isSetString)(t.type)&&t.type!==`object`&&t.type!==`array`?[t.type]:[]}function Y(e){if((0,b.isSetObject)(e))return J(e).find(e=>e!==`null`)}function X(e){return(0,_.isDate)(e)?(0,f.formatYYYYMMDD)(e):(0,y.isNumber)(e)?(0,p.isValidTimestamp)(e)&&e>1e9?(0,f.formatYYYYMMDD)(new Date(e)):e.toString():(0,x.isSetString)(e)?e:`1.0`}function Z(e,t,n){let r=n??t?.version??e?.version;return(0,v.isFunction)(r)?async e=>X(await Promise.resolve(r(e))):X(r)}function Q(e,t,n){return n??t.name??((0,x.isSetString)(e?.name)?e.name:(0,x.isSetString)(e?.displayName)?e.displayName:e.$id?(0,h.kebabCase)(e.$id):H(e))}function ae(e,t){let n=Q(e,t),r=Z(e,t);return n?(0,v.isFunction)(n)?(0,v.isFunction)(r)?async e=>`${(0,h.kebabCase)(await Promise.resolve(n(e)))}@${await Promise.resolve(r(e))}`:async e=>`${(0,h.kebabCase)(await Promise.resolve(n(e)))}@${r}`:(0,v.isFunction)(r)?async e=>`${(0,h.kebabCase)(n)}@${await Promise.resolve(r(e))}`:`${(0,h.kebabCase)(n)}@${r}`:(0,ee.nanoid)()}function $(e,t,n){let r=n??t.displayName??e?.displayName;if(r!==void 0)return r;let i=t.name;return(0,v.isFunction)(i)?async e=>(0,g.titleCase)(await Promise.resolve(i(e))):(0,g.titleCase)(i??H(e))}function oe(e,t,n,r){n.displayName??=$(t,n);let i=(0,v.isFunction)(n.displayName)?async t=>e.replaceAll(/\{\s*displayName\s*\}/g,await Promise.resolve(n.displayName(t))):e.replaceAll(/\{\s*displayName\s*\}/g,n.displayName),a=r??n.description??t?.description;return a=(0,v.isFunction)(a)?async e=>{let t=await Promise.resolve(a(e));return(0,x.isSetString)(t)?t:(0,v.isFunction)(i)?i(e):i}:(0,x.isSetString)(a)?a:i,a}function se(e,t,n){let r=e=>e.map((e,t)=>(0,x.isSetString)(e)?{description:`Example #${t+1}`,value:e}:(0,b.isSetObject)(e)&&`value`in e&&(0,x.isSetString)(e.value)?{description:e.description||`Example #${t+1}`,value:e.value}:void 0).filter(Boolean),i=n??t.examples??e?.examples??[];return(0,v.isFunction)(i)?async e=>r((0,d.toArray)(await Promise.resolve(i(e)))):r((0,d.toArray)(i))}function ce(e,t,n){return(0,v.isFunction)(n)||(0,v.isFunction)(t.links)?async r=>(0,m.getUnique)((0,d.toArray)((0,v.isFunction)(n)?await Promise.resolve(n(r)):n).concat((0,v.isFunction)(t.links)?await Promise.resolve(t.links(r)):t.links??[]).concat(e?.docs??[])):(0,m.getUnique)((0,d.toArray)(n).concat(t.links??[]).concat(e?.docs??[]))}Object.defineProperty(exports,"C",{enumerable:!0,get:function(){return R}}),Object.defineProperty(exports,"E",{enumerable:!0,get:function(){return L}}),Object.defineProperty(exports,"S",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"T",{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,"_",{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return oe}}),Object.defineProperty(exports,"b",{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return ae}}),Object.defineProperty(exports,"d",{enumerable:!0,get:function(){return Z}}),Object.defineProperty(exports,"f",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"g",{enumerable:!0,get:function(){return P}}),Object.defineProperty(exports,"h",{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return ce}}),Object.defineProperty(exports,"m",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"p",{enumerable:!0,get:function(){return U}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return se}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ie}}),Object.defineProperty(exports,"u",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"v",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"w",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"x",{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,"y",{enumerable:!0,get:function(){return j}});
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import{JSON_SCHEMA_METADATA_KEYS as e,SCHEMA_ARRAY_CONCAT_KEYWORDS as t,SCHEMA_RECORD_KEYWORDS as n,SCHEMA_SINGLE_KEYWORDS as r}from"./constants.mjs";import{isJsonSchema as i,isJsonSchemaLiteral as a,isJsonSchemaObject as o,isJsonSchemaString as s,isSchema as c}from"./type-checks.mjs";import{isInteger as l,isObject as u,isSetArray as d,isSetObject as f,isString as p}from"@stryke/type-checks";import{toArray as m}from"@stryke/convert/to-array";import{formatYYYYMMDD as h}from"@stryke/date/format";import{isValidTimestamp as ee}from"@stryke/date/validate";import{getUnique as g}from"@stryke/helpers/get-unique";import{kebabCase as _}from"@stryke/string-format/kebab-case";import{titleCase as v}from"@stryke/string-format/title-case";import{isDate as te}from"@stryke/type-checks/is-date";import{isFunction as y}from"@stryke/type-checks/is-function";import{isNumber as b}from"@stryke/type-checks/is-number";import{isSetObject as x}from"@stryke/type-checks/is-set-object";import{isSetString as S}from"@stryke/type-checks/is-set-string";import{nanoid as ne}from"@stryke/unique-id/nanoid";import{toBool as re}from"@stryke/convert/to-bool";import{camelCase as C}from"@stryke/string-format/camel-case";import{list as w}from"@stryke/string-format/list";import{isBoolean as T}from"@stryke/type-checks/is-boolean";import{isNull as E}from"@stryke/type-checks/is-null";import{isUndefined as D}from"@stryke/type-checks/is-undefined";import{findFileExtensionSafe as ie}from"@stryke/path/find";import{VALID_OBJECT_SOURCE_EXTENSIONS as O}from"@stryke/resolve/constants";import k from"defu";function A(e){let t=c(e)?e.schema:e;if(!i(t))throw TypeError(`The provided input is not a valid JSON Schema`);return t}function j(e){let t=A(e);if(!o(t))throw TypeError(`The provided input is not a valid JSON Schema object`);return t}function M(e){let t=j(e);return f(t.properties)?Object.entries(t.properties).reduce((e,[n,r])=>(r.name=n,r.required=!z(t,n),r.default=t.default?.[n]??r.default,e[n]=r,e),{}):{}}function N(e){return Object.values(M(e))}function P(e,t){let n=j(e);if(!f(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:!z(n,t),default:n.default?.[t]??r?.default}}function F(e,t,n){let r=j(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 I(e,a){let o={...e};for(let[e,s]of Object.entries(a)){let a=o[e];if(e===`required`)o[e]=g([...Array.isArray(a)?a:[],...Array.isArray(s)?s:[]]);else if(n.has(e)&&f(a)&&f(s)){let t={...a};for(let[e,n]of Object.entries(s)){let r=t[e];t[e]=i(r)&&i(n)?I(r,n):n}o[e]=t}else t.has(e)&&Array.isArray(a)&&Array.isArray(s)?o[e]=[...a,...s]:r.has(e)&&i(a)&&i(s)?o[e]=I(a,s):o[e]=s}return o}function L(...e){let t=e.map(e=>A(e));return t.length===0?{}:t.reduce((e,t)=>{let n=e.type,r=t.type;return n&&r&&n!==r?t:I(e,t)})}function ae(t,n){return k(t,Object.fromEntries(e.filter(e=>n[e]!==void 0).map(e=>[e,n[e]])))}function R(e){return f(e)?e.nullable===!0?!0:J(e).includes(`null`):!1}function z(e,t){if(!e.properties?.[t])throw Error(`The property "${t}" does not exist in the parent schema.`);return!(e.required??[]).includes(t)}function B(e){return O.includes(ie(e))}function V(e,t){return D(e)?`undefined`:E(e)?`null`:t===`boolean`||T(e)?String(re(e)):t===`number`||b(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 H(e){if(!e)return`unknown`;if(typeof e==`boolean`)return e?`unknown`:`never`;if(o(e)&&S(e.name))return e.name;let t=e;if(S(t.$ref))return/^#\/(?:definitions|\$defs)\/(.+)$/.exec(t.$ref)?.[1]??t.$ref;if(a(e)&&!D(e.const))return JSON.stringify(S(e.const)?e.const.replaceAll(/^['"`]|['"`]$/g,``):e.const);let n=Y(e);if(n)return n===`integer`||n===`number`?`number`:n;if(t.type===`array`&&Array.isArray(t.enum))return t.enum.map(e=>JSON.stringify(e)).join(` | `);if(t.const!==void 0)return JSON.stringify(t.const);if(t.type===`array`||t.items)return`${H(Array.isArray(t.items)?t.items[0]:t.items)}[]`;if(t.type===`object`||t.properties||t.additionalProperties){if(i(t.additionalProperties))return`{ [key: string]: ${H(t.additionalProperties)} }`;if(o(t)){let e=t.required??[];return`{ ${N(t).map(t=>{let n=!e.includes(t.name)||R(t)?`${e.includes(t.name)?``:`?`}${R(t)?` | null`:``}`:``;return`${t.name}${n}: ${H(t)}`}).join(`;
|
|
2
|
+
`)} }`}}return t.oneOf||t.anyOf?(t.oneOf??t.anyOf??[]).map(e=>H(e)).join(` | `):t.allOf?`object`:`unknown`}function U(e){return E(e)?`null`:T(e)?`boolean`:l(e)?`integer`:b(e)?`number`:p(e)?`string`:u(e)?`object`:Array.isArray(e)?`array`:void 0}function W(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 K(e){let t=e.type;return Array.isArray(t)?[...t]:t?[t]:[]}function q(e,t){return`${e} + ${JSON.stringify(t)}`}function oe(e,t={}){let n=e,r=typeof n==`boolean`?{}:{...n.definitions,...n.$defs},a={};function c(e){let t=a[e]??0;return a[e]=t+1,`${e}${t>0?`${t}`:``}`}function l(e,n,i,a,o=`errors`){if(typeof e==`boolean`)return e?[`${a} = ${n};`]:[`${o}.push({ path: ${i}, failure: "No value is allowed at this location" });`,`${a} = ${n};`];if(S(e.$ref)){let t=W(e.$ref);return t&&t in r?[`${a} = ${G(t)}(${n}, ${i}, ${o});`]:[`${a} = ${n};`]}let s=c(e.name?`${C(e.name)}Value`:`value`),l=c(e.name?`${C(e.name)}Path`:`path`),d=[`const ${s} = ${n};`,`const ${l} = ${i};`];return!t.ignoreDefaults&&e.default!==void 0?(d.push(`if (${s} === undefined${e.type===`string`?` || ${s} === ""`:e.type===`number`||e.type===`integer`?` || Number.isNaN(${s})`:``}) {`,` ${a} = ${JSON.stringify(e.default)};`,`} else {`),R(e)?(d.push(` if (${s} === null) {`,` ${a} = null;`,` } else {`),d.push(...u(e,s,l,a,o)),d.push(` }`)):d.push(...u(e,s,l,a,o)),d.push(`}`),d):(d.push(`if (${s} === undefined) {`,` ${o}.push({ path: ${l}, failure: "A value is required" });`,` ${a} = ${s};`,`} else {`),R(e)?(d.push(` if (${s} === null) {`,` ${a} = null;`,` } else {`),d.push(...u(e,s,l,a,o)),d.push(` }`)):d.push(...u(e,s,l,a,o)),d.push(`}`),d)}function u(e,t,n,r,i){let a=[];if(e.const!==void 0){let o=JSON.stringify(e.const);return a.push(`if (${e.type===`string`?t:`JSON.stringify(${t})`} !== ${o}) { ${i}.push({ path: ${n}, failure: "Expected the constant value " + ${o} }); }`,`${r} = ${o};`),a}if(Array.isArray(e.enum)){let o=JSON.stringify(e.enum);return a.push(`if (!${o}.some(allowed => JSON.stringify(allowed) === JSON.stringify(${t}))) { ${i}.push({ path: ${n}, failure: \`Expected one of: ${w(e.enum.map(e=>JSON.stringify(e)),{conjunction:`or`})}, instead received: \${JSON.stringify(${t})}\` }); }`,`${r} = ${t};`),a}if(Array.isArray(e.oneOf)||Array.isArray(e.anyOf)){let o=e.oneOf??e.anyOf??[],s=c(e.name?`${C(e.name)}Matched`:`matched`);a.push(`let ${s} = false;`);for(let i of o){let o=c(e.name?`${C(e.name)}BranchErrors`:`branchErrors`),u=c(e.name?`${C(e.name)}BranchResult`:`branchResult`);a.push(`if (!${s}) {`),a.push(` const ${o}: { path: string; failure: string }[] = [];`,` let ${u};`),a.push(...l(i,t,n,u,o)),a.push(` if (${o}.length === 0) {`,` ${r} = ${u};`,` ${s} = true;`,` }`,`}`)}return a.push(`if (!${s}) {`,` ${i}.push({ path: ${n}, failure: \`The provided value \${JSON.stringify(${t})} does not match the allowed schemas\` });`,` ${r} = ${t};`,`}`),a}if(Array.isArray(e.allOf)){let{allOf:o,...s}=e,c=L(s,...o);return a.push(...l(c,t,n,r,i)),a}let o=K(e);switch(Y(e)??o.find(e=>e!==`null`)??(e.properties?`object`:e.items?`array`:void 0)){case`object`:a.push(...f(e,t,n,r,i));break;case`array`:a.push(...p(e,t,n,r,i));break;case`string`:a.push(`if (typeof ${t} === "string") {`,` ${r} = ${t};`,`} else if (typeof ${t} === "number" || typeof ${t} === "boolean") {`,` ${r} = String(${t});`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a string value" });`,` ${r} = ${t};`,`}`);break;case`integer`:a.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 {`,` ${i}.push({ path: ${n}, failure: "Expected an integer value" });`,` ${r} = ${t};`,`}`);break;case`number`:a.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a number value" });`,` ${r} = ${t};`,`}`);break;case`boolean`:a.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 {`,` ${i}.push({ path: ${n}, failure: "Expected a boolean value" });`,` ${r} = ${t};`,`}`);break;case`null`:a.push(`if (${t} === null) {`,` ${r} = null;`,`} else {`,` ${i}.push({ path: ${n}, failure: "Expected a null value" });`,` ${r} = ${t};`,`}`);break;case void 0:default:a.push(`${r} = ${t};`);break}return a}function f(e,t,n,r,a){let u=H(e),f=[`if (typeof ${t} !== "object" || ${t} === null || Array.isArray(${t})) {`,` ${a}.push({ path: ${n}, failure: "Expected an object value" });`,` ${r} = ${t};`,`} else {`],p=c(u||e.name?`${C(u||e.name)}Schema`:`schema`);if(f.push(`const ${p} = {} as Record<string, any>`),o(e)){let r=new Set;for(let i of N(e)){r.add(i.name);let e;d(i.alias)?(e=`(${i.alias.map(e=>`${t}[${JSON.stringify(e)}]`).join(` ${s(i)?`||`:`??`} `)} ${s(i)?`||`:`??`} ${t}[${JSON.stringify(i.name)}])`,i.alias.forEach(e=>r.add(e))):e=`${t}[${JSON.stringify(i.name)}]`;let o=q(n,`.${i.name}`),u=c(i.name?`${C(i.name)}Property`:`property`),m=i.default===void 0?i.required?`${a}.push({ path: ${o}, failure: "Required property is missing" });`:``:`${p}[${JSON.stringify(i.name)}] = ${JSON.stringify(i.default)};`;f.push(` if (${e} !== undefined) {`,` let ${u};`),f.push(...l(i,e,o,u,a)),f.push(`${p}[${JSON.stringify(i.name)}] = ${u};`),m?f.push(`} else { ${m} }`):f.push(`}`)}let o=e.additionalProperties;if(i(o)){let i=c(u||e.name?`${C(u||e.name)}AdditionalProperties`:`additionalProperties`);f.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` let ${i};`),f.push(...l(o,`${t}[key]`,`${n} + "." + key`,i,a)),f.push(`${p}[key] = ${i};`,`}`)}else o!==!1&&f.push(` for (const key of Object.keys(${t})) {`,` if (${JSON.stringify([...r])}.includes(key)) { continue; }`,` ${p}[key] = ${t}[key];`,`}`)}return f.push(`${r} = ${p};`,`}`),f}function p(e,t,n,r,i){let a=[`if (!Array.isArray(${t})) {`,` ${i}.push({ path: ${n}, failure: "Expected an array value" });`,` ${r} = ${t};`,`} else {`],o=c(e.name?`${C(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(...l(e,`item`,q(n,`[${t}]`),`itemResult`,i)),a.push(`}`)}),c?(a.push(`else {`),a.push(...l(c,`item`,`${n} + "[" + index + "]"`,`itemResult`,i)),a.push(`}`)):a.push(`else { itemResult = item; }`),a.push(` ${o}.push(itemResult);`,` }`,` ${r} = ${o};`,`}`),a}let u=e.items??!0;return a.push(` for (let index = 0; index < ${t}.length; index += 1) {`,` const item = ${t}[index];`,` let itemResult;`),a.push(...l(u,`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(r).map(([e,t])=>`function ${G(e)}(inputValue, inputPath, errors) {
|
|
28
|
+
let result;
|
|
29
|
+
${l(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
|
+
${l(e,`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
|
+
}`}function se(t,n){if(!n||!x(t))return t;let r={...t},i=r;for(let t of e){let e=n[t];e!=null&&(i[t]=e)}return r}function J(e){if(!x(e))return[];let t=e;return Array.isArray(t.type)?t.type.filter(e=>S(e)):S(t.type)&&t.type!==`object`&&t.type!==`array`?[t.type]:[]}function Y(e){if(x(e))return J(e).find(e=>e!==`null`)}function X(e){return te(e)?h(e):b(e)?ee(e)&&e>1e9?h(new Date(e)):e.toString():S(e)?e:`1.0`}function Z(e,t,n){let r=n??t?.version??e?.version;return y(r)?async e=>X(await Promise.resolve(r(e))):X(r)}function Q(e,t,n){return n??t.name??(S(e?.name)?e.name:S(e?.displayName)?e.displayName:e.$id?_(e.$id):H(e))}function ce(e,t){let n=Q(e,t),r=Z(e,t);return n?y(n)?y(r)?async e=>`${_(await Promise.resolve(n(e)))}@${await Promise.resolve(r(e))}`:async e=>`${_(await Promise.resolve(n(e)))}@${r}`:y(r)?async e=>`${_(n)}@${await Promise.resolve(r(e))}`:`${_(n)}@${r}`:ne()}function $(e,t,n){let r=n??t.displayName??e?.displayName;if(r!==void 0)return r;let i=t.name;return y(i)?async e=>v(await Promise.resolve(i(e))):v(i??H(e))}function le(e,t,n,r){n.displayName??=$(t,n);let i=y(n.displayName)?async t=>e.replaceAll(/\{\s*displayName\s*\}/g,await Promise.resolve(n.displayName(t))):e.replaceAll(/\{\s*displayName\s*\}/g,n.displayName),a=r??n.description??t?.description;return a=y(a)?async e=>{let t=await Promise.resolve(a(e));return S(t)?t:y(i)?i(e):i}:S(a)?a:i,a}function ue(e,t,n){let r=e=>e.map((e,t)=>S(e)?{description:`Example #${t+1}`,value:e}:x(e)&&`value`in e&&S(e.value)?{description:e.description||`Example #${t+1}`,value:e.value}:void 0).filter(Boolean),i=n??t.examples??e?.examples??[];return y(i)?async e=>r(m(await Promise.resolve(i(e)))):r(m(i))}function de(e,t,n){return y(n)||y(t.links)?async r=>g(m(y(n)?await Promise.resolve(n(r)):n).concat(y(t.links)?await Promise.resolve(t.links(r)):t.links??[]).concat(e?.docs??[])):g(m(n).concat(t.links??[]).concat(e?.docs??[]))}export{R as C,ae as E,z as S,L as T,A as _,le as a,N as b,ce as c,Z as d,oe as f,F as g,V as h,J as i,de as l,H as m,X as n,$ as o,U as p,Y as r,ue as s,se as t,Q as u,j as v,B as w,P as x,M as y};
|
|
78
|
+
//# sourceMappingURL=metadata-DIEpQjbq.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"metadata-DIEpQjbq.mjs","names":[],"sources":[],"mappings":""}
|