@powerlines/schema 0.11.22 → 0.11.23
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/bundle.mjs.map +1 -1
- package/dist/codegen.cjs +44 -1
- package/dist/codegen.d.cts +19 -1
- package/dist/codegen.d.cts.map +1 -1
- package/dist/codegen.d.mts +19 -1
- package/dist/codegen.d.mts.map +1 -1
- package/dist/codegen.mjs +42 -1
- package/dist/codegen.mjs.map +1 -1
- package/dist/constants.cjs +19 -0
- package/dist/constants.d.cts +17 -0
- package/dist/constants.d.cts.map +1 -0
- package/dist/constants.d.mts +17 -0
- package/dist/constants.d.mts.map +1 -0
- package/dist/constants.mjs +18 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/extract.cjs +22 -4
- package/dist/extract.d.cts.map +1 -1
- package/dist/extract.d.mts.map +1 -1
- package/dist/extract.mjs +22 -4
- package/dist/extract.mjs.map +1 -1
- package/dist/helpers.cjs +54 -0
- package/dist/helpers.d.cts +26 -0
- package/dist/helpers.d.cts.map +1 -0
- package/dist/helpers.d.mts +26 -0
- package/dist/helpers.d.mts.map +1 -0
- package/dist/helpers.mjs +52 -0
- package/dist/helpers.mjs.map +1 -0
- package/dist/index.cjs +11 -2
- package/dist/index.d.cts +6 -4
- package/dist/index.d.mts +6 -4
- package/dist/index.mjs +5 -3
- package/dist/jtd.mjs.map +1 -1
- package/dist/reflection.cjs +13 -6
- package/dist/reflection.d.cts.map +1 -1
- package/dist/reflection.d.mts.map +1 -1
- package/dist/reflection.mjs +12 -6
- package/dist/reflection.mjs.map +1 -1
- package/dist/resolve.mjs.map +1 -1
- package/dist/type-checks.cjs +21 -2
- package/dist/type-checks.d.cts +16 -2
- package/dist/type-checks.d.cts.map +1 -1
- package/dist/type-checks.d.mts +16 -2
- package/dist/type-checks.d.mts.map +1 -1
- package/dist/type-checks.mjs +21 -4
- package/dist/type-checks.mjs.map +1 -1
- package/dist/types.d.cts +42 -12
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +42 -12
- package/dist/types.d.mts.map +1 -1
- package/package.json +15 -7
package/dist/bundle.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.mjs","names":[],"sources":["../src/bundle.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n CreateUnpluginResolverOptions,\n ResolveOptions,\n UnresolvedContext\n} from \"@powerlines/core\";\nimport { createUnpluginResolver } from \"@powerlines/core/lib/unplugin\";\nimport { resolveOptions } from \"@powerlines/unplugin/esbuild\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { DeepPartial } from \"@stryke/types/base\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport { build, OutputFile } from \"esbuild\";\nimport { createEsbuildPlugin } from \"unplugin\";\n\nexport type BundleOptions = DeepPartial<BuildOptions> & {\n name?: string;\n resolve?: DeepPartial<ResolveOptions>;\n};\n\n/**\n * Bundle a type definition to a module.\n *\n * @param context - The context object containing the environment paths.\n * @param file - The file path to bundle.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the bundled module.\n */\nexport async function bundle<TContext extends UnresolvedContext>(\n context: TContext,\n file: string,\n options: BundleOptions = {}\n): Promise<OutputFile> {\n const path = await context.fs.resolve(file);\n if (!path || !context.fs.existsSync(path)) {\n throw new Error(\n `Module not found: \"${file}\". Please check the path and try again.`\n );\n }\n\n const result = await build(\n defu(\n {\n entryPoints: [path],\n write: false,\n sourcemap: false,\n splitting: false,\n treeShaking: true,\n bundle: true,\n packages: \"bundle\",\n platform: \"node\",\n logLevel: \"silent\",\n ...omit(options, [\"name\", \"resolve\"])\n },\n resolveOptions(context),\n {\n plugins: [\n createEsbuildPlugin(\n createUnpluginResolver(context, {\n name: options.name ?? `${findFileName(file)} Bundler`,\n prefix: false,\n overrides: defu(\n options.resolve ?? {},\n { skipNodeModulesBundle: false },\n context.config.resolve\n ) as CreateUnpluginResolverOptions[\"overrides\"],\n silenceHookLogging: true\n })\n )()\n ]\n }\n )\n );\n if (result.errors.length > 0) {\n throw new Error(\n `Failed to bundle ${file}: ${result.errors\n .map(error => error.text)\n .join(\", \")}`\n );\n }\n if (result.warnings.length > 0) {\n context.warn(\n `Warnings while bundling ${file}: ${result.warnings\n .map(warning => warning.text)\n .join(\", \")}`\n );\n }\n if (!result.outputFiles || result.outputFiles.filter(Boolean).length === 0) {\n throw new Error(\n `No output files generated for ${\n file\n }. Please check the configuration and try again.`\n );\n }\n\n return result.outputFiles.filter(Boolean)[0]!;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8CA,eAAsB,OACpB,SACA,MACA,UAAyB,
|
|
1
|
+
{"version":3,"file":"bundle.mjs","names":[],"sources":["../src/bundle.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type {\n CreateUnpluginResolverOptions,\n ResolveOptions,\n UnresolvedContext\n} from \"@powerlines/core\";\nimport { createUnpluginResolver } from \"@powerlines/core/lib/unplugin\";\nimport { resolveOptions } from \"@powerlines/unplugin/esbuild\";\nimport { omit } from \"@stryke/helpers/omit\";\nimport { findFileName } from \"@stryke/path/file-path-fns\";\nimport { DeepPartial } from \"@stryke/types/base\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport { build, OutputFile } from \"esbuild\";\nimport { createEsbuildPlugin } from \"unplugin\";\n\nexport type BundleOptions = DeepPartial<BuildOptions> & {\n name?: string;\n resolve?: DeepPartial<ResolveOptions>;\n};\n\n/**\n * Bundle a type definition to a module.\n *\n * @param context - The context object containing the environment paths.\n * @param file - The file path to bundle.\n * @param options - Optional overrides for the ESBuild configuration.\n * @returns A promise that resolves to the bundled module.\n */\nexport async function bundle<TContext extends UnresolvedContext>(\n context: TContext,\n file: string,\n options: BundleOptions = {}\n): Promise<OutputFile> {\n const path = await context.fs.resolve(file);\n if (!path || !context.fs.existsSync(path)) {\n throw new Error(\n `Module not found: \"${file}\". Please check the path and try again.`\n );\n }\n\n const result = await build(\n defu(\n {\n entryPoints: [path],\n write: false,\n sourcemap: false,\n splitting: false,\n treeShaking: true,\n bundle: true,\n packages: \"bundle\",\n platform: \"node\",\n logLevel: \"silent\",\n ...omit(options, [\"name\", \"resolve\"])\n },\n resolveOptions(context),\n {\n plugins: [\n createEsbuildPlugin(\n createUnpluginResolver(context, {\n name: options.name ?? `${findFileName(file)} Bundler`,\n prefix: false,\n overrides: defu(\n options.resolve ?? {},\n { skipNodeModulesBundle: false },\n context.config.resolve\n ) as CreateUnpluginResolverOptions[\"overrides\"],\n silenceHookLogging: true\n })\n )()\n ]\n }\n )\n );\n if (result.errors.length > 0) {\n throw new Error(\n `Failed to bundle ${file}: ${result.errors\n .map(error => error.text)\n .join(\", \")}`\n );\n }\n if (result.warnings.length > 0) {\n context.warn(\n `Warnings while bundling ${file}: ${result.warnings\n .map(warning => warning.text)\n .join(\", \")}`\n );\n }\n if (!result.outputFiles || result.outputFiles.filter(Boolean).length === 0) {\n throw new Error(\n `No output files generated for ${\n file\n }. Please check the configuration and try again.`\n );\n }\n\n return result.outputFiles.filter(Boolean)[0]!;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8CA,eAAsB,OACpB,SACA,MACA,UAAyB,CAAC,GACL;CACrB,MAAM,OAAO,MAAM,QAAQ,GAAG,QAAQ,IAAI;CAC1C,IAAI,CAAC,QAAQ,CAAC,QAAQ,GAAG,WAAW,IAAI,GACtC,MAAM,IAAI,MACR,sBAAsB,KAAK,wCAC7B;CAGF,MAAM,SAAS,MAAM,MACnB,KACE;EACE,aAAa,CAAC,IAAI;EAClB,OAAO;EACP,WAAW;EACX,WAAW;EACX,aAAa;EACb,QAAQ;EACR,UAAU;EACV,UAAU;EACV,UAAU;EACV,GAAG,KAAK,SAAS,CAAC,QAAQ,SAAS,CAAC;CACtC,GACA,eAAe,OAAO,GACtB,EACE,SAAS,CACP,oBACE,uBAAuB,SAAS;EAC9B,MAAM,QAAQ,QAAQ,GAAG,aAAa,IAAI,EAAE;EAC5C,QAAQ;EACR,WAAW,KACT,QAAQ,WAAW,CAAC,GACpB,EAAE,uBAAuB,MAAM,GAC/B,QAAQ,OAAO,OACjB;EACA,oBAAoB;CACtB,CAAC,CACH,EAAE,CACJ,EACF,CACF,CACF;CACA,IAAI,OAAO,OAAO,SAAS,GACzB,MAAM,IAAI,MACR,oBAAoB,KAAK,IAAI,OAAO,OACjC,KAAI,UAAS,MAAM,IAAI,EACvB,KAAK,IAAI,GACd;CAEF,IAAI,OAAO,SAAS,SAAS,GAC3B,QAAQ,KACN,2BAA2B,KAAK,IAAI,OAAO,SACxC,KAAI,YAAW,QAAQ,IAAI,EAC3B,KAAK,IAAI,GACd;CAEF,IAAI,CAAC,OAAO,eAAe,OAAO,YAAY,OAAO,OAAO,EAAE,WAAW,GACvE,MAAM,IAAI,MACR,iCACE,KACD,gDACH;CAGF,OAAO,OAAO,YAAY,OAAO,OAAO,EAAE;AAC5C"}
|
package/dist/codegen.cjs
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_helpers = require('./helpers.cjs');
|
|
4
|
+
let _stryke_convert_to_bool = require("@stryke/convert/to-bool");
|
|
5
|
+
let _stryke_type_checks_is_boolean = require("@stryke/type-checks/is-boolean");
|
|
6
|
+
let _stryke_type_checks_is_null = require("@stryke/type-checks/is-null");
|
|
7
|
+
let _stryke_type_checks_is_number = require("@stryke/type-checks/is-number");
|
|
8
|
+
let _stryke_type_checks_is_undefined = require("@stryke/type-checks/is-undefined");
|
|
3
9
|
let ajv = require("ajv");
|
|
4
10
|
ajv = require_runtime.__toESM(ajv, 1);
|
|
5
11
|
let ajv_dist_standalone_index_js = require("ajv/dist/standalone/index.js");
|
|
@@ -7,6 +13,41 @@ ajv_dist_standalone_index_js = require_runtime.__toESM(ajv_dist_standalone_index
|
|
|
7
13
|
|
|
8
14
|
//#region src/codegen.ts
|
|
9
15
|
/**
|
|
16
|
+
* Stringifies a value as a string.
|
|
17
|
+
*
|
|
18
|
+
* @remarks
|
|
19
|
+
* This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
|
|
20
|
+
*
|
|
21
|
+
* @param value - The value to stringify.
|
|
22
|
+
* @returns A string representation of the value.
|
|
23
|
+
*/
|
|
24
|
+
function stringifyValue(value, type) {
|
|
25
|
+
return (0, _stryke_type_checks_is_undefined.isUndefined)(value) ? "undefined" : (0, _stryke_type_checks_is_null.isNull)(value) ? "null" : type === "boolean" || (0, _stryke_type_checks_is_boolean.isBoolean)(value) ? String((0, _stryke_convert_to_bool.toBool)(value)) : type && type.startsWith("float") ? Number.parseFloat(String(value)).toLocaleString(void 0, { maximumFractionDigits: 20 }) : type && ["int", "uint"].some((prefix) => type.startsWith(prefix)) || (0, _stryke_type_checks_is_number.isNumber)(value) ? Number.parseInt(String(value)).toLocaleString() : type === "timestamp" ? `"${new Date(String(value)).toISOString()}"` : JSON.stringify(String(value).replaceAll("\"", "\\\""), void 0, 2);
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
|
|
29
|
+
*
|
|
30
|
+
* @param schema - The JTD schema type to stringify.
|
|
31
|
+
* @returns A string representation of the JTD schema type.
|
|
32
|
+
*/
|
|
33
|
+
function stringifyType(schema) {
|
|
34
|
+
if (!schema) return "unknown";
|
|
35
|
+
if ("ref" in schema) return schema.ref;
|
|
36
|
+
if ("type" in schema) return [
|
|
37
|
+
"float",
|
|
38
|
+
"uint",
|
|
39
|
+
"int"
|
|
40
|
+
].some((prefix) => schema.type.startsWith(prefix)) ? "number" : schema.type === "timestamp" ? "string" : schema.type;
|
|
41
|
+
if ("enum" in schema) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
|
|
42
|
+
if ("elements" in schema) return `${stringifyType(schema.elements)}[]`;
|
|
43
|
+
if ("values" in schema) return `{ [key: string]: ${stringifyType(schema.values)} }`;
|
|
44
|
+
if ("properties" in schema || "optionalProperties" in schema) return `{ ${Object.entries(require_helpers.getProperties(schema)).map(([key, value]) => {
|
|
45
|
+
return `${key}${value.optional ? "?" : ""}: ${stringifyType(value)}`;
|
|
46
|
+
}).join(";\n")} }`;
|
|
47
|
+
if ("discriminator" in schema) return "object";
|
|
48
|
+
return "unknown";
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
10
51
|
* Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
|
|
11
52
|
*
|
|
12
53
|
* @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.
|
|
@@ -24,4 +65,6 @@ async function generateCode(schemas, refsOrFuncts) {
|
|
|
24
65
|
}
|
|
25
66
|
|
|
26
67
|
//#endregion
|
|
27
|
-
exports.generateCode = generateCode;
|
|
68
|
+
exports.generateCode = generateCode;
|
|
69
|
+
exports.stringifyType = stringifyType;
|
|
70
|
+
exports.stringifyValue = stringifyValue;
|
package/dist/codegen.d.cts
CHANGED
|
@@ -1,7 +1,25 @@
|
|
|
1
|
+
import { JTDSchemaType, JTDType } from "./types.cjs";
|
|
1
2
|
import { Options } from "ajv";
|
|
2
3
|
import standaloneCode from "ajv/dist/standalone/index.js";
|
|
3
4
|
|
|
4
5
|
//#region src/codegen.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* Stringifies a value as a string.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
|
|
11
|
+
*
|
|
12
|
+
* @param value - The value to stringify.
|
|
13
|
+
* @returns A string representation of the value.
|
|
14
|
+
*/
|
|
15
|
+
declare function stringifyValue(value?: unknown, type?: JTDType): string;
|
|
16
|
+
/**
|
|
17
|
+
* Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
|
|
18
|
+
*
|
|
19
|
+
* @param schema - The JTD schema type to stringify.
|
|
20
|
+
* @returns A string representation of the JTD schema type.
|
|
21
|
+
*/
|
|
22
|
+
declare function stringifyType(schema?: JTDSchemaType): string;
|
|
5
23
|
/**
|
|
6
24
|
* Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
|
|
7
25
|
*
|
|
@@ -11,5 +29,5 @@ import standaloneCode from "ajv/dist/standalone/index.js";
|
|
|
11
29
|
*/
|
|
12
30
|
declare function generateCode(schemas: Options["schemas"], refsOrFuncts?: Parameters<typeof standaloneCode>[1]): Promise<string>;
|
|
13
31
|
//#endregion
|
|
14
|
-
export { generateCode };
|
|
32
|
+
export { generateCode, stringifyType, stringifyValue };
|
|
15
33
|
//# sourceMappingURL=codegen.d.cts.map
|
package/dist/codegen.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.d.cts","names":[],"sources":["../src/codegen.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"codegen.d.cts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;;AAsCA;;;;;;;iBAAgB,cAAA,CAAe,KAAA,YAAiB,IAAA,GAAO,OAAO;AAAA;AA6B9D;;;;AAAoD;AA7BU,iBA6B9C,aAAA,CAAc,MAAsB,GAAb,aAAa;;;;;;;;iBAqD9B,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA"}
|
package/dist/codegen.d.mts
CHANGED
|
@@ -1,7 +1,25 @@
|
|
|
1
|
+
import { JTDSchemaType, JTDType } from "./types.mjs";
|
|
1
2
|
import { Options } from "ajv";
|
|
2
3
|
import standaloneCode from "ajv/dist/standalone/index.js";
|
|
3
4
|
|
|
4
5
|
//#region src/codegen.d.ts
|
|
6
|
+
/**
|
|
7
|
+
* Stringifies a value as a string.
|
|
8
|
+
*
|
|
9
|
+
* @remarks
|
|
10
|
+
* This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
|
|
11
|
+
*
|
|
12
|
+
* @param value - The value to stringify.
|
|
13
|
+
* @returns A string representation of the value.
|
|
14
|
+
*/
|
|
15
|
+
declare function stringifyValue(value?: unknown, type?: JTDType): string;
|
|
16
|
+
/**
|
|
17
|
+
* Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
|
|
18
|
+
*
|
|
19
|
+
* @param schema - The JTD schema type to stringify.
|
|
20
|
+
* @returns A string representation of the JTD schema type.
|
|
21
|
+
*/
|
|
22
|
+
declare function stringifyType(schema?: JTDSchemaType): string;
|
|
5
23
|
/**
|
|
6
24
|
* Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
|
|
7
25
|
*
|
|
@@ -11,5 +29,5 @@ import standaloneCode from "ajv/dist/standalone/index.js";
|
|
|
11
29
|
*/
|
|
12
30
|
declare function generateCode(schemas: Options["schemas"], refsOrFuncts?: Parameters<typeof standaloneCode>[1]): Promise<string>;
|
|
13
31
|
//#endregion
|
|
14
|
-
export { generateCode };
|
|
32
|
+
export { generateCode, stringifyType, stringifyValue };
|
|
15
33
|
//# sourceMappingURL=codegen.d.mts.map
|
package/dist/codegen.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.d.mts","names":[],"sources":["../src/codegen.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"codegen.d.mts","names":[],"sources":["../src/codegen.ts"],"mappings":";;;;;;;AAsCA;;;;;;;iBAAgB,cAAA,CAAe,KAAA,YAAiB,IAAA,GAAO,OAAO;AAAA;AA6B9D;;;;AAAoD;AA7BU,iBA6B9C,aAAA,CAAc,MAAsB,GAAb,aAAa;;;;;;;;iBAqD9B,YAAA,CACpB,OAAA,EAAS,OAAA,aACT,YAAA,GAAe,UAAA,QAAkB,cAAA,OAAkB,OAAA"}
|
package/dist/codegen.mjs
CHANGED
|
@@ -1,8 +1,49 @@
|
|
|
1
|
+
import { getProperties } from "./helpers.mjs";
|
|
2
|
+
import { toBool } from "@stryke/convert/to-bool";
|
|
3
|
+
import { isBoolean } from "@stryke/type-checks/is-boolean";
|
|
4
|
+
import { isNull } from "@stryke/type-checks/is-null";
|
|
5
|
+
import { isNumber } from "@stryke/type-checks/is-number";
|
|
6
|
+
import { isUndefined } from "@stryke/type-checks/is-undefined";
|
|
1
7
|
import Ajv from "ajv";
|
|
2
8
|
import standaloneCode from "ajv/dist/standalone/index.js";
|
|
3
9
|
|
|
4
10
|
//#region src/codegen.ts
|
|
5
11
|
/**
|
|
12
|
+
* Stringifies a value as a string.
|
|
13
|
+
*
|
|
14
|
+
* @remarks
|
|
15
|
+
* This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to "true" or "false", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.
|
|
16
|
+
*
|
|
17
|
+
* @param value - The value to stringify.
|
|
18
|
+
* @returns A string representation of the value.
|
|
19
|
+
*/
|
|
20
|
+
function stringifyValue(value, type) {
|
|
21
|
+
return isUndefined(value) ? "undefined" : isNull(value) ? "null" : type === "boolean" || isBoolean(value) ? String(toBool(value)) : type && type.startsWith("float") ? Number.parseFloat(String(value)).toLocaleString(void 0, { maximumFractionDigits: 20 }) : type && ["int", "uint"].some((prefix) => type.startsWith(prefix)) || isNumber(value) ? Number.parseInt(String(value)).toLocaleString() : type === "timestamp" ? `"${new Date(String(value)).toISOString()}"` : JSON.stringify(String(value).replaceAll("\"", "\\\""), void 0, 2);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.
|
|
25
|
+
*
|
|
26
|
+
* @param schema - The JTD schema type to stringify.
|
|
27
|
+
* @returns A string representation of the JTD schema type.
|
|
28
|
+
*/
|
|
29
|
+
function stringifyType(schema) {
|
|
30
|
+
if (!schema) return "unknown";
|
|
31
|
+
if ("ref" in schema) return schema.ref;
|
|
32
|
+
if ("type" in schema) return [
|
|
33
|
+
"float",
|
|
34
|
+
"uint",
|
|
35
|
+
"int"
|
|
36
|
+
].some((prefix) => schema.type.startsWith(prefix)) ? "number" : schema.type === "timestamp" ? "string" : schema.type;
|
|
37
|
+
if ("enum" in schema) return schema.enum.map((value) => JSON.stringify(value)).join(" | ");
|
|
38
|
+
if ("elements" in schema) return `${stringifyType(schema.elements)}[]`;
|
|
39
|
+
if ("values" in schema) return `{ [key: string]: ${stringifyType(schema.values)} }`;
|
|
40
|
+
if ("properties" in schema || "optionalProperties" in schema) return `{ ${Object.entries(getProperties(schema)).map(([key, value]) => {
|
|
41
|
+
return `${key}${value.optional ? "?" : ""}: ${stringifyType(value)}`;
|
|
42
|
+
}).join(";\n")} }`;
|
|
43
|
+
if ("discriminator" in schema) return "object";
|
|
44
|
+
return "unknown";
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
6
47
|
* Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.
|
|
7
48
|
*
|
|
8
49
|
* @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.
|
|
@@ -20,5 +61,5 @@ async function generateCode(schemas, refsOrFuncts) {
|
|
|
20
61
|
}
|
|
21
62
|
|
|
22
63
|
//#endregion
|
|
23
|
-
export { generateCode };
|
|
64
|
+
export { generateCode, stringifyType, stringifyValue };
|
|
24
65
|
//# sourceMappingURL=codegen.mjs.map
|
package/dist/codegen.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codegen.mjs","names":[],"sources":["../src/codegen.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Options } from \"ajv\";\nimport Ajv from \"ajv\";\nimport standaloneCode from \"ajv/dist/standalone\";\n\n/**\n * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.\n *\n * @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.\n * @param refsOrFuncts - An optional parameter that can be either an object containing schema references or a function that returns such an object. This parameter allows you to provide additional schemas that may be referenced by the main schemas, or to define custom functions that can be used in the generated validation code. If not provided, the function will generate code based solely on the provided schemas.\n * @returns A promise that resolves to a string containing the generated standalone validation code.\n */\nexport async function generateCode(\n schemas: Options[\"schemas\"],\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return standaloneCode(\n new Ajv({\n schemas,\n code: { source: true, esm: true }\n }),\n refsOrFuncts\n );\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"codegen.mjs","names":[],"sources":["../src/codegen.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport { toBool } from \"@stryke/convert/to-bool\";\nimport { isBoolean } from \"@stryke/type-checks/is-boolean\";\nimport { isNull } from \"@stryke/type-checks/is-null\";\nimport { isNumber } from \"@stryke/type-checks/is-number\";\nimport { isUndefined } from \"@stryke/type-checks/is-undefined\";\nimport type { Options } from \"ajv\";\nimport Ajv from \"ajv\";\nimport standaloneCode from \"ajv/dist/standalone\";\nimport { getProperties } from \"./helpers\";\nimport { JTDSchemaType, JTDType } from \"./types\";\n\n/**\n * Stringifies a value as a string.\n *\n * @remarks\n * This function is used to convert a value into a string representation that can be used in generated code, such as default values in TypeScript declarations. It handles different types of values, including booleans, numbers, and strings, and formats them appropriately. For example, boolean values are converted to \"true\" or \"false\", numbers are formatted with locale-specific separators, and strings are JSON-stringified with escaped quotes. The function also takes into account the type of the value when stringifying, allowing for specific formatting based on the type (e.g., different handling for integers vs. floats). This ensures that the generated code is both accurate and readable.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the value.\n */\nexport function stringifyValue(value?: unknown, type?: JTDType): string {\n return isUndefined(value)\n ? \"undefined\"\n : isNull(value)\n ? \"null\"\n : type === \"boolean\" || isBoolean(value)\n ? String(toBool(value))\n : type && type.startsWith(\"float\")\n ? Number.parseFloat(String(value)).toLocaleString(undefined, {\n maximumFractionDigits: 20\n })\n : (type && [\"int\", \"uint\"].some(prefix => type.startsWith(prefix))) ||\n isNumber(value)\n ? Number.parseInt(String(value)).toLocaleString()\n : type === \"timestamp\"\n ? `\"${new Date(String(value)).toISOString()}\"`\n : JSON.stringify(\n String(value).replaceAll('\"', '\\\\\"'),\n undefined,\n 2\n );\n}\n\n/**\n * Stringifies a JTD schema type into a string representation. This function takes a JTD schema type as input and returns a string that represents the type in a human-readable format. It handles various JTD schema constructs, such as references, primitive types, enums, arrays, objects, and discriminated unions. The resulting string can be used for documentation, error messages, or any context where a textual representation of the schema type is needed. The function recursively processes nested schemas to ensure that complex types are accurately represented in the output string.\n *\n * @param schema - The JTD schema type to stringify.\n * @returns A string representation of the JTD schema type.\n */\nexport function stringifyType(schema?: JTDSchemaType): string {\n if (!schema) {\n return \"unknown\";\n }\n\n if (\"ref\" in schema) {\n return schema.ref;\n }\n\n if (\"type\" in schema) {\n return [\"float\", \"uint\", \"int\"].some(prefix =>\n schema.type.startsWith(prefix)\n )\n ? \"number\"\n : schema.type === \"timestamp\"\n ? \"string\"\n : schema.type;\n }\n\n if (\"enum\" in schema) {\n return schema.enum.map(value => JSON.stringify(value)).join(\" | \");\n }\n\n if (\"elements\" in schema) {\n return `${stringifyType(schema.elements)}[]`;\n }\n\n if (\"values\" in schema) {\n return `{ [key: string]: ${stringifyType(schema.values)} }`;\n }\n\n if (\"properties\" in schema || \"optionalProperties\" in schema) {\n return `{ ${Object.entries(getProperties(schema))\n .map(([key, value]) => {\n return `${key}${value.optional ? \"?\" : \"\"}: ${stringifyType(value)}`;\n })\n .join(\";\\n\")} }`;\n }\n\n if (\"discriminator\" in schema) {\n return \"object\";\n }\n\n return \"unknown\";\n}\n\n/**\n * Generates standalone validation code for the provided JSON schemas using the Ajv library. This function takes an array of JSON schemas and an optional set of references or functions, and returns a string containing the generated validation code. The generated code can be used to validate data against the provided schemas without requiring the Ajv library at runtime, making it suitable for use in environments where minimizing dependencies is important.\n *\n * @param schemas - An array of JSON schemas to generate validation code for. Each schema should be a valid JSON schema object that defines the structure and constraints of the data to be validated.\n * @param refsOrFuncts - An optional parameter that can be either an object containing schema references or a function that returns such an object. This parameter allows you to provide additional schemas that may be referenced by the main schemas, or to define custom functions that can be used in the generated validation code. If not provided, the function will generate code based solely on the provided schemas.\n * @returns A promise that resolves to a string containing the generated standalone validation code.\n */\nexport async function generateCode(\n schemas: Options[\"schemas\"],\n refsOrFuncts?: Parameters<typeof standaloneCode>[1]\n) {\n return standaloneCode(\n new Ajv({\n schemas,\n code: { source: true, esm: true }\n }),\n refsOrFuncts\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,eAAe,OAAiB,MAAwB;CACtE,OAAO,YAAY,KAAK,IACpB,cACA,OAAO,KAAK,IACV,SACA,SAAS,aAAa,UAAU,KAAK,IACnC,OAAO,OAAO,KAAK,CAAC,IACpB,QAAQ,KAAK,WAAW,OAAO,IAC7B,OAAO,WAAW,OAAO,KAAK,CAAC,EAAE,eAAe,QAAW,EACzD,uBAAuB,GACzB,CAAC,IACA,QAAQ,CAAC,OAAO,MAAM,EAAE,MAAK,WAAU,KAAK,WAAW,MAAM,CAAC,KAC7D,SAAS,KAAK,IACd,OAAO,SAAS,OAAO,KAAK,CAAC,EAAE,eAAe,IAC9C,SAAS,cACP,IAAI,IAAI,KAAK,OAAO,KAAK,CAAC,EAAE,YAAY,EAAE,KAC1C,KAAK,UACH,OAAO,KAAK,EAAE,WAAW,MAAK,MAAK,GACnC,QACA,CACF;AAChB;;;;;;;AAQA,SAAgB,cAAc,QAAgC;CAC5D,IAAI,CAAC,QACH,OAAO;CAGT,IAAI,SAAS,QACX,OAAO,OAAO;CAGhB,IAAI,UAAU,QACZ,OAAO;EAAC;EAAS;EAAQ;CAAK,EAAE,MAAK,WACnC,OAAO,KAAK,WAAW,MAAM,CAC/B,IACI,WACA,OAAO,SAAS,cACd,WACA,OAAO;CAGf,IAAI,UAAU,QACZ,OAAO,OAAO,KAAK,KAAI,UAAS,KAAK,UAAU,KAAK,CAAC,EAAE,KAAK,KAAK;CAGnE,IAAI,cAAc,QAChB,OAAO,GAAG,cAAc,OAAO,QAAQ,EAAE;CAG3C,IAAI,YAAY,QACd,OAAO,oBAAoB,cAAc,OAAO,MAAM,EAAE;CAG1D,IAAI,gBAAgB,UAAU,wBAAwB,QACpD,OAAO,KAAK,OAAO,QAAQ,cAAc,MAAM,CAAC,EAC7C,KAAK,CAAC,KAAK,WAAW;EACrB,OAAO,GAAG,MAAM,MAAM,WAAW,MAAM,GAAG,IAAI,cAAc,KAAK;CACnE,CAAC,EACA,KAAK,KAAK,EAAE;CAGjB,IAAI,mBAAmB,QACrB,OAAO;CAGT,OAAO;AACT;;;;;;;;AASA,eAAsB,aACpB,SACA,cACA;CACA,OAAO,eACL,IAAI,IAAI;EACN;EACA,MAAM;GAAE,QAAQ;GAAM,KAAK;EAAK;CAClC,CAAC,GACD,YACF;AACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
//#region src/constants.ts
|
|
4
|
+
const JTDTypes = {
|
|
5
|
+
STRING: "string",
|
|
6
|
+
TIMESTAMP: "timestamp",
|
|
7
|
+
BOOLEAN: "boolean",
|
|
8
|
+
FLOAT32: "float32",
|
|
9
|
+
FLOAT64: "float64",
|
|
10
|
+
INT8: "int8",
|
|
11
|
+
UINT8: "uint8",
|
|
12
|
+
INT16: "int16",
|
|
13
|
+
UINT16: "uint16",
|
|
14
|
+
INT32: "int32",
|
|
15
|
+
UINT32: "uint32"
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
//#endregion
|
|
19
|
+
exports.JTDTypes = JTDTypes;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region src/constants.d.ts
|
|
2
|
+
declare const JTDTypes: {
|
|
3
|
+
readonly STRING: "string";
|
|
4
|
+
readonly TIMESTAMP: "timestamp";
|
|
5
|
+
readonly BOOLEAN: "boolean";
|
|
6
|
+
readonly FLOAT32: "float32";
|
|
7
|
+
readonly FLOAT64: "float64";
|
|
8
|
+
readonly INT8: "int8";
|
|
9
|
+
readonly UINT8: "uint8";
|
|
10
|
+
readonly INT16: "int16";
|
|
11
|
+
readonly UINT16: "uint16";
|
|
12
|
+
readonly INT32: "int32";
|
|
13
|
+
readonly UINT32: "uint32";
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { JTDTypes };
|
|
17
|
+
//# sourceMappingURL=constants.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.cts","names":[],"sources":["../src/constants.ts"],"mappings":";cAkBa,QAAA;EAAA"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region src/constants.d.ts
|
|
2
|
+
declare const JTDTypes: {
|
|
3
|
+
readonly STRING: "string";
|
|
4
|
+
readonly TIMESTAMP: "timestamp";
|
|
5
|
+
readonly BOOLEAN: "boolean";
|
|
6
|
+
readonly FLOAT32: "float32";
|
|
7
|
+
readonly FLOAT64: "float64";
|
|
8
|
+
readonly INT8: "int8";
|
|
9
|
+
readonly UINT8: "uint8";
|
|
10
|
+
readonly INT16: "int16";
|
|
11
|
+
readonly UINT16: "uint16";
|
|
12
|
+
readonly INT32: "int32";
|
|
13
|
+
readonly UINT32: "uint32";
|
|
14
|
+
};
|
|
15
|
+
//#endregion
|
|
16
|
+
export { JTDTypes };
|
|
17
|
+
//# sourceMappingURL=constants.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.d.mts","names":[],"sources":["../src/constants.ts"],"mappings":";cAkBa,QAAA;EAAA"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region src/constants.ts
|
|
2
|
+
const JTDTypes = {
|
|
3
|
+
STRING: "string",
|
|
4
|
+
TIMESTAMP: "timestamp",
|
|
5
|
+
BOOLEAN: "boolean",
|
|
6
|
+
FLOAT32: "float32",
|
|
7
|
+
FLOAT64: "float64",
|
|
8
|
+
INT8: "int8",
|
|
9
|
+
UINT8: "uint8",
|
|
10
|
+
INT16: "int16",
|
|
11
|
+
UINT16: "uint16",
|
|
12
|
+
INT32: "int32",
|
|
13
|
+
UINT32: "uint32"
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
//#endregion
|
|
17
|
+
export { JTDTypes };
|
|
18
|
+
//# sourceMappingURL=constants.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"constants.mjs","names":[],"sources":["../src/constants.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nexport const JTDTypes = {\n STRING: \"string\",\n TIMESTAMP: \"timestamp\",\n BOOLEAN: \"boolean\",\n FLOAT32: \"float32\",\n FLOAT64: \"float64\",\n INT8: \"int8\",\n UINT8: \"uint8\",\n INT16: \"int16\",\n UINT16: \"uint16\",\n INT32: \"int32\",\n UINT32: \"uint32\"\n} as const;\n"],"mappings":";AAkBA,MAAa,WAAW;CACtB,QAAQ;CACR,WAAW;CACX,SAAS;CACT,SAAS;CACT,SAAS;CACT,MAAM;CACN,OAAO;CACP,OAAO;CACP,QAAQ;CACR,OAAO;CACP,QAAQ;AACV"}
|
package/dist/extract.cjs
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
|
|
3
|
+
const require_type_checks = require('./type-checks.cjs');
|
|
3
4
|
const require_jtd = require('./jtd.cjs');
|
|
4
5
|
const require_reflection = require('./reflection.cjs');
|
|
5
6
|
const require_resolve = require('./resolve.cjs');
|
|
6
|
-
const require_type_checks = require('./type-checks.cjs');
|
|
7
7
|
let defu = require("defu");
|
|
8
8
|
defu = require_runtime.__toESM(defu, 1);
|
|
9
|
+
let _stryke_type_checks = require("@stryke/type-checks");
|
|
9
10
|
let _powerlines_core = require("@powerlines/core");
|
|
10
11
|
let _powerlines_deepkit_esbuild_plugin = require("@powerlines/deepkit/esbuild-plugin");
|
|
11
12
|
let _powerlines_deepkit_vendor_type = require("@powerlines/deepkit/vendor/type");
|
|
12
13
|
let _stryke_hash = require("@stryke/hash");
|
|
13
14
|
let _stryke_json = require("@stryke/json");
|
|
14
|
-
let
|
|
15
|
+
let _stryke_path_join = require("@stryke/path/join");
|
|
15
16
|
let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
|
|
16
17
|
let _stryke_zod = require("@stryke/zod");
|
|
17
18
|
|
|
@@ -199,6 +200,7 @@ async function extractSchema(context, input, options = {}) {
|
|
|
199
200
|
};
|
|
200
201
|
let source;
|
|
201
202
|
const variant = extractVariant(input);
|
|
203
|
+
const hash = extractHash(variant, input);
|
|
202
204
|
if (variant === "type-definition") {
|
|
203
205
|
const resolved = await require_resolve.resolve(context, input, (0, defu.default)(options, { plugins: [(0, _powerlines_deepkit_esbuild_plugin.esbuildPlugin)(context, {
|
|
204
206
|
reflection: "default",
|
|
@@ -218,7 +220,7 @@ async function extractSchema(context, input, options = {}) {
|
|
|
218
220
|
variant,
|
|
219
221
|
source,
|
|
220
222
|
schema: await extractSchemaSchema(source.schema, source.variant),
|
|
221
|
-
hash
|
|
223
|
+
hash
|
|
222
224
|
};
|
|
223
225
|
}
|
|
224
226
|
/**
|
|
@@ -250,7 +252,23 @@ async function extractSchema(context, input, options = {}) {
|
|
|
250
252
|
* @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.
|
|
251
253
|
*/
|
|
252
254
|
async function extract(context, input, options = {}) {
|
|
253
|
-
|
|
255
|
+
if (require_type_checks.isExtractedSchema(input) || require_type_checks.isSchema(input)) return input;
|
|
256
|
+
const variant = extractVariant(input);
|
|
257
|
+
const hash = extractHash(variant, input);
|
|
258
|
+
const cacheFilePath = (0, _stryke_path_join.joinPaths)(context.cachePath, "schemas", `${hash}.json`);
|
|
259
|
+
let result;
|
|
260
|
+
if (context.config.skipCache !== true && context.fs.existsSync(cacheFilePath)) {
|
|
261
|
+
const schema = await context.fs.read(cacheFilePath);
|
|
262
|
+
if (schema) result = {
|
|
263
|
+
variant,
|
|
264
|
+
hash,
|
|
265
|
+
schema: JSON.parse(schema)
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
result ??= await extractSchema(context, input, options);
|
|
269
|
+
if (!result?.schema) 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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`);
|
|
270
|
+
if (context.config.skipCache !== true) await context.fs.write(cacheFilePath, JSON.stringify(result.schema));
|
|
271
|
+
return result;
|
|
254
272
|
}
|
|
255
273
|
|
|
256
274
|
//#endregion
|
package/dist/extract.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;AAoEA;iBAAgB,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EAAO,WAAW;;;;;;;;AAAA;AA8BpB;iBAAgB,iBAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CACpD,UAAA,EAAY,IAAA,GAAO,aAAA,CAAc,SAAA;;;;;;;;;;iBAiBnB,iBAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CACpD,MAAA,YAAkB,aAAA,CAAc,SAAA;;;;;;;;iBAsClB,sBAAA,CACd,KAAA,EAAO,iBAAA,GACN,mBAAmB;;;AA3DsB;AAiB5C;;;;iBAuEgB,cAAA,CAAe,KAAA,EAAO,WAAA,GAAc,kBAAkB;;;;;;;;;iBAgBhD,mBAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CAEpD,KAAA,EAAO,iBAAA,EACP,OAAA,GAAU,kBAAA,GACT,OAAA,CAAQ,aAAA,CAAc,SAAA;;;;;;;AA1FkB;AAsC3C;iBA6FgB,aAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CACpD,OAAA,EAAS,mBAAA,EAAqB,KAAA,EAAO,iBAAA,GAAoB,YAAA;;;;;;;AA7FrC;AA6BtB;;;;;;;;AAAsE;AAgBtE;;;;iBAgHsB,aAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAE3B,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,OAAA,CAAQ,YAAA,IAChB,OAAA,CAAQ,eAAA,CAAgB,SAAA;;;;;;;;;;;;;;;;;;;;;;;AAlHO;AAyClC;;;;;iBAoKsB,OAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAE3B,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,OAAA,CAAQ,YAAA,IAChB,OAAA,CAAQ,MAAA,CAAO,SAAA"}
|
package/dist/extract.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract.d.mts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;
|
|
1
|
+
{"version":3,"file":"extract.d.mts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;AAoEA;iBAAgB,WAAA,CACd,OAAA,EAAS,kBAAA,EACT,KAAA,EAAO,WAAW;;;;;;;;AAAA;AA8BpB;iBAAgB,iBAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CACpD,UAAA,EAAY,IAAA,GAAO,aAAA,CAAc,SAAA;;;;;;;;;;iBAiBnB,iBAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CACpD,MAAA,YAAkB,aAAA,CAAc,SAAA;;;;;;;;iBAsClB,sBAAA,CACd,KAAA,EAAO,iBAAA,GACN,mBAAmB;;;AA3DsB;AAiB5C;;;;iBAuEgB,cAAA,CAAe,KAAA,EAAO,WAAA,GAAc,kBAAkB;;;;;;;;;iBAgBhD,mBAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CAEpD,KAAA,EAAO,iBAAA,EACP,OAAA,GAAU,kBAAA,GACT,OAAA,CAAQ,aAAA,CAAc,SAAA;;;;;;;AA1FkB;AAsC3C;iBA6FgB,aAAA,mBACI,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,EAAA,CACpD,OAAA,EAAS,mBAAA,EAAqB,KAAA,EAAO,iBAAA,GAAoB,YAAA;;;;;;;AA7FrC;AA6BtB;;;;;;;;AAAsE;AAgBtE;;;;iBAgHsB,aAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAE3B,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,OAAA,CAAQ,YAAA,IAChB,OAAA,CAAQ,eAAA,CAAgB,SAAA;;;;;;;;;;;;;;;;;;;;;;;AAlHO;AAyClC;;;;;iBAoKsB,OAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAE3B,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,EACP,OAAA,GAAS,OAAA,CAAQ,YAAA,IAChB,OAAA,CAAQ,MAAA,CAAO,SAAA"}
|
package/dist/extract.mjs
CHANGED
|
@@ -1,14 +1,15 @@
|
|
|
1
|
+
import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
|
|
1
2
|
import { jsonSchemaToJtd } from "./jtd.mjs";
|
|
2
3
|
import { reflectionToJsonSchema } from "./reflection.mjs";
|
|
3
4
|
import { resolve } from "./resolve.mjs";
|
|
4
|
-
import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
|
|
5
5
|
import defu from "defu";
|
|
6
|
+
import { isSetString } from "@stryke/type-checks";
|
|
6
7
|
import { isTypeDefinition } from "@powerlines/core";
|
|
7
8
|
import { esbuildPlugin } from "@powerlines/deepkit/esbuild-plugin";
|
|
8
9
|
import { isType, stringifyType } from "@powerlines/deepkit/vendor/type";
|
|
9
10
|
import { murmurhash } from "@stryke/hash";
|
|
10
11
|
import { isJsonSchemaObjectType, isStandardJsonSchema } from "@stryke/json";
|
|
11
|
-
import {
|
|
12
|
+
import { joinPaths } from "@stryke/path/join";
|
|
12
13
|
import { isSetObject as isSetObject$1 } from "@stryke/type-checks/is-set-object";
|
|
13
14
|
import { extractJsonSchema as extractJsonSchema$1, isZod3Type } from "@stryke/zod";
|
|
14
15
|
|
|
@@ -196,6 +197,7 @@ async function extractSchema(context, input, options = {}) {
|
|
|
196
197
|
};
|
|
197
198
|
let source;
|
|
198
199
|
const variant = extractVariant(input);
|
|
200
|
+
const hash = extractHash(variant, input);
|
|
199
201
|
if (variant === "type-definition") {
|
|
200
202
|
const resolved = await resolve(context, input, defu(options, { plugins: [esbuildPlugin(context, {
|
|
201
203
|
reflection: "default",
|
|
@@ -215,7 +217,7 @@ async function extractSchema(context, input, options = {}) {
|
|
|
215
217
|
variant,
|
|
216
218
|
source,
|
|
217
219
|
schema: await extractSchemaSchema(source.schema, source.variant),
|
|
218
|
-
hash
|
|
220
|
+
hash
|
|
219
221
|
};
|
|
220
222
|
}
|
|
221
223
|
/**
|
|
@@ -247,7 +249,23 @@ async function extractSchema(context, input, options = {}) {
|
|
|
247
249
|
* @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.
|
|
248
250
|
*/
|
|
249
251
|
async function extract(context, input, options = {}) {
|
|
250
|
-
|
|
252
|
+
if (isExtractedSchema(input) || isSchema(input)) return input;
|
|
253
|
+
const variant = extractVariant(input);
|
|
254
|
+
const hash = extractHash(variant, input);
|
|
255
|
+
const cacheFilePath = joinPaths(context.cachePath, "schemas", `${hash}.json`);
|
|
256
|
+
let result;
|
|
257
|
+
if (context.config.skipCache !== true && context.fs.existsSync(cacheFilePath)) {
|
|
258
|
+
const schema = await context.fs.read(cacheFilePath);
|
|
259
|
+
if (schema) result = {
|
|
260
|
+
variant,
|
|
261
|
+
hash,
|
|
262
|
+
schema: JSON.parse(schema)
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
result ??= await extractSchema(context, input, options);
|
|
266
|
+
if (!result?.schema) 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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`);
|
|
267
|
+
if (context.config.skipCache !== true) await context.fs.write(cacheFilePath, JSON.stringify(result.schema));
|
|
268
|
+
return result;
|
|
251
269
|
}
|
|
252
270
|
|
|
253
271
|
//#endregion
|
package/dist/extract.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchemaZod"],"sources":["../src/extract.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Context } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { murmurhash } from \"@stryke/hash\";\nimport {\n isJsonSchemaObjectType,\n isStandardJsonSchema,\n JsonSchemaType\n} from \"@stryke/json\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n extractJsonSchema as extractJsonSchemaZod,\n isZod3Type\n} from \"@stryke/zod\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport * as z3 from \"zod/v3\";\nimport { jsonSchemaToJtd } from \"./jtd\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isExtractedSchema,\n isJTDSchema,\n isSchema,\n isUntypedInput,\n isUntypedSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchemaLike,\n JTDSchemaType,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaMetadata,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n TypeDefinitionReference,\n UntypedInputObject,\n UntypedSchema\n} from \"./types\";\n\n/**\n * Creates a hash string for a given schema definition input. The function checks the type of the input and generates a hash based on its content. If the input is a Zod schema, it hashes the JSON representation of its internal definition. If the input is a Standard JSON Schema, it hashes the JSON representation of its internal standard schema. If the input is already a JSON Schema object, it hashes its JSON representation directly. If the input is a reflected Deepkit Type object, it hashes its JSON representation. The resulting hash string can be used for caching or comparison purposes.\n */\nexport function extractHash(\n variant: SchemaInputVariant,\n input: SchemaInput\n): string {\n if (isSetString(input)) {\n return murmurhash({ variant, input });\n } else if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return murmurhash({ variant, input: input._def });\n } else if (isStandardJsonSchema(input)) {\n return murmurhash({ variant, input: input[\"~standard\"] });\n } else if (isJsonSchemaObjectType(input)) {\n return murmurhash({ variant, input });\n } else if (isType(input)) {\n return murmurhash({ variant, input: stringifyType(input) });\n }\n }\n\n throw new Error(\n `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, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Converts a reflected Deepkit {@link @powerlines/deepkit/vendor/type#Type} into a JSON Schema (draft-07) representation.\n *\n * @remarks\n * This function delegates to an internal recursive walker that handles the full set of Deepkit reflection kinds.\n *\n * @param reflection - The reflected Deepkit Type to convert.\n * @returns A JSON Schema (draft-07) fragment representing the type, or `undefined` when no schema could be produced.\n */\nexport function extractReflection<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(reflection: Type): JTDSchemaType<TMetadata> | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema<TMetadata>(reflection);\n}\n\n/**\n * Extracts a JSON Type Definition (RFC 8927) schema from a given schema definition, if possible.\n *\n * @remarks\n * This function checks if the provided input is a Zod schema, a Standard JSON Schema, or already a JSON Schema object, extracts a JSON Schema fragment via the appropriate adapter (Zod and Standard Schema produce draft-07 fragments), and then converts that fragment into a valid JTD form suitable for AJV's JTD validator.\n *\n * @param schema - The schema definition to extract from. This can be a Zod schema, a Standard JSON Schema, or a JSON Schema object.\n * @returns The extracted JTD schema if successful, otherwise undefined.\n */\nexport function extractJsonSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: unknown): JTDSchemaType<TMetadata> | undefined {\n if (\n isSetObject(schema) &&\n (isZod3Type(schema) ||\n isStandardJsonSchema(schema) ||\n isJsonSchemaObjectType(schema) ||\n isUntypedInput(schema) ||\n isUntypedSchema(schema))\n ) {\n let jsonSchema: unknown;\n if (isZod3Type(schema)) {\n jsonSchema = extractJsonSchemaZod(schema);\n } else if (isStandardJsonSchema(schema)) {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n });\n } else if (isUntypedInput(schema)) {\n jsonSchema = schema.$schema;\n } else {\n jsonSchema = schema;\n }\n\n const jtd = jsonSchemaToJtd<TMetadata>(jsonSchema as JsonSchemaLike);\n if (jtd) {\n return jtd;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractResolvedVariant(\n input: SchemaSourceInput\n): SchemaSourceVariant {\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return \"zod3\";\n } else if (isStandardJsonSchema(input)) {\n return \"standard-schema\";\n } else if (isJTDSchema(input)) {\n return \"jtd-schema\";\n } else if (isJsonSchemaObjectType(input)) {\n return \"json-schema\";\n } else if (isType(input)) {\n return \"reflection\";\n } else if (isUntypedInput(input) || isUntypedSchema(input)) {\n return \"untyped\";\n }\n }\n\n throw new Error(\n `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 reflected Deepkit Type object, or an Untyped schema.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a reflected Deepkit Type object, or an Untyped schema. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractVariant(input: SchemaInput): SchemaInputVariant {\n if (isSetString(input) || isTypeDefinition(input)) {\n return \"type-definition\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\n/**\n * Extracts a JSON Schema object from a given schema definition input. The input can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding JSON Schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns the extracted JSON Schema if successful; otherwise, it throws an error.\n *\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param variant - The variant of the schema definition to extract.\n * @returns The extracted JSON Schema if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport async function extractSchemaSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JTDSchemaType<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JTDSchemaType<TMetadata> | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\"\n ) {\n const jsonSchema = extractJsonSchema<TMetadata>(input);\n if (jsonSchema) {\n schema = jsonSchemaToJtd<TMetadata>(jsonSchema);\n }\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection<TMetadata>(input as Type);\n } else if (resolvedVariant === \"jtd-schema\") {\n schema = input as JTDSchemaType<TMetadata>;\n }\n\n if (schema) {\n return schema;\n }\n\n throw new Error(\n `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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param variant - The variant of the schema definition to extract.\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractSource<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(variant: SchemaSourceVariant, input: SchemaSourceInput): SchemaSource {\n if (variant === \"zod3\") {\n return {\n hash: extractHash(variant, input),\n variant: \"zod3\",\n schema: input as z3.ZodTypeAny\n };\n } else if (variant === \"untyped\") {\n return {\n hash: extractHash(variant, input),\n variant: \"untyped\",\n schema: input as UntypedInputObject | UntypedSchema\n };\n } else if (variant === \"standard-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"standard-schema\",\n schema: input as StandardJSONSchemaV1\n };\n } else if (variant === \"json-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"json-schema\",\n schema: input as JsonSchemaType\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\n };\n } else if (variant === \"jtd-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"jtd-schema\",\n schema: input as JTDSchemaType<TMetadata>\n };\n }\n\n throw new Error(\n `Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extractSchema(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extractSchema(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extractSchema(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extractSchema(context, reflectionType);\n * ```\n *\n * @param context - The plugin context used for resolving the schema definition input.\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param options - Optional overrides for the ESBuild configuration used during resolution.\n * @returns A promise that resolves to a {@link ExtractedSchema} containing the extracted JSON Schema and its variant, or the bytecode if JSON Schema extraction is not possible.\n */\nexport async function extractSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<ExtractedSchema<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input;\n }\n\n if (isSchema<TMetadata>(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"jtd-schema\", input.schema),\n variant: \"jtd-schema\",\n schema: input.schema\n }\n };\n }\n\n let source: SchemaSource;\n\n const variant = extractVariant(input);\n if (variant === \"type-definition\") {\n const resolved = await resolve<SchemaSourceInput>(\n context,\n input as TypeDefinitionReference,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n );\n\n source = extractSource(extractResolvedVariant(resolved), resolved);\n } else if (\n [\n \"json-schema\",\n \"jtd-schema\",\n \"standard-schema\",\n \"zod3\",\n \"untyped\",\n \"reflection\"\n ].includes(variant)\n ) {\n source = extractSource(variant, input as SchemaSourceInput);\n } else {\n throw new Error(\n `Invalid schema definition input \"${\n variant\n }\". The variant must be one of \"type-definition\", \"json-schema\", \"jtd-schema\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchemaSchema<TMetadata>(source.schema, source.variant),\n hash: extractHash(variant, input)\n };\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://github.com/colinhacks/zod\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n * @see https://github.com/unjs/untyped\n * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html\n *\n * @param context - The {@link Context | context} used for resolving the {@link Schema | schema} definition input.\n * @param input - The input object or string to extract the {@link Schema | schema} from. This can be {@link TypeDefinitionReference | a string that references a Typescript module}, a [Zod v3 schema](https://github.com/colinhacks/zod), any type that adheres to [the Standard JSON Schema specification](https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec), a [JSON Schema object](https://json-schema.org/), a [JTD schema object](https://ajv.js.org/json-type-definition.html), an [untyped schema](https://github.com/unjs/untyped), or a [TypeScript type reflection](https://deepkit.io/en/documentation/runtime-types/reflection).\n * @param options - Optional overrides for the [ESBuild configuration](https://esbuild.github.io/api/#general-options) used during resolution.\n * @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.\n */\nexport async function extract<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<Schema<TMetadata>> {\n const result = await extractSchema<TMetadata>(context, input, options);\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmEA,SAAgB,YACd,SACA,OACQ;AACR,KAAI,YAAY,MAAM,CACpB,QAAO,WAAW;EAAE;EAAS;EAAO,CAAC;UAC5B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AAO;GAC7C,SAAS;GACT,QAAQ,MAAM;GACf;EACF;CAGH,IAAI;CAEJ,MAAM,UAAU,eAAe,MAAM;AACrC,KAAI,YAAY,mBAAmB;EACjC,MAAM,WAAW,MAAM,QACrB,SACA,OACA,KAAK,SAAS,EACZ,SAAS,CACP,cAAc,SAAS;GACrB,YAAY;GACZ,OAAO;GACR,CAAC,CACH,EACF,CAAC,CACH;AAED,WAAS,cAAc,uBAAuB,SAAS,EAAE,SAAS;YAElE;EACE;EACA;EACA;EACA;EACA;EACA;EACD,CAAC,SAAS,QAAQ,CAEnB,UAAS,cAAc,SAAS,MAA2B;KAE3D,OAAM,IAAI,MACR,oCACE,QACD,sIACF;AAGH,QAAO;EACL;EACA;EACA,QAAQ,MAAM,oBAA+B,OAAO,QAAQ,OAAO,QAAQ;EAC3E,MAAM,YAAY,SAAS,MAAM;EAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BH,eAAsB,QAIpB,SACA,OACA,UAAiC,EAAE,EACP;AAG5B,QAAO,MAFc,cAAyB,SAAS,OAAO,QAAQ"}
|
|
1
|
+
{"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchemaZod"],"sources":["../src/extract.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Context } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { murmurhash } from \"@stryke/hash\";\nimport {\n isJsonSchemaObjectType,\n isStandardJsonSchema,\n JsonSchemaType\n} from \"@stryke/json\";\nimport { joinPaths } from \"@stryke/path/join\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n extractJsonSchema as extractJsonSchemaZod,\n isZod3Type\n} from \"@stryke/zod\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport * as z3 from \"zod/v3\";\nimport { jsonSchemaToJtd } from \"./jtd\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isExtractedSchema,\n isJTDSchema,\n isSchema,\n isUntypedInput,\n isUntypedSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchemaLike,\n JTDSchemaType,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaMetadata,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n TypeDefinitionReference,\n UntypedInputObject,\n UntypedSchema\n} from \"./types\";\n\n/**\n * Creates a hash string for a given schema definition input. The function checks the type of the input and generates a hash based on its content. If the input is a Zod schema, it hashes the JSON representation of its internal definition. If the input is a Standard JSON Schema, it hashes the JSON representation of its internal standard schema. If the input is already a JSON Schema object, it hashes its JSON representation directly. If the input is a reflected Deepkit Type object, it hashes its JSON representation. The resulting hash string can be used for caching or comparison purposes.\n */\nexport function extractHash(\n variant: SchemaInputVariant,\n input: SchemaInput\n): string {\n if (isSetString(input)) {\n return murmurhash({ variant, input });\n } else if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return murmurhash({ variant, input: input._def });\n } else if (isStandardJsonSchema(input)) {\n return murmurhash({ variant, input: input[\"~standard\"] });\n } else if (isJsonSchemaObjectType(input)) {\n return murmurhash({ variant, input });\n } else if (isType(input)) {\n return murmurhash({ variant, input: stringifyType(input) });\n }\n }\n\n throw new Error(\n `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, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Converts a reflected Deepkit {@link @powerlines/deepkit/vendor/type#Type} into a JSON Schema (draft-07) representation.\n *\n * @remarks\n * This function delegates to an internal recursive walker that handles the full set of Deepkit reflection kinds.\n *\n * @param reflection - The reflected Deepkit Type to convert.\n * @returns A JSON Schema (draft-07) fragment representing the type, or `undefined` when no schema could be produced.\n */\nexport function extractReflection<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(reflection: Type): JTDSchemaType<TMetadata> | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema<TMetadata>(reflection);\n}\n\n/**\n * Extracts a JSON Type Definition (RFC 8927) schema from a given schema definition, if possible.\n *\n * @remarks\n * This function checks if the provided input is a Zod schema, a Standard JSON Schema, or already a JSON Schema object, extracts a JSON Schema fragment via the appropriate adapter (Zod and Standard Schema produce draft-07 fragments), and then converts that fragment into a valid JTD form suitable for AJV's JTD validator.\n *\n * @param schema - The schema definition to extract from. This can be a Zod schema, a Standard JSON Schema, or a JSON Schema object.\n * @returns The extracted JTD schema if successful, otherwise undefined.\n */\nexport function extractJsonSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: unknown): JTDSchemaType<TMetadata> | undefined {\n if (\n isSetObject(schema) &&\n (isZod3Type(schema) ||\n isStandardJsonSchema(schema) ||\n isJsonSchemaObjectType(schema) ||\n isUntypedInput(schema) ||\n isUntypedSchema(schema))\n ) {\n let jsonSchema: unknown;\n if (isZod3Type(schema)) {\n jsonSchema = extractJsonSchemaZod(schema);\n } else if (isStandardJsonSchema(schema)) {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n });\n } else if (isUntypedInput(schema)) {\n jsonSchema = schema.$schema;\n } else {\n jsonSchema = schema;\n }\n\n const jtd = jsonSchemaToJtd<TMetadata>(jsonSchema as JsonSchemaLike);\n if (jtd) {\n return jtd;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractResolvedVariant(\n input: SchemaSourceInput\n): SchemaSourceVariant {\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return \"zod3\";\n } else if (isStandardJsonSchema(input)) {\n return \"standard-schema\";\n } else if (isJTDSchema(input)) {\n return \"jtd-schema\";\n } else if (isJsonSchemaObjectType(input)) {\n return \"json-schema\";\n } else if (isType(input)) {\n return \"reflection\";\n } else if (isUntypedInput(input) || isUntypedSchema(input)) {\n return \"untyped\";\n }\n }\n\n throw new Error(\n `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 reflected Deepkit Type object, or an Untyped schema.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a reflected Deepkit Type object, or an Untyped schema. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractVariant(input: SchemaInput): SchemaInputVariant {\n if (isSetString(input) || isTypeDefinition(input)) {\n return \"type-definition\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\n/**\n * Extracts a JSON Schema object from a given schema definition input. The input can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding JSON Schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns the extracted JSON Schema if successful; otherwise, it throws an error.\n *\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param variant - The variant of the schema definition to extract.\n * @returns The extracted JSON Schema if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport async function extractSchemaSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JTDSchemaType<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JTDSchemaType<TMetadata> | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\"\n ) {\n const jsonSchema = extractJsonSchema<TMetadata>(input);\n if (jsonSchema) {\n schema = jsonSchemaToJtd<TMetadata>(jsonSchema);\n }\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection<TMetadata>(input as Type);\n } else if (resolvedVariant === \"jtd-schema\") {\n schema = input as JTDSchemaType<TMetadata>;\n }\n\n if (schema) {\n return schema;\n }\n\n throw new Error(\n `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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param variant - The variant of the schema definition to extract.\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractSource<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(variant: SchemaSourceVariant, input: SchemaSourceInput): SchemaSource {\n if (variant === \"zod3\") {\n return {\n hash: extractHash(variant, input),\n variant: \"zod3\",\n schema: input as z3.ZodTypeAny\n };\n } else if (variant === \"untyped\") {\n return {\n hash: extractHash(variant, input),\n variant: \"untyped\",\n schema: input as UntypedInputObject | UntypedSchema\n };\n } else if (variant === \"standard-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"standard-schema\",\n schema: input as StandardJSONSchemaV1\n };\n } else if (variant === \"json-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"json-schema\",\n schema: input as JsonSchemaType\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\n };\n } else if (variant === \"jtd-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"jtd-schema\",\n schema: input as JTDSchemaType<TMetadata>\n };\n }\n\n throw new Error(\n `Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extractSchema(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extractSchema(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extractSchema(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extractSchema(context, reflectionType);\n * ```\n *\n * @param context - The plugin context used for resolving the schema definition input.\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param options - Optional overrides for the ESBuild configuration used during resolution.\n * @returns A promise that resolves to a {@link ExtractedSchema} containing the extracted JSON Schema and its variant, or the bytecode if JSON Schema extraction is not possible.\n */\nexport async function extractSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<ExtractedSchema<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input;\n }\n\n if (isSchema<TMetadata>(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"jtd-schema\", input.schema),\n variant: \"jtd-schema\",\n schema: input.schema\n }\n };\n }\n\n let source: SchemaSource;\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n if (variant === \"type-definition\") {\n const resolved = await resolve<SchemaSourceInput>(\n context,\n input as TypeDefinitionReference,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n );\n\n source = extractSource(extractResolvedVariant(resolved), resolved);\n } else if (\n [\n \"json-schema\",\n \"jtd-schema\",\n \"standard-schema\",\n \"zod3\",\n \"untyped\",\n \"reflection\"\n ].includes(variant)\n ) {\n source = extractSource(variant, input as SchemaSourceInput);\n } else {\n throw new Error(\n `Invalid schema definition input \"${\n variant\n }\". The variant must be one of \"type-definition\", \"json-schema\", \"jtd-schema\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchemaSchema<TMetadata>(source.schema, source.variant),\n hash\n };\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://github.com/colinhacks/zod\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n * @see https://github.com/unjs/untyped\n * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html\n *\n * @param context - The {@link Context | context} used for resolving the {@link Schema | schema} definition input.\n * @param input - The input object or string to extract the {@link Schema | schema} from. This can be {@link TypeDefinitionReference | a string that references a Typescript module}, a [Zod v3 schema](https://github.com/colinhacks/zod), any type that adheres to [the Standard JSON Schema specification](https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec), a [JSON Schema object](https://json-schema.org/), a [JTD schema object](https://ajv.js.org/json-type-definition.html), an [untyped schema](https://github.com/unjs/untyped), or a [TypeScript type reflection](https://deepkit.io/en/documentation/runtime-types/reflection).\n * @param options - Optional overrides for the [ESBuild configuration](https://esbuild.github.io/api/#general-options) used during resolution.\n * @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.\n */\nexport async function extract<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<Schema<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input) || isSchema<TMetadata>(input)) {\n return input;\n }\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n const cacheFilePath = joinPaths(context.cachePath, \"schemas\", `${hash}.json`);\n\n let result: Schema<TMetadata> | undefined;\n if (\n context.config.skipCache !== true &&\n context.fs.existsSync(cacheFilePath)\n ) {\n const schema = await context.fs.read(cacheFilePath);\n if (schema) {\n result = {\n variant,\n hash,\n schema: JSON.parse(schema) as JTDSchemaType<TMetadata>\n };\n }\n }\n\n result ??= await extractSchema<TMetadata>(context, input, options);\n if (!result?.schema) {\n throw new Error(\n `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 JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n }\n\n if (context.config.skipCache !== true) {\n await context.fs.write(cacheFilePath, JSON.stringify(result.schema));\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoEA,SAAgB,YACd,SACA,OACQ;CACR,IAAI,YAAY,KAAK,GACnB,OAAO,WAAW;EAAE;EAAS;CAAM,CAAC;MAC/B,IAAIA,cAAY,KAAK,GAC1B;MAAI,WAAW,KAAK,GAClB,OAAO,WAAW;GAAE;GAAS,OAAO,MAAM;EAAK,CAAC;OAC3C,IAAI,qBAAqB,KAAK,GACnC,OAAO,WAAW;GAAE;GAAS,OAAO,MAAM;EAAa,CAAC;OACnD,IAAI,uBAAuB,KAAK,GACrC,OAAO,WAAW;GAAE;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