@dynz/to-json-schema 0.0.1

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/LICENSE.md ADDED
@@ -0,0 +1,65 @@
1
+ Business Source License
2
+ =======================
3
+
4
+ License text copyright (c) 2020 MariaDB Corporation Ab, All Rights Reserved.
5
+ “Business Source License” is a trademark of MariaDB Corporation Ab.
6
+
7
+ Parameters
8
+
9
+ Licensor: Ruben van Rooij
10
+ Licensed Works: Dynz. The Licensed Work is
11
+ (c) Ruben van Rooij
12
+ Additional Use Grant: You may make use of the Licensed Work strictly for
13
+ evaluation and/or non-production use only. Your use
14
+ does not include offering the Licensed Work to third
15
+ parties on a hosted or embedded basis.
16
+ Change Date: Four years from the date the Licensed Work is published
17
+ Change License: Apache-2.0
18
+
19
+ For information about commercial licensing arrangements for the Licensed Work,
20
+ please contact ruben@dynz.io.
21
+
22
+ Notice
23
+
24
+ Business Source License 1.1
25
+
26
+ Terms
27
+
28
+ The Licensor hereby grants you the right to copy, modify, create derivative
29
+ works, redistribute, and make non-production use of the Licensed Work. The
30
+ Licensor may make an Additional Use Grant, above, permitting limited production use.
31
+
32
+ Effective on the Change Date, or the fourth anniversary of the first publicly
33
+ available distribution of a specific version of the Licensed Work under this
34
+ License, whichever comes first, the Licensor hereby grants you rights under
35
+ the terms of the Change License, and the rights granted in the paragraph
36
+ above terminate.
37
+
38
+ If your use of the Licensed Work does not comply with the requirements
39
+ currently in effect as described in this License, you must purchase a
40
+ commercial license from the Licensor, its affiliated entities, or authorized
41
+ resellers, or you must refrain from using the Licensed Work.
42
+
43
+ All copies of the original and modified Licensed Work, and derivative works
44
+ of the Licensed Work, are subject to this License. This License applies
45
+ separately for each version of the Licensed Work and the Change Date may vary
46
+ for each version of the Licensed Work released by Licensor.
47
+
48
+ You must conspicuously display this License on each original or modified copy
49
+ of the Licensed Work. If you receive the Licensed Work in original or
50
+ modified form from a third party, the terms and conditions set forth in this
51
+ License apply to your use of that work.
52
+
53
+ Any use of the Licensed Work in violation of this License will automatically
54
+ terminate your rights under this License for the current and all other
55
+ versions of the Licensed Work.
56
+
57
+ This License does not grant you any right in any trademark or logo of
58
+ Licensor or its affiliates (provided that you may use a trademark or logo of
59
+ Licensor as expressly required by this License).
60
+
61
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
62
+ AN "AS IS" BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
63
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
64
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
65
+ TITLE.
package/dist/index.cjs ADDED
@@ -0,0 +1,375 @@
1
+ let dynz = require("dynz");
2
+
3
+ //#region src/report-issue.ts
4
+ /**
5
+ * Reports an unsupported or unresolvable conversion according to the
6
+ * configured error mode: throws, warns via `console.warn`, or is a no-op.
7
+ */
8
+ function reportIssue(context, message) {
9
+ if (context.errorMode === "throw") throw new Error(message);
10
+ if (context.errorMode === "warn") console.warn(`[@dynz/to-json-schema] ${message}`);
11
+ }
12
+
13
+ //#endregion
14
+ //#region src/resolve-static.ts
15
+ /**
16
+ * Attempts to extract a literal value from a rule parameter. Only values
17
+ * wrapped with `v()`/`val()`/`st()` (i.e. `{ type: "st" }`) are statically
18
+ * known — references, predicates and transformers depend on runtime data
19
+ * and cannot be represented in a JSON Schema document.
20
+ */
21
+ function resolveStatic(value) {
22
+ if (value !== void 0 && typeof value === "object" && "type" in value && value.type === "st") return {
23
+ ok: true,
24
+ value: value.value
25
+ };
26
+ return { ok: false };
27
+ }
28
+
29
+ //#endregion
30
+ //#region src/convert-rules.ts
31
+ function escapeRegExp(value) {
32
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
+ }
34
+ /**
35
+ * Writes a keyword, preserving whatever constraint is already there.
36
+ *
37
+ * Several dynz rules map onto the same JSON Schema keyword: two `regex` rules both want
38
+ * `pattern`, `one_of` wants the `enum` an options schema has already produced,
39
+ * `not_includes` and `not_one_of` both want `not`. A plain assignment would silently drop
40
+ * the constraint that got there first, so a second writer is moved into `allOf` — where
41
+ * both still have to hold.
42
+ */
43
+ function setKeyword(jsonSchema, keyword, value) {
44
+ if (jsonSchema[keyword] === void 0) {
45
+ jsonSchema[keyword] = value;
46
+ return;
47
+ }
48
+ jsonSchema.allOf = [...jsonSchema.allOf ?? [], { [keyword]: value }];
49
+ }
50
+ /**
51
+ * Applies a dynz rule to a JSON Schema in place. Rules whose value can't be
52
+ * statically resolved (references, predicates, transformers) or that have
53
+ * no JSON Schema equivalent are skipped and reported via `reportIssue`.
54
+ */
55
+ function applyRule(jsonSchema, rule, schemaType, context) {
56
+ switch (rule.type) {
57
+ case "min": {
58
+ const min = resolveStatic(rule.min);
59
+ if (min.ok) setKeyword(jsonSchema, "minimum", min.value);
60
+ else reportIssue(context, `"min" rule with a non-static value cannot be converted to JSON Schema.`);
61
+ break;
62
+ }
63
+ case "max": {
64
+ const max = resolveStatic(rule.max);
65
+ if (max.ok) setKeyword(jsonSchema, "maximum", max.value);
66
+ else reportIssue(context, `"max" rule with a non-static value cannot be converted to JSON Schema.`);
67
+ break;
68
+ }
69
+ case "min_length": {
70
+ const min = resolveStatic(rule.min);
71
+ if (min.ok) if (schemaType === "array") setKeyword(jsonSchema, "minItems", min.value);
72
+ else setKeyword(jsonSchema, "minLength", min.value);
73
+ else reportIssue(context, `"min_length" rule with a non-static value cannot be converted to JSON Schema.`);
74
+ break;
75
+ }
76
+ case "max_length": {
77
+ const max = resolveStatic(rule.max);
78
+ if (max.ok) if (schemaType === "array") setKeyword(jsonSchema, "maxItems", max.value);
79
+ else setKeyword(jsonSchema, "maxLength", max.value);
80
+ else reportIssue(context, `"max_length" rule with a non-static value cannot be converted to JSON Schema.`);
81
+ break;
82
+ }
83
+ case "min_entries": {
84
+ const min = resolveStatic(rule.min);
85
+ if (min.ok) setKeyword(jsonSchema, "minProperties", min.value);
86
+ else reportIssue(context, `"min_entries" rule with a non-static value cannot be converted to JSON Schema.`);
87
+ break;
88
+ }
89
+ case "max_entries": {
90
+ const max = resolveStatic(rule.max);
91
+ if (max.ok) setKeyword(jsonSchema, "maxProperties", max.value);
92
+ else reportIssue(context, `"max_entries" rule with a non-static value cannot be converted to JSON Schema.`);
93
+ break;
94
+ }
95
+ case "max_precision": {
96
+ const maxPrecision = resolveStatic(rule.maxPrecision);
97
+ if (maxPrecision.ok) setKeyword(jsonSchema, "multipleOf", 1 / 10 ** maxPrecision.value);
98
+ else reportIssue(context, `"max_precision" rule with a non-static value cannot be converted to JSON Schema.`);
99
+ break;
100
+ }
101
+ case "regex":
102
+ setKeyword(jsonSchema, "pattern", rule.regex);
103
+ if (rule.flags) reportIssue(context, `"regex" rule flags ("${rule.flags}") cannot be represented in JSON Schema's "pattern" keyword and were ignored.`);
104
+ break;
105
+ case "email":
106
+ setKeyword(jsonSchema, "format", "email");
107
+ break;
108
+ case "is_numeric":
109
+ setKeyword(jsonSchema, "pattern", "^[+-]?\\d+(\\.\\d+)?$");
110
+ break;
111
+ case "equals": {
112
+ const equals = resolveStatic(rule.equals);
113
+ if (equals.ok) setKeyword(jsonSchema, "const", equals.value);
114
+ else reportIssue(context, `"equals" rule with a non-static value cannot be converted to JSON Schema.`);
115
+ break;
116
+ }
117
+ case "includes": {
118
+ const includes = resolveStatic(rule.includes);
119
+ if (!includes.ok) {
120
+ reportIssue(context, `"includes" rule with a non-static value cannot be converted to JSON Schema.`);
121
+ break;
122
+ }
123
+ if (schemaType === "array") setKeyword(jsonSchema, "contains", { const: includes.value });
124
+ else setKeyword(jsonSchema, "pattern", escapeRegExp(String(includes.value)));
125
+ break;
126
+ }
127
+ case "not_includes": {
128
+ const notIncludes = resolveStatic(rule.notIncludes);
129
+ if (!notIncludes.ok) {
130
+ reportIssue(context, `"not_includes" rule with a non-static value cannot be converted to JSON Schema.`);
131
+ break;
132
+ }
133
+ setKeyword(jsonSchema, "not", schemaType === "array" ? { contains: { const: notIncludes.value } } : { pattern: escapeRegExp(String(notIncludes.value)) });
134
+ break;
135
+ }
136
+ case "one_of": {
137
+ const values = [];
138
+ for (const value of rule.values) {
139
+ const resolved = resolveStatic(value);
140
+ if (!resolved.ok) {
141
+ reportIssue(context, `"one_of" rule with a non-static value cannot be converted to JSON Schema.`);
142
+ return;
143
+ }
144
+ values.push(resolved.value);
145
+ }
146
+ setKeyword(jsonSchema, "enum", values);
147
+ break;
148
+ }
149
+ case "not_one_of": {
150
+ const values = [];
151
+ for (const value of rule.values) {
152
+ const resolved = resolveStatic(value);
153
+ if (!resolved.ok) {
154
+ reportIssue(context, `"not_one_of" rule with a non-static value cannot be converted to JSON Schema.`);
155
+ return;
156
+ }
157
+ values.push(resolved.value);
158
+ }
159
+ setKeyword(jsonSchema, "not", { enum: values });
160
+ break;
161
+ }
162
+ case "mime_type": {
163
+ const mimeType = resolveStatic(rule.mimeType);
164
+ if (!mimeType.ok) {
165
+ reportIssue(context, `"mime_type" rule with a non-static value cannot be converted to JSON Schema.`);
166
+ break;
167
+ }
168
+ if (typeof mimeType.value === "string") setKeyword(jsonSchema, "contentMediaType", mimeType.value);
169
+ else if (Array.isArray(mimeType.value) && mimeType.value.length === 1) setKeyword(jsonSchema, "contentMediaType", mimeType.value[0]);
170
+ else reportIssue(context, `"mime_type" rule with multiple mime types has no JSON Schema equivalent.`);
171
+ break;
172
+ }
173
+ case "min_date":
174
+ case "max_date":
175
+ case "before":
176
+ case "after":
177
+ reportIssue(context, `"${rule.type}" rule has no JSON Schema equivalent (date comparisons aren't representable).`);
178
+ break;
179
+ case "min_size":
180
+ case "max_size":
181
+ reportIssue(context, `"${rule.type}" rule has no JSON Schema equivalent (byte-size constraints aren't representable).`);
182
+ break;
183
+ case "custom":
184
+ reportIssue(context, `"custom" rule "${rule.name}" has no JSON Schema equivalent.`);
185
+ break;
186
+ case "conditional":
187
+ reportIssue(context, `"conditional" rule has no JSON Schema equivalent.`);
188
+ break;
189
+ default: reportIssue(context, `Unknown rule cannot be converted to JSON Schema.`);
190
+ }
191
+ }
192
+ function applyRules(jsonSchema, rules, schemaType, context) {
193
+ for (const rule of rules ?? []) applyRule(jsonSchema, rule, schemaType, context);
194
+ }
195
+
196
+ //#endregion
197
+ //#region src/convert-schema.ts
198
+ function isMandatory(schema) {
199
+ const isIncluded = schema.included === void 0 || schema.included === true;
200
+ const isRequired = schema.required === void 0 || schema.required === true;
201
+ return isIncluded && isRequired;
202
+ }
203
+ function jsonTypeOf(value) {
204
+ return typeof value;
205
+ }
206
+ function applyEnumValues(jsonSchema, values) {
207
+ jsonSchema.enum = values;
208
+ const types = Array.from(new Set(values.map(jsonTypeOf)));
209
+ if (types.length === 1) jsonSchema.type = types[0];
210
+ else if (types.length > 1) jsonSchema.type = types;
211
+ }
212
+ function collectOptionValues(options, context) {
213
+ const values = [];
214
+ const visit = (option) => {
215
+ if (typeof option !== "object") {
216
+ values.push(option);
217
+ return;
218
+ }
219
+ if (option.enabled === false) return;
220
+ if (typeof option.enabled === "object") reportIssue(context, `An "options" entry has a predicate-based "enabled" flag; whether it's enabled can't be determined statically, so it was included in the JSON Schema "enum" anyway.`);
221
+ visit(option.value);
222
+ };
223
+ for (const option of options) visit(option);
224
+ return values;
225
+ }
226
+ function isSchema(value) {
227
+ return typeof value === "object" && value !== null && "type" in value;
228
+ }
229
+ function shouldOmitField(schema, context) {
230
+ if (schema.included === false) return true;
231
+ return context.mode === "input" && schema.type === dynz.SchemaType.EXPRESSION;
232
+ }
233
+ function applyPrivacyWrapper(schema, innerSchema) {
234
+ if (schema.private !== true) return innerSchema;
235
+ return { oneOf: [{
236
+ type: "object",
237
+ properties: {
238
+ state: { const: "plain" },
239
+ value: innerSchema
240
+ },
241
+ required: ["state"]
242
+ }, {
243
+ type: "object",
244
+ properties: {
245
+ state: { const: "masked" },
246
+ value: { type: "string" }
247
+ },
248
+ required: ["state", "value"]
249
+ }] };
250
+ }
251
+ function applyDefault(schema, jsonSchema) {
252
+ if (schema.default === void 0) return;
253
+ jsonSchema.default = schema.default instanceof Date ? schema.default.toISOString() : schema.default;
254
+ }
255
+ /**
256
+ * Converts a dynz schema to a JSON Schema (2020-12) document. Rule values
257
+ * and schema kinds without a JSON Schema equivalent are handled per
258
+ * `context.errorMode`.
259
+ */
260
+ function convertSchema(schema, context) {
261
+ const jsonSchema = convertSchemaKind(schema, context);
262
+ applyDefault(schema, jsonSchema);
263
+ return applyPrivacyWrapper(schema, jsonSchema);
264
+ }
265
+ function convertSchemaKind(schema, context) {
266
+ switch (schema.type) {
267
+ case dynz.SchemaType.STRING: {
268
+ const jsonSchema = { type: "string" };
269
+ applyRules(jsonSchema, schema.rules, schema.type, context);
270
+ return jsonSchema;
271
+ }
272
+ case dynz.SchemaType.NUMBER: {
273
+ const jsonSchema = { type: "number" };
274
+ applyRules(jsonSchema, schema.rules, schema.type, context);
275
+ return jsonSchema;
276
+ }
277
+ case dynz.SchemaType.BOOLEAN: {
278
+ const jsonSchema = { type: "boolean" };
279
+ applyRules(jsonSchema, schema.rules, schema.type, context);
280
+ return jsonSchema;
281
+ }
282
+ case dynz.SchemaType.DATE: {
283
+ const jsonSchema = {
284
+ type: "string",
285
+ format: "date-time"
286
+ };
287
+ applyRules(jsonSchema, schema.rules, schema.type, context);
288
+ return jsonSchema;
289
+ }
290
+ case dynz.SchemaType.LITERAL: return { const: schema.value };
291
+ case dynz.SchemaType.ENUM: {
292
+ const jsonSchema = {};
293
+ applyEnumValues(jsonSchema, Object.values(schema.enum));
294
+ applyRules(jsonSchema, schema.rules, schema.type, context);
295
+ return jsonSchema;
296
+ }
297
+ case dynz.SchemaType.OPTIONS: {
298
+ const jsonSchema = {};
299
+ applyEnumValues(jsonSchema, collectOptionValues(schema.options, context));
300
+ applyRules(jsonSchema, schema.rules, schema.type, context);
301
+ return jsonSchema;
302
+ }
303
+ case dynz.SchemaType.FILE: {
304
+ const jsonSchema = { type: "string" };
305
+ applyRules(jsonSchema, schema.rules, schema.type, context);
306
+ return jsonSchema;
307
+ }
308
+ case dynz.SchemaType.EXPRESSION: return {};
309
+ case dynz.SchemaType.ARRAY: {
310
+ const jsonSchema = {
311
+ type: "array",
312
+ items: convertSchema(schema.schema, context)
313
+ };
314
+ applyRules(jsonSchema, schema.rules, schema.type, context);
315
+ return jsonSchema;
316
+ }
317
+ case dynz.SchemaType.OBJECT: {
318
+ const properties = {};
319
+ const required = [];
320
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
321
+ if (shouldOmitField(fieldSchema, context)) continue;
322
+ properties[key] = convertSchema(fieldSchema, context);
323
+ if (isMandatory(fieldSchema)) required.push(key);
324
+ }
325
+ const jsonSchema = {
326
+ type: "object",
327
+ properties
328
+ };
329
+ if (required.length > 0) jsonSchema.required = required;
330
+ applyRules(jsonSchema, schema.rules, schema.type, context);
331
+ return jsonSchema;
332
+ }
333
+ case dynz.SchemaType.DISCRIMINATED_UNION: return { oneOf: schema.schemas.map((member) => {
334
+ const properties = { [schema.key]: { const: member[schema.key] } };
335
+ const required = [schema.key];
336
+ for (const [key, value] of Object.entries(member)) {
337
+ if (key === schema.key || !isSchema(value) || shouldOmitField(value, context)) continue;
338
+ properties[key] = convertSchema(value, context);
339
+ if (isMandatory(value)) required.push(key);
340
+ }
341
+ return {
342
+ type: "object",
343
+ properties,
344
+ required
345
+ };
346
+ }) };
347
+ default:
348
+ reportIssue(context, `Unknown schema type cannot be converted to JSON Schema.`);
349
+ return {};
350
+ }
351
+ }
352
+
353
+ //#endregion
354
+ //#region src/to-standard-json-schema.ts
355
+ /**
356
+ * Converts a dynz schema to a standard JSON Schema (2020-12) document.
357
+ *
358
+ * Rule values that depend on runtime data (references, predicates,
359
+ * transformers) and schema kinds without a JSON Schema equivalent are
360
+ * handled according to `config.errorMode` (default `"warn"`). Whether
361
+ * `expression` fields are included is controlled by `config.mode`
362
+ * (default `"input"`, which omits them).
363
+ */
364
+ function toStandardJsonSchema(schema, config = {}) {
365
+ return {
366
+ $schema: "https://json-schema.org/draft/2020-12/schema",
367
+ ...convertSchema(schema, {
368
+ errorMode: config.errorMode ?? "warn",
369
+ mode: config.mode ?? "input"
370
+ })
371
+ };
372
+ }
373
+
374
+ //#endregion
375
+ exports.toStandardJsonSchema = toStandardJsonSchema;
@@ -0,0 +1,73 @@
1
+ import { Schema } from "dynz";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * A JSON Schema (2020-12) document. Loosely typed since the shape varies
7
+ * significantly by keyword combination.
8
+ */
9
+ interface JsonSchema {
10
+ $schema?: string;
11
+ type?: string | string[];
12
+ properties?: Record<string, JsonSchema>;
13
+ required?: string[];
14
+ items?: JsonSchema;
15
+ enum?: unknown[];
16
+ const?: unknown;
17
+ minimum?: number;
18
+ maximum?: number;
19
+ minLength?: number;
20
+ maxLength?: number;
21
+ minItems?: number;
22
+ maxItems?: number;
23
+ minProperties?: number;
24
+ maxProperties?: number;
25
+ pattern?: string;
26
+ format?: string;
27
+ multipleOf?: number;
28
+ contentMediaType?: string;
29
+ contains?: JsonSchema;
30
+ not?: JsonSchema;
31
+ oneOf?: JsonSchema[];
32
+ allOf?: JsonSchema[];
33
+ default?: unknown;
34
+ [key: string]: unknown;
35
+ }
36
+ /**
37
+ * The policy for handling schema kinds/rule values that cannot be
38
+ * represented in JSON Schema.
39
+ */
40
+ type ErrorMode = "throw" | "warn" | "ignore";
41
+ /**
42
+ * Whether the conversion targets the data a consumer sends in (`"input"`)
43
+ * or the data dynz produces after validation (`"output"`). `expression`
44
+ * schemas are computed/derived values that are never part of the input, so
45
+ * in `"input"` mode they're silently removed from the generated schema; in
46
+ * `"output"` mode they're included (using their best-effort mapping).
47
+ */
48
+ type ConversionMode = "input" | "output";
49
+ interface ConversionConfig {
50
+ /**
51
+ * Policy for handling unsupported/unresolvable rule values and schema
52
+ * kinds. Defaults to `"warn"`.
53
+ */
54
+ errorMode?: ErrorMode;
55
+ /**
56
+ * Whether to convert for input or output data. Defaults to `"input"`.
57
+ */
58
+ mode?: ConversionMode;
59
+ }
60
+ //#endregion
61
+ //#region src/to-standard-json-schema.d.ts
62
+ /**
63
+ * Converts a dynz schema to a standard JSON Schema (2020-12) document.
64
+ *
65
+ * Rule values that depend on runtime data (references, predicates,
66
+ * transformers) and schema kinds without a JSON Schema equivalent are
67
+ * handled according to `config.errorMode` (default `"warn"`). Whether
68
+ * `expression` fields are included is controlled by `config.mode`
69
+ * (default `"input"`, which omits them).
70
+ */
71
+ declare function toStandardJsonSchema<T extends Schema>(schema: T, config?: ConversionConfig): JsonSchema;
72
+ //#endregion
73
+ export { type ConversionConfig, type ErrorMode, type JsonSchema, toStandardJsonSchema };
@@ -0,0 +1,73 @@
1
+ import { Schema } from "dynz";
2
+
3
+ //#region src/types.d.ts
4
+
5
+ /**
6
+ * A JSON Schema (2020-12) document. Loosely typed since the shape varies
7
+ * significantly by keyword combination.
8
+ */
9
+ interface JsonSchema {
10
+ $schema?: string;
11
+ type?: string | string[];
12
+ properties?: Record<string, JsonSchema>;
13
+ required?: string[];
14
+ items?: JsonSchema;
15
+ enum?: unknown[];
16
+ const?: unknown;
17
+ minimum?: number;
18
+ maximum?: number;
19
+ minLength?: number;
20
+ maxLength?: number;
21
+ minItems?: number;
22
+ maxItems?: number;
23
+ minProperties?: number;
24
+ maxProperties?: number;
25
+ pattern?: string;
26
+ format?: string;
27
+ multipleOf?: number;
28
+ contentMediaType?: string;
29
+ contains?: JsonSchema;
30
+ not?: JsonSchema;
31
+ oneOf?: JsonSchema[];
32
+ allOf?: JsonSchema[];
33
+ default?: unknown;
34
+ [key: string]: unknown;
35
+ }
36
+ /**
37
+ * The policy for handling schema kinds/rule values that cannot be
38
+ * represented in JSON Schema.
39
+ */
40
+ type ErrorMode = "throw" | "warn" | "ignore";
41
+ /**
42
+ * Whether the conversion targets the data a consumer sends in (`"input"`)
43
+ * or the data dynz produces after validation (`"output"`). `expression`
44
+ * schemas are computed/derived values that are never part of the input, so
45
+ * in `"input"` mode they're silently removed from the generated schema; in
46
+ * `"output"` mode they're included (using their best-effort mapping).
47
+ */
48
+ type ConversionMode = "input" | "output";
49
+ interface ConversionConfig {
50
+ /**
51
+ * Policy for handling unsupported/unresolvable rule values and schema
52
+ * kinds. Defaults to `"warn"`.
53
+ */
54
+ errorMode?: ErrorMode;
55
+ /**
56
+ * Whether to convert for input or output data. Defaults to `"input"`.
57
+ */
58
+ mode?: ConversionMode;
59
+ }
60
+ //#endregion
61
+ //#region src/to-standard-json-schema.d.ts
62
+ /**
63
+ * Converts a dynz schema to a standard JSON Schema (2020-12) document.
64
+ *
65
+ * Rule values that depend on runtime data (references, predicates,
66
+ * transformers) and schema kinds without a JSON Schema equivalent are
67
+ * handled according to `config.errorMode` (default `"warn"`). Whether
68
+ * `expression` fields are included is controlled by `config.mode`
69
+ * (default `"input"`, which omits them).
70
+ */
71
+ declare function toStandardJsonSchema<T extends Schema>(schema: T, config?: ConversionConfig): JsonSchema;
72
+ //#endregion
73
+ export { type ConversionConfig, type ErrorMode, type JsonSchema, toStandardJsonSchema };
@@ -0,0 +1 @@
1
+ let e=require(`dynz`);function t(e,t){if(e.errorMode===`throw`)throw Error(t);e.errorMode===`warn`&&console.warn(`[@dynz/to-json-schema] ${t}`)}function n(e){return e!==void 0&&typeof e==`object`&&`type`in e&&e.type===`st`?{ok:!0,value:e.value}:{ok:!1}}function r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function i(e,t,n){if(e[t]===void 0){e[t]=n;return}e.allOf=[...e.allOf??[],{[t]:n}]}function a(e,a,o,s){switch(a.type){case`min`:{let r=n(a.min);r.ok?i(e,`minimum`,r.value):t(s,`"min" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max`:{let r=n(a.max);r.ok?i(e,`maximum`,r.value):t(s,`"max" rule with a non-static value cannot be converted to JSON Schema.`);break}case`min_length`:{let r=n(a.min);r.ok?o===`array`?i(e,`minItems`,r.value):i(e,`minLength`,r.value):t(s,`"min_length" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max_length`:{let r=n(a.max);r.ok?o===`array`?i(e,`maxItems`,r.value):i(e,`maxLength`,r.value):t(s,`"max_length" rule with a non-static value cannot be converted to JSON Schema.`);break}case`min_entries`:{let r=n(a.min);r.ok?i(e,`minProperties`,r.value):t(s,`"min_entries" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max_entries`:{let r=n(a.max);r.ok?i(e,`maxProperties`,r.value):t(s,`"max_entries" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max_precision`:{let r=n(a.maxPrecision);r.ok?i(e,`multipleOf`,1/10**r.value):t(s,`"max_precision" rule with a non-static value cannot be converted to JSON Schema.`);break}case`regex`:i(e,`pattern`,a.regex),a.flags&&t(s,`"regex" rule flags ("${a.flags}") cannot be represented in JSON Schema's "pattern" keyword and were ignored.`);break;case`email`:i(e,`format`,`email`);break;case`is_numeric`:i(e,`pattern`,`^[+-]?\\d+(\\.\\d+)?$`);break;case`equals`:{let r=n(a.equals);r.ok?i(e,`const`,r.value):t(s,`"equals" rule with a non-static value cannot be converted to JSON Schema.`);break}case`includes`:{let c=n(a.includes);if(!c.ok){t(s,`"includes" rule with a non-static value cannot be converted to JSON Schema.`);break}o===`array`?i(e,`contains`,{const:c.value}):i(e,`pattern`,r(String(c.value)));break}case`not_includes`:{let c=n(a.notIncludes);if(!c.ok){t(s,`"not_includes" rule with a non-static value cannot be converted to JSON Schema.`);break}i(e,`not`,o===`array`?{contains:{const:c.value}}:{pattern:r(String(c.value))});break}case`one_of`:{let r=[];for(let e of a.values){let i=n(e);if(!i.ok){t(s,`"one_of" rule with a non-static value cannot be converted to JSON Schema.`);return}r.push(i.value)}i(e,`enum`,r);break}case`not_one_of`:{let r=[];for(let e of a.values){let i=n(e);if(!i.ok){t(s,`"not_one_of" rule with a non-static value cannot be converted to JSON Schema.`);return}r.push(i.value)}i(e,`not`,{enum:r});break}case`mime_type`:{let r=n(a.mimeType);if(!r.ok){t(s,`"mime_type" rule with a non-static value cannot be converted to JSON Schema.`);break}typeof r.value==`string`?i(e,`contentMediaType`,r.value):Array.isArray(r.value)&&r.value.length===1?i(e,`contentMediaType`,r.value[0]):t(s,`"mime_type" rule with multiple mime types has no JSON Schema equivalent.`);break}case`min_date`:case`max_date`:case`before`:case`after`:t(s,`"${a.type}" rule has no JSON Schema equivalent (date comparisons aren't representable).`);break;case`min_size`:case`max_size`:t(s,`"${a.type}" rule has no JSON Schema equivalent (byte-size constraints aren't representable).`);break;case`custom`:t(s,`"custom" rule "${a.name}" has no JSON Schema equivalent.`);break;case`conditional`:t(s,`"conditional" rule has no JSON Schema equivalent.`);break;default:t(s,`Unknown rule cannot be converted to JSON Schema.`)}}function o(e,t,n,r){for(let i of t??[])a(e,i,n,r)}function s(e){let t=e.included===void 0||e.included===!0,n=e.required===void 0||e.required===!0;return t&&n}function c(e){return typeof e}function l(e,t){e.enum=t;let n=Array.from(new Set(t.map(c)));n.length===1?e.type=n[0]:n.length>1&&(e.type=n)}function u(e,n){let r=[],i=e=>{if(typeof e!=`object`){r.push(e);return}e.enabled!==!1&&(typeof e.enabled==`object`&&t(n,`An "options" entry has a predicate-based "enabled" flag; whether it's enabled can't be determined statically, so it was included in the JSON Schema "enum" anyway.`),i(e.value))};for(let t of e)i(t);return r}function d(e){return typeof e==`object`&&!!e&&`type`in e}function f(t,n){return t.included===!1?!0:n.mode===`input`&&t.type===e.SchemaType.EXPRESSION}function p(e,t){return e.private===!0?{oneOf:[{type:`object`,properties:{state:{const:`plain`},value:t},required:[`state`]},{type:`object`,properties:{state:{const:`masked`},value:{type:`string`}},required:[`state`,`value`]}]}:t}function m(e,t){e.default!==void 0&&(t.default=e.default instanceof Date?e.default.toISOString():e.default)}function h(e,t){let n=g(e,t);return m(e,n),p(e,n)}function g(n,r){switch(n.type){case e.SchemaType.STRING:{let e={type:`string`};return o(e,n.rules,n.type,r),e}case e.SchemaType.NUMBER:{let e={type:`number`};return o(e,n.rules,n.type,r),e}case e.SchemaType.BOOLEAN:{let e={type:`boolean`};return o(e,n.rules,n.type,r),e}case e.SchemaType.DATE:{let e={type:`string`,format:`date-time`};return o(e,n.rules,n.type,r),e}case e.SchemaType.LITERAL:return{const:n.value};case e.SchemaType.ENUM:{let e={};return l(e,Object.values(n.enum)),o(e,n.rules,n.type,r),e}case e.SchemaType.OPTIONS:{let e={};return l(e,u(n.options,r)),o(e,n.rules,n.type,r),e}case e.SchemaType.FILE:{let e={type:`string`};return o(e,n.rules,n.type,r),e}case e.SchemaType.EXPRESSION:return{};case e.SchemaType.ARRAY:{let e={type:`array`,items:h(n.schema,r)};return o(e,n.rules,n.type,r),e}case e.SchemaType.OBJECT:{let e={},t=[];for(let[i,a]of Object.entries(n.fields))f(a,r)||(e[i]=h(a,r),s(a)&&t.push(i));let i={type:`object`,properties:e};return t.length>0&&(i.required=t),o(i,n.rules,n.type,r),i}case e.SchemaType.DISCRIMINATED_UNION:return{oneOf:n.schemas.map(e=>{let t={[n.key]:{const:e[n.key]}},i=[n.key];for(let[a,o]of Object.entries(e))a===n.key||!d(o)||f(o,r)||(t[a]=h(o,r),s(o)&&i.push(a));return{type:`object`,properties:t,required:i}})};default:return t(r,`Unknown schema type cannot be converted to JSON Schema.`),{}}}function _(e,t={}){return{$schema:`https://json-schema.org/draft/2020-12/schema`,...h(e,{errorMode:t.errorMode??`warn`,mode:t.mode??`input`})}}exports.toStandardJsonSchema=_;
@@ -0,0 +1 @@
1
+ import{SchemaType as e}from"dynz";function t(e,t){if(e.errorMode===`throw`)throw Error(t);e.errorMode===`warn`&&console.warn(`[@dynz/to-json-schema] ${t}`)}function n(e){return e!==void 0&&typeof e==`object`&&`type`in e&&e.type===`st`?{ok:!0,value:e.value}:{ok:!1}}function r(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function i(e,t,n){if(e[t]===void 0){e[t]=n;return}e.allOf=[...e.allOf??[],{[t]:n}]}function a(e,a,o,s){switch(a.type){case`min`:{let r=n(a.min);r.ok?i(e,`minimum`,r.value):t(s,`"min" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max`:{let r=n(a.max);r.ok?i(e,`maximum`,r.value):t(s,`"max" rule with a non-static value cannot be converted to JSON Schema.`);break}case`min_length`:{let r=n(a.min);r.ok?o===`array`?i(e,`minItems`,r.value):i(e,`minLength`,r.value):t(s,`"min_length" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max_length`:{let r=n(a.max);r.ok?o===`array`?i(e,`maxItems`,r.value):i(e,`maxLength`,r.value):t(s,`"max_length" rule with a non-static value cannot be converted to JSON Schema.`);break}case`min_entries`:{let r=n(a.min);r.ok?i(e,`minProperties`,r.value):t(s,`"min_entries" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max_entries`:{let r=n(a.max);r.ok?i(e,`maxProperties`,r.value):t(s,`"max_entries" rule with a non-static value cannot be converted to JSON Schema.`);break}case`max_precision`:{let r=n(a.maxPrecision);r.ok?i(e,`multipleOf`,1/10**r.value):t(s,`"max_precision" rule with a non-static value cannot be converted to JSON Schema.`);break}case`regex`:i(e,`pattern`,a.regex),a.flags&&t(s,`"regex" rule flags ("${a.flags}") cannot be represented in JSON Schema's "pattern" keyword and were ignored.`);break;case`email`:i(e,`format`,`email`);break;case`is_numeric`:i(e,`pattern`,`^[+-]?\\d+(\\.\\d+)?$`);break;case`equals`:{let r=n(a.equals);r.ok?i(e,`const`,r.value):t(s,`"equals" rule with a non-static value cannot be converted to JSON Schema.`);break}case`includes`:{let c=n(a.includes);if(!c.ok){t(s,`"includes" rule with a non-static value cannot be converted to JSON Schema.`);break}o===`array`?i(e,`contains`,{const:c.value}):i(e,`pattern`,r(String(c.value)));break}case`not_includes`:{let c=n(a.notIncludes);if(!c.ok){t(s,`"not_includes" rule with a non-static value cannot be converted to JSON Schema.`);break}i(e,`not`,o===`array`?{contains:{const:c.value}}:{pattern:r(String(c.value))});break}case`one_of`:{let r=[];for(let e of a.values){let i=n(e);if(!i.ok){t(s,`"one_of" rule with a non-static value cannot be converted to JSON Schema.`);return}r.push(i.value)}i(e,`enum`,r);break}case`not_one_of`:{let r=[];for(let e of a.values){let i=n(e);if(!i.ok){t(s,`"not_one_of" rule with a non-static value cannot be converted to JSON Schema.`);return}r.push(i.value)}i(e,`not`,{enum:r});break}case`mime_type`:{let r=n(a.mimeType);if(!r.ok){t(s,`"mime_type" rule with a non-static value cannot be converted to JSON Schema.`);break}typeof r.value==`string`?i(e,`contentMediaType`,r.value):Array.isArray(r.value)&&r.value.length===1?i(e,`contentMediaType`,r.value[0]):t(s,`"mime_type" rule with multiple mime types has no JSON Schema equivalent.`);break}case`min_date`:case`max_date`:case`before`:case`after`:t(s,`"${a.type}" rule has no JSON Schema equivalent (date comparisons aren't representable).`);break;case`min_size`:case`max_size`:t(s,`"${a.type}" rule has no JSON Schema equivalent (byte-size constraints aren't representable).`);break;case`custom`:t(s,`"custom" rule "${a.name}" has no JSON Schema equivalent.`);break;case`conditional`:t(s,`"conditional" rule has no JSON Schema equivalent.`);break;default:t(s,`Unknown rule cannot be converted to JSON Schema.`)}}function o(e,t,n,r){for(let i of t??[])a(e,i,n,r)}function s(e){let t=e.included===void 0||e.included===!0,n=e.required===void 0||e.required===!0;return t&&n}function c(e){return typeof e}function l(e,t){e.enum=t;let n=Array.from(new Set(t.map(c)));n.length===1?e.type=n[0]:n.length>1&&(e.type=n)}function u(e,n){let r=[],i=e=>{if(typeof e!=`object`){r.push(e);return}e.enabled!==!1&&(typeof e.enabled==`object`&&t(n,`An "options" entry has a predicate-based "enabled" flag; whether it's enabled can't be determined statically, so it was included in the JSON Schema "enum" anyway.`),i(e.value))};for(let t of e)i(t);return r}function d(e){return typeof e==`object`&&!!e&&`type`in e}function f(t,n){return t.included===!1?!0:n.mode===`input`&&t.type===e.EXPRESSION}function p(e,t){return e.private===!0?{oneOf:[{type:`object`,properties:{state:{const:`plain`},value:t},required:[`state`]},{type:`object`,properties:{state:{const:`masked`},value:{type:`string`}},required:[`state`,`value`]}]}:t}function m(e,t){e.default!==void 0&&(t.default=e.default instanceof Date?e.default.toISOString():e.default)}function h(e,t){let n=g(e,t);return m(e,n),p(e,n)}function g(n,r){switch(n.type){case e.STRING:{let e={type:`string`};return o(e,n.rules,n.type,r),e}case e.NUMBER:{let e={type:`number`};return o(e,n.rules,n.type,r),e}case e.BOOLEAN:{let e={type:`boolean`};return o(e,n.rules,n.type,r),e}case e.DATE:{let e={type:`string`,format:`date-time`};return o(e,n.rules,n.type,r),e}case e.LITERAL:return{const:n.value};case e.ENUM:{let e={};return l(e,Object.values(n.enum)),o(e,n.rules,n.type,r),e}case e.OPTIONS:{let e={};return l(e,u(n.options,r)),o(e,n.rules,n.type,r),e}case e.FILE:{let e={type:`string`};return o(e,n.rules,n.type,r),e}case e.EXPRESSION:return{};case e.ARRAY:{let e={type:`array`,items:h(n.schema,r)};return o(e,n.rules,n.type,r),e}case e.OBJECT:{let e={},t=[];for(let[i,a]of Object.entries(n.fields))f(a,r)||(e[i]=h(a,r),s(a)&&t.push(i));let i={type:`object`,properties:e};return t.length>0&&(i.required=t),o(i,n.rules,n.type,r),i}case e.DISCRIMINATED_UNION:return{oneOf:n.schemas.map(e=>{let t={[n.key]:{const:e[n.key]}},i=[n.key];for(let[a,o]of Object.entries(e))a===n.key||!d(o)||f(o,r)||(t[a]=h(o,r),s(o)&&i.push(a));return{type:`object`,properties:t,required:i}})};default:return t(r,`Unknown schema type cannot be converted to JSON Schema.`),{}}}function _(e,t={}){return{$schema:`https://json-schema.org/draft/2020-12/schema`,...h(e,{errorMode:t.errorMode??`warn`,mode:t.mode??`input`})}}export{_ as toStandardJsonSchema};
package/dist/index.mjs ADDED
@@ -0,0 +1,375 @@
1
+ import { SchemaType } from "dynz";
2
+
3
+ //#region src/report-issue.ts
4
+ /**
5
+ * Reports an unsupported or unresolvable conversion according to the
6
+ * configured error mode: throws, warns via `console.warn`, or is a no-op.
7
+ */
8
+ function reportIssue(context, message) {
9
+ if (context.errorMode === "throw") throw new Error(message);
10
+ if (context.errorMode === "warn") console.warn(`[@dynz/to-json-schema] ${message}`);
11
+ }
12
+
13
+ //#endregion
14
+ //#region src/resolve-static.ts
15
+ /**
16
+ * Attempts to extract a literal value from a rule parameter. Only values
17
+ * wrapped with `v()`/`val()`/`st()` (i.e. `{ type: "st" }`) are statically
18
+ * known — references, predicates and transformers depend on runtime data
19
+ * and cannot be represented in a JSON Schema document.
20
+ */
21
+ function resolveStatic(value) {
22
+ if (value !== void 0 && typeof value === "object" && "type" in value && value.type === "st") return {
23
+ ok: true,
24
+ value: value.value
25
+ };
26
+ return { ok: false };
27
+ }
28
+
29
+ //#endregion
30
+ //#region src/convert-rules.ts
31
+ function escapeRegExp(value) {
32
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
33
+ }
34
+ /**
35
+ * Writes a keyword, preserving whatever constraint is already there.
36
+ *
37
+ * Several dynz rules map onto the same JSON Schema keyword: two `regex` rules both want
38
+ * `pattern`, `one_of` wants the `enum` an options schema has already produced,
39
+ * `not_includes` and `not_one_of` both want `not`. A plain assignment would silently drop
40
+ * the constraint that got there first, so a second writer is moved into `allOf` — where
41
+ * both still have to hold.
42
+ */
43
+ function setKeyword(jsonSchema, keyword, value) {
44
+ if (jsonSchema[keyword] === void 0) {
45
+ jsonSchema[keyword] = value;
46
+ return;
47
+ }
48
+ jsonSchema.allOf = [...jsonSchema.allOf ?? [], { [keyword]: value }];
49
+ }
50
+ /**
51
+ * Applies a dynz rule to a JSON Schema in place. Rules whose value can't be
52
+ * statically resolved (references, predicates, transformers) or that have
53
+ * no JSON Schema equivalent are skipped and reported via `reportIssue`.
54
+ */
55
+ function applyRule(jsonSchema, rule, schemaType, context) {
56
+ switch (rule.type) {
57
+ case "min": {
58
+ const min = resolveStatic(rule.min);
59
+ if (min.ok) setKeyword(jsonSchema, "minimum", min.value);
60
+ else reportIssue(context, `"min" rule with a non-static value cannot be converted to JSON Schema.`);
61
+ break;
62
+ }
63
+ case "max": {
64
+ const max = resolveStatic(rule.max);
65
+ if (max.ok) setKeyword(jsonSchema, "maximum", max.value);
66
+ else reportIssue(context, `"max" rule with a non-static value cannot be converted to JSON Schema.`);
67
+ break;
68
+ }
69
+ case "min_length": {
70
+ const min = resolveStatic(rule.min);
71
+ if (min.ok) if (schemaType === "array") setKeyword(jsonSchema, "minItems", min.value);
72
+ else setKeyword(jsonSchema, "minLength", min.value);
73
+ else reportIssue(context, `"min_length" rule with a non-static value cannot be converted to JSON Schema.`);
74
+ break;
75
+ }
76
+ case "max_length": {
77
+ const max = resolveStatic(rule.max);
78
+ if (max.ok) if (schemaType === "array") setKeyword(jsonSchema, "maxItems", max.value);
79
+ else setKeyword(jsonSchema, "maxLength", max.value);
80
+ else reportIssue(context, `"max_length" rule with a non-static value cannot be converted to JSON Schema.`);
81
+ break;
82
+ }
83
+ case "min_entries": {
84
+ const min = resolveStatic(rule.min);
85
+ if (min.ok) setKeyword(jsonSchema, "minProperties", min.value);
86
+ else reportIssue(context, `"min_entries" rule with a non-static value cannot be converted to JSON Schema.`);
87
+ break;
88
+ }
89
+ case "max_entries": {
90
+ const max = resolveStatic(rule.max);
91
+ if (max.ok) setKeyword(jsonSchema, "maxProperties", max.value);
92
+ else reportIssue(context, `"max_entries" rule with a non-static value cannot be converted to JSON Schema.`);
93
+ break;
94
+ }
95
+ case "max_precision": {
96
+ const maxPrecision = resolveStatic(rule.maxPrecision);
97
+ if (maxPrecision.ok) setKeyword(jsonSchema, "multipleOf", 1 / 10 ** maxPrecision.value);
98
+ else reportIssue(context, `"max_precision" rule with a non-static value cannot be converted to JSON Schema.`);
99
+ break;
100
+ }
101
+ case "regex":
102
+ setKeyword(jsonSchema, "pattern", rule.regex);
103
+ if (rule.flags) reportIssue(context, `"regex" rule flags ("${rule.flags}") cannot be represented in JSON Schema's "pattern" keyword and were ignored.`);
104
+ break;
105
+ case "email":
106
+ setKeyword(jsonSchema, "format", "email");
107
+ break;
108
+ case "is_numeric":
109
+ setKeyword(jsonSchema, "pattern", "^[+-]?\\d+(\\.\\d+)?$");
110
+ break;
111
+ case "equals": {
112
+ const equals = resolveStatic(rule.equals);
113
+ if (equals.ok) setKeyword(jsonSchema, "const", equals.value);
114
+ else reportIssue(context, `"equals" rule with a non-static value cannot be converted to JSON Schema.`);
115
+ break;
116
+ }
117
+ case "includes": {
118
+ const includes = resolveStatic(rule.includes);
119
+ if (!includes.ok) {
120
+ reportIssue(context, `"includes" rule with a non-static value cannot be converted to JSON Schema.`);
121
+ break;
122
+ }
123
+ if (schemaType === "array") setKeyword(jsonSchema, "contains", { const: includes.value });
124
+ else setKeyword(jsonSchema, "pattern", escapeRegExp(String(includes.value)));
125
+ break;
126
+ }
127
+ case "not_includes": {
128
+ const notIncludes = resolveStatic(rule.notIncludes);
129
+ if (!notIncludes.ok) {
130
+ reportIssue(context, `"not_includes" rule with a non-static value cannot be converted to JSON Schema.`);
131
+ break;
132
+ }
133
+ setKeyword(jsonSchema, "not", schemaType === "array" ? { contains: { const: notIncludes.value } } : { pattern: escapeRegExp(String(notIncludes.value)) });
134
+ break;
135
+ }
136
+ case "one_of": {
137
+ const values = [];
138
+ for (const value of rule.values) {
139
+ const resolved = resolveStatic(value);
140
+ if (!resolved.ok) {
141
+ reportIssue(context, `"one_of" rule with a non-static value cannot be converted to JSON Schema.`);
142
+ return;
143
+ }
144
+ values.push(resolved.value);
145
+ }
146
+ setKeyword(jsonSchema, "enum", values);
147
+ break;
148
+ }
149
+ case "not_one_of": {
150
+ const values = [];
151
+ for (const value of rule.values) {
152
+ const resolved = resolveStatic(value);
153
+ if (!resolved.ok) {
154
+ reportIssue(context, `"not_one_of" rule with a non-static value cannot be converted to JSON Schema.`);
155
+ return;
156
+ }
157
+ values.push(resolved.value);
158
+ }
159
+ setKeyword(jsonSchema, "not", { enum: values });
160
+ break;
161
+ }
162
+ case "mime_type": {
163
+ const mimeType = resolveStatic(rule.mimeType);
164
+ if (!mimeType.ok) {
165
+ reportIssue(context, `"mime_type" rule with a non-static value cannot be converted to JSON Schema.`);
166
+ break;
167
+ }
168
+ if (typeof mimeType.value === "string") setKeyword(jsonSchema, "contentMediaType", mimeType.value);
169
+ else if (Array.isArray(mimeType.value) && mimeType.value.length === 1) setKeyword(jsonSchema, "contentMediaType", mimeType.value[0]);
170
+ else reportIssue(context, `"mime_type" rule with multiple mime types has no JSON Schema equivalent.`);
171
+ break;
172
+ }
173
+ case "min_date":
174
+ case "max_date":
175
+ case "before":
176
+ case "after":
177
+ reportIssue(context, `"${rule.type}" rule has no JSON Schema equivalent (date comparisons aren't representable).`);
178
+ break;
179
+ case "min_size":
180
+ case "max_size":
181
+ reportIssue(context, `"${rule.type}" rule has no JSON Schema equivalent (byte-size constraints aren't representable).`);
182
+ break;
183
+ case "custom":
184
+ reportIssue(context, `"custom" rule "${rule.name}" has no JSON Schema equivalent.`);
185
+ break;
186
+ case "conditional":
187
+ reportIssue(context, `"conditional" rule has no JSON Schema equivalent.`);
188
+ break;
189
+ default: reportIssue(context, `Unknown rule cannot be converted to JSON Schema.`);
190
+ }
191
+ }
192
+ function applyRules(jsonSchema, rules, schemaType, context) {
193
+ for (const rule of rules ?? []) applyRule(jsonSchema, rule, schemaType, context);
194
+ }
195
+
196
+ //#endregion
197
+ //#region src/convert-schema.ts
198
+ function isMandatory(schema) {
199
+ const isIncluded = schema.included === void 0 || schema.included === true;
200
+ const isRequired = schema.required === void 0 || schema.required === true;
201
+ return isIncluded && isRequired;
202
+ }
203
+ function jsonTypeOf(value) {
204
+ return typeof value;
205
+ }
206
+ function applyEnumValues(jsonSchema, values) {
207
+ jsonSchema.enum = values;
208
+ const types = Array.from(new Set(values.map(jsonTypeOf)));
209
+ if (types.length === 1) jsonSchema.type = types[0];
210
+ else if (types.length > 1) jsonSchema.type = types;
211
+ }
212
+ function collectOptionValues(options, context) {
213
+ const values = [];
214
+ const visit = (option) => {
215
+ if (typeof option !== "object") {
216
+ values.push(option);
217
+ return;
218
+ }
219
+ if (option.enabled === false) return;
220
+ if (typeof option.enabled === "object") reportIssue(context, `An "options" entry has a predicate-based "enabled" flag; whether it's enabled can't be determined statically, so it was included in the JSON Schema "enum" anyway.`);
221
+ visit(option.value);
222
+ };
223
+ for (const option of options) visit(option);
224
+ return values;
225
+ }
226
+ function isSchema(value) {
227
+ return typeof value === "object" && value !== null && "type" in value;
228
+ }
229
+ function shouldOmitField(schema, context) {
230
+ if (schema.included === false) return true;
231
+ return context.mode === "input" && schema.type === SchemaType.EXPRESSION;
232
+ }
233
+ function applyPrivacyWrapper(schema, innerSchema) {
234
+ if (schema.private !== true) return innerSchema;
235
+ return { oneOf: [{
236
+ type: "object",
237
+ properties: {
238
+ state: { const: "plain" },
239
+ value: innerSchema
240
+ },
241
+ required: ["state"]
242
+ }, {
243
+ type: "object",
244
+ properties: {
245
+ state: { const: "masked" },
246
+ value: { type: "string" }
247
+ },
248
+ required: ["state", "value"]
249
+ }] };
250
+ }
251
+ function applyDefault(schema, jsonSchema) {
252
+ if (schema.default === void 0) return;
253
+ jsonSchema.default = schema.default instanceof Date ? schema.default.toISOString() : schema.default;
254
+ }
255
+ /**
256
+ * Converts a dynz schema to a JSON Schema (2020-12) document. Rule values
257
+ * and schema kinds without a JSON Schema equivalent are handled per
258
+ * `context.errorMode`.
259
+ */
260
+ function convertSchema(schema, context) {
261
+ const jsonSchema = convertSchemaKind(schema, context);
262
+ applyDefault(schema, jsonSchema);
263
+ return applyPrivacyWrapper(schema, jsonSchema);
264
+ }
265
+ function convertSchemaKind(schema, context) {
266
+ switch (schema.type) {
267
+ case SchemaType.STRING: {
268
+ const jsonSchema = { type: "string" };
269
+ applyRules(jsonSchema, schema.rules, schema.type, context);
270
+ return jsonSchema;
271
+ }
272
+ case SchemaType.NUMBER: {
273
+ const jsonSchema = { type: "number" };
274
+ applyRules(jsonSchema, schema.rules, schema.type, context);
275
+ return jsonSchema;
276
+ }
277
+ case SchemaType.BOOLEAN: {
278
+ const jsonSchema = { type: "boolean" };
279
+ applyRules(jsonSchema, schema.rules, schema.type, context);
280
+ return jsonSchema;
281
+ }
282
+ case SchemaType.DATE: {
283
+ const jsonSchema = {
284
+ type: "string",
285
+ format: "date-time"
286
+ };
287
+ applyRules(jsonSchema, schema.rules, schema.type, context);
288
+ return jsonSchema;
289
+ }
290
+ case SchemaType.LITERAL: return { const: schema.value };
291
+ case SchemaType.ENUM: {
292
+ const jsonSchema = {};
293
+ applyEnumValues(jsonSchema, Object.values(schema.enum));
294
+ applyRules(jsonSchema, schema.rules, schema.type, context);
295
+ return jsonSchema;
296
+ }
297
+ case SchemaType.OPTIONS: {
298
+ const jsonSchema = {};
299
+ applyEnumValues(jsonSchema, collectOptionValues(schema.options, context));
300
+ applyRules(jsonSchema, schema.rules, schema.type, context);
301
+ return jsonSchema;
302
+ }
303
+ case SchemaType.FILE: {
304
+ const jsonSchema = { type: "string" };
305
+ applyRules(jsonSchema, schema.rules, schema.type, context);
306
+ return jsonSchema;
307
+ }
308
+ case SchemaType.EXPRESSION: return {};
309
+ case SchemaType.ARRAY: {
310
+ const jsonSchema = {
311
+ type: "array",
312
+ items: convertSchema(schema.schema, context)
313
+ };
314
+ applyRules(jsonSchema, schema.rules, schema.type, context);
315
+ return jsonSchema;
316
+ }
317
+ case SchemaType.OBJECT: {
318
+ const properties = {};
319
+ const required = [];
320
+ for (const [key, fieldSchema] of Object.entries(schema.fields)) {
321
+ if (shouldOmitField(fieldSchema, context)) continue;
322
+ properties[key] = convertSchema(fieldSchema, context);
323
+ if (isMandatory(fieldSchema)) required.push(key);
324
+ }
325
+ const jsonSchema = {
326
+ type: "object",
327
+ properties
328
+ };
329
+ if (required.length > 0) jsonSchema.required = required;
330
+ applyRules(jsonSchema, schema.rules, schema.type, context);
331
+ return jsonSchema;
332
+ }
333
+ case SchemaType.DISCRIMINATED_UNION: return { oneOf: schema.schemas.map((member) => {
334
+ const properties = { [schema.key]: { const: member[schema.key] } };
335
+ const required = [schema.key];
336
+ for (const [key, value] of Object.entries(member)) {
337
+ if (key === schema.key || !isSchema(value) || shouldOmitField(value, context)) continue;
338
+ properties[key] = convertSchema(value, context);
339
+ if (isMandatory(value)) required.push(key);
340
+ }
341
+ return {
342
+ type: "object",
343
+ properties,
344
+ required
345
+ };
346
+ }) };
347
+ default:
348
+ reportIssue(context, `Unknown schema type cannot be converted to JSON Schema.`);
349
+ return {};
350
+ }
351
+ }
352
+
353
+ //#endregion
354
+ //#region src/to-standard-json-schema.ts
355
+ /**
356
+ * Converts a dynz schema to a standard JSON Schema (2020-12) document.
357
+ *
358
+ * Rule values that depend on runtime data (references, predicates,
359
+ * transformers) and schema kinds without a JSON Schema equivalent are
360
+ * handled according to `config.errorMode` (default `"warn"`). Whether
361
+ * `expression` fields are included is controlled by `config.mode`
362
+ * (default `"input"`, which omits them).
363
+ */
364
+ function toStandardJsonSchema(schema, config = {}) {
365
+ return {
366
+ $schema: "https://json-schema.org/draft/2020-12/schema",
367
+ ...convertSchema(schema, {
368
+ errorMode: config.errorMode ?? "warn",
369
+ mode: config.mode ?? "input"
370
+ })
371
+ };
372
+ }
373
+
374
+ //#endregion
375
+ export { toStandardJsonSchema };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@dynz/to-json-schema",
3
+ "version": "0.0.1",
4
+ "private": false,
5
+ "license": "BUSL-1.1",
6
+ "type": "module",
7
+ "sideEffects": false,
8
+ "keywords": [
9
+ "typescript",
10
+ "schema",
11
+ "validation",
12
+ "json-schema",
13
+ "form",
14
+ "type-safe"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/rubenvanrooij/dynz"
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "author": "Ruben van Rooij <ruben.van.rooij@gmail.com>",
27
+ "description": "Convert dynz schemas to standard JSON Schema.",
28
+ "main": "./dist/index.mjs",
29
+ "types": "./dist/index.d.mts",
30
+ "exports": {
31
+ ".": {
32
+ "import": {
33
+ "types": "./dist/index.d.mts",
34
+ "default": "./dist/index.mjs"
35
+ },
36
+ "require": {
37
+ "types": "./dist/index.d.cts",
38
+ "default": "./dist/index.cjs"
39
+ }
40
+ }
41
+ },
42
+ "peerDependencies": {
43
+ "dynz": "^1.0.0"
44
+ },
45
+ "devDependencies": {
46
+ "tsdown": "^0.16.5"
47
+ },
48
+ "scripts": {
49
+ "build": "tsdown",
50
+ "dev": "tsdown --watch",
51
+ "check-types": "tsc --noEmit",
52
+ "test": "vitest run",
53
+ "test:watch": "vitest run --watch"
54
+ }
55
+ }