@collective-intelligence/schema-codegen 0.0.0-stage → 0.1.16
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/README.md +173 -2
- package/dist/errors.d.ts +47 -0
- package/dist/generate.d.ts +6 -0
- package/dist/header.d.ts +10 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +37 -0
- package/dist/model.d.ts +122 -0
- package/dist/names.d.ts +20 -0
- package/dist/printers/contract.d.ts +22 -0
- package/dist/printers/effect.d.ts +7 -0
- package/dist/printers/source.d.ts +15 -0
- package/dist/printers/types.d.ts +3 -0
- package/dist/printers/zod.d.ts +3 -0
- package/dist/tuple.d.ts +16 -0
- package/dist/types.d.ts +56 -0
- package/package.json +49 -4
package/README.md
CHANGED
|
@@ -1,3 +1,174 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@collective-intelligence/schema-codegen`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Pure generator from Draft 2020-12 JSON Schema documents to TypeScript source.
|
|
4
|
+
It has no runtime dependency. It does no file IO and has no CLI. Callers pass
|
|
5
|
+
documents in and write the returned text. The `ci package codegen` command of
|
|
6
|
+
`@collective-intelligence/cli` is the caller for package declarations; see the
|
|
7
|
+
[CLI README](../cli/README.md#generate-typescript-schemas).
|
|
8
|
+
|
|
9
|
+
Targets:
|
|
10
|
+
|
|
11
|
+
- `types`: plain TypeScript types.
|
|
12
|
+
- `zod`: Zod schemas and inferred types.
|
|
13
|
+
- `effect`: `effect/Schema` schemas and types.
|
|
14
|
+
|
|
15
|
+
## Generate a module
|
|
16
|
+
|
|
17
|
+
The package exports `generateSchemaModule` and its types. The function is pure
|
|
18
|
+
and never throws. It returns the source text of one file for one target.
|
|
19
|
+
|
|
20
|
+
```ts
|
|
21
|
+
import { generateSchemaModule } from "@collective-intelligence/schema-codegen"
|
|
22
|
+
|
|
23
|
+
const result = generateSchemaModule({
|
|
24
|
+
target: "zod",
|
|
25
|
+
header: { packageFqn: "acme.billing", packageVersion: "1.0.0" },
|
|
26
|
+
schemas: [
|
|
27
|
+
{
|
|
28
|
+
name: "acme.billing.invoice#input",
|
|
29
|
+
document: { type: "object", properties: { id: { type: "string" } } },
|
|
30
|
+
fidelity: "exact"
|
|
31
|
+
}
|
|
32
|
+
]
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
if (result.errors === undefined) {
|
|
36
|
+
// Write result.source to <out>/acme.billing/zod.ts. result.warnings is data.
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- `SchemaInput.name` is `<component fqn>#<slot label>`. The generator builds
|
|
41
|
+
the export name from it: the PascalCase component `fqn` without the package
|
|
42
|
+
`fqn`, then the PascalCase slot label. Exports are sorted by component `fqn`,
|
|
43
|
+
then slot label. A name without `#<slot label>`, an invalid identifier, a name
|
|
44
|
+
that the target file already uses and two schemas with one export name are
|
|
45
|
+
errors (`reserved_name`, `invalid_name`, `name_clash`). The `zod` file uses
|
|
46
|
+
`z`, `RegExp` and `Infinity`; the `effect` file uses `Schema`, `RegExp` and
|
|
47
|
+
`Infinity`. The `types` file reserves no name. This holds for the names of
|
|
48
|
+
`$defs` entries too.
|
|
49
|
+
- `SchemaInput.fidelity` is `exact` or `structural`. A `structural` schema can
|
|
50
|
+
be stricter at runtime than its JSON Schema. Each `structural` schema gives a
|
|
51
|
+
`structural_fidelity` warning.
|
|
52
|
+
- `GenerateResult` is `{ source, warnings }` or `{ errors }`. One run collects
|
|
53
|
+
every error, each with a code, the schema name, a JSON Pointer and the
|
|
54
|
+
keyword (`null` when no single keyword is at fault).
|
|
55
|
+
- `Warning.kind` is `structural_fidelity`, `dropped_keyword`,
|
|
56
|
+
`format_annotation_only` or `closed_object_unenforced`.
|
|
57
|
+
- The output is byte-stable. The same input gives the same text: no timestamp,
|
|
58
|
+
tool version or hash. The library does not call a formatter.
|
|
59
|
+
|
|
60
|
+
## File header
|
|
61
|
+
|
|
62
|
+
Every file starts with a `//` comment header. The header names the target, the
|
|
63
|
+
package `fqn` and the package version, and says that the schemas are not
|
|
64
|
+
runtime validation authority. A blank line follows it. The `effect` header has
|
|
65
|
+
one more line about excess keys.
|
|
66
|
+
|
|
67
|
+
```ts
|
|
68
|
+
// @generated
|
|
69
|
+
// Target: zod
|
|
70
|
+
// Package: acme.billing
|
|
71
|
+
// Version: 1.0.0
|
|
72
|
+
// Generated schemas are a convenience and not runtime validation authority.
|
|
73
|
+
// The backend host validates.
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The `@generated` marker in the leading comment is how the CLI recognizes a file
|
|
77
|
+
that it may overwrite.
|
|
78
|
+
|
|
79
|
+
## Authority and requirements
|
|
80
|
+
|
|
81
|
+
Generated schemas are a convenience. The backend host validates; generated
|
|
82
|
+
files never replace it. The schemas describe the wire shape: the encoded JSON,
|
|
83
|
+
not decoded runtime values.
|
|
84
|
+
|
|
85
|
+
- `zod` output needs `zod` 4.4 or later. It uses `z.xor` for `oneOf`.
|
|
86
|
+
- `effect` output needs Effect v4 and imports `effect/Schema`.
|
|
87
|
+
- `types` output has no import.
|
|
88
|
+
|
|
89
|
+
## Keywords
|
|
90
|
+
|
|
91
|
+
Supported keywords:
|
|
92
|
+
|
|
93
|
+
- Types and values: `type`, `enum`, `const`.
|
|
94
|
+
- String: `minLength`, `maxLength`, `pattern`, `format`.
|
|
95
|
+
- Number: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`,
|
|
96
|
+
`multipleOf`.
|
|
97
|
+
- Object: `properties`, `required`, `additionalProperties`, `minProperties`,
|
|
98
|
+
`maxProperties`.
|
|
99
|
+
- Array: `items`, `prefixItems`, `minItems`, `maxItems`, `uniqueItems`.
|
|
100
|
+
- Composition: `anyOf`, `oneOf`, `allOf`.
|
|
101
|
+
- References: local `$ref` to a `$defs` entry of the same document, and a root
|
|
102
|
+
`$defs`. A `$defs` entry becomes a local declaration that is not exported.
|
|
103
|
+
- Annotations: `title`, `description`, `default`, `examples`, `deprecated`,
|
|
104
|
+
`readOnly`, `writeOnly`.
|
|
105
|
+
- Ignored: `$schema`, `$id`, `$anchor`, `$comment`, `$vocabulary` and every
|
|
106
|
+
keyword that starts with `x-`.
|
|
107
|
+
|
|
108
|
+
A constraint keyword needs `type`. `minLength`, `pattern`, `format`, the number
|
|
109
|
+
bounds, `properties`, `required`, `additionalProperties`, `minProperties`,
|
|
110
|
+
`maxProperties`, `items`, `prefixItems`, `minItems`, `maxItems` and
|
|
111
|
+
`uniqueItems` only constrain values of their own type, so a schema without
|
|
112
|
+
`type` also accepts every other value, and no target can say that. The
|
|
113
|
+
generator does not guess a type: each such keyword fails the run with
|
|
114
|
+
`unsupported_keyword_combination`, and `keyword` is the constraint. This holds
|
|
115
|
+
in `allOf`, `anyOf` and `oneOf` members, and in `$defs` entries, too.
|
|
116
|
+
|
|
117
|
+
A name in `required` that `properties` does not declare is a property that
|
|
118
|
+
`additionalProperties` describes: any value, or the `additionalProperties`
|
|
119
|
+
schema. With `additionalProperties: false` no object can satisfy it, so it
|
|
120
|
+
fails with `unsupported_keyword_combination` (`required+additionalProperties`)
|
|
121
|
+
at the `required` entry.
|
|
122
|
+
|
|
123
|
+
`prefixItems` describes the positions that exist and does not make them exist.
|
|
124
|
+
A position is required only below `minItems`; later positions are optional
|
|
125
|
+
tuple elements (`[A, B?]`). A position at or beyond `maxItems` does not exist,
|
|
126
|
+
and `items` after the last one is dropped.
|
|
127
|
+
|
|
128
|
+
These keywords fail the run, because the generator cannot express them:
|
|
129
|
+
`contains`, `dependentRequired`, `if`, `then`, `else`, `not`,
|
|
130
|
+
`patternProperties`, `unevaluatedItems`, `unevaluatedProperties`,
|
|
131
|
+
`$dynamicRef`, `$defs` below the root, a remote `$ref`, a recursive `$ref`, and
|
|
132
|
+
a `$ref` that does not point to a `$defs` entry. Any other keyword that does
|
|
133
|
+
not start with `x-` is an `unknown_keyword` error. The generator never
|
|
134
|
+
degrades a shape that changes what the schema accepts.
|
|
135
|
+
|
|
136
|
+
A validation-only keyword with no equivalent in a target is dropped. It stays
|
|
137
|
+
as an annotation and gives a warning (`dropped_keyword` or
|
|
138
|
+
`format_annotation_only`).
|
|
139
|
+
|
|
140
|
+
## Target limits
|
|
141
|
+
|
|
142
|
+
- `types`: a type cannot check values. Validation keywords (`minLength`,
|
|
143
|
+
`maxLength`, `pattern`, `format`, the number bounds, the property and item
|
|
144
|
+
counts, `uniqueItems`) become JSDoc tags and give `dropped_keyword`
|
|
145
|
+
warnings.
|
|
146
|
+
- `zod`: objects with `additionalProperties: false` are `z.strictObject`. An
|
|
147
|
+
object with no properties and no `additionalProperties` is an open record,
|
|
148
|
+
as in the other targets.
|
|
149
|
+
`format` is checked for `date-time`, `email`, `uuid` and `uri`; any other
|
|
150
|
+
format stays as `.meta` data and gives `format_annotation_only`.
|
|
151
|
+
`uniqueItems`, `minProperties` and `maxProperties` stay as `.meta` data and
|
|
152
|
+
give `dropped_keyword`.
|
|
153
|
+
- `effect`: `Schema.Struct` has no closed object. `additionalProperties: false`
|
|
154
|
+
is not enforced and gives one `closed_object_unenforced` warning per object;
|
|
155
|
+
excess keys are rejected only with the decode option
|
|
156
|
+
`onExcessProperty: "error"`. Only `format: uuid` is a format check; any other
|
|
157
|
+
format stays as an annotation and gives `format_annotation_only`. An object
|
|
158
|
+
that has declared keys and no extra schema cannot count its keys, so
|
|
159
|
+
`minProperties` and `maxProperties` stay as annotations and give
|
|
160
|
+
`dropped_keyword`. `allOf` merges plain objects only; other members
|
|
161
|
+
(`allof_not_plain_objects`, also for a `$ref` to one), and members that
|
|
162
|
+
declare one property in different ways (`allof_property_conflict`), fail the
|
|
163
|
+
run. Keywords of one schema object that do not merge, for example a `$ref`
|
|
164
|
+
with a constraint or a `type` with `oneOf`, fail with
|
|
165
|
+
`unsupported_keyword_combination`; its `keyword` lists them joined with `+`.
|
|
166
|
+
|
|
167
|
+
## Checks
|
|
168
|
+
|
|
169
|
+
```sh
|
|
170
|
+
bun test tests/package-contract.test.ts
|
|
171
|
+
bun run type-check
|
|
172
|
+
bun run build
|
|
173
|
+
bun run test:pack
|
|
174
|
+
```
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { CodegenError, SchemaName } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Stable error codes. `CodegenError.code` stays a plain string in the public
|
|
4
|
+
* types; every code this library emits is listed here.
|
|
5
|
+
*/
|
|
6
|
+
export type ErrorCode =
|
|
7
|
+
/** A keyword the generator cannot express, for example `not`. */
|
|
8
|
+
"unsupported_keyword"
|
|
9
|
+
/** A keyword outside the supported set that does not start with `x-`. */
|
|
10
|
+
| "unknown_keyword" | "dynamic_ref" | "remote_ref" | "recursive_ref"
|
|
11
|
+
/** A local `$ref` that does not point to a `$defs` entry of the document. */
|
|
12
|
+
| "unresolved_ref"
|
|
13
|
+
/** A keyword value or a subschema with the wrong JSON type. */
|
|
14
|
+
| "invalid_value"
|
|
15
|
+
/** Effect has no intersection: `allOf` merges plain objects only. */
|
|
16
|
+
| "allof_not_plain_objects"
|
|
17
|
+
/**
|
|
18
|
+
* Keywords of one schema object that cannot meet. `keyword` lists them
|
|
19
|
+
* joined with `+`. Effect cannot merge a `$ref` with a constraint, or a
|
|
20
|
+
* `type` with `oneOf`. A `required` name that nothing declares, next to
|
|
21
|
+
* `additionalProperties: false`, gives `required+additionalProperties` at
|
|
22
|
+
* the name. A constraint keyword without `type` (`minLength`, `properties`
|
|
23
|
+
* and the like) gives that keyword alone: the schema also accepts every
|
|
24
|
+
* value of the other types, which no target can express.
|
|
25
|
+
*/
|
|
26
|
+
| "unsupported_keyword_combination"
|
|
27
|
+
/** Two `allOf` members declare one property in different ways. */
|
|
28
|
+
| "allof_property_conflict"
|
|
29
|
+
/** An `enum` or `const` value that is an object or an array. */
|
|
30
|
+
| "unsupported_literal"
|
|
31
|
+
/** A schema name without the `#<slot label>` suffix. */
|
|
32
|
+
| "invalid_name"
|
|
33
|
+
/** Two declarations of one generated file have one name. */
|
|
34
|
+
| "name_clash"
|
|
35
|
+
/** A declaration name equals an import name of the target. */
|
|
36
|
+
| "reserved_name";
|
|
37
|
+
export interface ErrorCollector {
|
|
38
|
+
/**
|
|
39
|
+
* Records one error for the schema of this collector. `pointer` is the JSON
|
|
40
|
+
* Pointer to the schema object that holds the keyword, or to the value
|
|
41
|
+
* itself when `keyword` is `null`.
|
|
42
|
+
*/
|
|
43
|
+
readonly report: (code: ErrorCode, pointer: string, keyword: string | null) => void;
|
|
44
|
+
/** Every error in report order. */
|
|
45
|
+
readonly errors: readonly CodegenError[];
|
|
46
|
+
}
|
|
47
|
+
export declare const createErrorCollector: (schemaName: SchemaName) => ErrorCollector;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { GenerateSchemaModule } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Parses, names and prints the schemas of one file. The stages run in this
|
|
4
|
+
* order, and every stage before the printer reports all of its errors.
|
|
5
|
+
*/
|
|
6
|
+
export declare const generateSchemaModule: GenerateSchemaModule;
|
package/dist/header.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CodegenTarget, GenerateHeader } from "./types.js";
|
|
2
|
+
export interface HeaderInput extends GenerateHeader {
|
|
3
|
+
readonly target: CodegenTarget;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* The file header: a run of `//` lines that starts the file and ends with one
|
|
7
|
+
* newline. The text depends only on its input: no tool version, timestamp or
|
|
8
|
+
* hash.
|
|
9
|
+
*/
|
|
10
|
+
export declare const printHeader: ({ packageFqn, packageVersion, target }: HeaderInput) => string;
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
var effectNotice='Closed objects reject excess keys only through the decode option onExcessProperty: "error".';var printHeader=({packageFqn,packageVersion,target})=>{const lines=["@generated",`Target: ${target}`,`Package: ${packageFqn}`,`Version: ${packageVersion}`,"Generated schemas are a convenience and not runtime validation authority.","The backend host validates.",...target==="effect"?[effectNotice]:[]];return lines.map((line)=>`// ${line}
|
|
2
|
+
`).join("")};var createErrorCollector=(schemaName)=>{const errors=[];return{errors,report:(code,pointer,keyword)=>{errors.push({code,keyword,pointer,schemaName})}}};var annotationKeywords=["default","deprecated","description","examples","readOnly","title","writeOnly"];var ignoredKeywords=["$anchor","$comment","$id","$schema","$vocabulary"];var familyKeywords={array:["items","maxItems","minItems","prefixItems","uniqueItems"],number:["exclusiveMaximum","exclusiveMinimum","maximum","minimum","multipleOf"],object:["additionalProperties","maxProperties","minProperties","properties","required"],string:["format","maxLength","minLength","pattern"]};var structuralKeywords=["$defs","$ref","allOf","anyOf","const","enum","oneOf","type"];var supportedKeywords=new Set([...annotationKeywords,...ignoredKeywords,...structuralKeywords,...Object.values(familyKeywords).flat()]);var failingKeywords=new Set(["contains","dependentRequired","else","if","not","patternProperties","then","unevaluatedItems","unevaluatedProperties"]);var typeNames=["string","number","integer","boolean","null","object","array"];var noAnnotations={default:undefined,deprecated:undefined,description:undefined,examples:undefined,readOnly:undefined,title:undefined,writeOnly:undefined};var isObject=(value)=>typeof value==="object"&&value!==null&&!Array.isArray(value);var isString=(value)=>typeof value==="string";var isBoolean=(value)=>typeof value==="boolean";var isNumber=(value)=>typeof value==="number";var isArray=(value)=>Array.isArray(value);var isCount=(value)=>isNumber(value)&&Number.isInteger(value)&&value>=0;var isStringArray=(value)=>isArray(value)&&value.every(isString);var isTypeName=(value)=>typeNames.some((typeName)=>typeName===value);var unreachable=(value)=>{throw new Error(`Unhandled case: ${String(value)}`)};var escapePointer=(segment)=>segment.replaceAll("~","~0").replaceAll("/","~1");var childPointer=(pointer,...segments)=>{let child=pointer;for(const segment of segments){child=`${child}/${escapePointer(segment)}`}return child};var facet=(pointer,form)=>({annotations:noAnnotations,form,pointer});var unknownNode=(pointer)=>facet(pointer,{kind:"unknown"});var read=(ctx,schema,pointer,keyword,accepts)=>{const value=schema[keyword];if(value===undefined){return}if(accepts(value)){return value}ctx.report("invalid_value",pointer,keyword);return};var readNonEmptyArray=(ctx,schema,pointer,keyword)=>{const value=read(ctx,schema,pointer,keyword,isArray);if(value?.length===0){ctx.report("invalid_value",pointer,keyword);return}return value};var checkKeywords=(ctx,schema,pointer)=>{for(const keyword of Object.keys(schema)){if(keyword==="$dynamicRef"){ctx.report("dynamic_ref",pointer,keyword)}else if(failingKeywords.has(keyword)||keyword==="$defs"&&pointer!==""){ctx.report("unsupported_keyword",pointer,keyword)}else if(!supportedKeywords.has(keyword)&&!keyword.startsWith("x-")){ctx.report("unknown_keyword",pointer,keyword)}}};var parseAnnotations=(ctx,schema,pointer)=>{const title=read(ctx,schema,pointer,"title",isString);const description=read(ctx,schema,pointer,"description",isString);const deprecated=read(ctx,schema,pointer,"deprecated",isBoolean);const readOnly=read(ctx,schema,pointer,"readOnly",isBoolean);const writeOnly=read(ctx,schema,pointer,"writeOnly",isBoolean);const examples=read(ctx,schema,pointer,"examples",isArray);return{default:schema.default,deprecated,description,examples,readOnly,title,writeOnly}};var definitionName=(reference)=>{const prefix="#/$defs/";if(!reference.startsWith(prefix)){return}const key=reference.slice(prefix.length);return key.includes("/")?undefined:key.replaceAll("~1","/").replaceAll("~0","~")};var parseReference=(ctx,schema,pointer)=>{const target=read(ctx,schema,pointer,"$ref",isString);if(target===undefined){return}if(!target.startsWith("#")){ctx.report("remote_ref",pointer,"$ref");return}if(target==="#"){ctx.report("recursive_ref",pointer,"$ref");return}const name=definitionName(target);if(name===undefined||!ctx.definitionNames.has(name)){ctx.report("unresolved_ref",pointer,"$ref");return}ctx.references.push({name,owner:ctx.owner,pointer});return facet(pointer,{kind:"ref",name})};var parseExtra=(ctx,schema,pointer,keyword,whenAbsent)=>{const value=schema[keyword];if(value===undefined){return{kind:whenAbsent}}if(value===true){return{kind:"open"}}if(value===false){return{kind:"closed"}}const node=ctx.parseNode(ctx,value,childPointer(pointer,keyword));return node.form.kind==="unknown"?{kind:"open"}:{kind:"schema",node}};var parseString=(ctx,schema,pointer)=>{const minLength=read(ctx,schema,pointer,"minLength",isCount);const maxLength=read(ctx,schema,pointer,"maxLength",isCount);const pattern=read(ctx,schema,pointer,"pattern",isString);const format=read(ctx,schema,pointer,"format",isString);return{format,kind:"string",maxLength,minLength,pattern}};var parseNumber=(ctx,schema,pointer,kind)=>{const minimum=read(ctx,schema,pointer,"minimum",isNumber);const maximum=read(ctx,schema,pointer,"maximum",isNumber);const exclusiveMinimum=read(ctx,schema,pointer,"exclusiveMinimum",isNumber);const exclusiveMaximum=read(ctx,schema,pointer,"exclusiveMaximum",isNumber);const multipleOf=read(ctx,schema,pointer,"multipleOf",isNumber);return{exclusiveMaximum,exclusiveMinimum,kind,maximum,minimum,multipleOf}};var parseObject=(ctx,schema,pointer)=>{const requiredNames=read(ctx,schema,pointer,"required",isStringArray)??[];const required=new Set(requiredNames);const declared=read(ctx,schema,pointer,"properties",isObject)??{};const properties=Object.entries(declared).map(([name,value])=>({name,node:ctx.parseNode(ctx,value,childPointer(pointer,"properties",name)),required:required.has(name)}));const additionalProperties=parseExtra(ctx,schema,pointer,"additionalProperties","absent");const undeclared=requiredNames.flatMap((name,index)=>{if(Object.hasOwn(declared,name)||requiredNames.indexOf(name)!==index){return[]}if(additionalProperties.kind==="closed"){ctx.report("unsupported_keyword_combination",childPointer(pointer,"required",String(index)),"required+additionalProperties");return[]}return[{name,node:additionalProperties.kind==="schema"?additionalProperties.node:unknownNode(pointer),required:true}]});const minProperties=read(ctx,schema,pointer,"minProperties",isCount);const maxProperties=read(ctx,schema,pointer,"maxProperties",isCount);return{additionalProperties,kind:"object",maxProperties,minProperties,properties:[...properties,...undeclared]}};var parseArray=(ctx,schema,pointer)=>{const prefixItems=(read(ctx,schema,pointer,"prefixItems",isArray)??[]).map((value,index)=>ctx.parseNode(ctx,value,childPointer(pointer,"prefixItems",String(index))));const items=parseExtra(ctx,schema,pointer,"items","open");const minItems=read(ctx,schema,pointer,"minItems",isCount);const maxItems=read(ctx,schema,pointer,"maxItems",isCount);const uniqueItems=read(ctx,schema,pointer,"uniqueItems",isBoolean);return{items,kind:"array",maxItems,minItems,prefixItems,uniqueItems}};var parseType=(ctx,schema,pointer,typeName)=>{switch(typeName){case"string":{return parseString(ctx,schema,pointer)}case"number":case"integer":{return parseNumber(ctx,schema,pointer,typeName)}case"boolean":case"null":{return{kind:typeName}}case"object":{return parseObject(ctx,schema,pointer)}case"array":{return parseArray(ctx,schema,pointer)}default:{return unreachable(typeName)}}};var readTypeNames=(ctx,schema,pointer)=>{const value=schema.type;if(value===undefined){return}const names=isArray(value)?value:[value];if(names.length===0||!names.every(isTypeName)){ctx.report("invalid_value",pointer,"type");return}return[...new Set(names)]};var parseWithoutType=(ctx,schema,pointer)=>{for(const[typeName,keywords]of[["string",familyKeywords.string],["number",familyKeywords.number],["object",familyKeywords.object],["array",familyKeywords.array]]){const present=keywords.filter((keyword)=>Object.hasOwn(schema,keyword));if(present.length>0){parseType(ctx,schema,pointer,typeName)}if(schema.type===undefined){for(const keyword of present){ctx.report("unsupported_keyword_combination",pointer,keyword)}}}};var matchesType=(value,typeName)=>{switch(typeName){case"string":{return isString(value)}case"boolean":{return isBoolean(value)}case"number":{return isNumber(value)}case"integer":{return Number.isInteger(value)}case"null":{return value===null}case"object":{return isObject(value)}case"array":{return Array.isArray(value)}default:{return unreachable(typeName)}}};var typeAddsNothing=(schema,declaredTypes,literals)=>literals.length>0&&!Object.values(familyKeywords).flat().some((keyword)=>Object.hasOwn(schema,keyword))&&literals.every((value)=>declaredTypes.some((typeName)=>matchesType(value,typeName)));var parseTypeFacet=(ctx,schema,pointer,declaredTypes)=>{const[first,...rest]=declaredTypes.map((typeName)=>facet(pointer,parseType(ctx,schema,pointer,typeName)));if(first===undefined||rest.length===0){return first}return facet(pointer,{exclusive:false,kind:"union",members:[first,...rest]})};var parseMembers=(ctx,schema,pointer,keyword)=>readNonEmptyArray(ctx,schema,pointer,keyword)?.map((value,index)=>ctx.parseNode(ctx,value,childPointer(pointer,keyword,String(index))));var parseSchemaObject=(ctx,schema,pointer)=>{checkKeywords(ctx,schema,pointer);const annotations=parseAnnotations(ctx,schema,pointer);const facets=[];const reference=parseReference(ctx,schema,pointer);if(reference!==undefined){facets.push(reference)}const enumValues=readNonEmptyArray(ctx,schema,pointer,"enum");if(enumValues!==undefined){facets.push(facet(pointer,{kind:"enum",values:enumValues}))}if(schema.const!==undefined){facets.push(facet(pointer,{kind:"const",value:schema.const}))}const declaredTypes=readTypeNames(ctx,schema,pointer);const literals=[...enumValues??[],...schema.const===undefined?[]:[schema.const]];if(declaredTypes===undefined){parseWithoutType(ctx,schema,pointer)}const typeFacet=declaredTypes===undefined||typeAddsNothing(schema,declaredTypes,literals)?undefined:parseTypeFacet(ctx,schema,pointer,declaredTypes);if(typeFacet!==undefined){facets.push(typeFacet)}const anyOf=parseMembers(ctx,schema,pointer,"anyOf");if(anyOf!==undefined){facets.push(facet(pointer,{exclusive:false,kind:"union",members:anyOf}))}const oneOf=parseMembers(ctx,schema,pointer,"oneOf");if(oneOf!==undefined){facets.push(facet(pointer,{exclusive:true,kind:"union",members:oneOf}))}const allOf=parseMembers(ctx,schema,pointer,"allOf");if(allOf!==undefined){facets.push(facet(pointer,{kind:"all",members:allOf}))}const[only,...others]=facets;if(only===undefined){return{annotations,form:{kind:"unknown"},pointer}}return others.length===0?{...only,annotations}:{annotations,form:{kind:"all",members:facets},pointer}};var parseNode=(ctx,value,pointer)=>{if(value===true){return unknownNode(pointer)}if(!isObject(value)){ctx.report("invalid_value",pointer,null);return unknownNode(pointer)}return parseSchemaObject(ctx,value,pointer)};var dependenciesOf=(references,owner)=>references.filter((reference)=>reference.owner===owner).map((reference)=>reference.name);var reaches=(references,from,to)=>{const visited=new Set;const pending=[from];for(const current of pending){if(current===to){return true}if(!visited.has(current)){visited.add(current);pending.push(...dependenciesOf(references,current))}}return false};var reportRecursiveReferences=(ctx,references)=>{for(const{owner,name,pointer}of references){if(owner!==null&&reaches(references,name,owner)){ctx.report("recursive_ref",pointer,"$ref")}}};var inDependencyOrder=(definitions,references)=>{const byName=new Map(definitions.map((definition)=>[definition.name,definition]));const ordered=new Set;const visited=new Set;const visit=(name)=>{if(visited.has(name)){return}visited.add(name);for(const dependency of dependenciesOf(references,name)){visit(dependency)}const definition=byName.get(name);if(definition!==undefined){ordered.add(definition)}};for(const{name}of definitions){visit(name)}return[...ordered]};var parseSchema=({name,document})=>{const{report,errors}=createErrorCollector(name);const declared=document.$defs;const entries=isObject(declared)?Object.entries(declared):[];if(declared!==undefined&&!isObject(declared)){report("invalid_value","","$defs")}const references=[];const ctx={definitionNames:new Set(entries.map(([key])=>key)),owner:null,parseNode,references,report};const root=parseSchemaObject(ctx,document,"");const definitions=entries.map(([key,value])=>({name:key,node:ctx.parseNode({...ctx,owner:key},value,childPointer("","$defs",key))}));reportRecursiveReferences(ctx,references);if(errors.length>0){return{errors}}return{model:{definitions:inDependencyOrder(definitions,references),name,root}}};var wordSeparator=/[^A-Za-z0-9]+/u;var pascalCase=(text)=>text.split(wordSeparator).map((segment)=>segment.charAt(0).toUpperCase()+segment.slice(1)).join("");var splitName=(input)=>{const at=input.name.indexOf("#");return{fqn:input.name.slice(0,at),label:input.name.slice(at+1)}};var withoutPackage=(fqn,packageFqn)=>{if(fqn===packageFqn){return""}const prefix=`${packageFqn}.`;return fqn.startsWith(prefix)?fqn.slice(prefix.length):fqn};var compare=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var nameSchemas=(packageFqn,schemas)=>{const named=schemas.map((input)=>({input,...splitName(input)})).sort((left,right)=>compare(left.fqn,right.fqn)||compare(left.label,right.label)).map(({input,fqn,label})=>({exportName:pascalCase(withoutPackage(fqn,packageFqn))+pascalCase(label),input}));const uses=new Map;for(const{exportName}of named){uses.set(exportName,(uses.get(exportName)??0)+1)}const errors=named.filter(({exportName})=>(uses.get(exportName)??0)>1).map(({input})=>({code:"name_clash",keyword:null,pointer:"",schemaName:input.name}));return errors.length>0?{errors}:{named}};var defName=(exportName,key)=>exportName+pascalCase(key);var tupleLayout=({items,maxItems,minItems,prefixItems})=>({elements:prefixItems.slice(0,maxItems).map((node,index)=>({node,required:index<(minItems??0)})),rest:maxItems!==undefined&&maxItems<=prefixItems.length?{kind:"closed"}:items});var isMap=(value)=>!Array.isArray(value)&&Object(value)===value;var isList=(value)=>Array.isArray(value);var quote=(text)=>JSON.stringify(text);var plainKey=/^[A-Za-z_$][A-Za-z0-9_$]*$/u;var propertyKey=(name)=>{if(name==="__proto__"){return'["__proto__"]'}return plainKey.test(name)?name:quote(name)};var valueSource=(value)=>{if(isList(value)){return`[${value.map(valueSource).join(", ")}]`}if(isMap(value)){const entries=Object.entries(value).map(([name,item])=>`${propertyKey(name)}: ${valueSource(item)}`);return entries.length===0?"{}":`{ ${entries.join(", ")} }`}return JSON.stringify(value)};var importLine='import * as Schema from "effect/Schema"';var anyValue="Schema.Unknown";var invalid="Schema.Never";var ignore=()=>{};var printNode=(ctx,node,depth)=>ctx.print(ctx,node,depth);var unreachable2=(value)=>{throw new Error(`Unhandled case: ${String(value)}`)};var isPrimitive=(value)=>value!==null&&Object(value)!==value;var indent=(depth)=>" ".repeat(depth);var list=(open,close,items,depth)=>items.some((item)=>item.includes(`
|
|
3
|
+
`))?`${open}
|
|
4
|
+
${items.map((item)=>`${indent(depth+1)}${item}`).join(`,
|
|
5
|
+
`)}
|
|
6
|
+
${indent(depth)}${close}`:`${open}${items.join(", ")}${close}`;var struct=(entries,depth)=>entries.length===0?"Schema.Struct({})":`Schema.Struct({
|
|
7
|
+
${entries.map((entry)=>`${indent(depth+1)}${entry}`).join(`,
|
|
8
|
+
`)}
|
|
9
|
+
${indent(depth)}})`;var withChecks=(base,checks)=>checks.length===0?base:`${base}.check(${checks.join(", ")})`;var optionalKey=(expr)=>`Schema.optionalKey(${expr})`;var entry=(key,value)=>value===undefined?[]:[`${key}: ${valueSource(value)}`];var annotationEntries=(annotations,notes)=>[...entry("default",annotations.default),...entry("deprecated",annotations.deprecated),...entry("description",annotations.description),...entry("examples",annotations.examples),...notes,...entry("readOnly",annotations.readOnly),...entry("title",annotations.title),...entry("writeOnly",annotations.writeOnly)];var check=(name,bound)=>bound===undefined?[]:[`Schema.${name}(${bound})`];var stringChecks=({format,maxLength,minLength,pattern})=>[...check("isMinLength",minLength),...check("isMaxLength",maxLength),...pattern===undefined?[]:[`Schema.isPattern(new RegExp(${JSON.stringify(pattern)}))`],...format==="uuid"?["Schema.isUUID()"]:[]];var numberChecks=(form)=>[...form.kind==="integer"?["Schema.isInt()"]:[],...check("isGreaterThanOrEqualTo",form.minimum),...check("isGreaterThan",form.exclusiveMinimum),...check("isLessThanOrEqualTo",form.maximum),...check("isLessThan",form.exclusiveMaximum),...check("isMultipleOf",form.multipleOf)];var arrayChecks=({maxItems,minItems,uniqueItems})=>[...check("isMinLength",minItems),...check("isMaxLength",maxItems),...uniqueItems===true?["Schema.isUnique()"]:[]];var propertyCountChecks=({maxProperties,minProperties})=>[...check("isMinProperties",minProperties),...check("isMaxProperties",maxProperties)];var warnClosed=(ctx,pointer)=>{ctx.warn("closed_object_unenforced",pointer,"additionalProperties","additionalProperties false is not enforced: Schema.Struct ignores excess keys.")};var printsStruct=({additionalProperties:extra,properties})=>extra.kind==="closed"||extra.kind==="absent"&&properties.length>0;var droppedBoundNotes=(ctx,node)=>{const{form}=node;if(form.kind!=="object"||!printsStruct(form)){return[]}return[["minProperties",form.minProperties],["maxProperties",form.maxProperties]].flatMap(([keyword,bound])=>{if(bound===undefined){return[]}ctx.warn("dropped_keyword",node.pointer,keyword,`${keyword} is kept as an annotation: Schema.Struct decodes declared keys only.`);return[`${keyword}: ${bound}`]})};var formatNotes=(ctx,node)=>{const{form}=node;if(form.kind!=="string"||form.format===undefined){return[]}if(form.format==="uuid"){return[]}ctx.warn("format_annotation_only",node.pointer,"format",`format "${form.format}" is kept as an annotation: Schema has no check for it.`);return[`format: ${JSON.stringify(form.format)}`]};var restSchema=(ctx,extra,depth)=>extra.kind==="schema"?printNode(ctx,extra.node,depth):anyValue;var printProperty=(ctx,property,depth)=>{const expr=printNode(ctx,property.node,depth);return property.required?expr:optionalKey(expr)};var printStruct=(ctx,properties,depth)=>struct(properties.map((property)=>`${propertyKey(property.name)}: ${printProperty(ctx,property,depth+1)}`),depth);var objectRest=(ctx,pointer,{additionalProperties:extra,properties},depth)=>{if(extra.kind!=="schema"||properties.length===0){return restSchema(ctx,extra,depth)}const quiet={...ctx,report:ignore,warn:ignore};const members=new Set([printNode(ctx,extra.node,depth+1),...properties.map(({node})=>printNode(quiet,node,depth+1))]);if(members.size>1){ctx.warn("dropped_keyword",pointer,"additionalProperties","additionalProperties is loosened: extra keys also accept the type of a declared property.")}return`Schema.Union(${list("[","]",[...members],depth)})`};var printObject=(ctx,node,form,depth)=>{const{additionalProperties:extra,properties}=form;const closed=extra.kind==="closed";if(closed){warnClosed(ctx,node.pointer)}if(printsStruct(form)){return printStruct(ctx,properties,depth)}const record=(recordDepth)=>`Schema.Record(Schema.String, ${objectRest(ctx,node.pointer,form,recordDepth)})`;const base=properties.length===0?record(depth):`Schema.StructWithRest(${printStruct(ctx,properties,depth)}, ${list("[","]",[record(depth+1)],depth)})`;return withChecks(base,propertyCountChecks(form))};var printItems=(ctx,form,depth)=>{const{elements,rest}=tupleLayout(form);if(form.prefixItems.length===0){return rest.kind==="closed"?"Schema.Tuple([])":`Schema.Array(${restSchema(ctx,rest,depth)})`}const tuple=`Schema.Tuple(${list("[","]",elements.map(({node,required})=>printProperty(ctx,{name:"",node,required},depth+1)),depth)})`;return rest.kind==="closed"?tuple:`Schema.TupleWithRest(${tuple}, ${list("[","]",[restSchema(ctx,rest,depth+1)],depth)})`};var printArray=(ctx,form,depth)=>withChecks(printItems(ctx,form,depth),arrayChecks(form));var printLiterals=(ctx,node,keyword,values,depth)=>{if(values.some((value)=>value!==null&&!isPrimitive(value))){ctx.report("unsupported_literal",node.pointer,keyword);return invalid}const literals=values.filter(isPrimitive);const[first]=literals;if(first===undefined){return"Schema.Null"}const base=literals.length===1?`Schema.Literal(${JSON.stringify(first)})`:`Schema.Literals(${list("[","]",literals.map((literal)=>JSON.stringify(literal)),depth)})`;return literals.length<values.length?`Schema.NullOr(${base})`:base};var throughRef=(ctx,pointer,resolve)=>{const seen=new Set;return resolve({...ctx,report:(code,_pointer,keyword)=>{const key=`${code}:${keyword??""}`;if(!seen.has(key)){seen.add(key);ctx.report(code,pointer,keyword)}},warn:ignore})};var facetKeyword=({form})=>{switch(form.kind){case"ref":{return"$ref"}case"enum":{return"enum"}case"const":{return"const"}case"union":{return form.exclusive?"oneOf":"anyOf"}case"all":{return"allOf"}case"unknown":case"boolean":case"null":case"string":case"number":case"integer":case"object":case"array":{return"type"}default:{return unreachable2(form)}}};var plainFields=(ctx,node,depth)=>{const{form}=node;if(form.kind==="all"){const facets=form.members.filter((member)=>member.pointer===node.pointer);let combined=true;const facetCtx={...ctx,report:(code,pointer,keyword)=>{if(code==="allof_not_plain_objects"){combined=false}else{ctx.report(code,pointer,keyword)}}};const fields=form.members.flatMap((member)=>plainFields(facets.includes(member)&&member.form.kind!=="all"?facetCtx:ctx,member,depth));if(!combined){ctx.report("unsupported_keyword_combination",node.pointer,[...new Set(facets.map(facetKeyword))].join("+"))}return fields}if(form.kind==="ref"){const target=ctx.definitions.get(form.name);if(target===undefined){ctx.report("unresolved_ref",node.pointer,"$ref");return[]}return throughRef(ctx,node.pointer,(quiet)=>plainFields(quiet,target,depth))}if(form.kind==="object"&&(form.additionalProperties.kind==="absent"||form.additionalProperties.kind==="closed")&&form.minProperties===undefined&&form.maxProperties===undefined){if(form.additionalProperties.kind==="closed"){warnClosed(ctx,node.pointer)}return form.properties.map((property)=>({expr:printNode(ctx,property.node,depth),name:property.name,pointer:property.node.pointer,required:property.required}))}ctx.report("allof_not_plain_objects",node.pointer,null);return[]};var combine=(ctx,known,field)=>{const required=known.required||field.required;if(field.expr===anyValue||field.expr===known.expr){return{...known,required}}if(known.expr===anyValue){return{...field,required}}ctx.report("allof_property_conflict",field.pointer,null);return{...known,required}};var printAll=(ctx,node,depth)=>{const merged=new Map;for(const field of plainFields(ctx,node,depth+1)){const known=merged.get(field.name);merged.set(field.name,known===undefined?field:combine(ctx,known,field))}return struct([...merged.values()].map((field)=>`${propertyKey(field.name)}: ${field.required?field.expr:optionalKey(field.expr)}`),depth)};var printForm=(ctx,node,depth)=>{const{form}=node;switch(form.kind){case"unknown":{return anyValue}case"boolean":{return"Schema.Boolean"}case"null":{return"Schema.Null"}case"string":{return withChecks("Schema.String",stringChecks(form))}case"number":case"integer":{return withChecks("Schema.Number",numberChecks(form))}case"object":{return printObject(ctx,node,form,depth)}case"array":{return printArray(ctx,form,depth)}case"enum":{return printLiterals(ctx,node,"enum",form.values,depth)}case"const":{return printLiterals(ctx,node,"const",[form.value],depth)}case"ref":{return defName(ctx.exportName,form.name)}case"union":{const members=list("[","]",form.members.map((member)=>printNode(ctx,member,depth+1)),depth);return form.exclusive?`Schema.Union(${members}, { mode: "oneOf" })`:`Schema.Union(${members})`}case"all":{return printAll(ctx,node,depth)}default:{return unreachable2(form)}}};var printAnnotated=(ctx,node,depth)=>{const expr=printForm(ctx,node,depth);const entries=annotationEntries(node.annotations,[...formatNotes(ctx,node),...droppedBoundNotes(ctx,node)]);return entries.length===0?expr:`${expr}.annotate({ ${entries.join(", ")} })`};var printSchema=({exportName,model,schemaName},warnings,errors)=>{const collector=createErrorCollector(schemaName);const ctx={definitions:new Map(model.definitions.map(({name,node})=>[name,node])),exportName,print:printAnnotated,report:collector.report,warn:(kind,pointer,keyword,message)=>{warnings.push({keyword,kind,message,pointer,schemaName})}};const definitions=model.definitions.map(({name,node})=>`const ${defName(exportName,name)} = ${printNode(ctx,node,0)}`);const root=printNode(ctx,model.root,0);errors.push(...collector.errors);return[...definitions,`export const ${exportName} = ${root}
|
|
10
|
+
export type ${exportName} = typeof ${exportName}["Encoded"]`]};var printEffect=(schemas)=>{const warnings=[];const errors=[];const blocks=schemas.flatMap((schema)=>printSchema(schema,warnings,errors));if(errors.length>0){return{errors}}return{source:`${[importLine,...blocks].join(`
|
|
11
|
+
|
|
12
|
+
`)}
|
|
13
|
+
`,warnings}};var rank={intersection:1,primary:0,union:2};var operator={intersection:" & ",union:" | "};var identifier=/^[A-Za-z_$][\w$]*$/u;var lineBreak=/\r?\n/u;var unreachable3=(value)=>{throw new Error(`Unhandled case: ${String(value)}`)};var indent2=(depth)=>" ".repeat(depth);var literal=(value)=>JSON.stringify(value);var propertyKey2=(name)=>identifier.test(name)?name:JSON.stringify(name);var atom=(text)=>({precedence:"primary",text});var commentLines=(text)=>text.replaceAll("*/","*\\/").split(lineBreak).map((line)=>line.trimEnd());var droppedFrom=(entries)=>entries.flatMap(([keyword,value])=>value===undefined?[]:[{keyword,value:String(value)}]);var droppedKeywords=(form)=>{switch(form.kind){case"string":{return droppedFrom([["minLength",form.minLength],["maxLength",form.maxLength],["pattern",form.pattern],["format",form.format]])}case"number":case"integer":{return droppedFrom([["minimum",form.minimum],["exclusiveMinimum",form.exclusiveMinimum],["maximum",form.maximum],["exclusiveMaximum",form.exclusiveMaximum],["multipleOf",form.multipleOf]])}case"object":{return droppedFrom([["minProperties",form.minProperties],["maxProperties",form.maxProperties]])}case"array":{return droppedFrom([["minItems",form.minItems],["maxItems",form.maxItems],["uniqueItems",form.uniqueItems===true?"true":undefined]])}case"unknown":case"boolean":case"null":case"enum":case"const":case"ref":case"union":case"all":{return[]}default:{return unreachable3(form)}}};var docOf=(node,dropped)=>{const{default:defaultValue,description,title}=node.annotations;const paragraphs=[title,description].map((text)=>text?.trim()??"").filter((text)=>text!=="").map(commentLines);const tags=[...defaultValue===undefined?[]:[`@default ${JSON.stringify(defaultValue)}`],...dropped.map(({keyword,value})=>`@${keyword} ${value}`)].flatMap(commentLines);return[...paragraphs,tags].filter((section)=>section.length>0).flatMap((section,index)=>index===0?section:["",...section])};var docBlock=(doc,depth)=>{const[first,...others]=doc;if(first===undefined){return""}const pad=indent2(depth);if(others.length===0){return`${pad}/** ${first} */
|
|
14
|
+
`}const lines=doc.map((line)=>line===""?`${pad} *`:`${pad} * ${line}`);return`${[`${pad}/**`,...lines,`${pad} */`].join(`
|
|
15
|
+
`)}
|
|
16
|
+
`};var withInlineDoc=({doc,precedence,text})=>({precedence,text:doc.length===0?text:`/** ${doc.filter((line)=>line!=="").join(" ")} */ ${text}`});var within=({precedence,text},limit)=>rank[precedence]>rank[limit]?`(${text})`:text;var joinBodies=(bodies,precedence)=>{const members=[...new Map(bodies.map((body)=>[body.text,body])).values()];const[only]=members;if(members.length===1&&only!==undefined){return only}return{precedence,text:members.map((member)=>within(member,precedence)).join(operator[precedence])}};var reportDropped=(ctx,node,dropped)=>{for(const{keyword}of dropped){ctx.warnings.push({keyword,kind:"dropped_keyword",message:`The ${keyword} keyword has no TypeScript type. It stays as a JSDoc tag.`,pointer:node.pointer,schemaName:ctx.schemaName})}};var extraPart=(ctx,extra,depth)=>{switch(extra.kind){case"absent":case"open":{return{doc:[],...atom("unknown")}}case"closed":{return}case"schema":{return ctx.renderNode(ctx,extra.node,depth)}default:{return unreachable3(extra)}}};var indexType=(properties,extra)=>{if(extra.text==="unknown"){return"unknown"}const members=new Set([...properties.map(({part})=>part.text),extra.text,...properties.some(({required})=>!required)?["undefined"]:[]]);return[...members].join(" | ")};var renderObject=(ctx,form,depth)=>{const properties=form.properties.map((property)=>({name:property.name,part:ctx.renderNode(ctx,property.node,depth+1),required:property.required}));const additional=form.additionalProperties.kind==="absent"?{kind:properties.length===0?"open":"closed"}:form.additionalProperties;const extra=extraPart(ctx,additional,depth+1);const lines=properties.map(({name,part,required})=>`${docBlock(part.doc,depth+1)}${indent2(depth+1)}${propertyKey2(name)}${required?"":"?"}: ${part.text}`);if(extra!==undefined){lines.push(`${docBlock(extra.doc,depth+1)}${indent2(depth+1)}[key: string]: ${indexType(properties,extra)}`)}else if(properties.length===0){lines.push(`${indent2(depth+1)}[key: string]: never`)}return atom(`{
|
|
17
|
+
${lines.join(`
|
|
18
|
+
`)}
|
|
19
|
+
${indent2(depth)}}`)};var elementOf=(part)=>part.doc.length>0?`(${withInlineDoc(part).text})`:within(part,"primary");var optionalElement=(part)=>part.doc.length>0||part.precedence!=="primary"?`(${withInlineDoc(part).text})?`:`${part.text}?`;var renderArray=(ctx,form,depth)=>{const layout=tupleLayout(form);const prefix=layout.elements.map(({node,required})=>{const part=ctx.renderNode(ctx,node,depth);return required?withInlineDoc(part).text:optionalElement(part)});const items=extraPart(ctx,layout.rest,depth);const rest=items===undefined?undefined:elementOf(items);if(form.prefixItems.length===0){return atom(rest===undefined?"[]":`${rest}[]`)}const elements=rest===undefined?prefix:[...prefix,`...${rest}[]`];return atom(`[${elements.join(", ")}]`)};var renderForm=(ctx,node,depth)=>{const{form}=node;switch(form.kind){case"unknown":{return atom("unknown")}case"boolean":{return atom("boolean")}case"null":{return atom("null")}case"string":{return atom("string")}case"number":case"integer":{return atom("number")}case"enum":{return joinBodies(form.values.map((value)=>atom(literal(value))),"union")}case"const":{return atom(literal(form.value))}case"ref":{return atom(defName(ctx.exportName,form.name))}case"object":{return renderObject(ctx,form,depth)}case"array":{return renderArray(ctx,form,depth)}case"union":case"all":{return joinBodies(form.members.map((member)=>withInlineDoc(ctx.renderNode(ctx,member,depth))),form.kind==="union"?"union":"intersection")}default:{return unreachable3(form)}}};var renderNode=(ctx,node,depth)=>{const dropped=droppedKeywords(node.form);reportDropped(ctx,node,dropped);return{...renderForm(ctx,node,depth),doc:docOf(node,dropped)}};var declaration=(ctx,name,node,exported)=>{const part=renderNode(ctx,node,0);return`${docBlock(part.doc,0)}${exported?"export ":""}type ${name} = ${part.text}`};var declarationsOf=(warnings,{exportName,model,schemaName})=>{const ctx={exportName,renderNode,schemaName,warnings};return[...model.definitions.map(({name,node})=>declaration(ctx,defName(exportName,name),node,false)),declaration(ctx,exportName,model.root,true)]};var printTypes=(schemas)=>{const warnings=[];const declarations=schemas.flatMap((schema)=>declarationsOf(warnings,schema));return{source:declarations.length===0?"":`${declarations.join(`
|
|
20
|
+
|
|
21
|
+
`)}
|
|
22
|
+
`,warnings}};var maxLineLength=80;var unreachable4=(value)=>{throw new Error(`Unhandled case: ${String(value)}`)};var isText=(value)=>String(value)===value;var importStatement=`import { z } from ${quote("zod")}`;var indent3=(text)=>text.split(`
|
|
23
|
+
`).map((line)=>` ${line}`).join(`
|
|
24
|
+
`);var block=(open,items,close)=>items.length===0?`${open}${close}`:`${open}
|
|
25
|
+
${items.map(indent3).join(`,
|
|
26
|
+
`)}
|
|
27
|
+
${close}`;var list2=(open,items,close)=>{const line=`${open}${items.join(", ")}${close}`;return line.length<=maxLineLength&&!line.includes(`
|
|
28
|
+
`)?line:block(open,items,close)};var literalSource=(value)=>{if(isList(value)){return list2("z.tuple([",value.map(literalSource),"])")}if(isMap(value)){return block("z.strictObject({",Object.entries(value).map(([name,item])=>`${propertyKey(name)}: ${literalSource(item)}`),"})")}return`z.literal(${JSON.stringify(value)})`};var enumSource=(values)=>{const[only,...others]=values;if(only!==undefined&&others.length===0){return literalSource(only)}return values.every(isText)?list2("z.enum([",values.map(valueSource),"])"):list2("z.union([",values.map(literalSource),"])")};var call=(value,render)=>value===undefined?[]:[render(value)];var stringFormats=new Map([["date-time","z.iso.datetime()"],["email","z.email()"],["uuid","z.uuid()"],["uri","z.url()"]]);var stringBase=(format)=>{if(format===undefined){return"z.string()"}return stringFormats.get(format)??"z.string()"};var stringSource=({format,minLength,maxLength,pattern})=>[stringBase(format),...call(minLength,(value)=>`.min(${value})`),...call(maxLength,(value)=>`.max(${value})`),...call(pattern,(value)=>`.regex(new RegExp(${quote(value)}))`)].join("");var numberSource=({kind,minimum,exclusiveMinimum,maximum,exclusiveMaximum,multipleOf})=>[kind==="integer"?"z.int()":"z.number()",...call(minimum,(value)=>`.gte(${value})`),...call(exclusiveMinimum,(value)=>`.gt(${value})`),...call(maximum,(value)=>`.lte(${value})`),...call(exclusiveMaximum,(value)=>`.lt(${value})`),...call(multipleOf,(value)=>`.multipleOf(${value})`)].join("");var objectSource=(ctx,{properties,additionalProperties})=>{const entries=properties.map(({name,node,required})=>`${propertyKey(name)}: ${ctx.print(node)}${required?"":".optional()"}`);switch(additionalProperties.kind){case"absent":{return entries.length===0?"z.record(z.string(), z.unknown())":block("z.object({",entries,"})")}case"closed":{return block("z.strictObject({",entries,"})")}case"open":{return entries.length===0?"z.record(z.string(), z.unknown())":block("z.looseObject({",entries,"})")}case"schema":{const rest=ctx.print(additionalProperties.node);return entries.length===0?`z.record(z.string(), ${rest})`:`${block("z.looseObject({",entries,"})")}.catchall(${rest})`}default:{return unreachable4(additionalProperties)}}};var restSource=(ctx,items)=>{switch(items.kind){case"absent":case"open":{return"z.unknown()"}case"closed":{return}case"schema":{return ctx.print(items.node)}default:{return unreachable4(items)}}};var arraySource=(ctx,form)=>{const{minItems,maxItems}=form;const layout=tupleLayout(form);const prefix=layout.elements.map(({node,required})=>`${ctx.print(node)}${required?"":".optional()"}`);const rest=restSource(ctx,layout.rest);if(form.prefixItems.length===0&&rest!==undefined){return[`z.array(${rest})`,...call(minItems,(value)=>`.min(${value})`),...call(maxItems,(value)=>`.max(${value})`)].join("")}return[list2("z.tuple([",prefix,rest===undefined?"])":`], ${rest})`),...call(minItems,(value)=>`.check(z.minLength(${value}))`),...call(maxItems,(value)=>`.check(z.maxLength(${value}))`)].join("")};var intersectionSource=(members)=>{const[first="z.unknown()",...rest]=members;let source=first;for(const member of rest){source=list2("z.intersection(",[source,member],")")}return source};var formSource=(ctx,form)=>{switch(form.kind){case"unknown":{return"z.unknown()"}case"boolean":{return"z.boolean()"}case"null":{return"z.null()"}case"string":{return stringSource(form)}case"number":case"integer":{return numberSource(form)}case"object":{return objectSource(ctx,form)}case"array":{return arraySource(ctx,form)}case"enum":{return enumSource(form.values)}case"const":{return literalSource(form.value)}case"ref":{return defName(ctx.exportName,form.name)}case"union":{return list2(form.exclusive?"z.xor([":"z.union([",form.members.map((node)=>ctx.print(node)),"])")}case"all":{return intersectionSource(form.members.map((node)=>ctx.print(node)))}default:{return unreachable4(form)}}};var warn=(ctx,node,kind,keyword,message)=>{ctx.warnings.push({keyword,kind,message,pointer:node.pointer,schemaName:ctx.schemaName})};var dropKeyword=(ctx,node,keyword,value)=>{warn(ctx,node,"dropped_keyword",keyword,`Keyword "${keyword}" has no zod check and stays as .meta data.`);return[keyword,value]};var formNotes=(ctx,node)=>{const{form}=node;switch(form.kind){case"string":{if(form.format===undefined||stringFormats.has(form.format)){return[]}warn(ctx,node,"format_annotation_only","format",`Format "${form.format}" has no zod check and stays as .meta data.`);return[["format",form.format]]}case"object":{return[...form.minProperties===undefined?[]:[dropKeyword(ctx,node,"minProperties",form.minProperties)],...form.maxProperties===undefined?[]:[dropKeyword(ctx,node,"maxProperties",form.maxProperties)]]}case"array":{return form.uniqueItems===true?[dropKeyword(ctx,node,"uniqueItems",true)]:[]}default:{return[]}}};var annotationNotes=({annotations})=>[["title",annotations.title],["description",annotations.description],["deprecated",annotations.deprecated],["readOnly",annotations.readOnly],["writeOnly",annotations.writeOnly],["default",annotations.default],["examples",annotations.examples]].flatMap(([keyword,value])=>value===undefined?[]:[[keyword,value]]);var expression=(ctx,node)=>{const source=formSource(ctx,node.form);const notes=[...annotationNotes(node),...formNotes(ctx,node)];if(notes.length===0){return source}const entries=notes.map(([keyword,value])=>`${keyword}: ${valueSource(value)}`);return`${source}.meta({ ${entries.join(", ")} })`};var declarations=({exportName,model,schemaName},warnings)=>{const ctx={exportName,print:(node)=>expression(ctx,node),schemaName,warnings};const locals=model.definitions.map(({name,node})=>`const ${defName(exportName,name)} = ${ctx.print(node)}`);const root=[`export const ${exportName} = ${expression(ctx,model.root)}`,`export type ${exportName} = z.input<typeof ${exportName}>`].join(`
|
|
29
|
+
`);return[...locals,root].join(`
|
|
30
|
+
|
|
31
|
+
`)};var printZod=(schemas)=>{if(schemas.length===0){return{source:"",warnings:[]}}const warnings=[];const body=schemas.map((schema)=>declarations(schema,warnings));return{source:`${importStatement}
|
|
32
|
+
|
|
33
|
+
${body.join(`
|
|
34
|
+
|
|
35
|
+
`)}
|
|
36
|
+
`,warnings}};var printers={effect:printEffect,types:printTypes,zod:printZod};var reservedNames={effect:["Infinity","RegExp","Schema"],types:[],zod:["Infinity","RegExp","z"]};var identifier2=/^[A-Za-z_$][A-Za-z0-9_$]*$/u;var error=(code,schemaName,pointer)=>({code,keyword:null,pointer,schemaName});var hasSlot=({name})=>name.includes("#");var compare2=(left,right)=>{if(left===right){return 0}return left<right?-1:1};var inInputOrder=(schemas,errors)=>{const position=(schemaName)=>schemas.findIndex((schema)=>schema.name===schemaName);return[...errors].sort((left,right)=>position(left.schemaName)-position(right.schemaName)||compare2(left.pointer,right.pointer))};var declarationsOf2=(models,named)=>named.flatMap(({exportName,input})=>[{name:exportName,pointer:"",schemaName:input.name},...(models.get(input)?.definitions??[]).map(({name,node})=>({name:defName(exportName,name),pointer:node.pointer,schemaName:input.name}))]);var declarationErrors=(target,declarations)=>{const uses=new Map;for(const{name}of declarations){uses.set(name,(uses.get(name)??0)+1)}const reserved=reservedNames[target];return declarations.flatMap(({name,pointer,schemaName})=>{if(!identifier2.test(name)){return[error("invalid_name",schemaName,pointer)]}if(reserved.includes(name)){return[error("reserved_name",schemaName,pointer)]}return(uses.get(name)??0)>1?[error("name_clash",schemaName,pointer)]:[]})};var withoutRepeats=(warnings)=>{const seen=new Set;return warnings.filter((warning)=>{const key=JSON.stringify([warning.schemaName,warning.pointer,warning.kind,warning.keyword]);if(seen.has(key)){return false}seen.add(key);return true})};var structuralWarning=({schemaName})=>({kind:"structural_fidelity",message:"The projection is structural: the schema can reject values that the wire shape accepts.",pointer:"",schemaName});var generateSchemaModule=({header,schemas,target})=>{const parsed=schemas.map((schema)=>[schema,parseSchema(schema)]);const models=new Map(parsed.flatMap(([schema,{model}])=>model===undefined?[]:[[schema,model]]));const named=nameSchemas(header.packageFqn,schemas.filter(hasSlot));const namedSchemas=named.named??[];const errors=[...parsed.flatMap(([,result])=>result.errors??[]),...schemas.filter((schema)=>!hasSlot(schema)).map(({name})=>error("invalid_name",name,"")),...named.errors??[],...declarationErrors(target,declarationsOf2(models,namedSchemas))];if(errors.length>0){return{errors:inInputOrder(schemas,errors)}}const printable=namedSchemas.flatMap(({exportName,input})=>{const model=models.get(input);return model===undefined?[]:[{exportName,fidelity:input.fidelity,model,schemaName:input.name}]});const printed=printable.length===0?{source:"",warnings:[]}:printers[target](printable);if("errors"in printed){return{errors:inInputOrder(schemas,printed.errors)}}return{source:`${printHeader({...header,target})}
|
|
37
|
+
${printed.source}`,warnings:[...printable.filter(({fidelity})=>fidelity==="structural").map(structuralWarning),...withoutRepeats(printed.warnings)]}};export{generateSchemaModule};
|
package/dist/model.d.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { CodegenError, JsonObject, SchemaInput } from "./types.js";
|
|
2
|
+
type JsonValue = JsonObject[string];
|
|
3
|
+
/** Annotation keywords. Printers decide which of them reach the output. */
|
|
4
|
+
export interface Annotations {
|
|
5
|
+
readonly title: string | undefined;
|
|
6
|
+
readonly description: string | undefined;
|
|
7
|
+
readonly deprecated: boolean | undefined;
|
|
8
|
+
readonly readOnly: boolean | undefined;
|
|
9
|
+
readonly writeOnly: boolean | undefined;
|
|
10
|
+
readonly default: JsonValue | undefined;
|
|
11
|
+
readonly examples: readonly JsonValue[] | undefined;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* What a schema allows beyond its declared members: `additionalProperties` of
|
|
15
|
+
* an object or `items` after `prefixItems` of an array. `absent` is an
|
|
16
|
+
* object without the keyword (Q29); arrays use `open` instead.
|
|
17
|
+
*/
|
|
18
|
+
export type Extra = {
|
|
19
|
+
readonly kind: "absent" | "open" | "closed";
|
|
20
|
+
} | {
|
|
21
|
+
readonly kind: "schema";
|
|
22
|
+
readonly node: ModelNode;
|
|
23
|
+
};
|
|
24
|
+
export interface ObjectProperty {
|
|
25
|
+
readonly name: string;
|
|
26
|
+
readonly required: boolean;
|
|
27
|
+
readonly node: ModelNode;
|
|
28
|
+
}
|
|
29
|
+
/** Field names match the JSON Schema keywords they come from. */
|
|
30
|
+
export interface StringForm {
|
|
31
|
+
readonly kind: "string";
|
|
32
|
+
readonly minLength: number | undefined;
|
|
33
|
+
readonly maxLength: number | undefined;
|
|
34
|
+
readonly pattern: string | undefined;
|
|
35
|
+
readonly format: string | undefined;
|
|
36
|
+
}
|
|
37
|
+
export interface NumberForm {
|
|
38
|
+
readonly kind: "number" | "integer";
|
|
39
|
+
readonly minimum: number | undefined;
|
|
40
|
+
readonly maximum: number | undefined;
|
|
41
|
+
readonly exclusiveMinimum: number | undefined;
|
|
42
|
+
readonly exclusiveMaximum: number | undefined;
|
|
43
|
+
readonly multipleOf: number | undefined;
|
|
44
|
+
}
|
|
45
|
+
export interface ObjectForm {
|
|
46
|
+
readonly kind: "object";
|
|
47
|
+
readonly properties: readonly ObjectProperty[];
|
|
48
|
+
readonly additionalProperties: Extra;
|
|
49
|
+
readonly minProperties: number | undefined;
|
|
50
|
+
readonly maxProperties: number | undefined;
|
|
51
|
+
}
|
|
52
|
+
export interface ArrayForm {
|
|
53
|
+
readonly kind: "array";
|
|
54
|
+
readonly prefixItems: readonly ModelNode[];
|
|
55
|
+
readonly items: Extra;
|
|
56
|
+
readonly minItems: number | undefined;
|
|
57
|
+
readonly maxItems: number | undefined;
|
|
58
|
+
readonly uniqueItems: boolean | undefined;
|
|
59
|
+
}
|
|
60
|
+
export type Form =
|
|
61
|
+
/** No constraint on the value. */
|
|
62
|
+
{
|
|
63
|
+
readonly kind: "unknown";
|
|
64
|
+
} | {
|
|
65
|
+
readonly kind: "boolean";
|
|
66
|
+
} | {
|
|
67
|
+
readonly kind: "null";
|
|
68
|
+
} | StringForm | NumberForm | ObjectForm | ArrayForm | {
|
|
69
|
+
readonly kind: "enum";
|
|
70
|
+
readonly values: readonly JsonValue[];
|
|
71
|
+
} | {
|
|
72
|
+
readonly kind: "const";
|
|
73
|
+
readonly value: JsonValue;
|
|
74
|
+
}
|
|
75
|
+
/** A local `$ref`. `name` is the key in the `$defs` of the document. */
|
|
76
|
+
| {
|
|
77
|
+
readonly kind: "ref";
|
|
78
|
+
readonly name: string;
|
|
79
|
+
}
|
|
80
|
+
/** `anyOf`, or `oneOf` when `exclusive`. A `type` array also gives `anyOf`. */
|
|
81
|
+
| {
|
|
82
|
+
readonly kind: "union";
|
|
83
|
+
readonly exclusive: boolean;
|
|
84
|
+
readonly members: readonly ModelNode[];
|
|
85
|
+
}
|
|
86
|
+
/** `allOf`, or several constraint groups on one schema. */
|
|
87
|
+
| {
|
|
88
|
+
readonly kind: "all";
|
|
89
|
+
readonly members: readonly ModelNode[];
|
|
90
|
+
};
|
|
91
|
+
export interface ModelNode {
|
|
92
|
+
/** JSON Pointer into the schema document. */
|
|
93
|
+
readonly pointer: string;
|
|
94
|
+
readonly form: Form;
|
|
95
|
+
readonly annotations: Annotations;
|
|
96
|
+
}
|
|
97
|
+
export interface Definition {
|
|
98
|
+
/** The key in `$defs`. */
|
|
99
|
+
readonly name: string;
|
|
100
|
+
readonly node: ModelNode;
|
|
101
|
+
}
|
|
102
|
+
/** What the printers read. They never see the raw document. */
|
|
103
|
+
export interface Model {
|
|
104
|
+
readonly name: SchemaInput["name"];
|
|
105
|
+
readonly root: ModelNode;
|
|
106
|
+
/** In dependency order: an entry never refers to a later entry. */
|
|
107
|
+
readonly definitions: readonly Definition[];
|
|
108
|
+
}
|
|
109
|
+
export type ParseResult = {
|
|
110
|
+
readonly model: Model;
|
|
111
|
+
readonly errors?: never;
|
|
112
|
+
} | {
|
|
113
|
+
readonly errors: readonly CodegenError[];
|
|
114
|
+
readonly model?: never;
|
|
115
|
+
};
|
|
116
|
+
/**
|
|
117
|
+
* Builds the model of one schema, or reports every error found in it. The
|
|
118
|
+
* keyword policy lives here (Q25, Q27): supported keywords build the model,
|
|
119
|
+
* `x-` keywords are ignored and every other keyword is an error.
|
|
120
|
+
*/
|
|
121
|
+
export declare const parseSchema: ({ name, document }: Pick<SchemaInput, "name" | "document">) => ParseResult;
|
|
122
|
+
export {};
|
package/dist/names.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { CodegenError, SchemaInput } from "./types.js";
|
|
2
|
+
export interface NamedSchema {
|
|
3
|
+
readonly exportName: string;
|
|
4
|
+
readonly input: SchemaInput;
|
|
5
|
+
}
|
|
6
|
+
/** A failed run carries no named schemas. */
|
|
7
|
+
export type NameResult = {
|
|
8
|
+
readonly named: readonly NamedSchema[];
|
|
9
|
+
readonly errors?: never;
|
|
10
|
+
} | {
|
|
11
|
+
readonly errors: readonly CodegenError[];
|
|
12
|
+
readonly named?: never;
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Builds the export name of each schema and sorts by component `fqn`, then
|
|
16
|
+
* slot label. Two schemas with one export name fail with one error per slot.
|
|
17
|
+
*/
|
|
18
|
+
export declare const nameSchemas: (packageFqn: string, schemas: readonly SchemaInput[]) => NameResult;
|
|
19
|
+
/** Name of a local `$defs` declaration: the export name plus the PascalCase key. */
|
|
20
|
+
export declare const defName: (exportName: string, key: string) => string;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { Model } from "../model.js";
|
|
2
|
+
import type { CodegenError, SchemaFidelity, SchemaName, Warning } from "../types.js";
|
|
3
|
+
/** One schema ready to print: its parsed model and the names built for it. */
|
|
4
|
+
export interface PrintableSchema {
|
|
5
|
+
readonly exportName: string;
|
|
6
|
+
readonly fidelity: SchemaFidelity;
|
|
7
|
+
readonly model: Model;
|
|
8
|
+
readonly schemaName: SchemaName;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A printer returns the body of a Generated Schema File: imports, then the
|
|
12
|
+
* declarations in input order. For each schema, its local `$defs` declarations
|
|
13
|
+
* come first, in dependency order, then the root declaration.
|
|
14
|
+
* The caller adds the header. A printer never throws.
|
|
15
|
+
*/
|
|
16
|
+
export type PrintResult = {
|
|
17
|
+
readonly source: string;
|
|
18
|
+
readonly warnings: readonly Warning[];
|
|
19
|
+
} | {
|
|
20
|
+
readonly errors: readonly CodegenError[];
|
|
21
|
+
};
|
|
22
|
+
export type Printer = (schemas: readonly PrintableSchema[]) => PrintResult;
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { Printer } from "./contract.js";
|
|
2
|
+
/**
|
|
3
|
+
* The `effect` target (ARC-007). A closed object prints as `Schema.Struct`
|
|
4
|
+
* because Effect has no closed object: one warning per object, which the CLI
|
|
5
|
+
* counts for the summary (Q29, Q36).
|
|
6
|
+
*/
|
|
7
|
+
export declare const printEffect: Printer;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { JsonObject } from "../types.js";
|
|
2
|
+
type JsonValue = JsonObject[string];
|
|
3
|
+
/** `String` and `Object` return a JSON value unchanged only for these kinds. */
|
|
4
|
+
export declare const isMap: (value: JsonValue) => value is JsonObject;
|
|
5
|
+
export declare const isList: (value: JsonValue) => value is readonly JsonValue[];
|
|
6
|
+
export declare const quote: (text: string) => string;
|
|
7
|
+
/**
|
|
8
|
+
* The key of an object literal. `__proto__` must stay computed, or the
|
|
9
|
+
* literal sets the prototype instead of a property. A quoted `"__proto__"`
|
|
10
|
+
* does the same, so every printer reaches object keys through here.
|
|
11
|
+
*/
|
|
12
|
+
export declare const propertyKey: (name: string) => string;
|
|
13
|
+
/** A JSON value as a TypeScript expression on one line. */
|
|
14
|
+
export declare const valueSource: (value: JsonValue) => string;
|
|
15
|
+
export {};
|
package/dist/tuple.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ArrayForm, Extra, ModelNode } from "./model.js";
|
|
2
|
+
export interface TupleElement {
|
|
3
|
+
readonly node: ModelNode;
|
|
4
|
+
readonly required: boolean;
|
|
5
|
+
}
|
|
6
|
+
/** The positions a tuple has, and what may follow the last one. */
|
|
7
|
+
export interface TupleLayout {
|
|
8
|
+
readonly elements: readonly TupleElement[];
|
|
9
|
+
readonly rest: Extra;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* `prefixItems` constrains the positions that exist and does not make them
|
|
13
|
+
* exist. A position is required only below `minItems`. A position at or
|
|
14
|
+
* above `maxItems` cannot exist, and then nothing follows the last one.
|
|
15
|
+
*/
|
|
16
|
+
export declare const tupleLayout: ({ items, maxItems, minItems, prefixItems }: ArrayForm) => TupleLayout;
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/** A JSON value. Schema documents carry only these. */
|
|
2
|
+
type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
|
|
3
|
+
readonly [key: string]: JsonValue;
|
|
4
|
+
};
|
|
5
|
+
/** A JSON-serializable Draft 2020-12 schema document. */
|
|
6
|
+
export type JsonObject = Readonly<Record<string, JsonValue>>;
|
|
7
|
+
/** The source flavor the generator prints. */
|
|
8
|
+
export type CodegenTarget = "types" | "zod" | "effect";
|
|
9
|
+
/** `exact` schemas match the wire shape. `structural` schemas can be stricter at runtime. */
|
|
10
|
+
export type SchemaFidelity = "exact" | "structural";
|
|
11
|
+
/** `<component fqn>#<slot label>`. The generator builds the export name from it. */
|
|
12
|
+
export type SchemaName = `${string}#${string}`;
|
|
13
|
+
export interface SchemaInput {
|
|
14
|
+
readonly name: SchemaName;
|
|
15
|
+
readonly document: JsonObject;
|
|
16
|
+
readonly fidelity: SchemaFidelity;
|
|
17
|
+
}
|
|
18
|
+
/** Package identity printed in the generated file header. */
|
|
19
|
+
export interface GenerateHeader {
|
|
20
|
+
readonly packageFqn: string;
|
|
21
|
+
readonly packageVersion: string;
|
|
22
|
+
}
|
|
23
|
+
export interface GenerateInput {
|
|
24
|
+
readonly target: CodegenTarget;
|
|
25
|
+
readonly header: GenerateHeader;
|
|
26
|
+
readonly schemas: readonly SchemaInput[];
|
|
27
|
+
}
|
|
28
|
+
export interface Warning {
|
|
29
|
+
readonly kind: "structural_fidelity" | "dropped_keyword" | "format_annotation_only" | "closed_object_unenforced";
|
|
30
|
+
readonly schemaName: SchemaName;
|
|
31
|
+
/** JSON Pointer into the schema document. */
|
|
32
|
+
readonly pointer: string;
|
|
33
|
+
readonly keyword?: string;
|
|
34
|
+
readonly message: string;
|
|
35
|
+
}
|
|
36
|
+
export interface CodegenError {
|
|
37
|
+
readonly code: string;
|
|
38
|
+
readonly schemaName: SchemaName;
|
|
39
|
+
/** JSON Pointer into the schema document. */
|
|
40
|
+
readonly pointer: string;
|
|
41
|
+
/** `null` when the error is not about one keyword, for example a name clash. */
|
|
42
|
+
readonly keyword: string | null;
|
|
43
|
+
}
|
|
44
|
+
/** One run collects every error. A failed run carries no source. */
|
|
45
|
+
export type GenerateResult = {
|
|
46
|
+
readonly source: string;
|
|
47
|
+
readonly warnings: readonly Warning[];
|
|
48
|
+
readonly errors?: never;
|
|
49
|
+
} | {
|
|
50
|
+
readonly errors: readonly CodegenError[];
|
|
51
|
+
readonly source?: never;
|
|
52
|
+
readonly warnings?: never;
|
|
53
|
+
};
|
|
54
|
+
/** Pure. Returns errors instead of throwing. */
|
|
55
|
+
export type GenerateSchemaModule = (input: GenerateInput) => GenerateResult;
|
|
56
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/schema-codegen",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.16",
|
|
4
|
+
"description": "Pure generator from Draft 2020-12 JSON Schema documents to TypeScript, Zod and Effect Schema source.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"ci-source": "./src/index.ts",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "bun tools/build.ts",
|
|
23
|
+
"test": "bun --conditions=ci-source test && bun run test:pack",
|
|
24
|
+
"test:pack": "bun run build && bun tools/test-pack.ts",
|
|
25
|
+
"test:unit": "bun --conditions=ci-source test",
|
|
26
|
+
"format": "oxfmt --write .",
|
|
27
|
+
"format:check": "oxfmt --check .",
|
|
28
|
+
"format:check:staged": "oxfmt --check",
|
|
29
|
+
"lint": "node \"../../../.agents/scripts/managed-lint-runner.mjs\" --scope \"packages/public/schema-codegen\"",
|
|
30
|
+
"lint:staged": "oxlint --config oxlint.config.ts --no-error-on-unmatched-pattern",
|
|
31
|
+
"prepack": "bun run build",
|
|
32
|
+
"type-check": "bun check && bun check -p tsconfig.type-tests.json"
|
|
33
|
+
},
|
|
34
|
+
"publishConfig": {
|
|
35
|
+
"access": "public"
|
|
36
|
+
},
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@effect/eslint-plugin": "latest",
|
|
39
|
+
"@oxlint/plugins": "1.85.0",
|
|
40
|
+
"@typescript-eslint/utils": "8.22.0",
|
|
41
|
+
"bun-types": "^1.4.2",
|
|
42
|
+
"effect": "4.0.1",
|
|
43
|
+
"eslint": "9.39.5",
|
|
44
|
+
"oxfmt": "0.66.0",
|
|
45
|
+
"oxlint": "1.82.0",
|
|
46
|
+
"oxlint-tsgolint": "7.0.2001",
|
|
47
|
+
"typescript": "7.0.2",
|
|
48
|
+
"ultracite": "7.10.7",
|
|
49
|
+
"zod": "4.4.3"
|
|
50
|
+
}
|
|
51
|
+
}
|