@powerlines/schema 0.11.23 → 0.11.24

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/extract.cjs CHANGED
@@ -2,6 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
3
  const require_type_checks = require('./type-checks.cjs');
4
4
  const require_jtd = require('./jtd.cjs');
5
+ const require_persistence = require('./persistence.cjs');
5
6
  const require_reflection = require('./reflection.cjs');
6
7
  const require_resolve = require('./resolve.cjs');
7
8
  let defu = require("defu");
@@ -253,10 +254,10 @@ async function extractSchema(context, input, options = {}) {
253
254
  */
254
255
  async function extract(context, input, options = {}) {
255
256
  if (require_type_checks.isExtractedSchema(input) || require_type_checks.isSchema(input)) return input;
257
+ let result;
256
258
  const variant = extractVariant(input);
257
259
  const hash = extractHash(variant, input);
258
- const cacheFilePath = (0, _stryke_path_join.joinPaths)(context.cachePath, "schemas", `${hash}.json`);
259
- let result;
260
+ const cacheFilePath = (0, _stryke_path_join.joinPaths)(require_persistence.getCacheDirectory(context), `${hash}.json`);
260
261
  if (context.config.skipCache !== true && context.fs.existsSync(cacheFilePath)) {
261
262
  const schema = await context.fs.read(cacheFilePath);
262
263
  if (schema) result = {
@@ -267,7 +268,7 @@ async function extract(context, input, options = {}) {
267
268
  }
268
269
  result ??= await extractSchema(context, input, options);
269
270
  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
+ if (context.config.skipCache !== true) await require_persistence.writeSchema(context, result);
271
272
  return result;
272
273
  }
273
274
 
@@ -1 +1 @@
1
- {"version":3,"file":"extract.d.cts","names":[],"sources":["../src/extract.ts"],"mappings":";;;;;;;;AAoEA;iBAA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BACI,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,5 +1,6 @@
1
1
  import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
2
2
  import { jsonSchemaToJtd } from "./jtd.mjs";
3
+ import { getCacheDirectory, writeSchema } from "./persistence.mjs";
3
4
  import { reflectionToJsonSchema } from "./reflection.mjs";
4
5
  import { resolve } from "./resolve.mjs";
5
6
  import defu from "defu";
@@ -250,10 +251,10 @@ async function extractSchema(context, input, options = {}) {
250
251
  */
251
252
  async function extract(context, input, options = {}) {
252
253
  if (isExtractedSchema(input) || isSchema(input)) return input;
254
+ let result;
253
255
  const variant = extractVariant(input);
254
256
  const hash = extractHash(variant, input);
255
- const cacheFilePath = joinPaths(context.cachePath, "schemas", `${hash}.json`);
256
- let result;
257
+ const cacheFilePath = joinPaths(getCacheDirectory(context), `${hash}.json`);
257
258
  if (context.config.skipCache !== true && context.fs.existsSync(cacheFilePath)) {
258
259
  const schema = await context.fs.read(cacheFilePath);
259
260
  if (schema) result = {
@@ -264,7 +265,7 @@ async function extract(context, input, options = {}) {
264
265
  }
265
266
  result ??= await extractSchema(context, input, options);
266
267
  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
+ if (context.config.skipCache !== true) await writeSchema(context, result);
268
269
  return result;
269
270
  }
270
271
 
@@ -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 { 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;GAAS;EAAM,CAAC;OAC/B,IAAI,OAAO,KAAK,GACrB,OAAO,WAAW;GAAE;GAAS,OAAO,cAAc,KAAK;EAAE,CAAC;CAC5D;CAGF,MAAM,IAAI,MACR,4LACF;AACF;;;;;;;;;;AAWA,SAAgB,kBAEd,YAAwD;CACxD,IAAI,CAAC,OAAO,UAAU,GACpB;CAGF,OAAO,uBAAkC,UAAU;AACrD;;;;;;;;;;AAWA,SAAgB,kBAEd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A;EACA;EACA;EACA;CACF,EAAE,SAAS,OAAO,GAElB,SAAS,cAAc,SAAS,KAA0B;MAE1D,MAAM,IAAI,MACR,oCACE,QACD,qIACH;CAGF,OAAO;EACL;EACA;EACA,QAAQ,MAAM,oBAA+B,OAAO,QAAQ,OAAO,OAAO;EAC1E;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BA,eAAsB,QAIpB,SACA,OACA,UAAiC,CAAC,GACN;CAC5B,IAAI,kBAA6B,KAAK,KAAK,SAAoB,KAAK,GAClE,OAAO;CAGT,MAAM,UAAU,eAAe,KAAK;CACpC,MAAM,OAAO,YAAY,SAAS,KAAK;CACvC,MAAM,gBAAgB,UAAU,QAAQ,WAAW,WAAW,GAAG,KAAK,MAAM;CAE5E,IAAI;CACJ,IACE,QAAQ,OAAO,cAAc,QAC7B,QAAQ,GAAG,WAAW,aAAa,GACnC;EACA,MAAM,SAAS,MAAM,QAAQ,GAAG,KAAK,aAAa;EAClD,IAAI,QACF,SAAS;GACP;GACA;GACA,QAAQ,KAAK,MAAM,MAAM;EAC3B;CAEJ;CAEA,WAAW,MAAM,cAAyB,SAAS,OAAO,OAAO;CACjE,IAAI,CAAC,QAAQ,QACX,MAAM,IAAI,MACR,8MACF;CAGF,IAAI,QAAQ,OAAO,cAAc,MAC/B,MAAM,QAAQ,GAAG,MAAM,eAAe,KAAK,UAAU,OAAO,MAAM,CAAC;CAGrE,OAAO;AACT"}
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 { getCacheDirectory, writeSchema } from \"./persistence\";\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 let result: Schema<TMetadata> | undefined;\n\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n const cacheFilePath = joinPaths(getCacheDirectory(context), `${hash}.json`);\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 writeSchema(context, result);\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqEA,SAAgB,YACd,SACA,OACQ;CACR,IAAI,YAAY,KAAK,GACnB,OAAO,WAAW;EAAE;EAAS;CAAM,CAAC;MAC/B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AO,OAAO;CACjE,IAAI,CAAC,QAAQ,QACX,MAAM,IAAI,MACR,8MACF;CAGF,IAAI,QAAQ,OAAO,cAAc,MAC/B,MAAM,YAAY,SAAS,MAAM;CAGnC,OAAO;AACT"}
package/dist/index.cjs CHANGED
@@ -5,6 +5,7 @@ const require_helpers = require('./helpers.cjs');
5
5
  const require_codegen = require('./codegen.cjs');
6
6
  const require_constants = require('./constants.cjs');
7
7
  const require_jtd = require('./jtd.cjs');
8
+ const require_persistence = require('./persistence.cjs');
8
9
  const require_reflection = require('./reflection.cjs');
9
10
  const require_resolve = require('./resolve.cjs');
10
11
  const require_extract = require('./extract.cjs');
@@ -21,6 +22,8 @@ exports.extractSchemaSchema = require_extract.extractSchemaSchema;
21
22
  exports.extractSource = require_extract.extractSource;
22
23
  exports.extractVariant = require_extract.extractVariant;
23
24
  exports.generateCode = require_codegen.generateCode;
25
+ exports.getCacheDirectory = require_persistence.getCacheDirectory;
26
+ exports.getCacheFilePath = require_persistence.getCacheFilePath;
24
27
  exports.getProperties = require_helpers.getProperties;
25
28
  exports.isExtractedSchema = require_type_checks.isExtractedSchema;
26
29
  exports.isJTDSchema = require_type_checks.isJTDSchema;
@@ -31,9 +34,12 @@ exports.isUntypedInput = require_type_checks.isUntypedInput;
31
34
  exports.isUntypedSchema = require_type_checks.isUntypedSchema;
32
35
  exports.jsonSchemaToJtd = require_jtd.jsonSchemaToJtd;
33
36
  exports.mergeSchemas = require_helpers.mergeSchemas;
37
+ exports.readSchema = require_persistence.readSchema;
38
+ exports.readSchemaSafe = require_persistence.readSchemaSafe;
34
39
  exports.reflectionToJsonSchema = require_reflection.reflectionToJsonSchema;
35
40
  exports.resolve = require_resolve.resolve;
36
41
  exports.resolveModule = require_resolve.resolveModule;
37
42
  exports.resolveReflection = require_resolve.resolveReflection;
38
43
  exports.stringifyType = require_codegen.stringifyType;
39
- exports.stringifyValue = require_codegen.stringifyValue;
44
+ exports.stringifyValue = require_codegen.stringifyValue;
45
+ exports.writeSchema = require_persistence.writeSchema;
package/dist/index.d.cts CHANGED
@@ -5,7 +5,8 @@ import { JTDTypes } from "./constants.cjs";
5
5
  import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.cjs";
6
6
  import { getProperties, mergeSchemas } from "./helpers.cjs";
7
7
  import { jsonSchemaToJtd } from "./jtd.cjs";
8
+ import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.cjs";
8
9
  import { reflectionToJsonSchema } from "./reflection.cjs";
9
10
  import { resolve, resolveModule, resolveReflection } from "./resolve.cjs";
10
11
  import { isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.cjs";
11
- export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JTDTypes, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue };
12
+ export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JTDTypes, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, readSchema, readSchemaSafe, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
package/dist/index.d.mts CHANGED
@@ -5,7 +5,8 @@ import { JTDTypes } from "./constants.mjs";
5
5
  import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
6
6
  import { getProperties, mergeSchemas } from "./helpers.mjs";
7
7
  import { jsonSchemaToJtd } from "./jtd.mjs";
8
+ import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.mjs";
8
9
  import { reflectionToJsonSchema } from "./reflection.mjs";
9
10
  import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
10
11
  import { isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
11
- export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JTDTypes, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue };
12
+ export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaObjectForm, JTDSchemaObjectType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JTDTypes, JsonSchemaLike, JsonSchemaSchemaSource, ObjectSchema, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, readSchema, readSchemaSafe, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
package/dist/index.mjs CHANGED
@@ -4,8 +4,9 @@ import { getProperties, mergeSchemas } from "./helpers.mjs";
4
4
  import { generateCode, stringifyType, stringifyValue } from "./codegen.mjs";
5
5
  import { JTDTypes } from "./constants.mjs";
6
6
  import { jsonSchemaToJtd } from "./jtd.mjs";
7
+ import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.mjs";
7
8
  import { reflectionToJsonSchema } from "./reflection.mjs";
8
9
  import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
9
10
  import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
10
11
 
11
- export { JTDTypes, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue };
12
+ export { JTDTypes, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getProperties, isExtractedSchema, isJTDSchema, isJTDSchemaObject, isObjectSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, mergeSchemas, readSchema, readSchemaSafe, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
@@ -0,0 +1,76 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_runtime = require('./_virtual/_rolldown/runtime.cjs');
3
+ const require_type_checks = require('./type-checks.cjs');
4
+ const require_extract = require('./extract.cjs');
5
+ let _stryke_path_join = require("@stryke/path/join");
6
+
7
+ //#region src/persistence.ts
8
+ /**
9
+ * A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named "schemas". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.
10
+ *
11
+ * @param context - The context object providing access to the cache path.
12
+ * @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the "schemas" subdirectory.
13
+ */
14
+ function getCacheDirectory(context) {
15
+ return (0, _stryke_path_join.joinPaths)(context.cachePath, "schemas");
16
+ }
17
+ /**
18
+ * A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).
19
+ *
20
+ * @param context - The context object providing access to the cache path.
21
+ * @param input - The input schema from which to extract the variant and hash for constructing the cache file path.
22
+ * @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.
23
+ */
24
+ function getCacheFilePath(context, input) {
25
+ const hash = require_extract.extractHash(require_extract.extractVariant(input), input);
26
+ return (0, _stryke_path_join.joinPaths)(getCacheDirectory(context), `${hash}.json`);
27
+ }
28
+ /**
29
+ * Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.
30
+ *
31
+ * @param context - The context object providing access to the file system and cache path.
32
+ * @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.
33
+ * @throws Will throw an error if the provided input is not a valid schema.
34
+ */
35
+ async function writeSchema(context, schema) {
36
+ if (!require_type_checks.isSchema(schema)) throw new Error(`The provided input is not a valid schema. A valid schema must have a "variant" property indicating the type of the input and a "schema" property containing the parsed JTD schema object.`);
37
+ await context.fs.write(getCacheFilePath(context, schema), JSON.stringify(schema.schema));
38
+ }
39
+ /**
40
+ * A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.
41
+ *
42
+ * @param context - The context object providing access to the file system and cache path.
43
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
44
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.
45
+ */
46
+ async function readSchemaSafe(context, input) {
47
+ const cacheFilePath = getCacheFilePath(context, input);
48
+ if (!await context.fs.exists(cacheFilePath)) return;
49
+ const data = await context.fs.read(cacheFilePath);
50
+ if (!data) return;
51
+ return JSON.parse(data);
52
+ }
53
+ /**
54
+ * Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.
55
+ *
56
+ * @param context - The context object providing access to the file system and cache path.
57
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
58
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.
59
+ * @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.
60
+ */
61
+ async function readSchema(context, input) {
62
+ const schema = await readSchemaSafe(context, input);
63
+ if (!schema) {
64
+ const variant = require_extract.extractVariant(input);
65
+ const hash = require_extract.extractHash(variant, input);
66
+ throw new Error(`The ${variant} schema with hash "${hash}" does not exist in the cache. This may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. Please ensure that the schema is properly written to the cache before attempting to read it.`);
67
+ }
68
+ return schema;
69
+ }
70
+
71
+ //#endregion
72
+ exports.getCacheDirectory = getCacheDirectory;
73
+ exports.getCacheFilePath = getCacheFilePath;
74
+ exports.readSchema = readSchema;
75
+ exports.readSchemaSafe = readSchemaSafe;
76
+ exports.writeSchema = writeSchema;
@@ -0,0 +1,47 @@
1
+ import { Schema, SchemaInput, SchemaMetadata } from "./types.cjs";
2
+ import { Context } from "@powerlines/core";
3
+
4
+ //#region src/persistence.d.ts
5
+ /**
6
+ * A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named "schemas". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.
7
+ *
8
+ * @param context - The context object providing access to the cache path.
9
+ * @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the "schemas" subdirectory.
10
+ */
11
+ declare function getCacheDirectory(context: Context): string;
12
+ /**
13
+ * A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).
14
+ *
15
+ * @param context - The context object providing access to the cache path.
16
+ * @param input - The input schema from which to extract the variant and hash for constructing the cache file path.
17
+ * @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.
18
+ */
19
+ declare function getCacheFilePath(context: Context, input: SchemaInput): string;
20
+ /**
21
+ * Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.
22
+ *
23
+ * @param context - The context object providing access to the file system and cache path.
24
+ * @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.
25
+ * @throws Will throw an error if the provided input is not a valid schema.
26
+ */
27
+ declare function writeSchema<TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>, TContext extends Context = Context>(context: TContext, schema: Schema<TMetadata>): Promise<void>;
28
+ /**
29
+ * A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.
30
+ *
31
+ * @param context - The context object providing access to the file system and cache path.
32
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
33
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.
34
+ */
35
+ declare function readSchemaSafe<TContext extends Context = Context, TMetadata extends SchemaMetadata = SchemaMetadata>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata> | undefined>;
36
+ /**
37
+ * Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.
38
+ *
39
+ * @param context - The context object providing access to the file system and cache path.
40
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
41
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.
42
+ * @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.
43
+ */
44
+ declare function readSchema<TContext extends Context = Context, TMetadata extends SchemaMetadata = SchemaMetadata>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata>>;
45
+ //#endregion
46
+ export { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema };
47
+ //# sourceMappingURL=persistence.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistence.d.cts","names":[],"sources":["../src/persistence.ts"],"mappings":";;;;;;AA8BA;;;;iBAAgB,iBAAA,CAAkB,OAAgB,EAAP,OAAO;AAWlD;;;;;;;AAAA,iBAAgB,gBAAA,CAAiB,OAAA,EAAS,OAAA,EAAS,KAAA,EAAO,WAAW;;AAAA;AAcrE;;;;;iBAAsB,WAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAC3B,OAAA,EAAS,QAAA,EAAU,MAAA,EAAQ,MAAA,CAAO,SAAA,IAAU,OAAA;;;;;;;;iBAoBxB,cAAA,kBACH,OAAA,GAAU,OAAA,oBACT,cAAA,GAAiB,cAAA,CAAA,CAEnC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,GACN,OAAA,CAAQ,MAAA,CAAO,SAAA;;;;;;;;;iBAsBI,UAAA,kBACH,OAAA,GAAU,OAAA,oBACT,cAAA,GAAiB,cAAA,CAAA,CACnC,OAAA,EAAS,QAAA,EAAU,KAAA,EAAO,WAAA,GAAc,OAAA,CAAQ,MAAA,CAAO,SAAA"}
@@ -0,0 +1,47 @@
1
+ import { Schema, SchemaInput, SchemaMetadata } from "./types.mjs";
2
+ import { Context } from "@powerlines/core";
3
+
4
+ //#region src/persistence.d.ts
5
+ /**
6
+ * A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named "schemas". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.
7
+ *
8
+ * @param context - The context object providing access to the cache path.
9
+ * @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the "schemas" subdirectory.
10
+ */
11
+ declare function getCacheDirectory(context: Context): string;
12
+ /**
13
+ * A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).
14
+ *
15
+ * @param context - The context object providing access to the cache path.
16
+ * @param input - The input schema from which to extract the variant and hash for constructing the cache file path.
17
+ * @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.
18
+ */
19
+ declare function getCacheFilePath(context: Context, input: SchemaInput): string;
20
+ /**
21
+ * Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.
22
+ *
23
+ * @param context - The context object providing access to the file system and cache path.
24
+ * @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.
25
+ * @throws Will throw an error if the provided input is not a valid schema.
26
+ */
27
+ declare function writeSchema<TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>, TContext extends Context = Context>(context: TContext, schema: Schema<TMetadata>): Promise<void>;
28
+ /**
29
+ * A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.
30
+ *
31
+ * @param context - The context object providing access to the file system and cache path.
32
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
33
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.
34
+ */
35
+ declare function readSchemaSafe<TContext extends Context = Context, TMetadata extends SchemaMetadata = SchemaMetadata>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata> | undefined>;
36
+ /**
37
+ * Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.
38
+ *
39
+ * @param context - The context object providing access to the file system and cache path.
40
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
41
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.
42
+ * @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.
43
+ */
44
+ declare function readSchema<TContext extends Context = Context, TMetadata extends SchemaMetadata = SchemaMetadata>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata>>;
45
+ //#endregion
46
+ export { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema };
47
+ //# sourceMappingURL=persistence.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistence.d.mts","names":[],"sources":["../src/persistence.ts"],"mappings":";;;;;;AA8BA;;;;iBAAgB,iBAAA,CAAkB,OAAgB,EAAP,OAAO;AAWlD;;;;;;;AAAA,iBAAgB,gBAAA,CAAiB,OAAA,EAAS,OAAA,EAAS,KAAA,EAAO,WAAW;;AAAA;AAcrE;;;;;iBAAsB,WAAA,mBACF,OAAA,CAAQ,cAAA,IAAkB,OAAA,CAAQ,cAAA,oBACnC,OAAA,GAAU,OAAA,CAAA,CAC3B,OAAA,EAAS,QAAA,EAAU,MAAA,EAAQ,MAAA,CAAO,SAAA,IAAU,OAAA;;;;;;;;iBAoBxB,cAAA,kBACH,OAAA,GAAU,OAAA,oBACT,cAAA,GAAiB,cAAA,CAAA,CAEnC,OAAA,EAAS,QAAA,EACT,KAAA,EAAO,WAAA,GACN,OAAA,CAAQ,MAAA,CAAO,SAAA;;;;;;;;;iBAsBI,UAAA,kBACH,OAAA,GAAU,OAAA,oBACT,cAAA,GAAiB,cAAA,CAAA,CACnC,OAAA,EAAS,QAAA,EAAU,KAAA,EAAO,WAAA,GAAc,OAAA,CAAQ,MAAA,CAAO,SAAA"}
@@ -0,0 +1,71 @@
1
+ import { isSchema } from "./type-checks.mjs";
2
+ import { extractHash, extractVariant } from "./extract.mjs";
3
+ import { joinPaths } from "@stryke/path/join";
4
+
5
+ //#region src/persistence.ts
6
+ /**
7
+ * A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named "schemas". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.
8
+ *
9
+ * @param context - The context object providing access to the cache path.
10
+ * @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the "schemas" subdirectory.
11
+ */
12
+ function getCacheDirectory(context) {
13
+ return joinPaths(context.cachePath, "schemas");
14
+ }
15
+ /**
16
+ * A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).
17
+ *
18
+ * @param context - The context object providing access to the cache path.
19
+ * @param input - The input schema from which to extract the variant and hash for constructing the cache file path.
20
+ * @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.
21
+ */
22
+ function getCacheFilePath(context, input) {
23
+ const hash = extractHash(extractVariant(input), input);
24
+ return joinPaths(getCacheDirectory(context), `${hash}.json`);
25
+ }
26
+ /**
27
+ * Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.
28
+ *
29
+ * @param context - The context object providing access to the file system and cache path.
30
+ * @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.
31
+ * @throws Will throw an error if the provided input is not a valid schema.
32
+ */
33
+ async function writeSchema(context, schema) {
34
+ if (!isSchema(schema)) throw new Error(`The provided input is not a valid schema. A valid schema must have a "variant" property indicating the type of the input and a "schema" property containing the parsed JTD schema object.`);
35
+ await context.fs.write(getCacheFilePath(context, schema), JSON.stringify(schema.schema));
36
+ }
37
+ /**
38
+ * A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.
39
+ *
40
+ * @param context - The context object providing access to the file system and cache path.
41
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
42
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.
43
+ */
44
+ async function readSchemaSafe(context, input) {
45
+ const cacheFilePath = getCacheFilePath(context, input);
46
+ if (!await context.fs.exists(cacheFilePath)) return;
47
+ const data = await context.fs.read(cacheFilePath);
48
+ if (!data) return;
49
+ return JSON.parse(data);
50
+ }
51
+ /**
52
+ * Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.
53
+ *
54
+ * @param context - The context object providing access to the file system and cache path.
55
+ * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.
56
+ * @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.
57
+ * @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.
58
+ */
59
+ async function readSchema(context, input) {
60
+ const schema = await readSchemaSafe(context, input);
61
+ if (!schema) {
62
+ const variant = extractVariant(input);
63
+ const hash = extractHash(variant, input);
64
+ throw new Error(`The ${variant} schema with hash "${hash}" does not exist in the cache. This may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. Please ensure that the schema is properly written to the cache before attempting to read it.`);
65
+ }
66
+ return schema;
67
+ }
68
+
69
+ //#endregion
70
+ export { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema };
71
+ //# sourceMappingURL=persistence.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"persistence.mjs","names":[],"sources":["../src/persistence.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 { joinPaths } from \"@stryke/path/join\";\nimport { extractHash, extractVariant } from \"./extract\";\nimport { isSchema } from \"./type-checks\";\nimport { Schema, SchemaInput, SchemaMetadata } from \"./types\";\n\n/**\n * A helper function to get the cache directory path for storing schemas. This function takes a context object as input and returns the path to the cache directory where schemas are stored. The cache directory is constructed by joining the `cachePath` property from the context with a subdirectory named \"schemas\". This function is useful for centralizing the logic for determining where schema files should be cached, ensuring that all schema-related file operations use a consistent location for storing and retrieving cached schemas.\n *\n * @param context - The context object providing access to the cache path.\n * @returns The path to the cache directory for storing schemas, constructed by joining the context's `cachePath` with the \"schemas\" subdirectory.\n */\nexport function getCacheDirectory(context: Context): string {\n return joinPaths(context.cachePath, \"schemas\");\n}\n\n/**\n * A helper function to get the file path for a cached schema based on the provided context and schema input. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file by joining the cache directory path (obtained from the `getCacheDirectory` function) with a filename derived from the extracted hash. The resulting file path points to where the cached schema should be stored or retrieved from in the file system. This function is essential for ensuring that all operations related to caching schemas use a consistent method for determining the correct file path based on the schema's unique identifier (hash).\n *\n * @param context - The context object providing access to the cache path.\n * @param input - The input schema from which to extract the variant and hash for constructing the cache file path.\n * @returns The file path to the cached schema JSON file, constructed by joining the cache directory path with a filename derived from the extracted hash of the schema input.\n */\nexport function getCacheFilePath(context: Context, input: SchemaInput): string {\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n return joinPaths(getCacheDirectory(context), `${hash}.json`);\n}\n\n/**\n * Writes a given schema to the file system using the provided context. This function first checks if the input is a valid schema using the `isSchema` type guard. If the input is not a valid schema, it throws an error indicating that the provided input is invalid. If the input is valid, it proceeds to write the schema to a JSON file in the cache directory specified by the context. The file is named using the hash of the schema to ensure uniqueness and easy retrieval in future operations. The schema is serialized to JSON format before being written to the file system. This function is asynchronous and returns a promise that resolves once the writing operation is complete.\n *\n * @param context - The context object providing access to the file system and cache path.\n * @param schema - The schema to be written to the file system, which must be a valid schema object containing a `variant`, `schema`, and `hash` property.\n * @throws Will throw an error if the provided input is not a valid schema.\n */\nexport async function writeSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(context: TContext, schema: Schema<TMetadata>) {\n if (!isSchema<TMetadata>(schema)) {\n throw new Error(\n `The provided input is not a valid schema. A valid schema must have a \"variant\" property indicating the type of the input and a \"schema\" property containing the parsed JTD schema object.`\n );\n }\n\n await context.fs.write(\n getCacheFilePath(context, schema),\n JSON.stringify(schema.schema)\n );\n}\n\n/**\n * A helper function to read a schema from the file system using the provided context. This function first extracts the variant and hash from the input schema using the `extractVariant` and `extractHash` functions, respectively. It then constructs the file path to the cached schema JSON file based on the cache path provided in the context and the extracted hash. The function checks if the file exists in the cache; if it does not exist, it returns `undefined`. If the file exists, it reads the contents of the file, parses it as JSON, and returns the resulting object. This function is asynchronous and returns a promise that resolves to either the parsed schema object or `undefined` if the schema is not found in the cache.\n *\n * @param context - The context object providing access to the file system and cache path.\n * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.\n * @returns A promise that resolves to the parsed schema object if found in the cache, or `undefined` if the schema does not exist in the cache.\n */\nexport async function readSchemaSafe<\n TContext extends Context = Context,\n TMetadata extends SchemaMetadata = SchemaMetadata\n>(\n context: TContext,\n input: SchemaInput\n): Promise<Schema<TMetadata> | undefined> {\n const cacheFilePath = getCacheFilePath(context, input);\n if (!(await context.fs.exists(cacheFilePath))) {\n return undefined;\n }\n\n const data = await context.fs.read(cacheFilePath);\n if (!data) {\n return undefined;\n }\n\n return JSON.parse(data);\n}\n\n/**\n * Reads a schema from the file system using the provided context and input. This function first attempts to read the schema using the `readSchemaSafe` helper function, which returns `undefined` if the schema is not found in the cache. If the schema is not found, this function throws an error indicating that the schema with the specified variant and hash does not exist in the cache. The error message suggests that this may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. It advises ensuring that the schema is properly written to the cache before attempting to read it. If the schema is successfully read from the cache, it is returned as a parsed object. This function is asynchronous and returns a promise that resolves to the parsed schema object if found, or throws an error if the schema is not found in the cache.\n *\n * @param context - The context object providing access to the file system and cache path.\n * @param input - The input schema from which to extract the variant and hash for locating the cached schema file.\n * @returns A promise that resolves to the parsed schema object if found in the cache, or throws an error if the schema does not exist in the cache.\n * @throws Will throw an error if the schema with the specified variant and hash does not exist in the cache.\n */\nexport async function readSchema<\n TContext extends Context = Context,\n TMetadata extends SchemaMetadata = SchemaMetadata\n>(context: TContext, input: SchemaInput): Promise<Schema<TMetadata>> {\n const schema = await readSchemaSafe<TContext, TMetadata>(context, input);\n if (!schema) {\n const variant = extractVariant(input);\n const hash = extractHash(variant, input);\n\n throw new Error(\n `The ${variant} schema with hash \"${\n hash\n }\" does not exist in the cache. This may be due to a missing or corrupted cache file, or because the schema has not been written to the cache yet. Please ensure that the schema is properly written to the cache before attempting to read it.`\n );\n }\n\n return schema;\n}\n"],"mappings":";;;;;;;;;;;AA8BA,SAAgB,kBAAkB,SAA0B;CAC1D,OAAO,UAAU,QAAQ,WAAW,SAAS;AAC/C;;;;;;;;AASA,SAAgB,iBAAiB,SAAkB,OAA4B;CAE7E,MAAM,OAAO,YADG,eAAe,KACA,GAAG,KAAK;CAEvC,OAAO,UAAU,kBAAkB,OAAO,GAAG,GAAG,KAAK,MAAM;AAC7D;;;;;;;;AASA,eAAsB,YAGpB,SAAmB,QAA2B;CAC9C,IAAI,CAAC,SAAoB,MAAM,GAC7B,MAAM,IAAI,MACR,2LACF;CAGF,MAAM,QAAQ,GAAG,MACf,iBAAiB,SAAS,MAAM,GAChC,KAAK,UAAU,OAAO,MAAM,CAC9B;AACF;;;;;;;;AASA,eAAsB,eAIpB,SACA,OACwC;CACxC,MAAM,gBAAgB,iBAAiB,SAAS,KAAK;CACrD,IAAI,CAAE,MAAM,QAAQ,GAAG,OAAO,aAAa,GACzC;CAGF,MAAM,OAAO,MAAM,QAAQ,GAAG,KAAK,aAAa;CAChD,IAAI,CAAC,MACH;CAGF,OAAO,KAAK,MAAM,IAAI;AACxB;;;;;;;;;AAUA,eAAsB,WAGpB,SAAmB,OAAgD;CACnE,MAAM,SAAS,MAAM,eAAoC,SAAS,KAAK;CACvE,IAAI,CAAC,QAAQ;EACX,MAAM,UAAU,eAAe,KAAK;EACpC,MAAM,OAAO,YAAY,SAAS,KAAK;EAEvC,MAAM,IAAI,MACR,OAAO,QAAQ,qBACb,KACD,+OACH;CACF;CAEA,OAAO;AACT"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@powerlines/schema",
3
- "version": "0.11.23",
3
+ "version": "0.11.24",
4
4
  "private": false,
5
5
  "description": "A package containing a Powerlines plugin to assist in developing other Powerlines plugins.",
6
6
  "keywords": [
@@ -71,6 +71,10 @@
71
71
  "require": "./dist/helpers.cjs"
72
72
  },
73
73
  "./jtd": { "import": "./dist/jtd.mjs", "require": "./dist/jtd.cjs" },
74
+ "./persistence": {
75
+ "import": "./dist/persistence.mjs",
76
+ "require": "./dist/persistence.cjs"
77
+ },
74
78
  "./reflection": {
75
79
  "import": "./dist/reflection.mjs",
76
80
  "require": "./dist/reflection.cjs"
@@ -113,5 +117,5 @@
113
117
  "peerDependencies": { "zod": "^3.25.0 || ^4.0.0" },
114
118
  "peerDependenciesMeta": { "zod": { "optional": true } },
115
119
  "publishConfig": { "access": "public" },
116
- "gitHead": "f95fab7200cc5687144ea1b1ee4ba77b44000935"
120
+ "gitHead": "7fb37a42aa27f6cbc6b7412e259d0f7a79bac8ed"
117
121
  }