@geekmidas/schema 9.0.2 → 10.0.0-alpha.0

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/src/conversion.ts DELETED
@@ -1,220 +0,0 @@
1
- import type { StandardSchemaV1 } from '@standard-schema/spec';
2
-
3
- export enum SchemaVendor {
4
- zod = 'zod',
5
- valibot = 'valibot',
6
- }
7
-
8
- export type VendorConvertor = (schema: any) => Promise<any>;
9
- export type VendorConvertors = Record<SchemaVendor, VendorConvertor>;
10
-
11
- function isSchemaVendor(vendor?: string): vendor is SchemaVendor {
12
- if (!vendor) {
13
- return false;
14
- }
15
-
16
- return Object.values(SchemaVendor).includes(vendor as SchemaVendor);
17
- }
18
-
19
- export const StandardSchemaJsonSchema: VendorConvertors = {
20
- zod: async (schema): Promise<any> => {
21
- try {
22
- const { z } = await import('zod/v4').catch(() => ({ z: {} }));
23
-
24
- if ('toJSONSchema' in z && typeof z.toJSONSchema === 'function') {
25
- return z.toJSONSchema(schema);
26
- }
27
- const { zodToJsonSchema } = await import('zod-to-json-schema');
28
-
29
- const result = zodToJsonSchema(schema, {
30
- removeAdditionalStrategy: 'strict',
31
- });
32
-
33
- return result;
34
- } catch {
35
- // Fallback to basic conversion if zod-to-json-schema is not available
36
- return { type: 'object' };
37
- }
38
- },
39
- valibot: async (schema): Promise<any> => {
40
- const { toJsonSchema } = await import('@valibot/to-json-schema');
41
- return toJsonSchema(schema as any);
42
- },
43
- };
44
-
45
- function extractAndConvertDefs(
46
- jsonSchema: any,
47
- componentCollector?: {
48
- addSchema(id: string, schema: any): void;
49
- getReference(id: string): { $ref: string };
50
- },
51
- ): any {
52
- if (!jsonSchema || typeof jsonSchema !== 'object') {
53
- return jsonSchema;
54
- }
55
-
56
- // Process the schema recursively to update references
57
- const processSchema = (schema: any): any => {
58
- if (!schema || typeof schema !== 'object') {
59
- return schema;
60
- }
61
-
62
- // Handle $ref
63
- if (schema.$ref && typeof schema.$ref === 'string') {
64
- // Convert #/$defs/X to #/components/schemas/X
65
- if (schema.$ref.startsWith('#/$defs/')) {
66
- const refName = schema.$ref.replace('#/$defs/', '');
67
- return componentCollector
68
- ? componentCollector.getReference(refName)
69
- : schema;
70
- }
71
- return schema;
72
- }
73
-
74
- // Handle arrays
75
- if (Array.isArray(schema)) {
76
- return schema.map(processSchema);
77
- }
78
-
79
- // Process all properties recursively
80
- const processed: any = {};
81
- for (const [key, value] of Object.entries(schema)) {
82
- if (key === '$defs') {
83
- // Skip $defs as they've been extracted
84
- continue;
85
- }
86
- processed[key] = processSchema(value);
87
- }
88
- return processed;
89
- };
90
-
91
- // Extract $defs if present
92
- if (jsonSchema.$defs && componentCollector) {
93
- for (const [defName, defSchema] of Object.entries(jsonSchema.$defs)) {
94
- // Process the definition recursively to handle nested $refs
95
- const processedDefSchema = processSchema(defSchema);
96
- // Add each definition to the component collector
97
- componentCollector.addSchema(defName, processedDefSchema);
98
- }
99
- }
100
-
101
- // Process the schema and remove $defs
102
- const { $defs, ...schemaWithoutDefs } = jsonSchema;
103
- return processSchema(schemaWithoutDefs);
104
- }
105
-
106
- export async function convertStandardSchemaToJsonSchema(
107
- schema?: StandardSchemaV1,
108
- componentCollector?: {
109
- addSchema(id: string, schema: any): void;
110
- getReference(id: string): { $ref: string };
111
- },
112
- ): Promise<any> {
113
- if (!schema) {
114
- return undefined;
115
- }
116
-
117
- const vendor = schema['~standard']?.vendor;
118
- if (!isSchemaVendor(vendor)) {
119
- throw new Error(
120
- `Unsupported or missing vendor "${vendor}" for Standard Schema. Supported vendors are: ${Object.keys(StandardSchemaJsonSchema).join(', ')}`,
121
- );
122
- }
123
-
124
- const toJSONSchema = StandardSchemaJsonSchema[vendor];
125
- const jsonSchema = await toJSONSchema(schema);
126
-
127
- // Extract and convert $defs to components
128
- return extractAndConvertDefs(jsonSchema, componentCollector);
129
- }
130
-
131
- export async function getZodMetadata(
132
- schema: StandardSchemaV1,
133
- ): Promise<SchemaMeta | undefined> {
134
- const { ZodObject } = await import('zod/v4');
135
-
136
- if (schema instanceof ZodObject) {
137
- return schema.meta();
138
- }
139
-
140
- return undefined;
141
- }
142
-
143
- /**
144
- * Return JSON Schema for every schema registered in zod v4's global registry
145
- * via `.meta({ id })`. Returns an empty object when zod v4 is unavailable or
146
- * no schemas are registered.
147
- *
148
- * `unrepresentable: 'any'` keeps a single unrepresentable schema from
149
- * collapsing the whole result.
150
- */
151
- export async function getRegisteredZodJsonSchemas(): Promise<
152
- Record<string, any>
153
- > {
154
- try {
155
- const { z } = await import('zod/v4').catch(() => ({ z: null as any }));
156
- if (!z?.toJSONSchema || !z.globalRegistry) {
157
- return {};
158
- }
159
- const result = z.toJSONSchema(z.globalRegistry, {
160
- unrepresentable: 'any',
161
- });
162
- return (result?.schemas ?? {}) as Record<string, any>;
163
- } catch {
164
- return {};
165
- }
166
- }
167
-
168
- export async function getSchemaMetadata(
169
- schema: StandardSchemaV1,
170
- ): Promise<SchemaMeta | undefined> {
171
- const vendor = schema['~standard']?.vendor;
172
-
173
- if (vendor === 'zod') {
174
- return getZodMetadata(schema);
175
- }
176
-
177
- return undefined;
178
- }
179
-
180
- interface SchemaMeta {
181
- id?: string;
182
- }
183
-
184
- export async function convertSchemaWithComponents(
185
- schema: StandardSchemaV1 | undefined,
186
- componentCollector?: {
187
- addSchema(id: string, schema: any): void;
188
- getReference(id: string): { $ref: string };
189
- },
190
- ): Promise<any> {
191
- if (!schema) {
192
- return undefined;
193
- }
194
-
195
- // Convert to JSON Schema with component collector to handle $defs
196
- const jsonSchema = await convertStandardSchemaToJsonSchema(
197
- schema,
198
- componentCollector,
199
- );
200
-
201
- if (!componentCollector) {
202
- return jsonSchema;
203
- }
204
-
205
- // Check if this schema has metadata with an ID
206
- const metadata = await getSchemaMetadata(schema);
207
-
208
- // Also check if the JSON Schema itself has an id field (from Zod's meta)
209
- const schemaId = metadata?.id || jsonSchema?.id;
210
-
211
- if (schemaId) {
212
- // Remove the id from the schema before adding to components
213
- const { id, ...schemaWithoutId } = jsonSchema;
214
- // Add this schema to components and return a reference
215
- componentCollector.addSchema(schemaId, schemaWithoutId);
216
- return componentCollector.getReference(schemaId);
217
- }
218
-
219
- return jsonSchema;
220
- }
package/src/index.ts DELETED
@@ -1,15 +0,0 @@
1
- // Re-export conversion utilities for convenience
2
- export {
3
- convertSchemaWithComponents,
4
- convertStandardSchemaToJsonSchema,
5
- } from './conversion';
6
- export type { ComponentCollector, OpenApiSchemaOptions } from './openapi';
7
-
8
- // Re-export OpenAPI utilities for convenience
9
- export { buildOpenApiSchema, createComponentCollector } from './openapi';
10
- export type {
11
- ComposableStandardSchema,
12
- InferComposableStandardSchema,
13
- InferStandardSchema,
14
- InferStandardSchemaInput,
15
- } from './types';
package/src/openapi.ts DELETED
@@ -1,75 +0,0 @@
1
- import type { OpenAPIV3_1 } from 'openapi-types';
2
-
3
- export interface OpenApiSchemaOptions {
4
- title?: string;
5
- version?: string;
6
- description?: string;
7
- }
8
-
9
- export interface ComponentCollector {
10
- schemas: Record<string, OpenAPIV3_1.SchemaObject>;
11
- addSchema(id: string, schema: OpenAPIV3_1.SchemaObject): void;
12
- getReference(id: string): OpenAPIV3_1.ReferenceObject;
13
- }
14
-
15
- export function createComponentCollector(): ComponentCollector {
16
- const schemas: Record<string, OpenAPIV3_1.SchemaObject> = {};
17
-
18
- return {
19
- schemas,
20
- addSchema(id: string, schema: OpenAPIV3_1.SchemaObject) {
21
- schemas[id] = schema;
22
- },
23
- getReference(id: string): OpenAPIV3_1.ReferenceObject {
24
- return { $ref: `#/components/schemas/${id}` };
25
- },
26
- };
27
- }
28
-
29
- /**
30
- * Builds OpenAPI 3.1 schema from an array of endpoints.
31
- *
32
- * Note: This function requires endpoints with toOpenApi3Route method.
33
- * The actual implementation is in @geekmidas/constructs to avoid circular dependencies.
34
- */
35
- export async function buildOpenApiSchema(
36
- endpoints: Array<{
37
- toOpenApi3Route(collector?: ComponentCollector): Promise<any>;
38
- }>,
39
- options: OpenApiSchemaOptions = {},
40
- ): Promise<OpenAPIV3_1.Document> {
41
- const { title = 'API', version = '1.0.0', description } = options;
42
- const paths: OpenAPIV3_1.PathsObject = {};
43
- const componentCollector = createComponentCollector();
44
-
45
- for (const endpoint of endpoints) {
46
- const route = await endpoint.toOpenApi3Route(componentCollector);
47
-
48
- // Merge the route into the paths object
49
- for (const [path, methods] of Object.entries(route)) {
50
- if (!paths[path]) {
51
- paths[path] = {};
52
- }
53
- Object.assign(paths[path], methods);
54
- }
55
- }
56
-
57
- const doc: OpenAPIV3_1.Document = {
58
- openapi: '3.0.0',
59
- info: {
60
- title,
61
- version,
62
- ...(description && { description }),
63
- },
64
- paths,
65
- };
66
-
67
- // Add components if any schemas were collected
68
- if (Object.keys(componentCollector.schemas).length > 0) {
69
- doc.components = {
70
- schemas: componentCollector.schemas,
71
- };
72
- }
73
-
74
- return doc;
75
- }
package/src/parser.ts DELETED
@@ -1,30 +0,0 @@
1
- import type { StandardSchemaV1 } from '@standard-schema/spec';
2
- import type { InferStandardSchema } from './types';
3
-
4
- /**
5
- * Validates data against a StandardSchema.
6
- *
7
- * @param schema - The StandardSchema to validate against
8
- * @param data - The data to validate
9
- * @returns Validation result with value or issues
10
- */
11
- export function validate<T extends StandardSchemaV1>(schema: T, data: unknown) {
12
- return schema['~standard'].validate(data);
13
- }
14
-
15
- export async function parseSchema<T extends StandardSchemaV1>(
16
- schema: T,
17
- data: unknown,
18
- ): Promise<InferStandardSchema<T>> {
19
- if (!schema) {
20
- return undefined as InferStandardSchema<T>;
21
- }
22
-
23
- const parsed = await validate(schema as unknown as StandardSchemaV1, data);
24
-
25
- if (parsed.issues) {
26
- throw parsed.issues;
27
- }
28
-
29
- return parsed.value as InferStandardSchema<T>;
30
- }
package/src/types.ts DELETED
@@ -1,37 +0,0 @@
1
- import type { StandardSchemaV1 } from '@standard-schema/spec';
2
-
3
- export type InferStandardSchema<T> = T extends StandardSchemaV1
4
- ? StandardSchemaV1.InferOutput<T>
5
- : never;
6
-
7
- /**
8
- * The *input* type a Standard Schema accepts (before any transform/coercion),
9
- * as opposed to {@link InferStandardSchema} which is the output type.
10
- *
11
- * Use this for the value a producer must HAND TO the schema (e.g. an endpoint
12
- * handler's return that will be parsed by its output schema): the schema may
13
- * coerce it (a `Date` → an ISO `string`, a default applied, etc.), so the
14
- * producer should be allowed to supply the looser input type while consumers
15
- * still see the narrower output type.
16
- */
17
- export type InferStandardSchemaInput<T> = T extends StandardSchemaV1
18
- ? StandardSchemaV1.InferInput<T>
19
- : never;
20
-
21
- export type ComposableStandardSchema =
22
- | StandardSchemaV1
23
- | {
24
- [key: string]: StandardSchemaV1 | undefined;
25
- };
26
-
27
- export type InferComposableStandardSchema<T> = T extends StandardSchemaV1
28
- ? StandardSchemaV1.InferOutput<T>
29
- : T extends { [key: string]: StandardSchemaV1 | undefined }
30
- ? {
31
- [K in keyof T as T[K] extends StandardSchemaV1
32
- ? K
33
- : never]: T[K] extends StandardSchemaV1
34
- ? StandardSchemaV1.InferOutput<T[K]>
35
- : never;
36
- }
37
- : {};
package/tsconfig.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.base.json",
3
- "compilerOptions": {
4
- "outDir": "./dist",
5
- "rootDir": "./src",
6
- "composite": true
7
- },
8
- "include": ["src/**/*"]
9
- }
package/tsdown.config.ts DELETED
@@ -1,5 +0,0 @@
1
- import { defineConfig } from 'tsdown';
2
-
3
- export default defineConfig({
4
- external: ['@valibot/to-json-schema', 'zod', 'zod-to-json-schema'],
5
- });