@power-plant/schema 0.0.25 → 0.0.26

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/index.mjs CHANGED
@@ -1,3 +1,707 @@
1
- import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./constants-lk1mMbgx.mjs";import{$ as s,A as c,B as l,C as ee,D as te,E as ne,F as re,G as ie,H as ae,I as oe,J as u,K as d,L as se,M as ce,N as f,O as le,P as ue,Q as p,R as de,S as fe,T as pe,U as me,V as he,W as ge,X as _e,Y as m,Z as h,_ as ve,a as ye,b as be,c as xe,d as Se,et as g,f as Ce,g as we,h as Te,i as Ee,it as _,j as De,k as Oe,l as ke,m as v,n as Ae,nt as je,o as Me,p as y,q as Ne,r as Pe,rt as Fe,s as Ie,t as Le,tt as b,u as Re,v as x,w as ze,x as Be,y as Ve,z as He}from"./helpers-s2Zqtb-K.mjs";import{n as Ue,r as We,t as S}from"./storage-BccFP9xn.mjs";import{isSetObject as C}from"@stryke/type-checks/is-set-object";import{isSetString as w}from"@stryke/type-checks/is-set-string";import{isSetString as T}from"@stryke/type-checks";import{extractFileReference as E}from"@stryke/convert/extract-file-reference";import{resolveSafe as Ge}from"@stryke/fs/resolve";import{murmurhash as D}from"@stryke/hash";import{deepClone as Ke}from"@stryke/helpers/deep-clone";import{isStandardJsonSchema as O}from"@stryke/json";import{findFileExtensionSafe as qe}from"@stryke/path/find";import{VALID_OBJECT_SOURCE_EXTENSIONS as k}from"@stryke/resolve/constants";import{loadSafe as Je}from"@stryke/resolve/load";import{list as Ye}from"@stryke/string-format/list";import{extractJsonSchema as Xe,isZod3Type as A}from"@stryke/zod";import{createFSBackedSystem as Ze,createVirtualCompilerHost as Qe}from"@typescript/vfs";import{toJsonSchema as $e}from"@valibot/to-json-schema";import{dirname as j}from"node:path";import{createGenerator as et}from"ts-json-schema-generator/dist/factory/generator.js";import M from"typescript";const tt=new Set([...o,`default`,`examples`]);function nt(e){return tt.has(e)}function N(e){return!C(e)||e.type===`any`||Object.keys(e).filter(e=>!nt(e)).length===0}function P(e){if(N(e))return`any`;let t=e.type;if(w(t))return[t];if(Array.isArray(t))return t.filter(w);let n=_(e);return n.length>0?n:f(e)?[`object`]:x(e)?[`array`]:`any`}function F(e){return e.length>0?e:`schema`}function I(e,t){return JSON.stringify(e)===JSON.stringify(t)}function L(e,t,n=``){let r=[];if(N(e)||N(t))return r;let i=P(e),a=P(t);if(i!==`any`&&a!==`any`&&i.filter(e=>a.includes(e)).length===0)return r.push(`${F(n)} has conflicting types: ${i.join(`|`)} vs ${a.join(`|`)}`),r;let o=e.const,s=t.const;o!==void 0&&s!==void 0&&!I(o,s)&&r.push(`${F(n)} has conflicting const values`);let c=e.enum,l=t.enum;if(c?.length&&l?.length&&(l.some(e=>c.some(t=>I(t,e)))||r.push(`${F(n)} has enum values that do not overlap`)),f(e)&&f(t)){let i=e.properties??{},a=t.properties??{};for(let[e,t]of Object.entries(a)){let a=i[e],o=n?`${n}.${e}`:e;a&&v(a)&&v(t)&&r.push(...L(a,t,o))}}if(x(e)&&x(t)){let i=e.items,a=t.items;i&&a&&v(i)&&v(a)&&r.push(...L(i,a,n?`${n}[]`:`items`));let o=e.prefixItems,s=t.prefixItems;if(Array.isArray(o)&&Array.isArray(s)){let e=Math.min(o.length,s.length);for(let t=0;t<e;t++){let e=o[t],i=s[t];v(e)&&v(i)&&r.push(...L(e,i,n?`${n}[${t}]`:`[${t}]`))}}}return r}function rt(e,t,n=`schema`){let r=L(e,t);if(r.length>0)throw Error(`The ${n} schema contradicts the generator schema:\n${r.map(e=>`- ${e}`).join(`
2
- `)}`)}const R=`https://power-plant.invalid/`,z={noEmit:!0,emitDecoratorMetadata:!0,experimentalDecorators:!0,target:M.ScriptTarget.ES2022,module:M.ModuleKind.ESNext,strictNullChecks:!1,skipLibCheck:!0,skipDefaultLibCheck:!0,esModuleInterop:!0};function B(e,t){if(e.readFileSync)try{let n=e.readFileSync(t,`utf8`);return typeof n==`string`?n:void 0}catch{return}}function it(e,t){if(e.existsSync)try{return e.existsSync(t)}catch{return!1}if(e.statSync)try{return e.statSync(t),!0}catch{return!1}return B(e,t)!==void 0}function at(e,t){let n=e.fileExists.bind(e),r=e.readFile.bind(e),i=e.directoryExists.bind(e),a=e.realpath?.bind(e);e.fileExists=e=>it(t,e)||n(e),e.readFile=e=>{if(it(t,e)){let n=B(t,e);if(n!==void 0)return n}return r(e)},e.directoryExists=e=>{try{if(t.statSync){if(t.statSync(e)?.isDirectory?.())return!0}else if(t.existsSync?.(e))return!0}catch{}return i(e)},e.realpath&&t.realpathSync&&(e.realpath=e=>{try{return String(t.realpathSync(e))}catch{return a?.(e)??e}})}function ot(e,t,n){if(!t)return{...z};let r=(n?B(n,t):void 0)??M.sys.readFile(t);if(!r)return{...z};let i=M.parseConfigFileTextToJson(t,r);if(!i.config)return{...z};let a={...M.parseJsonConfigFileContent(i.config,e,j(t),{},t).options,noEmit:!0};return delete a.out,delete a.outDir,delete a.outFile,delete a.declaration,delete a.declarationDir,delete a.declarationMap,a}function st(e,t){let n=t.cwd??j(e),r=Ze,i=Qe,a=r(new Map,n,M);t.fs&&at(a,t.fs);let o=ot(a,t.tsconfig,t.fs),{compilerHost:s}=i(a,o,M);return M.createProgram({rootNames:[e],options:o,host:s})}function ct(e){return!(!C(e)||!(`schema`in e)||`hash`in e||`variant`in e||`source`in e)}function V(e){return ct(e)?e.schema:e}function lt(e){return e.endsWith(`#`)?e.slice(0,-1):e}function H(e){let t=e.indexOf(`#`);return t>=0?e.slice(0,t):e}function ut(e){return e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}function dt(e){return e.length===0?``:`/${e.map(e=>ut(e)).join(`/`)}`}function U(e,t){try{return lt(new URL(e,t).toString())}catch{return lt(e)}}function W(e,t,n,r,i){if(!C(e))return;let a=e,o=dt(t),s=T(a.$id)?U(a.$id,n):n,c=H(s);if(r.set(s,o),r.set(c,o),T(a.$anchor)&&r.set(`${c}#${a.$anchor}`,o),T(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)=>{W(n,[...t,e,String(a)],s,r,i)});continue}W(n,[...t,e],s,r,i)}}function G(e,t,n,r,i){if(!C(e))return;let a=e,o=T(a.$id)?U(a.$id,n):n;if(T(a.$ref)){let e=U(a.$ref,o),t=r.get(e)??r.get(H(e));t!==void 0&&(a.$ref=t.length>0?`#${t}`:`#`)}if(T(a.$dynamicRef)){let e=U(a.$dynamicRef,o),t=i.get(e);if(t)a.$dynamicRef=t;else{let t=r.get(e)??r.get(H(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)=>{G(n,[...t,e,String(a)],o,r,i)});continue}G(n,[...t,e],o,r,i)}}function K(e){if(!C(e))return e;let t=Ke(e),n=T(t.$id)?U(t.$id,R):R,r=new Map,i=new Map;return W(t,[],n,r,i),G(t,[],n,r,i),t}function q(e){if(s(e))return J(e);if(C(e)){if(h(e))return Y(e);let t=e;if(`$schema`in t&&s(t.$schema))return J(t.$schema)}return e}function ft(e){return Array.isArray(e)?e.map(e=>q(e)):e}function pt(e){return $e(e,{target:`draft-2020-12`})}function J(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`&&T(r)){n.$id=r;continue}if(e===`properties`||e===`patternProperties`||e===`dependentSchemas`||e===`$defs`||e===`definitions`){if(!C(r)){n[e]=r;continue}n[e]=Object.fromEntries(Object.entries(r).map(([e,t])=>[e,q(t)]));continue}if(e===`items`||e===`contains`||e===`if`||e===`then`||e===`else`||e===`not`||e===`propertyNames`||e===`additionalProperties`||e===`unevaluatedProperties`){n[e]=q(r);continue}if(e===`oneOf`||e===`anyOf`||e===`allOf`){n[e]=ft(r);continue}n[e]=r}return n}function Y(e){let t=e,n=s(t.$schema)?J(t.$schema):{},r={};for(let[e,n]of Object.entries(t)){if(e.startsWith(`$`)||!C(n))continue;if(h(n)){r[e]=Y(n);continue}let t=n;if(`$schema`in t&&s(t.$schema)){r[e]=J(t.$schema);continue}s(n)&&(r[e]=J(n))}if(!f(n))throw Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);let i={...C(n.properties)?n.properties:{},...r};return{...n,type:n.type??`object`,...Object.keys(i).length>0?{properties:i}:{}}}function X(e,t){let n=V(t);if(m(n)||d(n))return D({variant:e,input:n.schema});if(T(n)||typeof n==`boolean`)return D({variant:e,input:n});if(C(n)){if(A(n))return D({variant:e,input:n._def});if(O(n))return D({variant:e,input:n[`~standard`]});if(v(n))return D({variant:e,input:n});if(b(n))return D({variant:e,input:pt(n)});if(h(n))return D({variant:e,input:Y(n)});if(s(n))return D({variant:e,input:J(n)})}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 mt(e){if(C(e)){if(A(e))return Xe(e,{target:`draft-2020-12`});if(p(e))return Y(e);if(g(e))return J(e);if(O(e))return e[`~standard`].jsonSchema.input({target:`draft-2020-12`});if(b(e))return pt(e);if(v(e))return e}}function Z(e){if(C(e)){if(A(e))return`zod3`;if(p(e)||g(e))return`untyped`;if(O(e))return`standard-schema`;if(v(e))return`json-schema`;if(b(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 ht(e){let t=V(e);return m(t)||d(t)?t.variant:T(t)||y(t)?`file-reference`:Z(t)}async function gt(e,t){if(m(e))return e.schema;let n=t??Z(e),r;if((n===`zod3`||n===`json-schema`||n===`standard-schema`||n===`untyped`||n===`valibot`)&&(r=mt(e)),r)return K(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 Q(e,t){if(e===`zod3`)return{hash:X(e,t),variant:`zod3`,schema:t};if(e===`untyped`)return{hash:X(e,t),variant:`untyped`,schema:t};if(e===`standard-schema`)return{hash:X(e,t),variant:`standard-schema`,schema:t};if(e===`json-schema`)return{hash:X(e,t),variant:`json-schema`,schema:t};if(e===`valibot`)return{hash:X(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 _t(e,t={}){let n=E(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??`*`,i=await Ge(n.file,{fs:t.fs}),a=i||n.file;try{return et({path:a,type:r,expose:`all`,jsDoc:`extended`,markdownDescription:!0,fullDescription:!0,skipTypeCheck:!0,tsProgram:st(a,t),...t}).createSchema(r)}catch(e){throw Error(`Failed to generate a JSON schema for "${n.file}"${i&&i!==n.file?` (resolved: ${i})`:``} using the type "${r}". Error: ${e.message}`)}}async function $(e,t={}){let n=V(e);if(m(n))return n;if(d(n))return{...n,source:{hash:X(`json-schema`,n.schema),variant:`json-schema`,schema:n.schema}};let r,i=ht(n),a=X(i,n);if(i===`file-reference`){let e=E(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=qe(e.file);if(i&&!k.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: ${Ye(k,{conjunction:`or`})}.`);let a;t.storage&&(a=S(t.storage));let o=await Je(n,{...t,fs:a});o??=await _t(n,{...t,fs:a});let s=V(o);r=m(s)?s.source:d(s)?{hash:X(`json-schema`,s.schema),variant:`json-schema`,schema:s.schema}:Q(Z(s),s)}else if([`json-schema`,`standard-schema`,`zod3`,`untyped`,`valibot`,`reflection`].includes(i))r=Q(i,n);else throw Error(`Invalid schema definition input "${i}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);return{variant:i,source:r,schema:await gt(r.schema,r.variant),hash:a}}async function vt(e,t={}){let n=V(e);if(m(n)||u(n))return n;let r=await $(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{o as JSON_SCHEMA_METADATA_KEYS,n as JSON_SCHEMA_PRIMITIVE_TYPES,i as JSON_SCHEMA_TYPES,t as JsonSchemaTypeNames,e as SCHEMA_ARRAY_CONCAT_KEYWORDS,r as SCHEMA_RECORD_KEYWORDS,a as SCHEMA_SINGLE_KEYWORDS,Le as addProperty,je as applyJsonSchemaMetadata,rt as assertSchemasDoNotContradict,K as bundleReferences,Ue as createStoragePromises,vt as extract,X as extractHash,mt as extractJsonSchema,Z as extractResolvedVariant,gt as extractSchema,$ as extractSchemaWithSource,Q as extractSource,_t as extractTSType,ht as extractVariant,L as findSchemaContradictions,Ae as getJsonSchema,Pe as getJsonSchemaObject,Fe as getPrimarySchemaType,Ee as getProperties,ye as getPropertiesList,Me as getProperty,y as isFileReference,v as isJsonSchema,Te as isJsonSchemaAllOf,we as isJsonSchemaAny,ve as isJsonSchemaAnyOf,x as isJsonSchemaArray,Ve as isJsonSchemaBigint,be as isJsonSchemaBoolean,Be as isJsonSchemaDate,fe as isJsonSchemaDecimal,ee as isJsonSchemaEnum,ze as isJsonSchemaInteger,pe as isJsonSchemaKeywords,ne as isJsonSchemaLiteral,te as isJsonSchemaMap,le as isJsonSchemaNativeEnum,Oe as isJsonSchemaNever,c as isJsonSchemaNull,De as isJsonSchemaNullable,ce as isJsonSchemaNumber,f as isJsonSchemaObject,ue as isJsonSchemaPrimitiveType,re as isJsonSchemaPrimitiveUnion,oe as isJsonSchemaRecord,se as isJsonSchemaRef,de as isJsonSchemaSet,He as isJsonSchemaString,l as isJsonSchemaTuple,he as isJsonSchemaType,ae as isJsonSchemaUndefined,me as isJsonSchemaUnion,ge as isJsonSchemaUnknown,ie as isNullOnlyJsonSchema,Ie as isPropertyOptional,d as isSchema,xe as isSchemaNullable,Ne as isSchemaObject,u as isSchemaOf,m as isSchemaWithSource,_e as isStandardSchema,h as isUntypedConfig,p as isUntypedConfigStrict,s as isUntypedSchema,g as isUntypedSchemaStrict,b as isValibotSchema,ke as isValidSchemaConfigFile,S as mapStorageToFileSystem,Re as merge,Se as mergeMetadata,We as normalizeKey,_ as readSchemaTypes,Ce as traverseSchema};
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-COGt3eeW.mjs";
2
+ import { $ as isUntypedSchema, A as isJsonSchemaNull, B as isJsonSchemaTuple, C as isJsonSchemaEnum, D as isJsonSchemaMap, E as isJsonSchemaLiteral, F as isJsonSchemaPrimitiveUnion, G as isNullOnlyJsonSchema, H as isJsonSchemaUndefined, I as isJsonSchemaRecord, J as isSchemaOf, K as isSchema, L as isJsonSchemaRef, M as isJsonSchemaNumber, N as isJsonSchemaObject, O as isJsonSchemaNativeEnum, P as isJsonSchemaPrimitiveType, Q as isUntypedConfigStrict, R as isJsonSchemaSet, S as isJsonSchemaDecimal, T as isJsonSchemaKeywords, U as isJsonSchemaUnion, V as isJsonSchemaType, W as isJsonSchemaUnknown, X as isStandardSchema, Y as isSchemaWithSource, Z as isUntypedConfig, _ as isJsonSchemaAnyOf, a as getPropertiesList, b as isJsonSchemaBoolean, c as isSchemaNullable, d as mergeMetadata, et as isUntypedSchemaStrict, f as traverseSchema, g as isJsonSchemaAny, h as isJsonSchemaAllOf, i as getProperties, it as readSchemaTypes, j as isJsonSchemaNullable, k as isJsonSchemaNever, l as isValidSchemaConfigFile, m as isJsonSchema, n as getJsonSchema, nt as applyJsonSchemaMetadata, o as getProperty, p as isFileReference, q as isSchemaObject, r as getJsonSchemaObject, rt as getPrimarySchemaType, s as isPropertyOptional, t as addProperty, tt as isValibotSchema, u as merge, v as isJsonSchemaArray, w as isJsonSchemaInteger, x as isJsonSchemaDate, y as isJsonSchemaBigint, z as isJsonSchemaString } from "./helpers-reqtcaa8.mjs";
3
+ import { n as createStoragePromises, r as normalizeKey, t as mapStorageToFileSystem } from "./storage-C3BT2Xh-.mjs";
4
+ import { isSetObject } from "@stryke/type-checks/is-set-object";
5
+ import { isSetString } from "@stryke/type-checks/is-set-string";
6
+ import { isSetString as isSetString$1 } from "@stryke/type-checks";
7
+ import { extractFileReference } from "@stryke/convert/extract-file-reference";
8
+ import { resolveSafe } from "@stryke/fs/resolve";
9
+ import { murmurhash } from "@stryke/hash";
10
+ import { deepClone } from "@stryke/helpers/deep-clone";
11
+ import { isStandardJsonSchema } from "@stryke/json";
12
+ import { findFileExtensionSafe } from "@stryke/path/find";
13
+ import { VALID_OBJECT_SOURCE_EXTENSIONS } from "@stryke/resolve/constants";
14
+ import { loadSafe } from "@stryke/resolve/load";
15
+ import { list } from "@stryke/string-format/list";
16
+ import { extractJsonSchema as extractJsonSchema$1, isZod3Type } from "@stryke/zod";
17
+ import { createFSBackedSystem, createVirtualCompilerHost } from "@typescript/vfs";
18
+ import { toJsonSchema } from "@valibot/to-json-schema";
19
+ import { dirname } from "node:path";
20
+ import { createGenerator } from "ts-json-schema-generator/dist/factory/generator.js";
21
+ import ts from "typescript";
22
+
23
+ //#region src/compatibility.ts
24
+ const METADATA_KEYS = /* @__PURE__ */ new Set([
25
+ ...JSON_SCHEMA_METADATA_KEYS,
26
+ "default",
27
+ "examples"
28
+ ]);
29
+ function isMetadataKey(key) {
30
+ return METADATA_KEYS.has(key);
31
+ }
32
+ function isUnconstrainedSchema(schema) {
33
+ if (!isSetObject(schema)) return true;
34
+ if (schema.type === "any") return true;
35
+ return Object.keys(schema).filter((key) => !isMetadataKey(key)).length === 0;
36
+ }
37
+ function resolveSchemaTypes(schema) {
38
+ if (isUnconstrainedSchema(schema)) return "any";
39
+ const schemaType = schema.type;
40
+ if (isSetString(schemaType)) return [schemaType];
41
+ if (Array.isArray(schemaType)) return schemaType.filter(isSetString);
42
+ const primitiveTypes = readSchemaTypes(schema);
43
+ if (primitiveTypes.length > 0) return primitiveTypes;
44
+ if (isJsonSchemaObject(schema)) return ["object"];
45
+ if (isJsonSchemaArray(schema)) return ["array"];
46
+ return "any";
47
+ }
48
+ function formatPath(path) {
49
+ return path.length > 0 ? path : "schema";
50
+ }
51
+ function valuesEqual(left, right) {
52
+ return JSON.stringify(left) === JSON.stringify(right);
53
+ }
54
+ /**
55
+ * Finds structural contradictions between two JSON Schema fragments.
56
+ *
57
+ * @remarks
58
+ * Metadata-only keywords are ignored. Either schema may be unconstrained
59
+ * (`{}`, `{ type: "any" }`, or missing structural keywords) without
60
+ * producing contradictions.
61
+ *
62
+ * @param base - The base JSON Schema fragment.
63
+ * @param override - The JSON Schema fragment to compare against the base.
64
+ * @param path - Optional dot-separated path used in issue messages.
65
+ * @returns A list of human-readable contradiction descriptions.
66
+ */
67
+ function findSchemaContradictions(base, override, path = "") {
68
+ const issues = [];
69
+ if (isUnconstrainedSchema(base) || isUnconstrainedSchema(override)) return issues;
70
+ const baseTypes = resolveSchemaTypes(base);
71
+ const overrideTypes = resolveSchemaTypes(override);
72
+ if (baseTypes !== "any" && overrideTypes !== "any") {
73
+ if (baseTypes.filter((type) => overrideTypes.includes(type)).length === 0) {
74
+ issues.push(`${formatPath(path)} has conflicting types: ${baseTypes.join("|")} vs ${overrideTypes.join("|")}`);
75
+ return issues;
76
+ }
77
+ }
78
+ const baseConst = base.const;
79
+ const overrideConst = override.const;
80
+ if (baseConst !== void 0 && overrideConst !== void 0 && !valuesEqual(baseConst, overrideConst)) issues.push(`${formatPath(path)} has conflicting const values`);
81
+ const baseEnum = base.enum;
82
+ const overrideEnum = override.enum;
83
+ if (baseEnum?.length && overrideEnum?.length) {
84
+ if (!overrideEnum.some((value) => baseEnum.some((baseValue) => valuesEqual(baseValue, value)))) issues.push(`${formatPath(path)} has enum values that do not overlap`);
85
+ }
86
+ if (isJsonSchemaObject(base) && isJsonSchemaObject(override)) {
87
+ const baseProperties = base.properties ?? {};
88
+ const overrideProperties = override.properties ?? {};
89
+ for (const [key, overrideProperty] of Object.entries(overrideProperties)) {
90
+ const baseProperty = baseProperties[key];
91
+ const propertyPath = path ? `${path}.${key}` : key;
92
+ if (baseProperty && isJsonSchema(baseProperty) && isJsonSchema(overrideProperty)) issues.push(...findSchemaContradictions(baseProperty, overrideProperty, propertyPath));
93
+ }
94
+ }
95
+ if (isJsonSchemaArray(base) && isJsonSchemaArray(override)) {
96
+ const baseItems = base.items;
97
+ const overrideItems = override.items;
98
+ if (baseItems && overrideItems && isJsonSchema(baseItems) && isJsonSchema(overrideItems)) issues.push(...findSchemaContradictions(baseItems, overrideItems, path ? `${path}[]` : "items"));
99
+ const basePrefix = base.prefixItems;
100
+ const overridePrefix = override.prefixItems;
101
+ if (Array.isArray(basePrefix) && Array.isArray(overridePrefix)) {
102
+ const length = Math.min(basePrefix.length, overridePrefix.length);
103
+ for (let index = 0; index < length; index++) {
104
+ const baseItem = basePrefix[index];
105
+ const overrideItem = overridePrefix[index];
106
+ if (isJsonSchema(baseItem) && isJsonSchema(overrideItem)) issues.push(...findSchemaContradictions(baseItem, overrideItem, path ? `${path}[${index}]` : `[${index}]`));
107
+ }
108
+ }
109
+ }
110
+ return issues;
111
+ }
112
+ /**
113
+ * Asserts that two JSON Schema fragments do not structurally contradict each other.
114
+ *
115
+ * @param base - The base JSON Schema fragment.
116
+ * @param override - The JSON Schema fragment to compare against the base.
117
+ * @param label - A label used in the thrown error message.
118
+ * @throws {Error} When one or more structural contradictions are found.
119
+ */
120
+ function assertSchemasDoNotContradict(base, override, label = "schema") {
121
+ const issues = findSchemaContradictions(base, override);
122
+ if (issues.length > 0) throw new Error(`The ${label} schema contradicts the generator schema:\n${issues.map((issue) => `- ${issue}`).join("\n")}`);
123
+ }
124
+
125
+ //#endregion
126
+ //#region src/extract.ts
127
+ const SCHEMA_BUNDLE_BASE_URI = "https://power-plant.invalid/";
128
+ const DEFAULT_TS_COMPILER_OPTIONS = {
129
+ noEmit: true,
130
+ emitDecoratorMetadata: true,
131
+ experimentalDecorators: true,
132
+ target: ts.ScriptTarget.ES2022,
133
+ module: ts.ModuleKind.ESNext,
134
+ strictNullChecks: false,
135
+ skipLibCheck: true,
136
+ skipDefaultLibCheck: true,
137
+ esModuleInterop: true
138
+ };
139
+ function readFileAsString(fs, fileName) {
140
+ if (!fs.readFileSync) return;
141
+ try {
142
+ const content = fs.readFileSync(fileName, "utf8");
143
+ return typeof content === "string" ? content : void 0;
144
+ } catch {
145
+ return;
146
+ }
147
+ }
148
+ function fileExistsOnFs(fs, fileName) {
149
+ if (fs.existsSync) try {
150
+ return fs.existsSync(fileName);
151
+ } catch {
152
+ return false;
153
+ }
154
+ if (fs.statSync) try {
155
+ fs.statSync(fileName);
156
+ return true;
157
+ } catch {
158
+ return false;
159
+ }
160
+ return readFileAsString(fs, fileName) !== void 0;
161
+ }
162
+ /**
163
+ * Prefers `options.fs` for System I/O so virtual storage-backed files resolve
164
+ * through createFSBackedSystem instead of only the real disk.
165
+ */
166
+ function bindFileSystemToSystem(system, fs) {
167
+ const baseFileExists = system.fileExists.bind(system);
168
+ const baseReadFile = system.readFile.bind(system);
169
+ const baseDirectoryExists = system.directoryExists.bind(system);
170
+ const baseRealpath = system.realpath?.bind(system);
171
+ system.fileExists = (fileName) => fileExistsOnFs(fs, fileName) || baseFileExists(fileName);
172
+ system.readFile = (fileName) => {
173
+ if (fileExistsOnFs(fs, fileName)) {
174
+ const content = readFileAsString(fs, fileName);
175
+ if (content !== void 0) return content;
176
+ }
177
+ return baseReadFile(fileName);
178
+ };
179
+ system.directoryExists = (directory) => {
180
+ try {
181
+ if (fs.statSync) {
182
+ if (fs.statSync(directory)?.isDirectory?.()) return true;
183
+ } else if (fs.existsSync?.(directory)) return true;
184
+ } catch {}
185
+ return baseDirectoryExists(directory);
186
+ };
187
+ if (system.realpath && fs.realpathSync) system.realpath = (path) => {
188
+ try {
189
+ return String(fs.realpathSync(path));
190
+ } catch {
191
+ return baseRealpath?.(path) ?? path;
192
+ }
193
+ };
194
+ }
195
+ function resolveCompilerOptions(system, tsconfig, fs) {
196
+ if (!tsconfig) return { ...DEFAULT_TS_COMPILER_OPTIONS };
197
+ const raw = (fs ? readFileAsString(fs, tsconfig) : void 0) ?? ts.sys.readFile(tsconfig);
198
+ if (!raw) return { ...DEFAULT_TS_COMPILER_OPTIONS };
199
+ const parsed = ts.parseConfigFileTextToJson(tsconfig, raw);
200
+ if (!parsed.config) return { ...DEFAULT_TS_COMPILER_OPTIONS };
201
+ const options = {
202
+ ...ts.parseJsonConfigFileContent(parsed.config, system, dirname(tsconfig), {}, tsconfig).options,
203
+ noEmit: true
204
+ };
205
+ delete options.out;
206
+ delete options.outDir;
207
+ delete options.outFile;
208
+ delete options.declaration;
209
+ delete options.declarationDir;
210
+ delete options.declarationMap;
211
+ return options;
212
+ }
213
+ function createProgramFromFileSystem(rootFile, options) {
214
+ const projectRoot = options.cwd ?? dirname(rootFile);
215
+ const createSystem = createFSBackedSystem;
216
+ const createHost = createVirtualCompilerHost;
217
+ const system = createSystem(/* @__PURE__ */ new Map(), projectRoot, ts);
218
+ if (options.fs) bindFileSystemToSystem(system, options.fs);
219
+ const compilerOptions = resolveCompilerOptions(system, options.tsconfig, options.fs);
220
+ const { compilerHost } = createHost(system, compilerOptions, ts);
221
+ return ts.createProgram({
222
+ rootNames: [rootFile],
223
+ options: compilerOptions,
224
+ host: compilerHost
225
+ });
226
+ }
227
+ function isWrappedSchemaConfig(input) {
228
+ if (!isSetObject(input) || !("schema" in input)) return false;
229
+ if ("hash" in input || "variant" in input || "source" in input) return false;
230
+ return true;
231
+ }
232
+ function unwrapSchemaConfig(input) {
233
+ if (isWrappedSchemaConfig(input)) return input.schema;
234
+ return input;
235
+ }
236
+ function normalizeUri(uri) {
237
+ return uri.endsWith("#") ? uri.slice(0, -1) : uri;
238
+ }
239
+ function stripUriFragment(uri) {
240
+ const hashIndex = uri.indexOf("#");
241
+ return hashIndex >= 0 ? uri.slice(0, hashIndex) : uri;
242
+ }
243
+ function escapeJsonPointerToken(token) {
244
+ return token.replaceAll("~", "~0").replaceAll("/", "~1");
245
+ }
246
+ function toJsonPointer(path) {
247
+ if (path.length === 0) return "";
248
+ return `/${path.map((segment) => escapeJsonPointerToken(segment)).join("/")}`;
249
+ }
250
+ function resolveUri(reference, baseUri) {
251
+ try {
252
+ return normalizeUri(new URL(reference, baseUri).toString());
253
+ } catch {
254
+ return normalizeUri(reference);
255
+ }
256
+ }
257
+ function collectReferenceTargets(value, path, baseUri, uriToPointer, dynamicUriToFragment) {
258
+ if (!isSetObject(value)) return;
259
+ const schema = value;
260
+ const pointer = toJsonPointer(path);
261
+ const currentBaseUri = isSetString$1(schema.$id) ? resolveUri(schema.$id, baseUri) : baseUri;
262
+ const currentDocumentUri = stripUriFragment(currentBaseUri);
263
+ uriToPointer.set(currentBaseUri, pointer);
264
+ uriToPointer.set(currentDocumentUri, pointer);
265
+ if (isSetString$1(schema.$anchor)) uriToPointer.set(`${currentDocumentUri}#${schema.$anchor}`, pointer);
266
+ if (isSetString$1(schema.$dynamicAnchor)) {
267
+ const dynamicTarget = `${currentDocumentUri}#${schema.$dynamicAnchor}`;
268
+ uriToPointer.set(dynamicTarget, pointer);
269
+ dynamicUriToFragment.set(dynamicTarget, `#${schema.$dynamicAnchor}`);
270
+ }
271
+ for (const [key, child] of Object.entries(schema)) {
272
+ if (Array.isArray(child)) {
273
+ child.forEach((entry, index) => {
274
+ collectReferenceTargets(entry, [
275
+ ...path,
276
+ key,
277
+ String(index)
278
+ ], currentBaseUri, uriToPointer, dynamicUriToFragment);
279
+ });
280
+ continue;
281
+ }
282
+ collectReferenceTargets(child, [...path, key], currentBaseUri, uriToPointer, dynamicUriToFragment);
283
+ }
284
+ }
285
+ function rewriteReferenceTargets(value, path, baseUri, uriToPointer, dynamicUriToFragment) {
286
+ if (!isSetObject(value)) return;
287
+ const schema = value;
288
+ const currentBaseUri = isSetString$1(schema.$id) ? resolveUri(schema.$id, baseUri) : baseUri;
289
+ if (isSetString$1(schema.$ref)) {
290
+ const resolvedRefUri = resolveUri(schema.$ref, currentBaseUri);
291
+ const pointer = uriToPointer.get(resolvedRefUri) ?? uriToPointer.get(stripUriFragment(resolvedRefUri));
292
+ if (pointer !== void 0) schema.$ref = pointer.length > 0 ? `#${pointer}` : "#";
293
+ }
294
+ if (isSetString$1(schema.$dynamicRef)) {
295
+ const resolvedDynamicRefUri = resolveUri(schema.$dynamicRef, currentBaseUri);
296
+ const dynamicFragment = dynamicUriToFragment.get(resolvedDynamicRefUri);
297
+ if (dynamicFragment) schema.$dynamicRef = dynamicFragment;
298
+ else {
299
+ const pointer = uriToPointer.get(resolvedDynamicRefUri) ?? uriToPointer.get(stripUriFragment(resolvedDynamicRefUri));
300
+ if (pointer !== void 0) schema.$dynamicRef = pointer.length > 0 ? `#${pointer}` : "#";
301
+ }
302
+ }
303
+ for (const [key, child] of Object.entries(schema)) {
304
+ if (Array.isArray(child)) {
305
+ child.forEach((entry, index) => {
306
+ rewriteReferenceTargets(entry, [
307
+ ...path,
308
+ key,
309
+ String(index)
310
+ ], currentBaseUri, uriToPointer, dynamicUriToFragment);
311
+ });
312
+ continue;
313
+ }
314
+ rewriteReferenceTargets(child, [...path, key], currentBaseUri, uriToPointer, dynamicUriToFragment);
315
+ }
316
+ }
317
+ /**
318
+ * Bundles all external references in a JSON Schema into a single schema document by collecting all reference targets and rewriting the references to point to the bundled definitions. This ensures that the resulting schema is self-contained and can be used independently without relying on external documents.
319
+ *
320
+ * @param schema - The JSON Schema to bundle references for.
321
+ * @returns A new JSON Schema with all references bundled and rewritten to point to the bundled definitions.
322
+ */
323
+ function bundleReferences(schema) {
324
+ if (!isSetObject(schema)) return schema;
325
+ const bundledSchema = deepClone(schema);
326
+ const baseUri = isSetString$1(bundledSchema.$id) ? resolveUri(bundledSchema.$id, SCHEMA_BUNDLE_BASE_URI) : SCHEMA_BUNDLE_BASE_URI;
327
+ const uriToPointer = /* @__PURE__ */ new Map();
328
+ const dynamicUriToFragment = /* @__PURE__ */ new Map();
329
+ collectReferenceTargets(bundledSchema, [], baseUri, uriToPointer, dynamicUriToFragment);
330
+ rewriteReferenceTargets(bundledSchema, [], baseUri, uriToPointer, dynamicUriToFragment);
331
+ return bundledSchema;
332
+ }
333
+ function convertNestedUntypedSchema(value) {
334
+ if (isUntypedSchema(value)) return convertUntypedSchemaToJsonSchema(value);
335
+ if (isSetObject(value)) {
336
+ if (isUntypedConfig(value)) return convertUntypedConfigToJsonSchema(value);
337
+ const nested = value;
338
+ if ("$schema" in nested && isUntypedSchema(nested.$schema)) return convertUntypedSchemaToJsonSchema(nested.$schema);
339
+ }
340
+ return value;
341
+ }
342
+ function convertNestedUntypedSchemaArray(value) {
343
+ if (!Array.isArray(value)) return value;
344
+ return value.map((item) => convertNestedUntypedSchema(item));
345
+ }
346
+ function convertValibotSchemaToJsonSchema(schema) {
347
+ return toJsonSchema(schema, { target: "draft-2020-12" });
348
+ }
349
+ function convertUntypedSchemaToJsonSchema(schema) {
350
+ const source = schema;
351
+ const jsonSchema = {};
352
+ for (const [key, value] of Object.entries(source)) {
353
+ if (key === "tsType" || key === "markdownType" || key === "tags" || key === "args" || key === "resolve") continue;
354
+ if (key === "id" && isSetString$1(value)) {
355
+ jsonSchema.$id = value;
356
+ continue;
357
+ }
358
+ if (key === "properties" || key === "patternProperties" || key === "dependentSchemas" || key === "$defs" || key === "definitions") {
359
+ if (!isSetObject(value)) {
360
+ jsonSchema[key] = value;
361
+ continue;
362
+ }
363
+ jsonSchema[key] = Object.fromEntries(Object.entries(value).map(([propertyKey, propertyValue]) => [propertyKey, convertNestedUntypedSchema(propertyValue)]));
364
+ continue;
365
+ }
366
+ if (key === "items" || key === "contains" || key === "if" || key === "then" || key === "else" || key === "not" || key === "propertyNames" || key === "additionalProperties" || key === "unevaluatedProperties") {
367
+ jsonSchema[key] = convertNestedUntypedSchema(value);
368
+ continue;
369
+ }
370
+ if (key === "oneOf" || key === "anyOf" || key === "allOf") {
371
+ jsonSchema[key] = convertNestedUntypedSchemaArray(value);
372
+ continue;
373
+ }
374
+ jsonSchema[key] = value;
375
+ }
376
+ return jsonSchema;
377
+ }
378
+ function convertUntypedConfigToJsonSchema(input) {
379
+ const inputObject = input;
380
+ const base = isUntypedSchema(inputObject.$schema) ? convertUntypedSchemaToJsonSchema(inputObject.$schema) : {};
381
+ const properties = {};
382
+ for (const [key, value] of Object.entries(inputObject)) {
383
+ if (key.startsWith("$")) continue;
384
+ if (!isSetObject(value)) continue;
385
+ if (isUntypedConfig(value)) {
386
+ properties[key] = convertUntypedConfigToJsonSchema(value);
387
+ continue;
388
+ }
389
+ const nested = value;
390
+ if ("$schema" in nested && isUntypedSchema(nested.$schema)) {
391
+ properties[key] = convertUntypedSchemaToJsonSchema(nested.$schema);
392
+ continue;
393
+ }
394
+ if (isUntypedSchema(value)) properties[key] = convertUntypedSchemaToJsonSchema(value);
395
+ }
396
+ if (!isJsonSchemaObject(base)) throw new Error(`Failed to convert untyped input to JSON Schema. The base schema must be a valid JSON Schema object.`);
397
+ const mergedProperties = {
398
+ ...isSetObject(base.properties) ? base.properties : {},
399
+ ...properties
400
+ };
401
+ return {
402
+ ...base,
403
+ type: base.type ?? "object",
404
+ ...Object.keys(mergedProperties).length > 0 ? { properties: mergedProperties } : {}
405
+ };
406
+ }
407
+ /**
408
+ * Creates a hash string for a given schema definition input.
409
+ */
410
+ function extractHash(variant, input) {
411
+ const unwrappedConfig = unwrapSchemaConfig(input);
412
+ if (isSchemaWithSource(unwrappedConfig) || isSchema(unwrappedConfig)) return murmurhash({
413
+ variant,
414
+ input: unwrappedConfig.schema
415
+ });
416
+ if (isSetString$1(unwrappedConfig)) return murmurhash({
417
+ variant,
418
+ input: unwrappedConfig
419
+ });
420
+ else if (typeof unwrappedConfig === "boolean") return murmurhash({
421
+ variant,
422
+ input: unwrappedConfig
423
+ });
424
+ else if (isSetObject(unwrappedConfig)) {
425
+ if (isZod3Type(unwrappedConfig)) return murmurhash({
426
+ variant,
427
+ input: unwrappedConfig._def
428
+ });
429
+ else if (isStandardJsonSchema(unwrappedConfig)) return murmurhash({
430
+ variant,
431
+ input: unwrappedConfig["~standard"]
432
+ });
433
+ else if (isJsonSchema(unwrappedConfig)) return murmurhash({
434
+ variant,
435
+ input: unwrappedConfig
436
+ });
437
+ else if (isValibotSchema(unwrappedConfig)) return murmurhash({
438
+ variant,
439
+ input: convertValibotSchemaToJsonSchema(unwrappedConfig)
440
+ });
441
+ else if (isUntypedConfig(unwrappedConfig)) return murmurhash({
442
+ variant,
443
+ input: convertUntypedConfigToJsonSchema(unwrappedConfig)
444
+ });
445
+ else if (isUntypedSchema(unwrappedConfig)) return murmurhash({
446
+ variant,
447
+ input: convertUntypedSchemaToJsonSchema(unwrappedConfig)
448
+ });
449
+ }
450
+ throw new 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.`);
451
+ }
452
+ /**
453
+ * Extracts a JSON Schema from Zod, Standard Schema, Valibot, untyped, or JSON Schema inputs.
454
+ *
455
+ * @param schema - The schema input to extract a JSON Schema from.
456
+ * @returns The extracted JSON Schema, or `undefined` if the input is not a supported schema type.
457
+ */
458
+ function extractJsonSchema(schema) {
459
+ if (isSetObject(schema)) {
460
+ if (isZod3Type(schema)) return extractJsonSchema$1(schema, { target: "draft-2020-12" });
461
+ if (isUntypedConfigStrict(schema)) return convertUntypedConfigToJsonSchema(schema);
462
+ if (isUntypedSchemaStrict(schema)) return convertUntypedSchemaToJsonSchema(schema);
463
+ if (isStandardJsonSchema(schema)) return schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
464
+ if (isValibotSchema(schema)) return convertValibotSchemaToJsonSchema(schema);
465
+ if (isJsonSchema(schema)) return schema;
466
+ }
467
+ }
468
+ /**
469
+ * Resolves the concrete source variant for a schema source input.
470
+ *
471
+ * @param input - The schema source input to inspect.
472
+ * @returns The resolved schema source variant.
473
+ * @throws Will throw an error when the input cannot be mapped to a supported source variant.
474
+ */
475
+ function extractResolvedVariant(input) {
476
+ if (isSetObject(input)) {
477
+ if (isZod3Type(input)) return "zod3";
478
+ else if (isUntypedConfigStrict(input) || isUntypedSchemaStrict(input)) return "untyped";
479
+ else if (isStandardJsonSchema(input)) return "standard-schema";
480
+ else if (isJsonSchema(input)) return "json-schema";
481
+ else if (isValibotSchema(input)) return "valibot";
482
+ }
483
+ throw new 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.`);
484
+ }
485
+ /**
486
+ * Determines the top-level input variant for schema extraction.
487
+ *
488
+ * @param input - The schema input to classify.
489
+ * @returns The resolved schema input variant.
490
+ */
491
+ function extractVariant(input) {
492
+ const unwrappedConfig = unwrapSchemaConfig(input);
493
+ if (isSchemaWithSource(unwrappedConfig) || isSchema(unwrappedConfig)) return unwrappedConfig.variant;
494
+ if (isSetString$1(unwrappedConfig) || isFileReference(unwrappedConfig)) return "file-reference";
495
+ return extractResolvedVariant(unwrappedConfig);
496
+ }
497
+ /**
498
+ * Extracts and normalizes a JSON Schema from a concrete schema source input.
499
+ *
500
+ * @param input - The schema source input to extract from.
501
+ * @param variant - Optional source variant override. When omitted, the variant is inferred from the input.
502
+ * @returns A promise that resolves to a bundled JSON Schema.
503
+ * @throws Will throw an error if no valid JSON Schema can be extracted from the input.
504
+ */
505
+ async function extractSchema(input, variant) {
506
+ if (isSchemaWithSource(input)) return input.schema;
507
+ const resolvedVariant = variant ?? extractResolvedVariant(input);
508
+ let schema;
509
+ if (resolvedVariant === "zod3" || resolvedVariant === "json-schema" || resolvedVariant === "standard-schema" || resolvedVariant === "untyped" || resolvedVariant === "valibot") schema = extractJsonSchema(input);
510
+ if (schema) return bundleReferences(schema);
511
+ throw new 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.`);
512
+ }
513
+ /**
514
+ * Builds source metadata for a schema input using a known source variant.
515
+ *
516
+ * @param variant - The schema source variant associated with the input.
517
+ * @param input - The schema source input to wrap.
518
+ * @returns The normalized schema source payload, including the source hash and variant.
519
+ * @throws Will throw an error if the provided variant is unsupported.
520
+ */
521
+ function extractSource(variant, input) {
522
+ if (variant === "zod3") return {
523
+ hash: extractHash(variant, input),
524
+ variant: "zod3",
525
+ schema: input
526
+ };
527
+ else if (variant === "untyped") return {
528
+ hash: extractHash(variant, input),
529
+ variant: "untyped",
530
+ schema: input
531
+ };
532
+ else if (variant === "standard-schema") return {
533
+ hash: extractHash(variant, input),
534
+ variant: "standard-schema",
535
+ schema: input
536
+ };
537
+ else if (variant === "json-schema") return {
538
+ hash: extractHash(variant, input),
539
+ variant: "json-schema",
540
+ schema: input
541
+ };
542
+ else if (variant === "valibot") return {
543
+ hash: extractHash(variant, input),
544
+ variant: "valibot",
545
+ schema: input
546
+ };
547
+ throw new 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.`);
548
+ }
549
+ /**
550
+ * 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.
551
+ *
552
+ * @param input - The type definition to compile. This can be either a string or a {@link FileReference} object.
553
+ * @param options - Optional overrides reserved for API compatibility.
554
+ * @returns A promise that resolves to the generated JSON Schema.
555
+ */
556
+ async function extractTSType(input, options = {}) {
557
+ const fileReference = extractFileReference(input);
558
+ if (!fileReference) throw new 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.`);
559
+ const exportName = fileReference.export ?? "*";
560
+ const resolvedPath = await resolveSafe(fileReference.file, { fs: options.fs });
561
+ const filePath = resolvedPath || fileReference.file;
562
+ try {
563
+ return createGenerator({
564
+ path: filePath,
565
+ type: exportName,
566
+ expose: "all",
567
+ jsDoc: "extended",
568
+ markdownDescription: true,
569
+ fullDescription: true,
570
+ skipTypeCheck: true,
571
+ tsProgram: createProgramFromFileSystem(filePath, options),
572
+ ...options
573
+ }).createSchema(exportName);
574
+ } catch (error) {
575
+ throw new Error(`Failed to generate a JSON schema for "${fileReference.file}"${resolvedPath && resolvedPath !== fileReference.file ? ` (resolved: ${resolvedPath})` : ""} using the type "${exportName}". Error: ${error.message}`);
576
+ }
577
+ }
578
+ /**
579
+ * 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.
580
+ *
581
+ * @example
582
+ * ```ts
583
+ * Resolve a schema definition from a JSON schema file
584
+ * const schema1 = await extract(context, "./schemas/my-json-schema.json");
585
+ * // Resolve a schema definition from a TypeScript module export
586
+ * const schema2 = await extract(context, "./schemas.ts#MySchema");
587
+ * // Resolve a schema definition from a JSON Schema object
588
+ * const schema3 = await extract(context, schemaObject);
589
+ * // Resolve a schema definition from a Zod schema
590
+ * const schema4 = await extract(context, zodSchema);
591
+ * // Resolve a schema definition from a Valibot schema
592
+ * const schema5 = await extract(context, valibotSchema);
593
+ * // Resolve a schema definition from an untyped schema
594
+ * const schema6 = await extract(context, untypedSchema);
595
+ * ```
596
+ *
597
+ * @see https://zod.dev/
598
+ * @see https://valibot.dev/
599
+ * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec
600
+ * @see https://json-schema.org/
601
+ * @see https://ajv.js.org/json-type-definition.html
602
+ * @see https://github.com/vega/ts-json-schema-generator
603
+ * @see https://github.com/unjs/untyped
604
+ * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html
605
+ *
606
+ * @param input - The schema definition input to extract, 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.
607
+ * @param options - Optional overrides for the configuration used during extraction.
608
+ * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
609
+ * @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.
610
+ */
611
+ async function extractSchemaWithSource(input, options = {}) {
612
+ const unwrappedConfig = unwrapSchemaConfig(input);
613
+ if (isSchemaWithSource(unwrappedConfig)) return unwrappedConfig;
614
+ if (isSchema(unwrappedConfig)) return {
615
+ ...unwrappedConfig,
616
+ source: {
617
+ hash: extractHash("json-schema", unwrappedConfig.schema),
618
+ variant: "json-schema",
619
+ schema: unwrappedConfig.schema
620
+ }
621
+ };
622
+ let source;
623
+ const variant = extractVariant(unwrappedConfig);
624
+ const hash = extractHash(variant, unwrappedConfig);
625
+ if (variant === "file-reference") {
626
+ const fileReference = extractFileReference(unwrappedConfig);
627
+ if (!fileReference) throw new Error(`Failed to extract a valid file reference from the provided input "${JSON.stringify(unwrappedConfig)}". 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.`);
628
+ const extension = findFileExtensionSafe(fileReference.file);
629
+ if (extension && !VALID_OBJECT_SOURCE_EXTENSIONS.includes(extension)) throw new Error(`The provided schema file input "${fileReference.file}" has an invalid file extension (.${extension}). Please ensure that the file has one of the following extensions: ${list(VALID_OBJECT_SOURCE_EXTENSIONS, { conjunction: "or" })}.`);
630
+ let fs;
631
+ if (options.storage) fs = mapStorageToFileSystem(options.storage);
632
+ let resolved = await loadSafe(unwrappedConfig, {
633
+ ...options,
634
+ fs
635
+ });
636
+ resolved ??= await extractTSType(unwrappedConfig, {
637
+ ...options,
638
+ fs
639
+ });
640
+ const resolvedConfig = unwrapSchemaConfig(resolved);
641
+ if (isSchemaWithSource(resolvedConfig)) source = resolvedConfig.source;
642
+ else if (isSchema(resolvedConfig)) source = {
643
+ hash: extractHash("json-schema", resolvedConfig.schema),
644
+ variant: "json-schema",
645
+ schema: resolvedConfig.schema
646
+ };
647
+ else source = extractSource(extractResolvedVariant(resolvedConfig), resolvedConfig);
648
+ } else if ([
649
+ "json-schema",
650
+ "standard-schema",
651
+ "zod3",
652
+ "untyped",
653
+ "valibot",
654
+ "reflection"
655
+ ].includes(variant)) source = extractSource(variant, unwrappedConfig);
656
+ else throw new Error(`Invalid schema definition input "${variant}". The variant must be one of "file-reference", "json-schema", "standard-schema", "zod3", "valibot", "untyped", or "reflection".`);
657
+ return {
658
+ variant,
659
+ source,
660
+ schema: await extractSchema(source.schema, source.variant),
661
+ hash
662
+ };
663
+ }
664
+ /**
665
+ * 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.
666
+ *
667
+ * @example
668
+ * ```ts
669
+ * Resolve a schema definition from a JSON schema file
670
+ * const schema1 = await extract(context, "./schemas/my-json-schema.json");
671
+ * // Resolve a schema definition from a TypeScript module export
672
+ * const schema2 = await extract(context, "./schemas.ts#MySchema");
673
+ * // Resolve a schema definition from a JSON Schema object
674
+ * const schema3 = await extract(context, schemaObject);
675
+ * // Resolve a schema definition from a Zod schema
676
+ * const schema4 = await extract(context, zodSchema);
677
+ * // Resolve a schema definition from a Valibot schema
678
+ * const schema5 = await extract(context, valibotSchema);
679
+ * // Resolve a schema definition from an untyped schema
680
+ * const schema6 = await extract(context, untypedSchema);
681
+ * ```
682
+ *
683
+ * @see https://zod.dev/
684
+ * @see https://valibot.dev/
685
+ * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec
686
+ * @see https://json-schema.org/
687
+ * @see https://ajv.js.org/json-type-definition.html
688
+ * @see https://github.com/vega/ts-json-schema-generator
689
+ * @see https://github.com/unjs/untyped
690
+ * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html
691
+ *
692
+ * @param input - The schema definition input to extract, 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.
693
+ * @param options - Optional overrides for the configuration used during extraction.
694
+ * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.
695
+ * @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.
696
+ */
697
+ async function extract(input, options = {}) {
698
+ const unwrappedConfig = unwrapSchemaConfig(input);
699
+ if (isSchemaWithSource(unwrappedConfig) || isSchemaOf(unwrappedConfig)) return unwrappedConfig;
700
+ const result = await extractSchemaWithSource(input, options);
701
+ if (!result?.schema) throw new 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.`);
702
+ return result;
703
+ }
704
+
705
+ //#endregion
706
+ export { JSON_SCHEMA_METADATA_KEYS, JSON_SCHEMA_PRIMITIVE_TYPES, JSON_SCHEMA_TYPES, JsonSchemaTypeNames, SCHEMA_ARRAY_CONCAT_KEYWORDS, SCHEMA_RECORD_KEYWORDS, SCHEMA_SINGLE_KEYWORDS, addProperty, applyJsonSchemaMetadata, assertSchemasDoNotContradict, bundleReferences, createStoragePromises, extract, extractHash, extractJsonSchema, extractResolvedVariant, extractSchema, extractSchemaWithSource, extractSource, extractTSType, extractVariant, findSchemaContradictions, getJsonSchema, getJsonSchemaObject, 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, isUntypedConfig, isUntypedConfigStrict, isUntypedSchema, isUntypedSchemaStrict, isValibotSchema, isValidSchemaConfigFile, mapStorageToFileSystem, merge, mergeMetadata, normalizeKey, readSchemaTypes, traverseSchema };
3
707
  //# sourceMappingURL=index.mjs.map