@fabrika/check 0.9.0-dev.14 → 0.9.0-dev.15
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/package.json +6 -6
- package/src/ast.ts +17 -0
- package/src/contract.ts +29 -6
- package/src/inputs.ts +4 -2
- package/src/layout.ts +4 -1
- package/src/limits.ts +13 -3
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +2 -1
- package/src/reader/value.ts +5 -5
- package/src/rules/literal.ts +3 -1
- package/src/rules/structure.ts +7 -6
- package/types/src/ast.d.ts +2 -0
- package/types/src/layout.d.ts +4 -1
- package/types/src/limits.d.ts +12 -2
- package/types/src/reader/schema.d.ts +5 -2
- package/types/src/reader/value.d.ts +2 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/check",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.15",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -47,11 +47,11 @@
|
|
|
47
47
|
},
|
|
48
48
|
"dependencies": {
|
|
49
49
|
"@babel/parser": "8.0.7",
|
|
50
|
-
"@fabrika/app": "0.9.0-dev.
|
|
51
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
52
|
-
"@fabrika/db": "0.9.0-dev.
|
|
53
|
-
"@fabrika/operations-contract": "0.9.0-dev.
|
|
54
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
50
|
+
"@fabrika/app": "0.9.0-dev.15",
|
|
51
|
+
"@fabrika/auth-core": "0.9.0-dev.15",
|
|
52
|
+
"@fabrika/db": "0.9.0-dev.15",
|
|
53
|
+
"@fabrika/operations-contract": "0.9.0-dev.15",
|
|
54
|
+
"@fabrika/platform-node": "0.9.0-dev.15",
|
|
55
55
|
"zod": "^3.25.76"
|
|
56
56
|
}
|
|
57
57
|
}
|
package/src/ast.ts
CHANGED
|
@@ -287,6 +287,23 @@ export const nodeDepth = (root: AstNode): number => {
|
|
|
287
287
|
return deepest
|
|
288
288
|
}
|
|
289
289
|
|
|
290
|
+
/** The number of syntax nodes in the tree below `root`, `root` included, counted without recursion. */
|
|
291
|
+
export const nodeCount = (root: AstNode): number => {
|
|
292
|
+
let count = 0
|
|
293
|
+
const pending: AstNode[] = [root]
|
|
294
|
+
for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
|
|
295
|
+
count++
|
|
296
|
+
for (const [key, value] of Object.entries(node)) {
|
|
297
|
+
if (NON_CHILD_KEYS.has(key)) continue
|
|
298
|
+
if (isNode(value)) pending.push(value)
|
|
299
|
+
else if (Array.isArray(value)) {
|
|
300
|
+
for (const item of value) if (isNode(item)) pending.push(item)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return count
|
|
305
|
+
}
|
|
306
|
+
|
|
290
307
|
export const parseModule = (file: string, text: string): ParseResult => {
|
|
291
308
|
try {
|
|
292
309
|
// Nothing reads a comment from the node it is attached to; `ast.comments` lists them all.
|
package/src/contract.ts
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
import { type AnyContract, compileContract } from '@fabrika/app/contract'
|
|
6
6
|
import type { ContractArtifact, TablePolicyArtifact } from '@fabrika/auth-core'
|
|
7
7
|
import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
|
|
8
|
-
import { child, children, importedSpecifiers, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
|
|
8
|
+
import { child, children, importedSpecifiers, nodeCount, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
|
|
9
9
|
import { type Finding, formatFinding } from './finding'
|
|
10
10
|
import { ModuleGraph } from './graph'
|
|
11
11
|
import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_FILE } from './layout'
|
|
@@ -161,21 +161,34 @@ export function contractModules(graph: ModuleGraph, entry: ParsedModule): Parsed
|
|
|
161
161
|
return [...reached.values()]
|
|
162
162
|
}
|
|
163
163
|
|
|
164
|
-
/** The source and syntax
|
|
164
|
+
/** The source and syntax limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
|
|
165
165
|
function sourceBudget(modules: readonly ParsedModule[], entry = CONTRACT_FILE): Finding[] {
|
|
166
166
|
const findings: Finding[] = []
|
|
167
167
|
const bytes = modules.reduce((total, module) => total + module.bytes, 0)
|
|
168
168
|
if (bytes > CONTRACT_LIMITS.sourceBytes) {
|
|
169
169
|
findings.push(overBudget(entry, `${entry} and its modules are ${bytes} bytes, over ${CONTRACT_LIMITS.sourceBytes}`))
|
|
170
170
|
}
|
|
171
|
+
let nodes = 0
|
|
171
172
|
for (const module of modules) {
|
|
173
|
+
if (module.bytes > CONTRACT_LIMITS.moduleBytes) {
|
|
174
|
+
findings.push(overBudget(module.file, moduleTooLarge(module.bytes)))
|
|
175
|
+
}
|
|
172
176
|
if (nodeDepth(module.program) > CONTRACT_LIMITS.astDepth) {
|
|
173
177
|
findings.push(overBudget(module.file, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`))
|
|
174
178
|
}
|
|
179
|
+
nodes += heldNodes(module)
|
|
180
|
+
}
|
|
181
|
+
if (nodes > CONTRACT_LIMITS.astNodes) {
|
|
182
|
+
findings.push(overBudget(entry, `${entry} and its modules hold ${nodes} syntax nodes, over the budget of ${CONTRACT_LIMITS.astNodes}`))
|
|
175
183
|
}
|
|
176
184
|
return findings
|
|
177
185
|
}
|
|
178
186
|
|
|
187
|
+
const moduleTooLarge = (bytes: number): string => `the module is ${bytes} bytes, over ${CONTRACT_LIMITS.moduleBytes} for one module`
|
|
188
|
+
|
|
189
|
+
/** The syntax nodes the reader holds of a module: all but its top-level type declarations. */
|
|
190
|
+
const heldNodes = (module: ParsedModule): number => nodeCount(withoutTypeDeclarations(module).program)
|
|
191
|
+
|
|
179
192
|
function overBudget(file: string, message: string): Finding {
|
|
180
193
|
return {
|
|
181
194
|
file,
|
|
@@ -193,8 +206,8 @@ type ParsedGraph = { readonly ok: true; readonly graph: ModuleGraph } | { readon
|
|
|
193
206
|
/**
|
|
194
207
|
* Parses `entry` (`fabrika.contract.ts` or `src/db/tables.ts`) and the modules its imports reach among `files`, and
|
|
195
208
|
* nothing else; each module as its shell slice, so an import only a handler uses is never followed. Every candidate of an import is parsed, so that `rules/literal.ts` sees an ambiguous or directory
|
|
196
|
-
* import; the
|
|
197
|
-
* walks it.
|
|
209
|
+
* import; the byte limits hold before a module is parsed, and the depth and node limits right after, before any
|
|
210
|
+
* recursive rule walks it.
|
|
198
211
|
*/
|
|
199
212
|
function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): ParsedGraph {
|
|
200
213
|
const modules = new Map<string, ParsedModule>()
|
|
@@ -203,13 +216,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
|
|
|
203
216
|
return { ok: false, findings: [missingFile(entry)] }
|
|
204
217
|
}
|
|
205
218
|
let bytes = 0
|
|
219
|
+
let nodes = 0
|
|
206
220
|
const queue = [entry]
|
|
207
221
|
for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
|
|
208
222
|
const text = files.get(path)
|
|
209
223
|
if (modules.has(path) || text === undefined || !isSourceFile(path)) {
|
|
210
224
|
continue
|
|
211
225
|
}
|
|
212
|
-
|
|
226
|
+
const moduleBytes = utf8Bytes(text)
|
|
227
|
+
if (moduleBytes > CONTRACT_LIMITS.moduleBytes) {
|
|
228
|
+
return { ok: false, findings: [overBudget(path, moduleTooLarge(moduleBytes))] }
|
|
229
|
+
}
|
|
230
|
+
bytes += moduleBytes
|
|
213
231
|
if (bytes > CONTRACT_LIMITS.sourceBytes) {
|
|
214
232
|
return { ok: false, findings: [overBudget(path, `${entry} and its modules are over ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
|
|
215
233
|
}
|
|
@@ -229,7 +247,12 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
|
|
|
229
247
|
if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
|
|
230
248
|
return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
|
|
231
249
|
}
|
|
232
|
-
|
|
250
|
+
const held = withoutTypeDeclarations(parsed.module)
|
|
251
|
+
nodes += nodeCount(held.program)
|
|
252
|
+
if (nodes > CONTRACT_LIMITS.astNodes) {
|
|
253
|
+
return { ok: false, findings: [overBudget(path, `${entry} and its modules hold over ${CONTRACT_LIMITS.astNodes} syntax nodes`)] }
|
|
254
|
+
}
|
|
255
|
+
modules.set(path, held)
|
|
233
256
|
for (const specifier of importedSpecifiers(parsed.module)) {
|
|
234
257
|
const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
|
|
235
258
|
if (resolution?.kind === 'file') {
|
package/src/inputs.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
// Which files of an application the static reader needs. Control reads a commit file by file, and the reader cannot
|
|
2
2
|
// tell a missing file from one it was not given, so the caller asks here until nothing is missing. Worker-safe.
|
|
3
3
|
|
|
4
|
-
import { importedSpecifiers } from './ast'
|
|
4
|
+
import { importedSpecifiers, utf8Bytes } from './ast'
|
|
5
5
|
import { parseJsonc } from './jsonc'
|
|
6
6
|
import { CONTRACT_FILE, isRelativeSpecifier, isSourceFile, joinRelative, resolveRelative, TABLES_FILE } from './layout'
|
|
7
|
+
import { CONTRACT_LIMITS } from './limits'
|
|
7
8
|
import { parseShellModule } from './slice'
|
|
8
9
|
import { BUNFIG_FILE } from './trust'
|
|
9
10
|
|
|
@@ -49,7 +50,8 @@ export function contractReaderInputs(files: ReadonlyMap<string, string>, exists:
|
|
|
49
50
|
want(path)
|
|
50
51
|
continue
|
|
51
52
|
}
|
|
52
|
-
|
|
53
|
+
// A module over the limit is not parsed here: the reader refuses it, and its own parse would be the peak.
|
|
54
|
+
const parsed = isSourceFile(path) && utf8Bytes(text) <= CONTRACT_LIMITS.moduleBytes ? parseShellModule(path, text).parsed : undefined
|
|
53
55
|
if (parsed?.ok !== true) continue
|
|
54
56
|
for (const specifier of importedSpecifiers(parsed.module)) {
|
|
55
57
|
if (!isRelativeSpecifier(specifier)) continue
|
package/src/layout.ts
CHANGED
|
@@ -26,7 +26,10 @@ export const APP_KIT_FILE = 'src/app-kit.ts'
|
|
|
26
26
|
/** The shared zod schemas the shell and the SPA import: one module, or a directory of them once it grows. */
|
|
27
27
|
export const SCHEMAS_FILE = 'src/schemas.ts'
|
|
28
28
|
export const SCHEMAS_DIR = 'src/schemas/'
|
|
29
|
-
/**
|
|
29
|
+
/**
|
|
30
|
+
* Pure code the SPA and every slice may import: it loads nothing but `zod/v4`, `@fabrika/app/schema` and other modules of
|
|
31
|
+
* its own directory.
|
|
32
|
+
*/
|
|
30
33
|
export const SHARED_DIR = 'src/shared/'
|
|
31
34
|
/** `src/db/`: the tables, the generated schema and their generated tests; never a slice. */
|
|
32
35
|
export const DATABASE_DIR = 'src/db/'
|
package/src/limits.ts
CHANGED
|
@@ -4,12 +4,22 @@
|
|
|
4
4
|
* step runs.
|
|
5
5
|
*/
|
|
6
6
|
export const CONTRACT_LIMITS = {
|
|
7
|
-
/**
|
|
8
|
-
|
|
7
|
+
/**
|
|
8
|
+
* UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. Control reads them in a Cloudflare
|
|
9
|
+
* Worker, whose isolate has 128 MB; handler bodies are sliced out before the parse, so they cost bytes, not nodes.
|
|
10
|
+
*/
|
|
11
|
+
sourceBytes: 4 * 1024 * 1024,
|
|
12
|
+
/** UTF-8 bytes of one module: its own parse is the peak while it is read, and a dense one needs up to 340 times it. */
|
|
13
|
+
moduleBytes: 512 * 1024,
|
|
14
|
+
/**
|
|
15
|
+
* Syntax nodes the reader holds over each graph (the contract's, the tables'), top-level type declarations left out.
|
|
16
|
+
* At this, `sourceBytes` and `schemaNodes` together, Control's read needs a 95 MB heap of its 128 MB isolate.
|
|
17
|
+
*/
|
|
18
|
+
astNodes: 400_000,
|
|
9
19
|
/** Nesting of syntax nodes in one module; the contracts in this repository reach 25. */
|
|
10
20
|
astDepth: 128,
|
|
11
21
|
/** Schema nodes once every shared schema is expanded where the contract uses it, over the whole contract. */
|
|
12
|
-
schemaNodes:
|
|
22
|
+
schemaNodes: 60_000,
|
|
13
23
|
/** Nesting of one schema: objects, arrays, unions and wrappers. */
|
|
14
24
|
schemaDepth: 32,
|
|
15
25
|
} as const
|
package/src/reader/schema.ts
CHANGED
|
@@ -1,551 +1,81 @@
|
|
|
1
|
-
//
|
|
2
|
-
//
|
|
1
|
+
// A `z` chain of the contract subset read as the schema `@fabrika/app/schema` holds as data, one factory or method at a
|
|
2
|
+
// time. Each step is replayed against zod at once, through the same replay the runtime builds with, so a refused step
|
|
3
|
+
// is reported where it stands, and `@fabrika/app`'s `describeContract` reads exactly the schema the evaluated module
|
|
4
|
+
// would hold. The reader keeps the recipe, not the zod: what it builds stays in the bounded cache of the replay.
|
|
3
5
|
|
|
6
|
+
import { DataEnum, DataObject, DataSchema, SCHEMA_SUBSET, SchemaRefusal, Unreadable, zodSchemaOf } from '@fabrika/app/schema'
|
|
4
7
|
import { z } from 'zod/v4'
|
|
5
8
|
import type { LiteralValue } from './value'
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
/** A schema the reader holds: one it read from a chain, or a framework schema (`signedToken()`, `file()`). */
|
|
11
|
+
export type ReadSchema = DataSchema | z.ZodType
|
|
8
12
|
|
|
9
|
-
export type
|
|
10
|
-
readonly ok: false
|
|
11
|
-
readonly message: string
|
|
12
|
-
readonly allowed: string
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
const SUBSET = 'a schema of the supported z subset (packages/check/CLAUDE.md)'
|
|
13
|
+
export type SchemaStep = { readonly factory: string; readonly iso: boolean } | { readonly method: string; readonly receiver: ReadSchema | undefined }
|
|
16
14
|
|
|
17
|
-
|
|
18
|
-
|
|
15
|
+
export type BuiltSchema = { readonly ok: true; readonly schema: DataSchema } | {
|
|
16
|
+
readonly ok: false
|
|
19
17
|
readonly message: string
|
|
20
18
|
readonly allowed: string
|
|
21
|
-
|
|
22
|
-
constructor(message: string, allowed: string) {
|
|
23
|
-
this.message = message
|
|
24
|
-
this.allowed = allowed
|
|
25
|
-
}
|
|
26
19
|
}
|
|
27
20
|
|
|
28
21
|
export function buildSchema(step: SchemaStep, args: readonly LiteralValue[]): BuiltSchema {
|
|
29
22
|
try {
|
|
30
|
-
const
|
|
31
|
-
? (step.
|
|
32
|
-
:
|
|
33
|
-
|
|
23
|
+
const node = 'factory' in step
|
|
24
|
+
? nodeOf(step.factory, step.iso, null, args.map(argument))
|
|
25
|
+
: nodeOf(step.method, false, receiverOf(step.receiver), args.map(argument))
|
|
26
|
+
// Built now, so a refusal points at its step; the build stays cached for the step that follows.
|
|
27
|
+
zodSchemaOf(node)
|
|
28
|
+
return { ok: true, schema: node }
|
|
34
29
|
} catch (error) {
|
|
35
|
-
if (error instanceof
|
|
30
|
+
if (error instanceof SchemaRefusal) {
|
|
36
31
|
return { ok: false, message: error.message, allowed: error.allowed }
|
|
37
32
|
}
|
|
38
|
-
|
|
39
|
-
const message = error instanceof Error ? (error.message.split('\n')[0] ?? error.message) : 'zod refused the schema'
|
|
40
|
-
return { ok: false, message: `zod refuses this schema: ${message}`, allowed: SUBSET }
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
function factory(name: string, args: readonly LiteralValue[]): z.ZodType {
|
|
45
|
-
const call = `z.${name}()`
|
|
46
|
-
switch (name) {
|
|
47
|
-
case 'string':
|
|
48
|
-
return z.string(messageParams(call, only(call, args, 0)))
|
|
49
|
-
case 'number':
|
|
50
|
-
return z.number(messageParams(call, only(call, args, 0)))
|
|
51
|
-
case 'int':
|
|
52
|
-
return z.int(messageParams(call, only(call, args, 0)))
|
|
53
|
-
case 'boolean':
|
|
54
|
-
return z.boolean(messageParams(call, only(call, args, 0)))
|
|
55
|
-
case 'null':
|
|
56
|
-
return z.null(messageParams(call, only(call, args, 0)))
|
|
57
|
-
case 'uuid':
|
|
58
|
-
return z.uuid(uuidParams(call, only(call, args, 0)))
|
|
59
|
-
case 'email':
|
|
60
|
-
return z.email(messageParams(call, only(call, args, 0)))
|
|
61
|
-
case 'url':
|
|
62
|
-
return z.url(messageParams(call, only(call, args, 0)))
|
|
63
|
-
case 'literal': {
|
|
64
|
-
const [value, params] = between(call, args, 1, 2)
|
|
65
|
-
const literal = literalValues(call, value)
|
|
66
|
-
return Array.isArray(literal) ? z.literal(literal, messageParams(call, params)) : z.literal(literal, messageParams(call, params))
|
|
67
|
-
}
|
|
68
|
-
case 'enum': {
|
|
69
|
-
const [values, params] = between(call, args, 1, 2)
|
|
70
|
-
const entries = enumEntries(call, values)
|
|
71
|
-
return Array.isArray(entries) ? z.enum(entries, messageParams(call, params)) : z.enum(entries, messageParams(call, params))
|
|
72
|
-
}
|
|
73
|
-
case 'strictObject': {
|
|
74
|
-
const [shape, params] = between(call, args, 1, 2)
|
|
75
|
-
return z.strictObject(schemaShape(call, shape), messageParams(call, params))
|
|
76
|
-
}
|
|
77
|
-
case 'array': {
|
|
78
|
-
const [element, params] = between(call, args, 1, 2)
|
|
79
|
-
return z.array(schema(call, element), messageParams(call, params))
|
|
80
|
-
}
|
|
81
|
-
case 'tuple':
|
|
82
|
-
return tuple(call, args)
|
|
83
|
-
case 'union': {
|
|
84
|
-
const [options, params] = between(call, args, 1, 2)
|
|
85
|
-
return z.union(schemaList(call, options), messageParams(call, params))
|
|
86
|
-
}
|
|
87
|
-
case 'discriminatedUnion': {
|
|
88
|
-
const [discriminator, options, params] = between(call, args, 2, 3)
|
|
89
|
-
const [first, ...rest] = schemaList(call, options).map((option) => objectSchema(call, option))
|
|
90
|
-
if (first === undefined) {
|
|
91
|
-
throw new Refusal(`${call} has no option`, 'z.discriminatedUnion(<key>, [z.strictObject({ … }), …])')
|
|
92
|
-
}
|
|
93
|
-
return z.discriminatedUnion(text(call, discriminator), [first, ...rest], messageParams(call, params))
|
|
94
|
-
}
|
|
95
|
-
case 'record': {
|
|
96
|
-
const [key, value, params] = between(call, args, 2, 3)
|
|
97
|
-
return z.record(recordKey(call, schema(call, key)), schema(call, value), messageParams(call, params))
|
|
98
|
-
}
|
|
99
|
-
case 'optional':
|
|
100
|
-
return z.optional(schema(call, exactly(call, args, 1)[0]))
|
|
101
|
-
case 'nullable':
|
|
102
|
-
return z.nullable(schema(call, exactly(call, args, 1)[0]))
|
|
103
|
-
default:
|
|
104
|
-
throw new Refusal(`'${name}' is not in the supported schema subset`, SUBSET)
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
function isoFormat(name: string, args: readonly LiteralValue[]): z.ZodType {
|
|
109
|
-
const call = `z.iso.${name}()`
|
|
110
|
-
switch (name) {
|
|
111
|
-
case 'date':
|
|
112
|
-
return z.iso.date(messageParams(call, only(call, args, 0)))
|
|
113
|
-
case 'datetime':
|
|
114
|
-
return z.iso.datetime(datetimeParams(call, only(call, args, 0)))
|
|
115
|
-
case 'time':
|
|
116
|
-
return z.iso.time(timeParams(call, only(call, args, 0)))
|
|
117
|
-
case 'duration':
|
|
118
|
-
return z.iso.duration(messageParams(call, only(call, args, 0)))
|
|
119
|
-
default:
|
|
120
|
-
throw new Refusal(`'iso.${name}' is not in the supported schema subset`, SUBSET)
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
function method(name: string, receiver: z.ZodType | undefined, args: readonly LiteralValue[]): z.ZodType {
|
|
125
|
-
const call = `.${name}()`
|
|
126
|
-
if (receiver === undefined) {
|
|
127
|
-
throw new Refusal('a schema method without a schema', SUBSET)
|
|
128
|
-
}
|
|
129
|
-
switch (name) {
|
|
130
|
-
case 'min':
|
|
131
|
-
case 'max':
|
|
132
|
-
case 'length': {
|
|
133
|
-
const [bound, params] = between(call, args, 1, 2)
|
|
134
|
-
const value = number(call, bound)
|
|
135
|
-
const message = messageParams(call, params)
|
|
136
|
-
if (receiver instanceof z.ZodString || receiver instanceof z.ZodStringFormat) {
|
|
137
|
-
return name === 'min' ? receiver.min(value, message) : name === 'max' ? receiver.max(value, message) : receiver.length(value, message)
|
|
138
|
-
}
|
|
139
|
-
if (receiver instanceof z.ZodArray) {
|
|
140
|
-
return name === 'min' ? receiver.min(value, message) : name === 'max' ? receiver.max(value, message) : receiver.length(value, message)
|
|
141
|
-
}
|
|
142
|
-
if (receiver instanceof z.ZodNumber && name !== 'length') {
|
|
143
|
-
return name === 'min' ? receiver.min(value, message) : receiver.max(value, message)
|
|
144
|
-
}
|
|
145
|
-
throw unsupported(call, receiver)
|
|
146
|
-
}
|
|
147
|
-
case 'nonempty': {
|
|
148
|
-
const message = messageParams(call, only(call, args, 0))
|
|
149
|
-
if (receiver instanceof z.ZodString || receiver instanceof z.ZodStringFormat || receiver instanceof z.ZodArray) {
|
|
150
|
-
return receiver.nonempty(message)
|
|
151
|
-
}
|
|
152
|
-
throw unsupported(call, receiver)
|
|
153
|
-
}
|
|
154
|
-
case 'email':
|
|
155
|
-
case 'url':
|
|
156
|
-
case 'uuid': {
|
|
157
|
-
const params = only(call, args, 0)
|
|
158
|
-
if (!(receiver instanceof z.ZodString)) {
|
|
159
|
-
throw unsupported(call, receiver)
|
|
160
|
-
}
|
|
161
|
-
return name === 'email'
|
|
162
|
-
? receiver.email(messageParams(call, params))
|
|
163
|
-
: name === 'url'
|
|
164
|
-
? receiver.url(messageParams(call, params))
|
|
165
|
-
: receiver.uuid(uuidParams(call, params))
|
|
166
|
-
}
|
|
167
|
-
case 'startsWith':
|
|
168
|
-
case 'endsWith':
|
|
169
|
-
case 'includes':
|
|
170
|
-
case 'regex': {
|
|
171
|
-
const [argument, params] = between(call, args, 1, 2)
|
|
172
|
-
if (!(receiver instanceof z.ZodString || receiver instanceof z.ZodStringFormat)) {
|
|
173
|
-
throw unsupported(call, receiver)
|
|
174
|
-
}
|
|
175
|
-
switch (name) {
|
|
176
|
-
case 'startsWith':
|
|
177
|
-
return receiver.startsWith(text(call, argument), messageParams(call, params))
|
|
178
|
-
case 'endsWith':
|
|
179
|
-
return receiver.endsWith(text(call, argument), messageParams(call, params))
|
|
180
|
-
case 'includes':
|
|
181
|
-
return receiver.includes(text(call, argument), includesParams(call, params))
|
|
182
|
-
default:
|
|
183
|
-
return receiver.regex(regex(call, argument), messageParams(call, params))
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
case 'int':
|
|
187
|
-
case 'positive':
|
|
188
|
-
case 'negative':
|
|
189
|
-
case 'nonnegative':
|
|
190
|
-
case 'nonpositive': {
|
|
191
|
-
const message = messageParams(call, only(call, args, 0))
|
|
192
|
-
if (!(receiver instanceof z.ZodNumber)) {
|
|
193
|
-
throw unsupported(call, receiver)
|
|
194
|
-
}
|
|
195
|
-
switch (name) {
|
|
196
|
-
case 'int':
|
|
197
|
-
return receiver.int(message)
|
|
198
|
-
case 'positive':
|
|
199
|
-
return receiver.positive(message)
|
|
200
|
-
case 'negative':
|
|
201
|
-
return receiver.negative(message)
|
|
202
|
-
case 'nonnegative':
|
|
203
|
-
return receiver.nonnegative(message)
|
|
204
|
-
default:
|
|
205
|
-
return receiver.nonpositive(message)
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
case 'gt':
|
|
209
|
-
case 'gte':
|
|
210
|
-
case 'lt':
|
|
211
|
-
case 'lte':
|
|
212
|
-
case 'multipleOf': {
|
|
213
|
-
const [bound, params] = between(call, args, 1, 2)
|
|
214
|
-
const value = number(call, bound)
|
|
215
|
-
const message = messageParams(call, params)
|
|
216
|
-
if (!(receiver instanceof z.ZodNumber)) {
|
|
217
|
-
throw unsupported(call, receiver)
|
|
218
|
-
}
|
|
219
|
-
switch (name) {
|
|
220
|
-
case 'gt':
|
|
221
|
-
return receiver.gt(value, message)
|
|
222
|
-
case 'gte':
|
|
223
|
-
return receiver.gte(value, message)
|
|
224
|
-
case 'lt':
|
|
225
|
-
return receiver.lt(value, message)
|
|
226
|
-
case 'lte':
|
|
227
|
-
return receiver.lte(value, message)
|
|
228
|
-
default:
|
|
229
|
-
return receiver.multipleOf(value, message)
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
case 'optional':
|
|
233
|
-
exactly(call, args, 0)
|
|
234
|
-
return receiver.optional()
|
|
235
|
-
case 'nullable':
|
|
236
|
-
exactly(call, args, 0)
|
|
237
|
-
return receiver.nullable()
|
|
238
|
-
case 'nullish':
|
|
239
|
-
exactly(call, args, 0)
|
|
240
|
-
return receiver.nullish()
|
|
241
|
-
case 'array':
|
|
242
|
-
exactly(call, args, 0)
|
|
243
|
-
return receiver.array()
|
|
244
|
-
case 'default':
|
|
245
|
-
return receiver.default(plain(call, exactly(call, args, 1)[0]))
|
|
246
|
-
case 'describe':
|
|
247
|
-
return receiver.describe(text(call, exactly(call, args, 1)[0]))
|
|
248
|
-
case 'or':
|
|
249
|
-
return receiver.or(schema(call, exactly(call, args, 1)[0]))
|
|
250
|
-
case 'extend':
|
|
251
|
-
case 'pick':
|
|
252
|
-
case 'omit':
|
|
253
|
-
case 'partial': {
|
|
254
|
-
if (!(receiver instanceof z.ZodObject)) {
|
|
255
|
-
throw unsupported(call, receiver)
|
|
256
|
-
}
|
|
257
|
-
if (name === 'extend') {
|
|
258
|
-
return receiver.extend(schemaShape(call, exactly(call, args, 1)[0]))
|
|
259
|
-
}
|
|
260
|
-
if (name === 'partial') {
|
|
261
|
-
const [mask] = between(call, args, 0, 1)
|
|
262
|
-
return mask === undefined ? receiver.partial() : receiver.partial(keyMask(call, mask))
|
|
263
|
-
}
|
|
264
|
-
const mask = keyMask(call, exactly(call, args, 1)[0])
|
|
265
|
-
return name === 'pick' ? receiver.pick(mask) : receiver.omit(mask)
|
|
266
|
-
}
|
|
267
|
-
default:
|
|
268
|
-
throw new Refusal(`'${name}' is not in the supported schema subset`, SUBSET)
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
function tuple(call: string, args: readonly LiteralValue[]): z.ZodType {
|
|
273
|
-
const [items, second, third] = between(call, args, 1, 3)
|
|
274
|
-
const [first, ...rest] = schemaList(call, items)
|
|
275
|
-
const restSchema = second?.kind === 'schema' ? second.schema : undefined
|
|
276
|
-
const params = messageParams(call, restSchema === undefined ? second : third)
|
|
277
|
-
if (restSchema === undefined && third !== undefined) {
|
|
278
|
-
throw new Refusal(`${call} takes its items, an optional rest schema and options`, 'z.tuple([<schemas>], <rest schema>)')
|
|
279
|
-
}
|
|
280
|
-
if (first === undefined) {
|
|
281
|
-
if (restSchema !== undefined) {
|
|
282
|
-
throw new Refusal(`${call} with a rest and no item`, 'z.array(<schema>)')
|
|
283
|
-
}
|
|
284
|
-
return z.tuple([], params)
|
|
285
|
-
}
|
|
286
|
-
return restSchema === undefined ? z.tuple([first, ...rest], params) : z.tuple([first, ...rest], restSchema, params)
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
// ── Arguments ───────────────────────────────────────────────────────────────────────────────────
|
|
290
|
-
|
|
291
|
-
function between(call: string, args: readonly LiteralValue[], min: number, max: number): readonly (LiteralValue | undefined)[] {
|
|
292
|
-
if (args.length < min || args.length > max) {
|
|
293
|
-
const count = min === max ? `${min}` : `${min} to ${max}`
|
|
294
|
-
throw new Refusal(`${call} takes ${count} arguments, not ${args.length}`, SUBSET)
|
|
295
|
-
}
|
|
296
|
-
return Array.from({ length: max }, (_, index) => args[index])
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
function exactly(call: string, args: readonly LiteralValue[], count: number): readonly (LiteralValue | undefined)[] {
|
|
300
|
-
return between(call, args, count, count)
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
/** The one optional argument of a call that takes only options. */
|
|
304
|
-
function only(call: string, args: readonly LiteralValue[], required: 0): LiteralValue | undefined {
|
|
305
|
-
return between(call, args, required, 1)[0]
|
|
306
|
-
}
|
|
307
|
-
|
|
308
|
-
function expected(call: string, what: string, value: LiteralValue | undefined): Refusal {
|
|
309
|
-
return new Refusal(`${call} takes ${what}${value === undefined ? '' : `, not a ${value.kind}`}`, SUBSET)
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
function schema(call: string, value: LiteralValue | undefined): z.ZodType {
|
|
313
|
-
if (value?.kind !== 'schema') {
|
|
314
|
-
throw expected(call, 'a schema', value)
|
|
315
|
-
}
|
|
316
|
-
return value.schema
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
function number(call: string, value: LiteralValue | undefined): number {
|
|
320
|
-
if (value?.kind !== 'number') {
|
|
321
|
-
throw expected(call, 'a number', value)
|
|
322
|
-
}
|
|
323
|
-
return value.value
|
|
324
|
-
}
|
|
325
|
-
|
|
326
|
-
function text(call: string, value: LiteralValue | undefined): string {
|
|
327
|
-
if (value?.kind !== 'string') {
|
|
328
|
-
throw expected(call, 'a string', value)
|
|
329
|
-
}
|
|
330
|
-
return value.value
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
function regex(call: string, value: LiteralValue | undefined): RegExp {
|
|
334
|
-
if (value?.kind !== 'regex') {
|
|
335
|
-
throw expected(call, 'a regular expression literal', value)
|
|
33
|
+
throw error
|
|
336
34
|
}
|
|
337
|
-
return value.value
|
|
338
35
|
}
|
|
339
36
|
|
|
340
|
-
|
|
341
|
-
if (value?.kind !== 'array') {
|
|
342
|
-
throw expected(call, 'an array of schemas', value)
|
|
343
|
-
}
|
|
344
|
-
return value.items.map((item) => schema(call, item))
|
|
345
|
-
}
|
|
37
|
+
const OBJECT_METHODS: ReadonlySet<string> = new Set(['extend', 'pick', 'omit', 'partial'])
|
|
346
38
|
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
39
|
+
/** The node of the class `@fabrika/app/schema`'s builder makes for the same call: an object, an enum, or any schema. */
|
|
40
|
+
function nodeOf(name: string, iso: boolean, receiver: DataSchema | null, args: readonly unknown[]): DataSchema {
|
|
41
|
+
const object = receiver === null ? name === 'strictObject' : OBJECT_METHODS.has(name) || (name === 'describe' && isObject(receiver))
|
|
42
|
+
if (object) {
|
|
43
|
+
return new DataObject<z.core.$ZodShape, z.core.$ZodObjectConfig>(name, iso, receiver, args)
|
|
350
44
|
}
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
function keyMask(call: string, value: LiteralValue | undefined): Record<string, true> {
|
|
355
|
-
if (value?.kind !== 'object' || [...value.entries.values()].some((entry) => entry.kind !== 'boolean' || !entry.value)) {
|
|
356
|
-
throw expected(call, 'an object of keys set to true', value)
|
|
45
|
+
if ((receiver === null && name === 'enum') || (name === 'describe' && receiver instanceof DataEnum)) {
|
|
46
|
+
return new DataEnum<z.core.util.EnumLike>(name, iso, receiver, args)
|
|
357
47
|
}
|
|
358
|
-
return
|
|
48
|
+
return new DataSchema(name, iso, receiver, args)
|
|
359
49
|
}
|
|
360
50
|
|
|
361
|
-
function
|
|
362
|
-
|
|
363
|
-
throw new Refusal(`${call} takes object options`, 'z.discriminatedUnion(<key>, [z.strictObject({ … }), …])')
|
|
364
|
-
}
|
|
365
|
-
return option
|
|
51
|
+
function isObject(schema: DataSchema): boolean {
|
|
52
|
+
return schema instanceof DataObject || schema.wrapped instanceof z.ZodObject
|
|
366
53
|
}
|
|
367
54
|
|
|
368
|
-
function
|
|
369
|
-
if (
|
|
370
|
-
|
|
55
|
+
function receiverOf(receiver: ReadSchema | undefined): DataSchema {
|
|
56
|
+
if (receiver === undefined) {
|
|
57
|
+
throw new SchemaRefusal('a schema method without a schema', SCHEMA_SUBSET)
|
|
371
58
|
}
|
|
372
|
-
|
|
59
|
+
return receiver instanceof DataSchema ? receiver : DataSchema.wrap(receiver)
|
|
373
60
|
}
|
|
374
61
|
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
switch (value?.kind) {
|
|
62
|
+
/** A read argument as the evaluated call would get it; any other kind stays one the replay refuses by its name. */
|
|
63
|
+
function argument(value: LiteralValue): unknown {
|
|
64
|
+
switch (value.kind) {
|
|
379
65
|
case 'string':
|
|
380
66
|
case 'number':
|
|
381
67
|
case 'boolean':
|
|
68
|
+
case 'regex':
|
|
382
69
|
return value.value
|
|
383
70
|
case 'null':
|
|
384
71
|
return null
|
|
385
|
-
default:
|
|
386
|
-
throw expected(call, 'a string, number, boolean or null', value)
|
|
387
|
-
}
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
function literalValues(call: string, value: LiteralValue | undefined): Primitive | Primitive[] {
|
|
391
|
-
return value?.kind === 'array' ? value.items.map((item) => primitive(call, item)) : primitive(call, value)
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
function enumEntries(call: string, value: LiteralValue | undefined): string[] | Record<string, string | number> {
|
|
395
|
-
if (value?.kind === 'array') {
|
|
396
|
-
return value.items.map((item) => text(call, item))
|
|
397
|
-
}
|
|
398
|
-
if (value?.kind === 'object') {
|
|
399
|
-
return Object.fromEntries([...value.entries].map(([key, entry]) => [key, entry.kind === 'number' ? entry.value : text(call, entry)]))
|
|
400
|
-
}
|
|
401
|
-
throw expected(call, 'an array of strings or an object', value)
|
|
402
|
-
}
|
|
403
|
-
|
|
404
|
-
/** A value with no schema or builder in it, as the evaluated literal would be. */
|
|
405
|
-
function plain(call: string, value: LiteralValue | undefined): unknown {
|
|
406
|
-
switch (value?.kind) {
|
|
407
72
|
case 'array':
|
|
408
|
-
return value.items.map(
|
|
73
|
+
return value.items.map(argument)
|
|
409
74
|
case 'object':
|
|
410
|
-
return Object.fromEntries([...value.entries].map(([key, entry]) => [key,
|
|
75
|
+
return Object.fromEntries([...value.entries].map(([key, entry]) => [key, argument(entry)]))
|
|
76
|
+
case 'schema':
|
|
77
|
+
return value.schema
|
|
411
78
|
default:
|
|
412
|
-
return
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
|
|
416
|
-
// ── Options ─────────────────────────────────────────────────────────────────────────────────────
|
|
417
|
-
|
|
418
|
-
/** An error message changes no shape; `error` and `message` are the only options every step takes. */
|
|
419
|
-
interface MessageParams {
|
|
420
|
-
message?: string
|
|
421
|
-
error?: string
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
const MESSAGE_KEYS = ['message', 'error'] as const
|
|
425
|
-
|
|
426
|
-
function options(call: string, value: LiteralValue | undefined, keys: readonly string[]): ReadonlyMap<string, LiteralValue> | string | undefined {
|
|
427
|
-
if (value === undefined || value.kind === 'string') {
|
|
428
|
-
return value?.value
|
|
429
|
-
}
|
|
430
|
-
if (value.kind !== 'object') {
|
|
431
|
-
throw expected(call, 'an error message or an options object', value)
|
|
432
|
-
}
|
|
433
|
-
for (const key of value.entries.keys()) {
|
|
434
|
-
if (!keys.includes(key)) {
|
|
435
|
-
throw new Refusal(`'${key}' is not an option the contract reads for ${call}`, `options among ${keys.join(', ')}`)
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
return value.entries
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
function messageFields(call: string, entries: ReadonlyMap<string, LiteralValue>): MessageParams {
|
|
442
|
-
const params: MessageParams = {}
|
|
443
|
-
const message = entries.get('message')
|
|
444
|
-
const error = entries.get('error')
|
|
445
|
-
if (message !== undefined) {
|
|
446
|
-
params.message = text(call, message)
|
|
447
|
-
}
|
|
448
|
-
if (error !== undefined) {
|
|
449
|
-
params.error = text(call, error)
|
|
79
|
+
return new Unreadable(value.kind)
|
|
450
80
|
}
|
|
451
|
-
return params
|
|
452
|
-
}
|
|
453
|
-
|
|
454
|
-
function messageParams(call: string, value: LiteralValue | undefined): string | MessageParams | undefined {
|
|
455
|
-
const read = options(call, value, MESSAGE_KEYS)
|
|
456
|
-
return read === undefined || typeof read === 'string' ? read : messageFields(call, read)
|
|
457
|
-
}
|
|
458
|
-
|
|
459
|
-
const UUID_VERSIONS = ['v1', 'v2', 'v3', 'v4', 'v5', 'v6', 'v7', 'v8'] as const
|
|
460
|
-
|
|
461
|
-
type UuidVersion = (typeof UUID_VERSIONS)[number]
|
|
462
|
-
|
|
463
|
-
function isUuidVersion(version: string): version is UuidVersion {
|
|
464
|
-
return UUID_VERSIONS.some((known) => known === version)
|
|
465
|
-
}
|
|
466
|
-
|
|
467
|
-
function uuidParams(call: string, value: LiteralValue | undefined): string | (MessageParams & { version?: UuidVersion }) | undefined {
|
|
468
|
-
const read = options(call, value, [...MESSAGE_KEYS, 'version'])
|
|
469
|
-
if (read === undefined || typeof read === 'string') {
|
|
470
|
-
return read
|
|
471
|
-
}
|
|
472
|
-
const params: MessageParams & { version?: UuidVersion } = messageFields(call, read)
|
|
473
|
-
const version = read.get('version')
|
|
474
|
-
if (version !== undefined) {
|
|
475
|
-
const name = text(call, version)
|
|
476
|
-
if (!isUuidVersion(name)) {
|
|
477
|
-
throw new Refusal(`'${name}' is not a UUID version`, `one of ${UUID_VERSIONS.join(', ')}`)
|
|
478
|
-
}
|
|
479
|
-
params.version = name
|
|
480
|
-
}
|
|
481
|
-
return params
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
function precision(call: string, value: LiteralValue): number | null {
|
|
485
|
-
return value.kind === 'null' ? null : number(call, value)
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
function datetimeParams(
|
|
489
|
-
call: string,
|
|
490
|
-
value: LiteralValue | undefined,
|
|
491
|
-
): string | (MessageParams & { offset?: boolean; local?: boolean; precision?: number | null }) | undefined {
|
|
492
|
-
const read = options(call, value, [...MESSAGE_KEYS, 'offset', 'local', 'precision'])
|
|
493
|
-
if (read === undefined || typeof read === 'string') {
|
|
494
|
-
return read
|
|
495
|
-
}
|
|
496
|
-
const params: MessageParams & { offset?: boolean; local?: boolean; precision?: number | null } = messageFields(call, read)
|
|
497
|
-
const offset = read.get('offset')
|
|
498
|
-
const local = read.get('local')
|
|
499
|
-
const digits = read.get('precision')
|
|
500
|
-
if (offset !== undefined) {
|
|
501
|
-
params.offset = flag(call, offset)
|
|
502
|
-
}
|
|
503
|
-
if (local !== undefined) {
|
|
504
|
-
params.local = flag(call, local)
|
|
505
|
-
}
|
|
506
|
-
if (digits !== undefined) {
|
|
507
|
-
params.precision = precision(call, digits)
|
|
508
|
-
}
|
|
509
|
-
return params
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
function timeParams(call: string, value: LiteralValue | undefined): string | (MessageParams & { precision?: number | null }) | undefined {
|
|
513
|
-
const read = options(call, value, [...MESSAGE_KEYS, 'precision'])
|
|
514
|
-
if (read === undefined || typeof read === 'string') {
|
|
515
|
-
return read
|
|
516
|
-
}
|
|
517
|
-
const params: MessageParams & { precision?: number | null } = messageFields(call, read)
|
|
518
|
-
const digits = read.get('precision')
|
|
519
|
-
if (digits !== undefined) {
|
|
520
|
-
params.precision = precision(call, digits)
|
|
521
|
-
}
|
|
522
|
-
return params
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
/** `.includes()` takes its options only as an object. */
|
|
526
|
-
function includesParams(call: string, value: LiteralValue | undefined): (MessageParams & { position?: number }) | undefined {
|
|
527
|
-
const read = options(call, value, [...MESSAGE_KEYS, 'position'])
|
|
528
|
-
if (typeof read === 'string') {
|
|
529
|
-
throw new Refusal(`${call} takes its options as an object`, "{ message: '…' }")
|
|
530
|
-
}
|
|
531
|
-
if (read === undefined) {
|
|
532
|
-
return undefined
|
|
533
|
-
}
|
|
534
|
-
const params: MessageParams & { position?: number } = messageFields(call, read)
|
|
535
|
-
const position = read.get('position')
|
|
536
|
-
if (position !== undefined) {
|
|
537
|
-
params.position = number(call, position)
|
|
538
|
-
}
|
|
539
|
-
return params
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
function flag(call: string, value: LiteralValue): boolean {
|
|
543
|
-
if (value.kind !== 'boolean') {
|
|
544
|
-
throw expected(call, 'a boolean option', value)
|
|
545
|
-
}
|
|
546
|
-
return value.value
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
function unsupported(call: string, receiver: z.ZodType): Refusal {
|
|
550
|
-
return new Refusal(`${call} is not a method of a ${receiver._zod.def.type} schema in the contract subset`, SUBSET)
|
|
551
81
|
}
|
package/src/reader/surface.ts
CHANGED
|
@@ -38,6 +38,7 @@ import {
|
|
|
38
38
|
unknownOptions,
|
|
39
39
|
type Vocabulary,
|
|
40
40
|
} from '@fabrika/app/contract'
|
|
41
|
+
import { DataObject } from '@fabrika/app/schema'
|
|
41
42
|
import {
|
|
42
43
|
type CspSource,
|
|
43
44
|
isLocale,
|
|
@@ -182,7 +183,7 @@ class SurfaceReader {
|
|
|
182
183
|
const [definition] = args(value, 'attachment', 1, 1)
|
|
183
184
|
const options = builderOptions(definition, value, 'attachment')
|
|
184
185
|
const row = this.#schema(options.get('row'), value, 'row')
|
|
185
|
-
if (!(row instanceof z.ZodObject)) {
|
|
186
|
+
if (!(row instanceof z.ZodObject || row instanceof DataObject)) {
|
|
186
187
|
throw new Refused(options.get('row')?.at ?? value.at, 'the row is not an object schema', 'row: z.strictObject({ … })')
|
|
187
188
|
}
|
|
188
189
|
const maxRows = optionalNumber(options.get('maxRows'), 'maxRows')
|
package/src/reader/value.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// Reads the literal subset of `rules/literal.ts` into values, without executing the application: names resolve through
|
|
2
|
-
// `ModuleGraph`, `z` chains build
|
|
2
|
+
// `ModuleGraph`, `z` chains build schemas held as data (each step checked against zod), `c.*` calls stay unapplied for `surface.ts`.
|
|
3
3
|
|
|
4
4
|
import { file, signedToken, WebhookSecret } from '@fabrika/app/contract'
|
|
5
5
|
import type { z } from 'zod/v4'
|
|
@@ -18,7 +18,7 @@ import {
|
|
|
18
18
|
stringStepProblem,
|
|
19
19
|
} from '../rules/literal'
|
|
20
20
|
import type { ReaderProblems } from './problems'
|
|
21
|
-
import { buildSchema } from './schema'
|
|
21
|
+
import { buildSchema, type ReadSchema } from './schema'
|
|
22
22
|
|
|
23
23
|
/**
|
|
24
24
|
* The builder kit a call belongs to: `c` of `defineContract` and `l` of its link's `procedures`; `app`, the kit
|
|
@@ -41,7 +41,7 @@ export type LiteralValue =
|
|
|
41
41
|
/** `nodes` counts the schema with every shared part expanded, as the artifact will hold it; `depth` its nesting. */
|
|
42
42
|
| {
|
|
43
43
|
readonly kind: 'schema'
|
|
44
|
-
readonly schema:
|
|
44
|
+
readonly schema: ReadSchema
|
|
45
45
|
readonly nodes: number
|
|
46
46
|
readonly depth: number
|
|
47
47
|
/** The chain that built it, factory first (`iso` for `z.iso.*`), across a const and the methods applied to it. */
|
|
@@ -553,7 +553,7 @@ export class ValueReader {
|
|
|
553
553
|
return args === null ? null : { kind: 'contract', args, at: located }
|
|
554
554
|
}
|
|
555
555
|
|
|
556
|
-
/** `z.<factory>(…)` or `z.iso.<format>(…)`, then `.<method>(…)` links, each
|
|
556
|
+
/** `z.<factory>(…)` or `z.iso.<format>(…)`, then `.<method>(…)` links, each checked against zod as it is applied. */
|
|
557
557
|
#zodChain(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
|
|
558
558
|
const isIso = links[0]?.kind === 'member' && links[0].name === 'iso'
|
|
559
559
|
const steps = this.#steps(located, links, isIso ? 1 : 0)
|
|
@@ -595,7 +595,7 @@ export class ValueReader {
|
|
|
595
595
|
return null
|
|
596
596
|
}
|
|
597
597
|
}
|
|
598
|
-
let schema:
|
|
598
|
+
let schema: ReadSchema | undefined = receiver?.schema
|
|
599
599
|
let size: SchemaSize = receiver === null ? { nodes: 0, depth: 0 } : { nodes: receiver.nodes, depth: receiver.depth }
|
|
600
600
|
for (const step of steps) {
|
|
601
601
|
const at = { module: located.module, node: step.call }
|
package/src/rules/literal.ts
CHANGED
|
@@ -29,6 +29,8 @@ export type BuilderKind =
|
|
|
29
29
|
/** The only imported names a literal module may use: the builders the platform reads without executing them. */
|
|
30
30
|
export const BUILDER_IMPORTS: Readonly<Record<string, Readonly<Record<string, BuilderKind>>>> = {
|
|
31
31
|
'zod/v4': { z: 'zod', '*': 'zod' },
|
|
32
|
+
// The same subset, each schema held as data; the reader reads both alike.
|
|
33
|
+
'@fabrika/app/schema': { z: 'zod', '*': 'zod' },
|
|
32
34
|
'@fabrika/app/contract': {
|
|
33
35
|
defineContract: 'contract',
|
|
34
36
|
defineVocabulary: 'vocabulary',
|
|
@@ -164,7 +166,7 @@ const ALLOWED_SCHEMA = 'a schema of the supported z subset (packages/check/CLAUD
|
|
|
164
166
|
const ALLOWED_CALLBACK =
|
|
165
167
|
'a function only as a builder callback: defineContract(…, (c) => ({ … })), app.contract((c) => ({ … })), app.group(…, (r) => ({ … })), procedures: (l) => ({ … }) of a link or an export, and the handler of .handle(…)'
|
|
166
168
|
const ALLOWED_IMPORT =
|
|
167
|
-
'z from zod/v4, defineContract, defineVocabulary or defineApp from @fabrika/app/contract, defineTables from @fabrika/db/tables, or a literal const of the application'
|
|
169
|
+
'z from zod/v4 or @fabrika/app/schema, defineContract, defineVocabulary or defineApp from @fabrika/app/contract, defineTables from @fabrika/db/tables, or a literal const of the application'
|
|
168
170
|
|
|
169
171
|
export type Link = { readonly kind: 'member'; readonly name: string | undefined; readonly node: AstNode } | {
|
|
170
172
|
readonly kind: 'call'
|
package/src/rules/structure.ts
CHANGED
|
@@ -129,12 +129,13 @@ const runtimeClosure = (graph: StructureGraph, start: Targets, descend: (path: s
|
|
|
129
129
|
const isDataPackage = (specifier: string): boolean => specifier === '@fabrika/db' || specifier.startsWith('@fabrika/db/')
|
|
130
130
|
|
|
131
131
|
/** The framework modules logic and queries may import; the rest of `@fabrika/*` is the framework's own composition. */
|
|
132
|
-
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/db'])
|
|
132
|
+
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/app/schema', '@fabrika/db'])
|
|
133
133
|
|
|
134
134
|
/** The framework modules an SPA loads: the typed client, its React hooks, the component kit and its challenge widget. */
|
|
135
135
|
const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
136
136
|
'@fabrika/app/client',
|
|
137
137
|
'@fabrika/app/react',
|
|
138
|
+
'@fabrika/app/schema',
|
|
138
139
|
'@fabrika/ui',
|
|
139
140
|
'@fabrika/ui/challenge',
|
|
140
141
|
'@fabrika/ui/styles.css',
|
|
@@ -142,7 +143,7 @@ const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
|
142
143
|
])
|
|
143
144
|
|
|
144
145
|
const SPA_ALLOWED =
|
|
145
|
-
'@fabrika/app/client, @fabrika/app/react, @fabrika/ui, @fabrika/ui/challenge, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
146
|
+
'@fabrika/app/client, @fabrika/app/react, @fabrika/app/schema, @fabrika/ui, @fabrika/ui/challenge, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
146
147
|
|
|
147
148
|
const isSchemaModule = (path: string): boolean => path === SCHEMAS_FILE || path.startsWith(SCHEMAS_DIR)
|
|
148
149
|
|
|
@@ -169,18 +170,18 @@ const checkSpaReference = (graph: StructureGraph, reference: ModuleReference, ta
|
|
|
169
170
|
if (server !== undefined) report(reference.node, 'spa-server-import', viaMessage(reference, server, 'server code', 'the SPA'), SPA_ALLOWED)
|
|
170
171
|
}
|
|
171
172
|
|
|
172
|
-
/** The
|
|
173
|
-
const
|
|
173
|
+
/** The packages shared code loads, zod's schemas either way; everything else it needs is in other modules of `src/shared/`. */
|
|
174
|
+
const SHARED_PACKAGES: ReadonlySet<string> = new Set(['zod/v4', '@fabrika/app/schema'])
|
|
174
175
|
|
|
175
176
|
/** A shared module runs in the SPA and in every slice, so it loads nothing either side lacks. */
|
|
176
177
|
const checkSharedReference = (reference: ModuleReference, targets: Targets, report: Report): void => {
|
|
177
|
-
const outside = targets.packages.find((specifier) => specifier
|
|
178
|
+
const outside = targets.packages.find((specifier) => !SHARED_PACKAGES.has(specifier)) ?? targets.files.find((path) => !isSharedModule(path))
|
|
178
179
|
if (outside === undefined) return
|
|
179
180
|
report(
|
|
180
181
|
reference.node,
|
|
181
182
|
'shared-import',
|
|
182
183
|
viaMessage(reference, outside, 'outside src/shared/', 'shared code'),
|
|
183
|
-
'zod/v4 and other modules under src/shared/; a type-only import of anything else',
|
|
184
|
+
'zod/v4, @fabrika/app/schema and other modules under src/shared/; a type-only import of anything else',
|
|
184
185
|
)
|
|
185
186
|
}
|
|
186
187
|
|
package/types/src/ast.d.ts
CHANGED
|
@@ -64,6 +64,8 @@ export declare const walk: (root: AstNode, visit: (node: AstNode, ancestors: rea
|
|
|
64
64
|
export declare const utf8Bytes: (text: string) => number;
|
|
65
65
|
/** The nesting depth of the tree below `root`, measured without recursion, so a deep tree cannot exhaust the stack. */
|
|
66
66
|
export declare const nodeDepth: (root: AstNode) => number;
|
|
67
|
+
/** The number of syntax nodes in the tree below `root`, `root` included, counted without recursion. */
|
|
68
|
+
export declare const nodeCount: (root: AstNode) => number;
|
|
67
69
|
export declare const parseModule: (file: string, text: string) => ParseResult;
|
|
68
70
|
/** The sources of a module's import and re-export declarations; `rules/literal.ts` decides which of them are allowed. */
|
|
69
71
|
export declare const importedSpecifiers: (module: ParsedModule) => string[];
|
package/types/src/layout.d.ts
CHANGED
|
@@ -25,7 +25,10 @@ export declare const APP_KIT_FILE = "src/app-kit.ts";
|
|
|
25
25
|
/** The shared zod schemas the shell and the SPA import: one module, or a directory of them once it grows. */
|
|
26
26
|
export declare const SCHEMAS_FILE = "src/schemas.ts";
|
|
27
27
|
export declare const SCHEMAS_DIR = "src/schemas/";
|
|
28
|
-
/**
|
|
28
|
+
/**
|
|
29
|
+
* Pure code the SPA and every slice may import: it loads nothing but `zod/v4`, `@fabrika/app/schema` and other modules of
|
|
30
|
+
* its own directory.
|
|
31
|
+
*/
|
|
29
32
|
export declare const SHARED_DIR = "src/shared/";
|
|
30
33
|
/** `src/db/`: the tables, the generated schema and their generated tests; never a slice. */
|
|
31
34
|
export declare const DATABASE_DIR = "src/db/";
|
package/types/src/limits.d.ts
CHANGED
|
@@ -4,12 +4,22 @@
|
|
|
4
4
|
* step runs.
|
|
5
5
|
*/
|
|
6
6
|
export declare const CONTRACT_LIMITS: {
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. Control reads them in a Cloudflare
|
|
9
|
+
* Worker, whose isolate has 128 MB; handler bodies are sliced out before the parse, so they cost bytes, not nodes.
|
|
10
|
+
*/
|
|
8
11
|
readonly sourceBytes: number;
|
|
12
|
+
/** UTF-8 bytes of one module: its own parse is the peak while it is read, and a dense one needs up to 340 times it. */
|
|
13
|
+
readonly moduleBytes: number;
|
|
14
|
+
/**
|
|
15
|
+
* Syntax nodes the reader holds over each graph (the contract's, the tables'), top-level type declarations left out.
|
|
16
|
+
* At this, `sourceBytes` and `schemaNodes` together, Control's read needs a 95 MB heap of its 128 MB isolate.
|
|
17
|
+
*/
|
|
18
|
+
readonly astNodes: 400000;
|
|
9
19
|
/** Nesting of syntax nodes in one module; the contracts in this repository reach 25. */
|
|
10
20
|
readonly astDepth: 128;
|
|
11
21
|
/** Schema nodes once every shared schema is expanded where the contract uses it, over the whole contract. */
|
|
12
|
-
readonly schemaNodes:
|
|
22
|
+
readonly schemaNodes: 60000;
|
|
13
23
|
/** Nesting of one schema: objects, arrays, unions and wrappers. */
|
|
14
24
|
readonly schemaDepth: 32;
|
|
15
25
|
};
|
|
@@ -1,15 +1,18 @@
|
|
|
1
|
+
import { DataSchema } from '@fabrika/app/schema';
|
|
1
2
|
import { z } from 'zod/v4';
|
|
2
3
|
import type { LiteralValue } from './value';
|
|
4
|
+
/** A schema the reader holds: one it read from a chain, or a framework schema (`signedToken()`, `file()`). */
|
|
5
|
+
export type ReadSchema = DataSchema | z.ZodType;
|
|
3
6
|
export type SchemaStep = {
|
|
4
7
|
readonly factory: string;
|
|
5
8
|
readonly iso: boolean;
|
|
6
9
|
} | {
|
|
7
10
|
readonly method: string;
|
|
8
|
-
readonly receiver:
|
|
11
|
+
readonly receiver: ReadSchema | undefined;
|
|
9
12
|
};
|
|
10
13
|
export type BuiltSchema = {
|
|
11
14
|
readonly ok: true;
|
|
12
|
-
readonly schema:
|
|
15
|
+
readonly schema: DataSchema;
|
|
13
16
|
} | {
|
|
14
17
|
readonly ok: false;
|
|
15
18
|
readonly message: string;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import type { z } from 'zod/v4';
|
|
2
1
|
import { type AstNode, type ParsedModule } from '../ast';
|
|
3
2
|
import type { Located, ModuleGraph } from '../graph';
|
|
4
3
|
import type { ReaderProblems } from './problems';
|
|
4
|
+
import { type ReadSchema } from './schema';
|
|
5
5
|
/**
|
|
6
6
|
* The builder kit a call belongs to: `c` of `defineContract` and `l` of its link's `procedures`; `app`, the kit
|
|
7
7
|
* `defineApp` returned; `c` of `app.contract` (`shell`) and `r` of a group, a link or an export (`endpoints`).
|
|
@@ -42,7 +42,7 @@ export type LiteralValue = {
|
|
|
42
42
|
/** `nodes` counts the schema with every shared part expanded, as the artifact will hold it; `depth` its nesting. */
|
|
43
43
|
| {
|
|
44
44
|
readonly kind: 'schema';
|
|
45
|
-
readonly schema:
|
|
45
|
+
readonly schema: ReadSchema;
|
|
46
46
|
readonly nodes: number;
|
|
47
47
|
readonly depth: number;
|
|
48
48
|
/** The chain that built it, factory first (`iso` for `z.iso.*`), across a const and the methods applied to it. */
|