@powerlines/schema 0.11.28 → 0.11.37

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.
Files changed (82) hide show
  1. package/dist/bundle.cjs +34 -20
  2. package/dist/bundle.d.cts +3 -3
  3. package/dist/bundle.d.cts.map +1 -1
  4. package/dist/bundle.d.mts +3 -3
  5. package/dist/bundle.d.mts.map +1 -1
  6. package/dist/bundle.mjs +35 -21
  7. package/dist/bundle.mjs.map +1 -1
  8. package/dist/codegen.cjs +55 -8
  9. package/dist/codegen.d.cts +12 -6
  10. package/dist/codegen.d.cts.map +1 -1
  11. package/dist/codegen.d.mts +12 -6
  12. package/dist/codegen.d.mts.map +1 -1
  13. package/dist/codegen.mjs +52 -8
  14. package/dist/codegen.mjs.map +1 -1
  15. package/dist/constants.cjs +42 -0
  16. package/dist/constants.d.cts +15 -0
  17. package/dist/constants.d.cts.map +1 -0
  18. package/dist/constants.d.mts +15 -0
  19. package/dist/constants.d.mts.map +1 -0
  20. package/dist/constants.mjs +39 -0
  21. package/dist/constants.mjs.map +1 -0
  22. package/dist/extract.cjs +144 -95
  23. package/dist/extract.d.cts +34 -69
  24. package/dist/extract.d.cts.map +1 -1
  25. package/dist/extract.d.mts +34 -69
  26. package/dist/extract.d.mts.map +1 -1
  27. package/dist/extract.mjs +144 -95
  28. package/dist/extract.mjs.map +1 -1
  29. package/dist/helpers.cjs +87 -0
  30. package/dist/helpers.d.cts +48 -0
  31. package/dist/helpers.d.cts.map +1 -0
  32. package/dist/helpers.d.mts +48 -0
  33. package/dist/helpers.d.mts.map +1 -0
  34. package/dist/helpers.mjs +84 -0
  35. package/dist/helpers.mjs.map +1 -0
  36. package/dist/index.cjs +29 -5
  37. package/dist/index.d.cts +8 -5
  38. package/dist/index.d.mts +8 -5
  39. package/dist/index.mjs +7 -4
  40. package/dist/metadata.cjs +80 -0
  41. package/dist/metadata.d.cts +52 -0
  42. package/dist/metadata.d.cts.map +1 -0
  43. package/dist/metadata.d.mts +52 -0
  44. package/dist/metadata.d.mts.map +1 -0
  45. package/dist/metadata.mjs +76 -0
  46. package/dist/metadata.mjs.map +1 -0
  47. package/dist/persistence.cjs +75 -0
  48. package/dist/persistence.d.cts +47 -0
  49. package/dist/persistence.d.cts.map +1 -0
  50. package/dist/persistence.d.mts +47 -0
  51. package/dist/persistence.d.mts.map +1 -0
  52. package/dist/persistence.mjs +71 -0
  53. package/dist/persistence.mjs.map +1 -0
  54. package/dist/reflection.cjs +292 -299
  55. package/dist/reflection.d.cts +3 -16
  56. package/dist/reflection.d.cts.map +1 -1
  57. package/dist/reflection.d.mts +3 -16
  58. package/dist/reflection.d.mts.map +1 -1
  59. package/dist/reflection.mjs +291 -299
  60. package/dist/reflection.mjs.map +1 -1
  61. package/dist/resolve.cjs +7 -7
  62. package/dist/resolve.mjs +7 -7
  63. package/dist/resolve.mjs.map +1 -1
  64. package/dist/type-checks.cjs +126 -25
  65. package/dist/type-checks.d.cts +45 -23
  66. package/dist/type-checks.d.cts.map +1 -1
  67. package/dist/type-checks.d.mts +45 -23
  68. package/dist/type-checks.d.mts.map +1 -1
  69. package/dist/type-checks.mjs +125 -25
  70. package/dist/type-checks.mjs.map +1 -1
  71. package/dist/types.d.cts +237 -95
  72. package/dist/types.d.cts.map +1 -1
  73. package/dist/types.d.mts +237 -95
  74. package/dist/types.d.mts.map +1 -1
  75. package/package.json +24 -8
  76. package/dist/jtd.cjs +0 -385
  77. package/dist/jtd.d.cts +0 -15
  78. package/dist/jtd.d.cts.map +0 -1
  79. package/dist/jtd.d.mts +0 -15
  80. package/dist/jtd.d.mts.map +0 -1
  81. package/dist/jtd.mjs +0 -384
  82. package/dist/jtd.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchemaZod"],"sources":["../src/extract.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Context } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { esbuildPlugin } from \"@powerlines/deepkit/esbuild-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { murmurhash } from \"@stryke/hash\";\nimport {\n isJsonSchemaObjectType,\n isStandardJsonSchema,\n JsonSchemaType\n} from \"@stryke/json\";\nimport { isSetString } from \"@stryke/type-checks\";\nimport { isSetObject } from \"@stryke/type-checks/is-set-object\";\nimport {\n extractJsonSchema as extractJsonSchemaZod,\n isZod3Type\n} from \"@stryke/zod\";\nimport defu from \"defu\";\nimport type { BuildOptions } from \"esbuild\";\nimport * as z3 from \"zod/v3\";\nimport { jsonSchemaToJtd } from \"./jtd\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isExtractedSchema,\n isJTDSchema,\n isSchema,\n isUntypedInput,\n isUntypedSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchemaLike,\n JTDSchemaType,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaMetadata,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n TypeDefinitionReference,\n UntypedInputObject,\n UntypedSchema\n} from \"./types\";\n\n/**\n * Creates a hash string for a given schema definition input. The function checks the type of the input and generates a hash based on its content. If the input is a Zod schema, it hashes the JSON representation of its internal definition. If the input is a Standard JSON Schema, it hashes the JSON representation of its internal standard schema. If the input is already a JSON Schema object, it hashes its JSON representation directly. If the input is a reflected Deepkit Type object, it hashes its JSON representation. The resulting hash string can be used for caching or comparison purposes.\n */\nexport function extractHash(\n variant: SchemaInputVariant,\n input: SchemaInput\n): string {\n if (isSetString(input)) {\n return murmurhash({ variant, input });\n } else if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return murmurhash({ variant, input: input._def });\n } else if (isStandardJsonSchema(input)) {\n return murmurhash({ variant, input: input[\"~standard\"] });\n } else if (isJsonSchemaObjectType(input)) {\n return murmurhash({ variant, input });\n } else if (isType(input)) {\n return murmurhash({ variant, input: stringifyType(input) });\n }\n }\n\n throw new Error(\n `Failed to create an input hash for the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Converts a reflected Deepkit {@link @powerlines/deepkit/vendor/type#Type} into a JSON Schema (draft-07) representation.\n *\n * @remarks\n * This function delegates to an internal recursive walker that handles the full set of Deepkit reflection kinds.\n *\n * @param reflection - The reflected Deepkit Type to convert.\n * @returns A JSON Schema (draft-07) fragment representing the type, or `undefined` when no schema could be produced.\n */\nexport function extractReflection<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(reflection: Type): JTDSchemaType<TMetadata> | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema<TMetadata>(reflection);\n}\n\n/**\n * Extracts a JSON Type Definition (RFC 8927) schema from a given schema definition, if possible.\n *\n * @remarks\n * This function checks if the provided input is a Zod schema, a Standard JSON Schema, or already a JSON Schema object, extracts a JSON Schema fragment via the appropriate adapter (Zod and Standard Schema produce draft-07 fragments), and then converts that fragment into a valid JTD form suitable for AJV's JTD validator.\n *\n * @param schema - The schema definition to extract from. This can be a Zod schema, a Standard JSON Schema, or a JSON Schema object.\n * @returns The extracted JTD schema if successful, otherwise undefined.\n */\nexport function extractJsonSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(schema: unknown): JTDSchemaType<TMetadata> | undefined {\n if (\n isSetObject(schema) &&\n (isZod3Type(schema) ||\n isStandardJsonSchema(schema) ||\n isJsonSchemaObjectType(schema) ||\n isUntypedInput(schema) ||\n isUntypedSchema(schema))\n ) {\n let jsonSchema: unknown;\n if (isZod3Type(schema)) {\n jsonSchema = extractJsonSchemaZod(schema);\n } else if (isStandardJsonSchema(schema)) {\n jsonSchema = schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n });\n } else if (isUntypedInput(schema)) {\n jsonSchema = schema.$schema;\n } else {\n jsonSchema = schema;\n }\n\n const jtd = jsonSchemaToJtd<TMetadata>(jsonSchema as JsonSchemaLike);\n if (jtd) {\n return jtd;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractResolvedVariant(\n input: SchemaSourceInput\n): SchemaSourceVariant {\n if (isSetObject(input)) {\n if (isZod3Type(input)) {\n return \"zod3\";\n } else if (isStandardJsonSchema(input)) {\n return \"standard-schema\";\n } else if (isJTDSchema(input)) {\n return \"jtd-schema\";\n } else if (isJsonSchemaObjectType(input)) {\n return \"json-schema\";\n } else if (isType(input)) {\n return \"reflection\";\n } else if (isUntypedInput(input) || isUntypedSchema(input)) {\n return \"untyped\";\n }\n }\n\n throw new Error(\n `Failed to determine the variant of the provided schema definition input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a reflected Deepkit Type object, or an Untyped schema.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a reflected Deepkit Type object, or an Untyped schema. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractVariant(input: SchemaInput): SchemaInputVariant {\n if (isSetString(input) || isTypeDefinition(input)) {\n return \"type-definition\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\n/**\n * Extracts a JSON Schema object from a given schema definition input. The input can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding JSON Schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns the extracted JSON Schema if successful; otherwise, it throws an error.\n *\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param variant - The variant of the schema definition to extract.\n * @returns The extracted JSON Schema if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport async function extractSchemaSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JTDSchemaType<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JTDSchemaType<TMetadata> | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\"\n ) {\n const jsonSchema = extractJsonSchema<TMetadata>(input);\n if (jsonSchema) {\n schema = jsonSchemaToJtd<TMetadata>(jsonSchema);\n }\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection<TMetadata>(input as Type);\n } else if (resolvedVariant === \"jtd-schema\") {\n schema = input as JTDSchemaType<TMetadata>;\n }\n\n if (schema) {\n return schema;\n }\n\n throw new Error(\n `Failed to extract a valid schema from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Extracts a schema definition from a given input object, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object. The function checks the type of the input and attempts to extract the corresponding schema based on its variant. If the input is a Zod schema, it extracts the JSON Schema using the `extractJsonSchema` function. If the input is a Standard JSON Schema, it retrieves the JSON Schema targeting draft-07. If the input is already a JSON Schema object, it uses it directly. If the input is a reflected Deepkit Type object, it extracts the schema using the `extractReflection` function. The function returns a `Schema` containing the extracted schema and its variant if successful; otherwise, it throws an error.\n *\n * @param variant - The variant of the schema definition to extract.\n * @param input - The input object to extract the schema definition from.\n * @returns A `Schema` containing the extracted schema and its variant if successful.\n * @throws An error if the input does not contain a valid schema definition.\n */\nexport function extractSource<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>\n>(variant: SchemaSourceVariant, input: SchemaSourceInput): SchemaSource {\n if (variant === \"zod3\") {\n return {\n hash: extractHash(variant, input),\n variant: \"zod3\",\n schema: input as z3.ZodTypeAny\n };\n } else if (variant === \"untyped\") {\n return {\n hash: extractHash(variant, input),\n variant: \"untyped\",\n schema: input as UntypedInputObject | UntypedSchema\n };\n } else if (variant === \"standard-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"standard-schema\",\n schema: input as StandardJSONSchemaV1\n };\n } else if (variant === \"json-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"json-schema\",\n schema: input as JsonSchemaType\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\n };\n } else if (variant === \"jtd-schema\") {\n return {\n hash: extractHash(variant, input),\n variant: \"jtd-schema\",\n schema: input as JTDSchemaType<TMetadata>\n };\n }\n\n throw new Error(\n `Failed to extract source information from the provided input. The input must be a Zod schema, a Standard JSON Schema, a JSON Schema object, a JTD schema, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extractSchema(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extractSchema(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extractSchema(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extractSchema(context, reflectionType);\n * ```\n *\n * @param context - The plugin context used for resolving the schema definition input.\n * @param input - The schema definition input to extract the JSON Schema from. This can be a Zod schema, a Standard JSON Schema, a JSON Schema object, or a TypeScript type definition.\n * @param options - Optional overrides for the ESBuild configuration used during resolution.\n * @returns A promise that resolves to a {@link ExtractedSchema} containing the extracted JSON Schema and its variant, or the bytecode if JSON Schema extraction is not possible.\n */\nexport async function extractSchema<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<ExtractedSchema<TMetadata>> {\n if (isExtractedSchema<TMetadata>(input)) {\n return input;\n }\n\n if (isSchema<TMetadata>(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"jtd-schema\", input.schema),\n variant: \"jtd-schema\",\n schema: input.schema\n }\n };\n }\n\n let source: SchemaSource;\n\n const variant = extractVariant(input);\n if (variant === \"type-definition\") {\n const resolved = await resolve<SchemaSourceInput>(\n context,\n input as TypeDefinitionReference,\n defu(options, {\n plugins: [\n esbuildPlugin(context, {\n reflection: \"default\",\n level: \"all\"\n })\n ]\n })\n );\n\n source = extractSource(extractResolvedVariant(resolved), resolved);\n } else if (\n [\n \"json-schema\",\n \"jtd-schema\",\n \"standard-schema\",\n \"zod3\",\n \"untyped\",\n \"reflection\"\n ].includes(variant)\n ) {\n source = extractSource(variant, input as SchemaSourceInput);\n } else {\n throw new Error(\n `Invalid schema definition input \"${\n variant\n }\". The variant must be one of \"type-definition\", \"json-schema\", \"jtd-schema\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchemaSchema<TMetadata>(source.schema, source.variant),\n hash: extractHash(variant, input)\n };\n}\n\n/**\n * Resolves the provided entry points to their corresponding type definitions. The function accepts an array of entry points, which can be strings (file paths) or type definition objects. It processes each entry point, resolving file paths and glob patterns to find matching files. For each resolved file, it creates a type definition object and resolves it using the `resolveInput` function. The function returns an array of resolved entry type definitions.\n *\n * @example\n * ```ts\n * // Resolve a schema definition from a file path\n * const schema1 = await extract(context, \"./schemas.ts#MySchema\");\n * // Resolve a schema definition from a JSON Schema object\n * const schema2 = await extract(context, schemaObject);\n * // Resolve a schema definition from a Zod schema\n * const schema3 = await extract(context, zodSchema);\n * // Resolve a schema definition from a reflected Deepkit Type object\n * const schema4 = await extract(context, reflectionType);\n * ```\n *\n * @see https://github.com/colinhacks/zod\n * @see https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec\n * @see https://json-schema.org/\n * @see https://ajv.js.org/json-type-definition.html\n * @see https://deepkit.io/en/documentation/runtime-types/reflection\n * @see https://github.com/unjs/untyped\n * @see https://www.typescriptlang.org/docs/handbook/2/types-from-types.html\n *\n * @param context - The {@link Context | context} used for resolving the {@link Schema | schema} definition input.\n * @param input - The input object or string to extract the {@link Schema | schema} from. This can be {@link TypeDefinitionReference | a string that references a Typescript module}, a [Zod v3 schema](https://github.com/colinhacks/zod), any type that adheres to [the Standard JSON Schema specification](https://standardschema.dev/json-schema#what-schema-libraries-support-this-spec), a [JSON Schema object](https://json-schema.org/), a [JTD schema object](https://ajv.js.org/json-type-definition.html), an [untyped schema](https://github.com/unjs/untyped), or a [TypeScript type reflection](https://deepkit.io/en/documentation/runtime-types/reflection).\n * @param options - Optional overrides for the [ESBuild configuration](https://esbuild.github.io/api/#general-options) used during resolution.\n * @returns A promise that resolves to a {@link Schema | schema} object parsed from the input.\n */\nexport async function extract<\n TMetadata extends Partial<SchemaMetadata> = Partial<SchemaMetadata>,\n TContext extends Context = Context\n>(\n context: TContext,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<Schema<TMetadata>> {\n const result = await extractSchema<TMetadata>(context, input, options);\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmEA,SAAgB,YACd,SACA,OACQ;AACR,KAAI,YAAY,MAAM,CACpB,QAAO,WAAW;EAAE;EAAS;EAAO,CAAC;UAC5BA,cAAY,MAAM,EAC3B;MAAI,WAAW,MAAM,CACnB,QAAO,WAAW;GAAE;GAAS,OAAO,MAAM;GAAM,CAAC;WACxC,qBAAqB,MAAM,CACpC,QAAO,WAAW;GAAE;GAAS,OAAO,MAAM;GAAc,CAAC;WAChD,uBAAuB,MAAM,CACtC,QAAO,WAAW;GAAE;GAAS;GAAO,CAAC;WAC5B,OAAO,MAAM,CACtB,QAAO,WAAW;GAAE;GAAS,OAAO,cAAc,MAAM;GAAE,CAAC;;AAI/D,OAAM,IAAI,MACR,6LACD;;;;;;;;;;;AAYH,SAAgB,kBAEd,YAAwD;AACxD,KAAI,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OAAM,IAAI,MACR,oCACE,QACD,sIACF;AAGH,QAAO;EACL;EACA;EACA,QAAQ,MAAM,oBAA+B,OAAO,QAAQ,OAAO,QAAQ;EAC3E,MAAM,YAAY,SAAS,MAAM;EAClC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BH,eAAsB,QAIpB,SACA,OACA,UAAiC,EAAE,EACP;AAG5B,QAAO,MAFc,cAAyB,SAAS,OAAO,QAAQ"}
1
+ {"version":3,"file":"extract.mjs","names":["isSetObject","extractJsonSchemaZod"],"sources":["../src/extract.ts"],"sourcesContent":["/* -------------------------------------------------------------------\n\n ⚡ Storm Software - Powerlines\n\n This code was released as part of the Powerlines project. Powerlines\n is maintained by Storm Software under the Apache-2.0 license, and is\n free for commercial and private use. For more information, please visit\n our licensing page at https://stormsoftware.com/licenses/projects/powerlines.\n\n Website: https://stormsoftware.com\n Repository: https://github.com/storm-software/powerlines\n Documentation: https://docs.stormsoftware.com/projects/powerlines\n Contact: https://stormsoftware.com/contact\n\n SPDX-License-Identifier: Apache-2.0\n\n ------------------------------------------------------------------- */\n\nimport type { Context } from \"@powerlines/core\";\nimport { isTypeDefinition } from \"@powerlines/core\";\nimport { rolldownPlugin } from \"@powerlines/deepkit/rolldown-plugin\";\nimport { isType, stringifyType, Type } from \"@powerlines/deepkit/vendor/type\";\nimport { StandardJSONSchemaV1 } from \"@standard-schema/spec\";\nimport { murmurhash } from \"@stryke/hash\";\nimport { isStandardJsonSchema } 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 \"rolldown\";\nimport * as z3 from \"zod/v3\";\nimport { getCacheDirectory, writeSchema } from \"./persistence\";\nimport { reflectionToJsonSchema } from \"./reflection\";\nimport { resolve } from \"./resolve\";\nimport {\n isExtractedSchema,\n isJsonSchema,\n isSchema,\n isUntypedInput,\n isUntypedSchema\n} from \"./type-checks\";\nimport {\n ExtractedSchema,\n JsonSchema,\n Schema,\n SchemaInput,\n SchemaInputVariant,\n SchemaSource,\n SchemaSourceInput,\n SchemaSourceVariant,\n TypeDefinitionReference,\n UntypedInputObject,\n UntypedSchema\n} from \"./types\";\n\nfunction convertNestedUntypedSchema(value: unknown): unknown {\n if (isUntypedSchema(value)) {\n return convertUntypedSchemaToJsonSchema(value);\n }\n\n if (isSetObject(value)) {\n if (isUntypedInput(value)) {\n return convertUntypedInputToJsonSchema(value);\n }\n\n const nested = value as Record<string, unknown>;\n if (\"$schema\" in nested && isUntypedSchema(nested.$schema)) {\n return convertUntypedSchemaToJsonSchema(nested.$schema);\n }\n }\n\n return value;\n}\n\nfunction convertNestedUntypedSchemaArray(value: unknown): unknown {\n if (!Array.isArray(value)) {\n return value;\n }\n\n return value.map(item => convertNestedUntypedSchema(item));\n}\n\nfunction convertUntypedSchemaToJsonSchema<T = unknown>(\n schema: UntypedSchema | Record<string, unknown>\n): JsonSchema<T> {\n const source = schema as Record<string, unknown>;\n const jsonSchema: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(source)) {\n if (\n key === \"tsType\" ||\n key === \"markdownType\" ||\n key === \"tags\" ||\n key === \"args\" ||\n key === \"resolve\"\n ) {\n continue;\n }\n\n if (key === \"id\" && isSetString(value)) {\n jsonSchema.$id = value;\n continue;\n }\n\n if (\n key === \"properties\" ||\n key === \"patternProperties\" ||\n key === \"dependentSchemas\" ||\n key === \"$defs\" ||\n key === \"definitions\"\n ) {\n if (!isSetObject(value)) {\n jsonSchema[key] = value;\n continue;\n }\n\n jsonSchema[key] = Object.fromEntries(\n Object.entries(value).map(([propertyKey, propertyValue]) => [\n propertyKey,\n convertNestedUntypedSchema(propertyValue)\n ])\n );\n continue;\n }\n\n if (\n key === \"items\" ||\n key === \"contains\" ||\n key === \"if\" ||\n key === \"then\" ||\n key === \"else\" ||\n key === \"not\" ||\n key === \"propertyNames\" ||\n key === \"additionalProperties\" ||\n key === \"unevaluatedProperties\"\n ) {\n jsonSchema[key] = convertNestedUntypedSchema(value);\n continue;\n }\n\n if (key === \"oneOf\" || key === \"anyOf\" || key === \"allOf\") {\n jsonSchema[key] = convertNestedUntypedSchemaArray(value);\n continue;\n }\n\n jsonSchema[key] = value;\n }\n\n return jsonSchema as JsonSchema<T>;\n}\n\nfunction convertUntypedInputToJsonSchema<T = unknown>(\n input: UntypedInputObject\n): JsonSchema<T> {\n const inputObject = input as Record<string, unknown>;\n const base = isUntypedSchema(inputObject.$schema)\n ? convertUntypedSchemaToJsonSchema<T>(inputObject.$schema)\n : ({} as JsonSchema<T>);\n const properties: Record<string, JsonSchema<T>> = {};\n\n for (const [key, value] of Object.entries(inputObject)) {\n if (key.startsWith(\"$\")) {\n continue;\n }\n\n if (!isSetObject(value)) {\n continue;\n }\n\n if (isUntypedInput(value)) {\n properties[key] = convertUntypedInputToJsonSchema<T>(value);\n continue;\n }\n\n const nested = value as Record<string, unknown>;\n if (\"$schema\" in nested && isUntypedSchema(nested.$schema)) {\n properties[key] = convertUntypedSchemaToJsonSchema<T>(nested.$schema);\n continue;\n }\n\n if (isUntypedSchema(value)) {\n properties[key] = convertUntypedSchemaToJsonSchema<T>(value);\n }\n }\n\n const baseProperties = isSetObject(base.properties)\n ? (base.properties as Record<string, JsonSchema<T>>)\n : {};\n const mergedProperties = {\n ...baseProperties,\n ...properties\n };\n\n return {\n ...base,\n type: base.type ?? \"object\",\n ...(Object.keys(mergedProperties).length > 0\n ? { properties: mergedProperties }\n : {})\n } as JsonSchema<T>;\n}\n\n/**\n * Creates a hash string for a given schema definition input.\n */\nexport function extractHash<T = unknown>(\n variant: SchemaInputVariant,\n input: SchemaInput<T>\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 (isJsonSchema(input)) {\n return murmurhash({ variant, input });\n } else if (isUntypedInput(input)) {\n return murmurhash({\n variant,\n input: convertUntypedInputToJsonSchema(input)\n });\n } else if (isUntypedSchema(input)) {\n return murmurhash({\n variant,\n input: convertUntypedSchemaToJsonSchema(input)\n });\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 Type} into a JSON Schema (draft-07) representation.\n */\nexport function extractReflection<T = unknown>(\n reflection: Type\n): JsonSchema<T> | undefined {\n if (!isType(reflection)) {\n return undefined;\n }\n\n return reflectionToJsonSchema<T>(reflection);\n}\n\n/**\n * Extracts a JSON Schema from Zod, Standard Schema, untyped, or JSON Schema inputs.\n */\nexport function extractJsonSchema<T = unknown>(\n schema: unknown\n): JsonSchema<T> | undefined {\n if (\n isSetObject(schema) &&\n (isZod3Type(schema) ||\n isStandardJsonSchema(schema) ||\n isJsonSchema(schema) ||\n isUntypedInput(schema) ||\n isUntypedSchema(schema))\n ) {\n if (isZod3Type(schema)) {\n return extractJsonSchemaZod(schema) as JsonSchema<T>;\n }\n if (isStandardJsonSchema(schema)) {\n return schema[\"~standard\"].jsonSchema.input({\n target: \"draft-2020-12\"\n }) as JsonSchema<T>;\n }\n if (isUntypedInput(schema)) {\n return convertUntypedInputToJsonSchema<T>(schema);\n }\n if (isUntypedSchema(schema)) {\n return convertUntypedSchemaToJsonSchema<T>(schema);\n }\n return schema;\n }\n\n return undefined;\n}\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 (isJsonSchema(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\nexport function extractVariant<T = unknown>(\n input: SchemaInput<T>\n): SchemaInputVariant {\n if (isSetString(input) || isTypeDefinition(input)) {\n return \"type-definition\";\n }\n\n return extractResolvedVariant(input as SchemaSourceInput);\n}\n\nexport async function extractSchemaSchema<T = unknown>(\n input: SchemaSourceInput,\n variant?: SchemaInputVariant\n): Promise<JsonSchema<T>> {\n if (isExtractedSchema<T>(input)) {\n return input.schema;\n }\n\n const resolvedVariant = variant ?? extractResolvedVariant(input);\n\n let schema: JsonSchema<T> | undefined;\n if (\n resolvedVariant === \"zod3\" ||\n resolvedVariant === \"json-schema\" ||\n resolvedVariant === \"standard-schema\" ||\n resolvedVariant === \"untyped\"\n ) {\n schema = extractJsonSchema<T>(input);\n } else if (resolvedVariant === \"reflection\") {\n schema = extractReflection(input as Type);\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, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\nexport function extractSource(\n variant: SchemaSourceVariant,\n input: SchemaSourceInput\n): 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 JsonSchema\n };\n } else if (variant === \"reflection\") {\n return {\n hash: extractHash(variant, input),\n variant: \"reflection\",\n schema: input as Type\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, an untyped schema, or a reflected Deepkit Type object.`\n );\n}\n\n/**\n * Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object. If the input is a type definition reference (e.g. a file path with an export), it will be resolved and bundled using ESBuild to obtain the actual schema definition before extraction.\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 *\n * @param context - The context object providing access to the file system and cache path.\n * @param input - The schema definition input to extract, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object. If the input is a string or a type definition reference, it will be resolved and bundled to obtain the actual schema definition before extraction.\n * @param options - Optional overrides for the ESBuild configuration used during extraction. This can include custom plugins, loaders, or other build options to control how the schema definition is resolved and bundled when the input is a type definition reference.\n * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object. The function will attempt to extract a valid JSON Schema from the provided input, and if successful, it will return the schema. If the extraction process fails or if the input is not a valid schema definition, it will throw an error indicating the failure.\n */\nexport async function extractSchema<T = unknown>(\n context: Context,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<ExtractedSchema<T>> {\n if (isExtractedSchema<T>(input)) {\n return input;\n }\n\n if (isSchema<T>(input)) {\n return {\n ...input,\n source: {\n hash: extractHash(\"json-schema\", input.schema),\n variant: \"json-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 rolldownPlugin(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 \"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\", \"standard-schema\", \"zod3\", \"untyped\", or \"reflection\".`\n );\n }\n\n return {\n variant,\n source,\n schema: await extractSchemaSchema<T>(source.schema, source.variant),\n hash\n };\n}\n\n/**\n * Extracts a JSON Schema from a given schema definition input, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object. If the input is a type definition reference (e.g. a file path with an export), it will be resolved and bundled using ESBuild to obtain the actual schema definition before extraction.\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 context object providing access to the file system and cache path.\n * @param input - The schema definition input to extract, which can be a Zod schema, a Standard JSON Schema, a JSON Schema object, an untyped schema, or a reflected Deepkit Type object.\n * @param options - Optional overrides for the ESBuild configuration used during extraction.\n * @returns A promise that resolves to the extracted and normalized schema as a JSON Schema object.\n * @throws Will throw an error if the input is not a valid schema definition or if the extraction process fails to produce a valid schema.\n */\nexport async function extract<T = unknown>(\n context: Context,\n input: SchemaInput,\n options: Partial<BuildOptions> = {}\n): Promise<Schema<T>> {\n if (isExtractedSchema<T>(input) || isSchema<T>(input)) {\n return input;\n }\n\n let result: Schema<T> | 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 JsonSchema\n };\n }\n }\n\n result ??= await extractSchema<T>(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, 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":";;;;;;;;;;;;;;;;AA2DA,SAAS,2BAA2B,OAAyB;CAC3D,IAAI,gBAAgB,KAAK,GACvB,OAAO,iCAAiC,KAAK;CAG/C,IAAIA,cAAY,KAAK,GAAG;EACtB,IAAI,eAAe,KAAK,GACtB,OAAO,gCAAgC,KAAK;EAG9C,MAAM,SAAS;EACf,IAAI,aAAa,UAAU,gBAAgB,OAAO,OAAO,GACvD,OAAO,iCAAiC,OAAO,OAAO;CAE1D;CAEA,OAAO;AACT;AAEA,SAAS,gCAAgC,OAAyB;CAChE,IAAI,CAAC,MAAM,QAAQ,KAAK,GACtB,OAAO;CAG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CAAC,GACd;CACpB,IAAI,kBAAqB,KAAK,KAAK,SAAY,KAAK,GAClD,OAAO;CAGT,IAAI;CAEJ,MAAM,UAAU,eAAe,KAAK;CACpC,MAAM,OAAO,YAAY,SAAS,KAAK;CAEvC,MAAM,gBAAgB,UAAU,kBAAkB,OAAO,GAAG,GAAG,KAAK,MAAM;CAC1E,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,cAAiB,SAAS,OAAO,OAAO;CACzD,IAAI,CAAC,QAAQ,QACX,MAAM,IAAI,MACR,gMACF;CAGF,IAAI,QAAQ,OAAO,cAAc,MAC/B,MAAM,YAAY,SAAS,MAAM;CAGnC,OAAO;AACT"}
@@ -0,0 +1,87 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_metadata = require('./metadata.cjs');
3
+ const require_type_checks = require('./type-checks.cjs');
4
+ let defu = require("defu");
5
+ let _stryke_type_checks = require("@stryke/type-checks");
6
+
7
+ //#region src/helpers.ts
8
+ /**
9
+ * Extracts object properties from a JSON Schema object form.
10
+ *
11
+ * @remarks
12
+ * This function returns an empty object if the schema is not an object form or if it has no properties.
13
+ *
14
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
15
+ * @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
16
+ */
17
+ function getProperties(obj) {
18
+ const properties = {};
19
+ const schema = require_type_checks.isSchema(obj) ? obj.schema : obj;
20
+ if (!require_type_checks.isJsonSchemaObject(schema) || !(0, _stryke_type_checks.isSetObject)(schema.properties)) return properties;
21
+ for (const [key, value] of Object.entries(schema.properties)) properties[key] = {
22
+ ...value,
23
+ name: key,
24
+ nullable: require_metadata.isSchemaNullable(value) || require_metadata.isPropertyOptional(schema, key)
25
+ };
26
+ return properties;
27
+ }
28
+ /**
29
+ * Returns object properties as an array.
30
+ *
31
+ * @remarks
32
+ * This is a convenience function that extracts properties using `getProperties` and returns them as an array.
33
+ *
34
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
35
+ * @returns An array of JSON Schema fragments representing the properties, each including metadata.
36
+ */
37
+ function getPropertiesList(obj) {
38
+ return Object.values(getProperties(obj));
39
+ }
40
+ /**
41
+ * Adds a property to a JSON Schema object form.
42
+ *
43
+ * @remarks
44
+ * This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.
45
+ *
46
+ * @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.
47
+ * @param name - The name of the property to add.
48
+ * @param property - The JSON Schema fragment representing the property's schema, including metadata.
49
+ * @throws Will throw an error if the provided schema is not an object form.
50
+ */
51
+ function addProperty(obj, name, property) {
52
+ const schema = require_type_checks.isSchema(obj) ? obj.schema : obj;
53
+ if (!require_type_checks.isJsonSchemaObject(schema)) throw new Error("Cannot add property to non-object schema");
54
+ schema.properties ??= {};
55
+ schema.required ??= [];
56
+ schema.properties[name] = {
57
+ ...property,
58
+ name
59
+ };
60
+ if (property?.optional) schema.required = schema.required.filter((key) => key !== name);
61
+ else if (!schema.required.includes(name)) schema.required.push(name);
62
+ if (schema.required.length === 0) delete schema.required;
63
+ }
64
+ /**
65
+ * Merges multiple JSON Schema object forms into one.
66
+ *
67
+ * @remarks
68
+ * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
69
+ *
70
+ * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.
71
+ * @returns A new JSON Schema object that is the result of merging all input schemas.
72
+ */
73
+ function mergeSchemas(...schemas) {
74
+ const result = {};
75
+ for (const schema of schemas) {
76
+ const jsonSchema = require_type_checks.isSchema(schema) ? schema.schema : schema;
77
+ if (!require_type_checks.isJsonSchemaObject(jsonSchema)) continue;
78
+ (0, defu.defu)(result, jsonSchema);
79
+ }
80
+ return result;
81
+ }
82
+
83
+ //#endregion
84
+ exports.addProperty = addProperty;
85
+ exports.getProperties = getProperties;
86
+ exports.getPropertiesList = getPropertiesList;
87
+ exports.mergeSchemas = mergeSchemas;
@@ -0,0 +1,48 @@
1
+ import { JsonSchema, JsonSchemaProperty, Schema } from "./types.cjs";
2
+
3
+ //#region src/helpers.d.ts
4
+ /**
5
+ * Extracts object properties from a JSON Schema object form.
6
+ *
7
+ * @remarks
8
+ * This function returns an empty object if the schema is not an object form or if it has no properties.
9
+ *
10
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
11
+ * @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
12
+ */
13
+ declare function getProperties<T extends Record<string, any> = Record<string, any>>(obj: Schema<T> | JsonSchema<T>): Record<string, JsonSchemaProperty<T>>;
14
+ /**
15
+ * Returns object properties as an array.
16
+ *
17
+ * @remarks
18
+ * This is a convenience function that extracts properties using `getProperties` and returns them as an array.
19
+ *
20
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
21
+ * @returns An array of JSON Schema fragments representing the properties, each including metadata.
22
+ */
23
+ declare function getPropertiesList<T extends Record<string, any> = Record<string, any>>(obj: Schema<T> | JsonSchema<T>): Array<JsonSchemaProperty<T>>;
24
+ /**
25
+ * Adds a property to a JSON Schema object form.
26
+ *
27
+ * @remarks
28
+ * This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.
29
+ *
30
+ * @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.
31
+ * @param name - The name of the property to add.
32
+ * @param property - The JSON Schema fragment representing the property's schema, including metadata.
33
+ * @throws Will throw an error if the provided schema is not an object form.
34
+ */
35
+ declare function addProperty<T extends Record<string, any> = Record<string, any>>(obj: Schema<T> | JsonSchema<T>, name: string, property: JsonSchemaProperty<T>): void;
36
+ /**
37
+ * Merges multiple JSON Schema object forms into one.
38
+ *
39
+ * @remarks
40
+ * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
41
+ *
42
+ * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.
43
+ * @returns A new JSON Schema object that is the result of merging all input schemas.
44
+ */
45
+ declare function mergeSchemas<T extends Record<string, any> = Record<string, any>>(...schemas: (JsonSchema<T> | Schema<T>)[]): JsonSchema<T>;
46
+ //#endregion
47
+ export { addProperty, getProperties, getPropertiesList, mergeSchemas };
48
+ //# sourceMappingURL=helpers.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.cts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;;;AAsCA;;;;;;;iBAAgB,aAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAChC,GAAA,EAAK,MAAA,CAAO,CAAA,IAAK,UAAA,CAAW,CAAA,IAAK,MAAA,SAAe,kBAAA,CAAmB,CAAA;;;;;;;;;;iBA2BrD,iBAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAChC,GAAA,EAAK,MAAA,CAAO,CAAA,IAAK,UAAA,CAAW,CAAA,IAAK,KAAA,CAAM,kBAAA,CAAmB,CAAA;;;;;;;;;AA7BU;AA2BtE;;iBAiBgB,WAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAEhC,GAAA,EAAK,MAAA,CAAO,CAAA,IAAK,UAAA,CAAW,CAAA,GAC5B,IAAA,UACA,QAAA,EAAU,kBAAA,CAAmB,CAAA;;;;;;;;;;iBA+Bf,YAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAAA,GAC7B,OAAA,GAAU,UAAA,CAAW,CAAA,IAAK,MAAA,CAAO,CAAA,OAAQ,UAAA,CAAW,CAAA"}
@@ -0,0 +1,48 @@
1
+ import { JsonSchema, JsonSchemaProperty, Schema } from "./types.mjs";
2
+
3
+ //#region src/helpers.d.ts
4
+ /**
5
+ * Extracts object properties from a JSON Schema object form.
6
+ *
7
+ * @remarks
8
+ * This function returns an empty object if the schema is not an object form or if it has no properties.
9
+ *
10
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
11
+ * @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
12
+ */
13
+ declare function getProperties<T extends Record<string, any> = Record<string, any>>(obj: Schema<T> | JsonSchema<T>): Record<string, JsonSchemaProperty<T>>;
14
+ /**
15
+ * Returns object properties as an array.
16
+ *
17
+ * @remarks
18
+ * This is a convenience function that extracts properties using `getProperties` and returns them as an array.
19
+ *
20
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
21
+ * @returns An array of JSON Schema fragments representing the properties, each including metadata.
22
+ */
23
+ declare function getPropertiesList<T extends Record<string, any> = Record<string, any>>(obj: Schema<T> | JsonSchema<T>): Array<JsonSchemaProperty<T>>;
24
+ /**
25
+ * Adds a property to a JSON Schema object form.
26
+ *
27
+ * @remarks
28
+ * This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.
29
+ *
30
+ * @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.
31
+ * @param name - The name of the property to add.
32
+ * @param property - The JSON Schema fragment representing the property's schema, including metadata.
33
+ * @throws Will throw an error if the provided schema is not an object form.
34
+ */
35
+ declare function addProperty<T extends Record<string, any> = Record<string, any>>(obj: Schema<T> | JsonSchema<T>, name: string, property: JsonSchemaProperty<T>): void;
36
+ /**
37
+ * Merges multiple JSON Schema object forms into one.
38
+ *
39
+ * @remarks
40
+ * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
41
+ *
42
+ * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.
43
+ * @returns A new JSON Schema object that is the result of merging all input schemas.
44
+ */
45
+ declare function mergeSchemas<T extends Record<string, any> = Record<string, any>>(...schemas: (JsonSchema<T> | Schema<T>)[]): JsonSchema<T>;
46
+ //#endregion
47
+ export { addProperty, getProperties, getPropertiesList, mergeSchemas };
48
+ //# sourceMappingURL=helpers.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.d.mts","names":[],"sources":["../src/helpers.ts"],"mappings":";;;;;AAsCA;;;;;;;iBAAgB,aAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAChC,GAAA,EAAK,MAAA,CAAO,CAAA,IAAK,UAAA,CAAW,CAAA,IAAK,MAAA,SAAe,kBAAA,CAAmB,CAAA;;;;;;;;;;iBA2BrD,iBAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAChC,GAAA,EAAK,MAAA,CAAO,CAAA,IAAK,UAAA,CAAW,CAAA,IAAK,KAAA,CAAM,kBAAA,CAAmB,CAAA;;;;;;;;;AA7BU;AA2BtE;;iBAiBgB,WAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAEhC,GAAA,EAAK,MAAA,CAAO,CAAA,IAAK,UAAA,CAAW,CAAA,GAC5B,IAAA,UACA,QAAA,EAAU,kBAAA,CAAmB,CAAA;;;;;;;;;;iBA+Bf,YAAA,WACJ,MAAA,gBAAsB,MAAA,cAAA,CAAA,GAC7B,OAAA,GAAU,UAAA,CAAW,CAAA,IAAK,MAAA,CAAO,CAAA,OAAQ,UAAA,CAAW,CAAA"}
@@ -0,0 +1,84 @@
1
+ import { isPropertyOptional, isSchemaNullable } from "./metadata.mjs";
2
+ import { isJsonSchemaObject, isSchema } from "./type-checks.mjs";
3
+ import { defu as defu$1 } from "defu";
4
+ import { isSetObject } from "@stryke/type-checks";
5
+
6
+ //#region src/helpers.ts
7
+ /**
8
+ * Extracts object properties from a JSON Schema object form.
9
+ *
10
+ * @remarks
11
+ * This function returns an empty object if the schema is not an object form or if it has no properties.
12
+ *
13
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
14
+ * @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.
15
+ */
16
+ function getProperties(obj) {
17
+ const properties = {};
18
+ const schema = isSchema(obj) ? obj.schema : obj;
19
+ if (!isJsonSchemaObject(schema) || !isSetObject(schema.properties)) return properties;
20
+ for (const [key, value] of Object.entries(schema.properties)) properties[key] = {
21
+ ...value,
22
+ name: key,
23
+ nullable: isSchemaNullable(value) || isPropertyOptional(schema, key)
24
+ };
25
+ return properties;
26
+ }
27
+ /**
28
+ * Returns object properties as an array.
29
+ *
30
+ * @remarks
31
+ * This is a convenience function that extracts properties using `getProperties` and returns them as an array.
32
+ *
33
+ * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.
34
+ * @returns An array of JSON Schema fragments representing the properties, each including metadata.
35
+ */
36
+ function getPropertiesList(obj) {
37
+ return Object.values(getProperties(obj));
38
+ }
39
+ /**
40
+ * Adds a property to a JSON Schema object form.
41
+ *
42
+ * @remarks
43
+ * This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.
44
+ *
45
+ * @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.
46
+ * @param name - The name of the property to add.
47
+ * @param property - The JSON Schema fragment representing the property's schema, including metadata.
48
+ * @throws Will throw an error if the provided schema is not an object form.
49
+ */
50
+ function addProperty(obj, name, property) {
51
+ const schema = isSchema(obj) ? obj.schema : obj;
52
+ if (!isJsonSchemaObject(schema)) throw new Error("Cannot add property to non-object schema");
53
+ schema.properties ??= {};
54
+ schema.required ??= [];
55
+ schema.properties[name] = {
56
+ ...property,
57
+ name
58
+ };
59
+ if (property?.optional) schema.required = schema.required.filter((key) => key !== name);
60
+ else if (!schema.required.includes(name)) schema.required.push(name);
61
+ if (schema.required.length === 0) delete schema.required;
62
+ }
63
+ /**
64
+ * Merges multiple JSON Schema object forms into one.
65
+ *
66
+ * @remarks
67
+ * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.
68
+ *
69
+ * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.
70
+ * @returns A new JSON Schema object that is the result of merging all input schemas.
71
+ */
72
+ function mergeSchemas(...schemas) {
73
+ const result = {};
74
+ for (const schema of schemas) {
75
+ const jsonSchema = isSchema(schema) ? schema.schema : schema;
76
+ if (!isJsonSchemaObject(jsonSchema)) continue;
77
+ defu$1(result, jsonSchema);
78
+ }
79
+ return result;
80
+ }
81
+
82
+ //#endregion
83
+ export { addProperty, getProperties, getPropertiesList, mergeSchemas };
84
+ //# sourceMappingURL=helpers.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"helpers.mjs","names":[],"sources":["../src/helpers.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 { isSetObject } from \"@stryke/type-checks\";\nimport { defu } from \"defu\";\nimport { isPropertyOptional, isSchemaNullable } from \"./metadata\";\nimport { isJsonSchemaObject, isSchema } from \"./type-checks\";\nimport {\n JsonSchema,\n JsonSchemaObject,\n JsonSchemaProperty,\n Schema\n} from \"./types\";\n\n/**\n * Extracts object properties from a JSON Schema object form.\n *\n * @remarks\n * This function returns an empty object if the schema is not an object form or if it has no properties.\n *\n * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.\n * @returns An object mapping property names to their corresponding JSON Schema fragments, including metadata.\n */\nexport function getProperties<\n T extends Record<string, any> = Record<string, any>\n>(obj: Schema<T> | JsonSchema<T>): Record<string, JsonSchemaProperty<T>> {\n const properties: Record<string, JsonSchemaProperty<T>> = {};\n const schema: JsonSchema<T> = isSchema<T>(obj) ? obj.schema : obj;\n if (!isJsonSchemaObject<T>(schema) || !isSetObject(schema.properties)) {\n return properties;\n }\n\n for (const [key, value] of Object.entries(schema.properties)) {\n properties[key] = {\n ...value,\n name: key,\n nullable: isSchemaNullable<T>(value) || isPropertyOptional(schema, key)\n };\n }\n\n return properties;\n}\n\n/**\n * Returns object properties as an array.\n *\n * @remarks\n * This is a convenience function that extracts properties using `getProperties` and returns them as an array.\n *\n * @param obj - The JSON Schema object form or a Schema wrapper to extract properties from.\n * @returns An array of JSON Schema fragments representing the properties, each including metadata.\n */\nexport function getPropertiesList<\n T extends Record<string, any> = Record<string, any>\n>(obj: Schema<T> | JsonSchema<T>): Array<JsonSchemaProperty<T>> {\n return Object.values(getProperties<T>(obj));\n}\n\n/**\n * Adds a property to a JSON Schema object form.\n *\n * @remarks\n * This function modifies the provided schema in place by adding a new property with the specified name and schema. It also updates the `required` array based on the `optional` flag of the property. If the property is marked as optional, it will be removed from the `required` array; otherwise, it will be added to it.\n *\n * @param obj - The JSON Schema object form or a Schema wrapper to which the property should be added.\n * @param name - The name of the property to add.\n * @param property - The JSON Schema fragment representing the property's schema, including metadata.\n * @throws Will throw an error if the provided schema is not an object form.\n */\nexport function addProperty<\n T extends Record<string, any> = Record<string, any>\n>(\n obj: Schema<T> | JsonSchema<T>,\n name: string,\n property: JsonSchemaProperty<T>\n): void {\n const schema = (isSchema<T>(obj) ? obj.schema : obj) as JsonSchemaObject<T>;\n if (!isJsonSchemaObject<T>(schema)) {\n throw new Error(\"Cannot add property to non-object schema\");\n }\n\n schema.properties ??= {};\n schema.required ??= [];\n\n schema.properties[name] = { ...property, name };\n if (property?.optional) {\n schema.required = schema.required.filter(key => key !== name);\n } else if (!schema.required.includes(name)) {\n schema.required.push(name);\n }\n\n if (schema.required.length === 0) {\n delete schema.required;\n }\n}\n\n/**\n * Merges multiple JSON Schema object forms into one.\n *\n * @remarks\n * This function takes multiple JSON Schema objects or Schema wrappers and merges them into a single JSON Schema object. The merging process combines properties and metadata from all provided schemas, with later schemas in the arguments list taking precedence over earlier ones in case of conflicts. The resulting schema will include all unique properties and metadata from the input schemas.\n *\n * @param schemas - An array of JSON Schema objects or Schema wrappers to merge.\n * @returns A new JSON Schema object that is the result of merging all input schemas.\n */\nexport function mergeSchemas<\n T extends Record<string, any> = Record<string, any>\n>(...schemas: (JsonSchema<T> | Schema<T>)[]): JsonSchema<T> {\n const result: JsonSchema<T> = {} as JsonSchema<T>;\n for (const schema of schemas) {\n const jsonSchema: JsonSchema<T> = isSchema<T>(schema)\n ? schema.schema\n : schema;\n if (!isJsonSchemaObject<T>(jsonSchema)) {\n continue;\n }\n\n defu(result, jsonSchema);\n }\n\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAsCA,SAAgB,cAEd,KAAuE;CACvE,MAAM,aAAoD,CAAC;CAC3D,MAAM,SAAwB,SAAY,GAAG,IAAI,IAAI,SAAS;CAC9D,IAAI,CAAC,mBAAsB,MAAM,KAAK,CAAC,YAAY,OAAO,UAAU,GAClE,OAAO;CAGT,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,OAAO,UAAU,GACzD,WAAW,OAAO;EAChB,GAAG;EACH,MAAM;EACN,UAAU,iBAAoB,KAAK,KAAK,mBAAmB,QAAQ,GAAG;CACxE;CAGF,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,kBAEd,KAA8D;CAC9D,OAAO,OAAO,OAAO,cAAiB,GAAG,CAAC;AAC5C;;;;;;;;;;;;AAaA,SAAgB,YAGd,KACA,MACA,UACM;CACN,MAAM,SAAU,SAAY,GAAG,IAAI,IAAI,SAAS;CAChD,IAAI,CAAC,mBAAsB,MAAM,GAC/B,MAAM,IAAI,MAAM,0CAA0C;CAG5D,OAAO,eAAe,CAAC;CACvB,OAAO,aAAa,CAAC;CAErB,OAAO,WAAW,QAAQ;EAAE,GAAG;EAAU;CAAK;CAC9C,IAAI,UAAU,UACZ,OAAO,WAAW,OAAO,SAAS,QAAO,QAAO,QAAQ,IAAI;MACvD,IAAI,CAAC,OAAO,SAAS,SAAS,IAAI,GACvC,OAAO,SAAS,KAAK,IAAI;CAG3B,IAAI,OAAO,SAAS,WAAW,GAC7B,OAAO,OAAO;AAElB;;;;;;;;;;AAWA,SAAgB,aAEd,GAAG,SAAuD;CAC1D,MAAM,SAAwB,CAAC;CAC/B,KAAK,MAAM,UAAU,SAAS;EAC5B,MAAM,aAA4B,SAAY,MAAM,IAChD,OAAO,SACP;EACJ,IAAI,CAAC,mBAAsB,UAAU,GACnC;EAGF,OAAK,QAAQ,UAAU;CACzB;CAEA,OAAO;AACT"}
package/dist/index.cjs CHANGED
@@ -1,12 +1,20 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
2
  const require_bundle = require('./bundle.cjs');
3
+ const require_constants = require('./constants.cjs');
4
+ const require_metadata = require('./metadata.cjs');
5
+ const require_type_checks = require('./type-checks.cjs');
6
+ const require_helpers = require('./helpers.cjs');
3
7
  const require_codegen = require('./codegen.cjs');
4
- const require_jtd = require('./jtd.cjs');
8
+ const require_persistence = require('./persistence.cjs');
5
9
  const require_reflection = require('./reflection.cjs');
6
10
  const require_resolve = require('./resolve.cjs');
7
- const require_type_checks = require('./type-checks.cjs');
8
11
  const require_extract = require('./extract.cjs');
9
12
 
13
+ exports.JSON_SCHEMA_DATA_TYPES = require_constants.JSON_SCHEMA_DATA_TYPES;
14
+ exports.JSON_SCHEMA_METADATA_KEYS = require_constants.JSON_SCHEMA_METADATA_KEYS;
15
+ exports.JsonSchemaTypes = require_constants.JsonSchemaTypes;
16
+ exports.addProperty = require_helpers.addProperty;
17
+ exports.applySchemaMetadata = require_metadata.applySchemaMetadata;
10
18
  exports.bundle = require_bundle.bundle;
11
19
  exports.extract = require_extract.extract;
12
20
  exports.extractHash = require_extract.extractHash;
@@ -18,13 +26,29 @@ exports.extractSchemaSchema = require_extract.extractSchemaSchema;
18
26
  exports.extractSource = require_extract.extractSource;
19
27
  exports.extractVariant = require_extract.extractVariant;
20
28
  exports.generateCode = require_codegen.generateCode;
29
+ exports.getCacheDirectory = require_persistence.getCacheDirectory;
30
+ exports.getCacheFilePath = require_persistence.getCacheFilePath;
31
+ exports.getPrimarySchemaType = require_metadata.getPrimarySchemaType;
32
+ exports.getProperties = require_helpers.getProperties;
33
+ exports.getPropertiesList = require_helpers.getPropertiesList;
21
34
  exports.isExtractedSchema = require_type_checks.isExtractedSchema;
22
- exports.isJTDSchema = require_type_checks.isJTDSchema;
35
+ exports.isJsonSchema = require_type_checks.isJsonSchema;
36
+ exports.isJsonSchemaObject = require_type_checks.isJsonSchemaObject;
37
+ exports.isNullOnlyJsonSchema = require_type_checks.isNullOnlyJsonSchema;
38
+ exports.isNullableSchema = require_codegen.isNullableSchema;
39
+ exports.isPropertyOptional = require_metadata.isPropertyOptional;
23
40
  exports.isSchema = require_type_checks.isSchema;
41
+ exports.isSchemaNullable = require_metadata.isSchemaNullable;
24
42
  exports.isUntypedInput = require_type_checks.isUntypedInput;
25
43
  exports.isUntypedSchema = require_type_checks.isUntypedSchema;
26
- exports.jsonSchemaToJtd = require_jtd.jsonSchemaToJtd;
44
+ exports.mergeSchemas = require_helpers.mergeSchemas;
45
+ exports.readSchema = require_persistence.readSchema;
46
+ exports.readSchemaSafe = require_persistence.readSchemaSafe;
47
+ exports.readSchemaTypes = require_metadata.readSchemaTypes;
27
48
  exports.reflectionToJsonSchema = require_reflection.reflectionToJsonSchema;
28
49
  exports.resolve = require_resolve.resolve;
29
50
  exports.resolveModule = require_resolve.resolveModule;
30
- exports.resolveReflection = require_resolve.resolveReflection;
51
+ exports.resolveReflection = require_resolve.resolveReflection;
52
+ exports.stringifyType = require_codegen.stringifyType;
53
+ exports.stringifyValue = require_codegen.stringifyValue;
54
+ exports.writeSchema = require_persistence.writeSchema;
package/dist/index.d.cts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { BundleOptions, bundle } from "./bundle.cjs";
2
- import { generateCode } from "./codegen.cjs";
3
- import { BaseSchemaSource, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.cjs";
2
+ import { BaseSchemaSource, ExtractedSchema, JsonSchema, JsonSchemaLike, JsonSchemaObject, JsonSchemaPrimitiveType, JsonSchemaProperty, JsonSchemaSchemaSource, JsonType, NumberFormat, NumberKeywords, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, StringKeywords, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.cjs";
3
+ import { generateCode, isNullableSchema, stringifyType, stringifyValue } from "./codegen.cjs";
4
+ import { JSON_SCHEMA_DATA_TYPES, JSON_SCHEMA_METADATA_KEYS, JsonSchemaTypes } from "./constants.cjs";
4
5
  import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.cjs";
5
- import { jsonSchemaToJtd } from "./jtd.cjs";
6
+ import { addProperty, getProperties, getPropertiesList, mergeSchemas } from "./helpers.cjs";
7
+ import { applySchemaMetadata, getPrimarySchemaType, isPropertyOptional, isSchemaNullable, readSchemaTypes } from "./metadata.cjs";
8
+ import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.cjs";
6
9
  import { reflectionToJsonSchema } from "./reflection.cjs";
7
10
  import { resolve, resolveModule, resolveReflection } from "./resolve.cjs";
8
- import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.cjs";
9
- export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, 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, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
11
+ import { isExtractedSchema, isJsonSchema, isJsonSchemaObject, isNullOnlyJsonSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.cjs";
12
+ export { BaseSchemaSource, BundleOptions, ExtractedSchema, JSON_SCHEMA_DATA_TYPES, JSON_SCHEMA_METADATA_KEYS, JsonSchema, JsonSchemaLike, JsonSchemaObject, JsonSchemaPrimitiveType, JsonSchemaProperty, JsonSchemaSchemaSource, JsonSchemaTypes, JsonType, NumberFormat, NumberKeywords, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, StringKeywords, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, addProperty, applySchemaMetadata, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getPrimarySchemaType, getProperties, getPropertiesList, isExtractedSchema, isJsonSchema, isJsonSchemaObject, isNullOnlyJsonSchema, isNullableSchema, isPropertyOptional, isSchema, isSchemaNullable, isUntypedInput, isUntypedSchema, mergeSchemas, readSchema, readSchemaSafe, readSchemaTypes, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
package/dist/index.d.mts CHANGED
@@ -1,9 +1,12 @@
1
1
  import { BundleOptions, bundle } from "./bundle.mjs";
2
- import { generateCode } from "./codegen.mjs";
3
- import { BaseSchemaSource, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.mjs";
2
+ import { BaseSchemaSource, ExtractedSchema, JsonSchema, JsonSchemaLike, JsonSchemaObject, JsonSchemaPrimitiveType, JsonSchemaProperty, JsonSchemaSchemaSource, JsonType, NumberFormat, NumberKeywords, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, StringKeywords, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource } from "./types.mjs";
3
+ import { generateCode, isNullableSchema, stringifyType, stringifyValue } from "./codegen.mjs";
4
+ import { JSON_SCHEMA_DATA_TYPES, JSON_SCHEMA_METADATA_KEYS, JsonSchemaTypes } from "./constants.mjs";
4
5
  import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
5
- import { jsonSchemaToJtd } from "./jtd.mjs";
6
+ import { addProperty, getProperties, getPropertiesList, mergeSchemas } from "./helpers.mjs";
7
+ import { applySchemaMetadata, getPrimarySchemaType, isPropertyOptional, isSchemaNullable, readSchemaTypes } from "./metadata.mjs";
8
+ import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.mjs";
6
9
  import { reflectionToJsonSchema } from "./reflection.mjs";
7
10
  import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
8
- import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
9
- export { BaseSchemaSource, BundleOptions, ExtractedSchema, JTDNumberType, JTDSchemaSchemaSource, JTDSchemaType, JTDStringType, JTDType, JsonSchemaLike, JsonSchemaSchemaSource, 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, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
11
+ import { isExtractedSchema, isJsonSchema, isJsonSchemaObject, isNullOnlyJsonSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
12
+ export { BaseSchemaSource, BundleOptions, ExtractedSchema, JSON_SCHEMA_DATA_TYPES, JSON_SCHEMA_METADATA_KEYS, JsonSchema, JsonSchemaLike, JsonSchemaObject, JsonSchemaPrimitiveType, JsonSchemaProperty, JsonSchemaSchemaSource, JsonSchemaTypes, JsonType, NumberFormat, NumberKeywords, ReflectionSchemaSource, Schema, SchemaInput, SchemaInputVariant, SchemaMetadata, SchemaSource, SchemaSourceInput, SchemaSourceVariant, StandardSchemaSchemaSource, StringKeywords, TypeDefinitionReference, UntypedInputObject, UntypedSchema, UntypedSchemaSource, Zod3SchemaSource, addProperty, applySchemaMetadata, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getPrimarySchemaType, getProperties, getPropertiesList, isExtractedSchema, isJsonSchema, isJsonSchemaObject, isNullOnlyJsonSchema, isNullableSchema, isPropertyOptional, isSchema, isSchemaNullable, isUntypedInput, isUntypedSchema, mergeSchemas, readSchema, readSchemaSafe, readSchemaTypes, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
package/dist/index.mjs CHANGED
@@ -1,9 +1,12 @@
1
1
  import { bundle } from "./bundle.mjs";
2
- import { generateCode } from "./codegen.mjs";
3
- import { jsonSchemaToJtd } from "./jtd.mjs";
2
+ import { JSON_SCHEMA_DATA_TYPES, JSON_SCHEMA_METADATA_KEYS, JsonSchemaTypes } from "./constants.mjs";
3
+ import { applySchemaMetadata, getPrimarySchemaType, isPropertyOptional, isSchemaNullable, readSchemaTypes } from "./metadata.mjs";
4
+ import { isExtractedSchema, isJsonSchema, isJsonSchemaObject, isNullOnlyJsonSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
5
+ import { addProperty, getProperties, getPropertiesList, mergeSchemas } from "./helpers.mjs";
6
+ import { generateCode, isNullableSchema, stringifyType, stringifyValue } from "./codegen.mjs";
7
+ import { getCacheDirectory, getCacheFilePath, readSchema, readSchemaSafe, writeSchema } from "./persistence.mjs";
4
8
  import { reflectionToJsonSchema } from "./reflection.mjs";
5
9
  import { resolve, resolveModule, resolveReflection } from "./resolve.mjs";
6
- import { isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema } from "./type-checks.mjs";
7
10
  import { extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant } from "./extract.mjs";
8
11
 
9
- export { bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, isExtractedSchema, isJTDSchema, isSchema, isUntypedInput, isUntypedSchema, jsonSchemaToJtd, reflectionToJsonSchema, resolve, resolveModule, resolveReflection };
12
+ export { JSON_SCHEMA_DATA_TYPES, JSON_SCHEMA_METADATA_KEYS, JsonSchemaTypes, addProperty, applySchemaMetadata, bundle, extract, extractHash, extractJsonSchema, extractReflection, extractResolvedVariant, extractSchema, extractSchemaSchema, extractSource, extractVariant, generateCode, getCacheDirectory, getCacheFilePath, getPrimarySchemaType, getProperties, getPropertiesList, isExtractedSchema, isJsonSchema, isJsonSchemaObject, isNullOnlyJsonSchema, isNullableSchema, isPropertyOptional, isSchema, isSchemaNullable, isUntypedInput, isUntypedSchema, mergeSchemas, readSchema, readSchemaSafe, readSchemaTypes, reflectionToJsonSchema, resolve, resolveModule, resolveReflection, stringifyType, stringifyValue, writeSchema };
@@ -0,0 +1,80 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ const require_constants = require('./constants.cjs');
3
+ let _stryke_type_checks = require("@stryke/type-checks");
4
+ let _stryke_type_checks_is_set_object = require("@stryke/type-checks/is-set-object");
5
+
6
+ //#region src/metadata.ts
7
+ /**
8
+ * Applies Powerlines schema metadata onto a JSON Schema fragment.
9
+ *
10
+ * @param schema - The JSON Schema fragment to apply metadata to.
11
+ * @param metadata - The Powerlines schema metadata to apply.
12
+ * @returns A new JSON Schema fragment with the metadata applied.
13
+ */
14
+ function applySchemaMetadata(schema, metadata) {
15
+ if (!metadata) return schema;
16
+ const result = { ...schema };
17
+ for (const key of require_constants.JSON_SCHEMA_METADATA_KEYS) {
18
+ const value = metadata[key];
19
+ if (value !== void 0 && value !== null) result[key] = value;
20
+ }
21
+ return result;
22
+ }
23
+ /**
24
+ * Returns whether a JSON Schema fragment accepts `null`.
25
+ *
26
+ * @remarks
27
+ * This is true if the schema has `nullable: true` or if its `type` includes `"null"`.
28
+ *
29
+ * @param schema - The JSON Schema fragment to check.
30
+ * @returns `true` if the schema accepts `null`, otherwise `false`.
31
+ */
32
+ function isSchemaNullable(schema) {
33
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(schema)) return false;
34
+ if (schema.nullable === true) return true;
35
+ return readSchemaTypes(schema).includes("null");
36
+ }
37
+ /**
38
+ * Returns whether an object property is optional (not listed in `required`).
39
+ *
40
+ * @remarks
41
+ * In JSON Schema, object properties are optional by default unless they are listed in the `required` array of the parent schema. This function checks whether a given property name is not included in the `required` array of its parent schema, indicating that it is optional.
42
+ *
43
+ * @param parent - The parent JSON Schema object containing the property.
44
+ * @param propertyName - The name of the property to check for optionality.
45
+ * @returns `true` if the property is optional, otherwise `false`.
46
+ */
47
+ function isPropertyOptional(parent, propertyName) {
48
+ return !(parent.required ?? []).includes(propertyName);
49
+ }
50
+ /**
51
+ * Normalizes the JSON Schema `type` keyword to a string array.
52
+ *
53
+ * @remarks
54
+ * This function ensures that the `type` keyword of a JSON Schema fragment is always represented as an array of strings, even if it was originally defined as a single string. This normalization simplifies type checking and processing of JSON Schemas by providing a consistent format for the `type` information.
55
+ *
56
+ * @param schema - The JSON Schema fragment to read types from.
57
+ * @returns An array of JSON Schema primitive type names defined in the `type` keyword, or an empty array if no valid types are found.
58
+ */
59
+ function readSchemaTypes(schema) {
60
+ if (Array.isArray(schema?.type)) return schema.type.filter(_stryke_type_checks.isSetString);
61
+ if ((0, _stryke_type_checks.isSetString)(schema?.type)) return [schema.type];
62
+ return [];
63
+ }
64
+ /**
65
+ * Returns the primary non-null JSON Schema type name for a fragment.
66
+ *
67
+ * @param schema - The JSON Schema fragment to check.
68
+ * @returns The primary non-null JSON Schema type name, or `undefined` if none is found.
69
+ */
70
+ function getPrimarySchemaType(schema) {
71
+ if (!(0, _stryke_type_checks_is_set_object.isSetObject)(schema)) return;
72
+ return readSchemaTypes(schema).find((type) => type !== "null");
73
+ }
74
+
75
+ //#endregion
76
+ exports.applySchemaMetadata = applySchemaMetadata;
77
+ exports.getPrimarySchemaType = getPrimarySchemaType;
78
+ exports.isPropertyOptional = isPropertyOptional;
79
+ exports.isSchemaNullable = isSchemaNullable;
80
+ exports.readSchemaTypes = readSchemaTypes;