@fabrika/check 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1087 @@
1
+ // The `defineContract(…)` value as the evaluated module holds it: the vocabulary, and the surface each `c.*` builder
2
+ // builds. Every builder copies the fields `@fabrika/app`'s kit copies and records its other option keys in
3
+ // `unknownOptions`, so `buildArtifact` refuses them with the runtime's own words.
4
+
5
+ import {
6
+ type AccessDeclaration,
7
+ type AnyContract,
8
+ type AnyMount,
9
+ attachmentOutput,
10
+ type Builder,
11
+ type CronJob,
12
+ type CspDeclaration,
13
+ type DeclaredDeclaration,
14
+ declaredOf,
15
+ type DimensionDef,
16
+ type Export,
17
+ type ExportAccessDeclaration,
18
+ type FileCollection,
19
+ type ImportDeclaration,
20
+ type KitImportDeclaration,
21
+ kitImportsSection,
22
+ kitUnknownOptions,
23
+ type LinkAccessDeclaration,
24
+ type ProcedureDeclaration,
25
+ type ProcedureType,
26
+ type QueryTree,
27
+ type RoleDef,
28
+ type Schema,
29
+ type SpaAccessDeclaration,
30
+ type Surface,
31
+ SURFACE_SECTIONS,
32
+ unknownOptions,
33
+ type Vocabulary,
34
+ } from '@fabrika/app/contract'
35
+ import {
36
+ type CspSource,
37
+ isLocale,
38
+ isMessageKind,
39
+ type Locale,
40
+ LOCALES,
41
+ type MailTemplate,
42
+ mailTemplateProblems,
43
+ type MailTemplates,
44
+ MESSAGE_KINDS,
45
+ type MessageKind,
46
+ type RpcCaller,
47
+ } from '@fabrika/auth-core'
48
+ import { z } from 'zod/v4'
49
+ import type { Located } from '../graph'
50
+ import { CONTRACT_LIMITS } from '../limits'
51
+ import type { ReaderProblems } from './problems'
52
+ import { type AppValue, describeKind, type Kit, kitName, type LiteralValue, schemaLimits } from './value'
53
+
54
+ /** A refused value; thrown inside this module and recorded where the reader can go on with the next entry. */
55
+ class Refused {
56
+ readonly at: Located
57
+ readonly message: string
58
+ readonly allowed: string
59
+
60
+ constructor(at: Located, message: string, allowed: string) {
61
+ this.at = at
62
+ this.message = message
63
+ this.allowed = allowed
64
+ }
65
+ }
66
+
67
+ const MAIL_ALLOWED =
68
+ "a one-line subject, a text with {{actionUrl}} and an optional HTML body of the e-mail subset, naming only the message's placeholders"
69
+
70
+ const MOUNT_BUILDERS = ['rpc', 'link', 'spa', 'health', 'form', 'webhook'] as const
71
+ const MOUNT_ALLOWED = `one of c.${MOUNT_BUILDERS.join(', c.')}(…)`
72
+ const KIT_MOUNT_ALLOWED = 'one of c.rpc, c.spa, c.health, c.form(…), or a const of app.link(…) or app.webhook(…)'
73
+ const CONTRACT_ALLOWED = 'export const contract = app.contract((c) => ({ … })), or defineContract(vocabulary, (c) => ({ … }))'
74
+
75
+ /** Which builders a surface is written with: `defineContract`'s `c`, or the staged kit's (`app.*` and its `c`). */
76
+ type Form = 'surface' | 'kit'
77
+ const ACCESS_ALLOWED = '{ member: true }, { action, over }, { action, in, from }, { action, on, from }, { action, creates } or { action, app: true }'
78
+
79
+ type Entries = ReadonlyMap<string, LiteralValue>
80
+
81
+ interface Tree<Leaf> {
82
+ readonly [name: string]: Leaf | Tree<Leaf>
83
+ }
84
+
85
+ /** Reads a `defineContract(…)` value into the contract `defineContract` returns; `null` after recording why not. */
86
+ export function readContractValue(value: LiteralValue, problems: ReaderProblems): AnyContract | null {
87
+ return new SurfaceReader(problems).contract(value)
88
+ }
89
+
90
+ class SurfaceReader {
91
+ readonly #problems: ReaderProblems
92
+ #complete = true
93
+ #schemaNodes = 0
94
+
95
+ constructor(problems: ReaderProblems) {
96
+ this.#problems = problems
97
+ }
98
+
99
+ contract(value: LiteralValue): AnyContract | null {
100
+ const read = this.#attempt(() => {
101
+ if (value.kind === 'kit-contract') {
102
+ return this.#kitContract(value.app, value)
103
+ }
104
+ if (value.kind !== 'contract') {
105
+ throw new Refused(value.at, `the contract is a ${describeKind(value)}`, CONTRACT_ALLOWED)
106
+ }
107
+ const [vocabularyValue, callback] = args(value, 'defineContract', 2, 2)
108
+ if (callback?.kind !== 'callback' || vocabularyValue === undefined) {
109
+ throw new Refused(value.at, 'defineContract takes the vocabulary and a builder callback', 'defineContract(vocabulary, (c) => ({ … }))')
110
+ }
111
+ return { vocabulary: this.#vocabulary(vocabularyValue), surface: this.#surface(callback.result, 'surface') }
112
+ })
113
+ if (read === null || !this.#complete) {
114
+ return null
115
+ }
116
+ return { vocabulary: read.vocabulary, dimensions: read.vocabulary.dimensions, surface: read.surface }
117
+ }
118
+
119
+ /** `app.contract((c) => ({ … }))`: the kit's vocabulary, the surface, and the imports section the kit derives. */
120
+ #kitContract(
121
+ app: AppValue,
122
+ value: Extract<LiteralValue, { kind: 'kit-contract' }>,
123
+ ): { vocabulary: Vocabulary<string, string, string>; surface: Surface } {
124
+ const [callback] = args(value, 'app.contract', 1, 1)
125
+ if (callback?.kind !== 'callback') {
126
+ throw new Refused(value.at, 'app.contract takes a builder callback', 'app.contract((c) => ({ … }))')
127
+ }
128
+ const vocabulary = this.#vocabulary(app.vocabulary)
129
+ const imports = this.#attempt(() => kitImports(app.options)) ?? undefined
130
+ const surface = this.#surface(callback.result, 'kit')
131
+ return { vocabulary, surface: imports === undefined ? surface : { ...surface, imports: kitImportsSection(imports, surface) } }
132
+ }
133
+
134
+ /** Runs one entry's read; a refusal is recorded and the reader goes on, so one read reports every entry. */
135
+ #attempt<T>(read: () => T): T | null {
136
+ try {
137
+ return read()
138
+ } catch (error) {
139
+ if (!(error instanceof Refused)) {
140
+ throw error
141
+ }
142
+ this.#problems.add(error.at, error.message, error.allowed)
143
+ this.#complete = false
144
+ return null
145
+ }
146
+ }
147
+
148
+ /**
149
+ * A schema where the contract places it. `compileContract` describes each placement apart, so the expanded nodes of
150
+ * every placement count towards one budget for the whole contract.
151
+ */
152
+ #schema(value: LiteralValue | undefined, owner: Owner, field: string): Schema {
153
+ const read = schema(value, owner, field)
154
+ this.#schemaNodes += value?.kind === 'schema' ? value.nodes : 0
155
+ if (this.#schemaNodes > CONTRACT_LIMITS.schemaNodes) {
156
+ throw new Refused(owner.at, `the contract's schemas expand to over ${CONTRACT_LIMITS.schemaNodes} nodes`, schemaLimits())
157
+ }
158
+ return read
159
+ }
160
+
161
+ /** A procedure's output: a schema, or `attachment({ … })`, built as `@fabrika/app`'s `attachment` builds it. */
162
+ #output(value: LiteralValue | undefined, owner: BuilderValue): Schema {
163
+ if (value?.kind !== 'attachment') {
164
+ return this.#schema(value, owner, 'output')
165
+ }
166
+ const [definition] = args(value, 'attachment', 1, 1)
167
+ const options = builderOptions(definition, value, 'attachment')
168
+ const row = this.#schema(options.get('row'), value, 'row')
169
+ if (!(row instanceof z.ZodObject)) {
170
+ throw new Refused(options.get('row')?.at ?? value.at, 'the row is not an object schema', 'row: z.strictObject({ … })')
171
+ }
172
+ const maxRows = optionalNumber(options.get('maxRows'), 'maxRows')
173
+ return attachmentOutput(row, {
174
+ format: text(options.get('format'), value, 'format'),
175
+ filename: text(options.get('filename'), value, 'filename'),
176
+ maxBytes: numeric(options.get('maxBytes'), value, 'maxBytes'),
177
+ ...(maxRows === undefined ? {} : { maxRows }),
178
+ unknownOptions: optionKeys(options, 'attachment'),
179
+ })
180
+ }
181
+
182
+ #each<T>(entries: Entries, read: (name: string, value: LiteralValue) => T): Record<string, T> {
183
+ const result: Record<string, T> = {}
184
+ for (const [name, value] of entries) {
185
+ const entry = this.#attempt(() => read(name, value))
186
+ if (entry !== null) {
187
+ result[name] = entry
188
+ }
189
+ }
190
+ return result
191
+ }
192
+
193
+ // ── Vocabulary ──────────────────────────────────────────────────────────────────────────────
194
+
195
+ #vocabulary(value: LiteralValue): Vocabulary<string, string, string> {
196
+ const fields = strictFields(value, 'the vocabulary', ['app', 'dimensions', 'actions', 'roles'], [
197
+ 'locale',
198
+ 'displayName',
199
+ 'mail',
200
+ 'members',
201
+ 'directory',
202
+ ])
203
+ const locale = fields.get('locale')
204
+ const displayName = fields.get('displayName')
205
+ const mail = fields.get('mail')
206
+ const members = fields.get('members')
207
+ const memberFields = members === undefined ? undefined : strictFields(members, 'the vocabulary members', ['manage', 'list'], [])
208
+ const directory = fields.get('directory')
209
+ return {
210
+ app: text(fields.get('app'), value, 'app'),
211
+ ...(locale === undefined ? {} : { locale: localeOf(locale, value) }),
212
+ ...(displayName === undefined ? {} : { displayName: text(displayName, value, 'displayName') }),
213
+ ...(mail === undefined ? {} : { mail: this.#mail(mail) }),
214
+ ...(memberFields === undefined
215
+ ? {}
216
+ : { members: { manage: text(memberFields.get('manage'), value, 'manage'), list: text(memberFields.get('list'), value, 'list') } }),
217
+ ...(directory === undefined ? {} : { directory: directoryOf(directory, value) }),
218
+ dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
219
+ actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
220
+ roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
221
+ }
222
+ }
223
+
224
+ /** The vocabulary's `mail`: message → language → `{ subject, text }`, each refused at the string it is wrong in. */
225
+ #mail(value: LiteralValue): MailTemplates {
226
+ const templates: { [K in MessageKind]?: { [L in Locale]?: MailTemplate } } = {}
227
+ for (const [kind, byLocale] of strictFields(value, 'mail', [], MESSAGE_KINDS)) {
228
+ if (!isMessageKind(kind)) continue
229
+ const declared: { [L in Locale]?: MailTemplate } = {}
230
+ for (const [locale, entry] of strictFields(byLocale, `mail.${kind}`, [], LOCALES)) {
231
+ if (!isLocale(locale)) continue
232
+ const fields = strictFields(entry, `mail.${kind}.${locale}`, ['subject', 'text'], ['html'])
233
+ const html = fields.get('html')
234
+ const template = {
235
+ subject: text(fields.get('subject'), entry, 'subject'),
236
+ text: text(fields.get('text'), entry, 'text'),
237
+ ...(html === undefined ? {} : { html: text(html, entry, 'html') }),
238
+ }
239
+ for (const problem of mailTemplateProblems(kind, template)) {
240
+ const at = problem.startsWith('the subject') ? fields.get('subject') : problem.startsWith('the HTML') ? html : fields.get('text')
241
+ this.#problems.add(at?.at ?? entry.at, `mail.${kind}.${locale}: ${problem}`, MAIL_ALLOWED)
242
+ this.#complete = false
243
+ }
244
+ declared[locale] = template
245
+ }
246
+ templates[kind] = declared
247
+ }
248
+ return templates
249
+ }
250
+
251
+ #dimension(name: string, value: LiteralValue): DimensionDef<string, string, string> {
252
+ const fields = strictFields(value, `dimension '${name}'`, [], ['in', 'creator', 'members', 'directory'])
253
+ const members = fields.get('members')
254
+ const memberFields = members === undefined ? undefined : strictFields(members, `dimension '${name}' members`, ['manage', 'list'], [])
255
+ const directory = fields.get('directory')
256
+ return {
257
+ in: optionalText(fields.get('in'), 'in'),
258
+ creator: optionalText(fields.get('creator'), 'creator'),
259
+ members: memberFields === undefined
260
+ ? undefined
261
+ : { manage: text(memberFields.get('manage'), value, 'manage'), list: text(memberFields.get('list'), value, 'list') },
262
+ ...(directory === undefined ? {} : { directory: directoryOf(directory, value) }),
263
+ }
264
+ }
265
+
266
+ #role(name: string, value: LiteralValue): RoleDef<string, string, string> {
267
+ const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external'])
268
+ const member = fields.get('member')
269
+ const memberFields = member === undefined ? undefined : strictFields(member, `role '${name}' member`, ['scope', 'assignableBy'], [])
270
+ const external = fields.get('external')
271
+ return {
272
+ grants: texts(fields.get('grants'), value, 'grants'),
273
+ member: memberFields === undefined
274
+ ? undefined
275
+ : { scope: text(memberFields.get('scope'), value, 'scope'), assignableBy: texts(memberFields.get('assignableBy'), value, 'assignableBy') },
276
+ ...(external === undefined ? {} : { external: externalOf(external) }),
277
+ }
278
+ }
279
+
280
+ // ── Surface ─────────────────────────────────────────────────────────────────────────────────
281
+
282
+ #surface(value: LiteralValue, form: Form): Surface {
283
+ if (value.kind !== 'object') {
284
+ throw new Refused(
285
+ value.at,
286
+ `the builder callback returns a ${describeKind(value)}`,
287
+ '(c) => ({ <mount>: c.rpc(…), …, files: { … }, jobs: { … } })',
288
+ )
289
+ }
290
+ const mounts: Record<string, AnyMount> = {}
291
+ for (const [name, entry] of value.entries) {
292
+ if (isSection(name)) {
293
+ continue
294
+ }
295
+ const mount = this.#attempt(() => (form === 'kit' ? this.#kitMount(entry) : this.#mount(entry)))
296
+ if (mount !== null) {
297
+ mounts[name] = mount
298
+ }
299
+ }
300
+ const section = (name: string): Entries | undefined => {
301
+ const entry = value.entries.get(name)
302
+ return entry === undefined ? undefined : (this.#attempt(() => entries(entry, entry, name)) ?? undefined)
303
+ }
304
+ const files = section('files')
305
+ const jobs = section('jobs')
306
+ const exports = section('exports')
307
+ const importsEntry = value.entries.get('imports')
308
+ if (form === 'kit' && importsEntry !== undefined) {
309
+ this.#attempt(() => {
310
+ throw new Refused(importsEntry.at, 'the imports section of the kit contract', 'defineApp(vocabulary, tables, { imports }); remove the section')
311
+ })
312
+ }
313
+ const imports = form === 'kit' ? undefined : section('imports')
314
+ const csp = value.entries.get('csp')
315
+ return {
316
+ ...mounts,
317
+ files: files === undefined ? undefined : this.#each(files, (_, entry) => this.#files(entry, form)),
318
+ jobs: jobs === undefined ? undefined : this.#each(jobs, (_, entry) => (form === 'kit' ? this.#kitCron(entry) : this.#cron(entry))),
319
+ exports: exports === undefined ? undefined : this.#each(exports, (_, entry) => (form === 'kit' ? this.#kitExport(entry) : this.#export(entry))),
320
+ imports: imports === undefined ? undefined : this.#each(imports, (name, entry) => importDeclaration(name, entry)),
321
+ csp: csp === undefined ? undefined : (this.#attempt(() => cspDeclaration(csp)) ?? undefined),
322
+ }
323
+ }
324
+
325
+ #mount(value: LiteralValue): AnyMount {
326
+ const builder = surfaceBuilder(value, MOUNT_BUILDERS, MOUNT_ALLOWED)
327
+ const at = builder.value
328
+ switch (builder.name) {
329
+ case 'rpc': {
330
+ const [prefix, optionsValue, procedures] = args(at, 'c.rpc', 3, 3)
331
+ const options = builderOptions(optionsValue, at, 'c.rpc')
332
+ return {
333
+ kind: 'rpc',
334
+ prefix: text(prefix, at, 'the prefix'),
335
+ callers: rpcCallers(options.get('callers'), at),
336
+ procedures: this.#tree(procedures, at, 'surface', (leaf) => this.#procedure(leaf, 'surface', accessDeclaration)),
337
+ unknownOptions: optionKeys(options, 'rpc'),
338
+ }
339
+ }
340
+ case 'link': {
341
+ const [prefix, optionsValue] = args(at, 'c.link', 2, 2)
342
+ const options = builderOptions(optionsValue, at, 'c.link')
343
+ const callback = options.get('procedures')
344
+ if (callback?.kind !== 'callback') {
345
+ throw new Refused(callback?.at ?? at.at, 'c.link needs procedures as a builder callback', 'procedures: (l) => ({ <name>: l.query({ … }) })')
346
+ }
347
+ return {
348
+ kind: 'link',
349
+ prefix: text(prefix, at, 'the prefix'),
350
+ spa: text(options.get('spa'), at, 'spa'),
351
+ dimension: text(options.get('dimension'), at, 'dimension'),
352
+ grants: texts(options.get('grants'), at, 'grants'),
353
+ issuedBy: text(options.get('issuedBy'), at, 'issuedBy'),
354
+ maxDays: numeric(options.get('maxDays'), at, 'maxDays'),
355
+ procedures: this.#tree(callback.result, at, 'link', (leaf) => this.#procedure(leaf, 'link', linkAccessDeclaration)),
356
+ unknownOptions: optionKeys(options, 'link'),
357
+ }
358
+ }
359
+ case 'spa': {
360
+ const [prefix, optionsValue] = args(at, 'c.spa', 2, 2)
361
+ const options = builderOptions(optionsValue, at, 'c.spa')
362
+ return {
363
+ kind: 'spa',
364
+ prefix: text(prefix, at, 'the prefix'),
365
+ dir: text(options.get('dir'), at, 'dir'),
366
+ access: spaAccessDeclaration(options.get('access'), at),
367
+ public: options.has('public') ? texts(options.get('public'), at, 'public') : undefined,
368
+ unknownOptions: optionKeys(options, 'spa'),
369
+ }
370
+ }
371
+ case 'health': {
372
+ const [path] = args(at, 'c.health', 1, 1)
373
+ return { kind: 'health', path: text(path, at, 'the path') }
374
+ }
375
+ case 'form': {
376
+ const [path, optionsValue] = args(at, 'c.form', 2, 2)
377
+ const options = builderOptions(optionsValue, at, 'c.form')
378
+ return {
379
+ kind: 'form',
380
+ path: text(path, at, 'the path'),
381
+ input: this.#schema(options.get('input'), at, 'input'),
382
+ appendTo: text(options.get('appendTo'), at, 'appendTo'),
383
+ maxBytes: optionalNumber(options.get('maxBytes'), 'maxBytes'),
384
+ rate: formRate(options.get('rate')),
385
+ honeypot: optionalText(options.get('honeypot'), 'honeypot'),
386
+ challenge: formChallenge(options.get('challenge')),
387
+ then: optionalText(options.get('then'), 'then'),
388
+ unknownOptions: optionKeys(options, 'form'),
389
+ }
390
+ }
391
+ case 'webhook': {
392
+ const [path, optionsValue] = args(at, 'c.webhook', 2, 2)
393
+ const options = builderOptions(optionsValue, at, 'c.webhook')
394
+ const scheme = options.get('scheme')
395
+ if (scheme?.kind !== 'string' || scheme.value !== 'github-sha256') {
396
+ throw new Refused(scheme?.at ?? at.at, 'c.webhook needs a known scheme', "scheme: 'github-sha256'")
397
+ }
398
+ return {
399
+ kind: 'webhook',
400
+ path: text(path, at, 'the path'),
401
+ scheme: scheme.value,
402
+ boundTo: text(options.get('boundTo'), at, 'boundTo'),
403
+ actions: texts(options.get('actions'), at, 'actions'),
404
+ input: this.#schema(options.get('input'), at, 'input'),
405
+ maxBytes: optionalNumber(options.get('maxBytes'), 'maxBytes'),
406
+ unknownOptions: optionKeys(options, 'webhook'),
407
+ }
408
+ }
409
+ }
410
+ }
411
+
412
+ /** A mount of the kit contract: `c.rpc(prefix, groups)`, a shell mount, or an `app.link` or `app.webhook` const. */
413
+ #kitMount(value: LiteralValue): AnyMount {
414
+ const builder = value.kind === 'builder' ? { name: value.name, kit: value.kit, args: value.args, at: value.at } : undefined
415
+ if (builder?.kit === 'shell' && builder.name === 'rpc') {
416
+ const [prefix, groupsValue] = args(builder, 'c.rpc', 2, 2)
417
+ const path = text(prefix, builder, 'the prefix')
418
+ const read = this.#groups(groupsValue, builder)
419
+ const [first] = read.groups
420
+ if (first === undefined) {
421
+ throw new Refused(groupsValue?.at ?? builder.at, `c.rpc('${path}') mounts no group`, `c.rpc('${path}', { <name>: <group> })`)
422
+ }
423
+ if (read.groups.some((group) => !sameCallers(group.callers, first.callers))) {
424
+ throw new Refused(builder.at, 'every group of one RPC mount names the same callers, in the same order', "callers: ['human'] in each group")
425
+ }
426
+ return {
427
+ kind: 'rpc',
428
+ prefix: path,
429
+ callers: first.callers,
430
+ procedures: read.procedures,
431
+ unknownOptions: [...new Set(read.groups.flatMap((group) => group.unknownOptions))],
432
+ }
433
+ }
434
+ if (builder?.kit === 'shell' && (builder.name === 'spa' || builder.name === 'health' || builder.name === 'form')) {
435
+ return this.#mount(asSurface(builder))
436
+ }
437
+ if (builder?.kit === 'app' && builder.name === 'link') {
438
+ const [prefix, optionsValue] = args(builder, 'app.link', 2, 2)
439
+ const options = builderOptions(optionsValue, builder, 'app.link')
440
+ const callback = options.get('procedures')
441
+ if (callback?.kind !== 'callback') {
442
+ throw new Refused(
443
+ callback?.at ?? builder.at,
444
+ 'app.link needs procedures as a builder callback',
445
+ 'procedures: (l) => ({ <name>: l.query({ … }) })',
446
+ )
447
+ }
448
+ return {
449
+ kind: 'link',
450
+ prefix: text(prefix, builder, 'the prefix'),
451
+ spa: text(options.get('spa'), builder, 'spa'),
452
+ dimension: text(options.get('dimension'), builder, 'dimension'),
453
+ grants: texts(options.get('grants'), builder, 'grants'),
454
+ issuedBy: text(options.get('issuedBy'), builder, 'issuedBy'),
455
+ maxDays: numeric(options.get('maxDays'), builder, 'maxDays'),
456
+ procedures: this.#tree(callback.result, builder, 'endpoints', (leaf) => this.#procedure(leaf, 'endpoints', linkAccessDeclaration)),
457
+ unknownOptions: optionKeys(options, 'link'),
458
+ }
459
+ }
460
+ if (builder?.kit === 'app' && builder.name === 'webhook') {
461
+ const mount = this.#mount(asSurface(builder))
462
+ if (mount.kind !== 'webhook') {
463
+ throw new Refused(builder.at, 'app.webhook(…) read as another mount', 'app.webhook(path, { … })')
464
+ }
465
+ const options = builderOptions(builder.args[1], builder, 'app.webhook')
466
+ return { ...mount, declared: declared(options), unknownOptions: kitOptionKeys(options, 'webhook') }
467
+ }
468
+ throw new Refused(value.at, `a ${describeKind(value)} where a mount of the kit stands`, KIT_MOUNT_ALLOWED)
469
+ }
470
+
471
+ /** The groups `c.rpc` mounts: one `app.group(…)`, or groups by name, nested; the procedures nest by the same names. */
472
+ #groups(
473
+ value: LiteralValue | undefined,
474
+ owner: BuilderValue,
475
+ ): { readonly groups: readonly ReadGroup[]; readonly procedures: Tree<ProcedureDeclaration<Schema>> } {
476
+ if (value?.kind === 'builder' && value.kit === 'app' && value.name === 'group') {
477
+ const at = { name: value.name, kit: value.kit, args: value.args, at: value.at }
478
+ const [optionsValue, callback] = args(at, 'app.group', 2, 2)
479
+ const options = builderOptions(optionsValue, at, 'app.group')
480
+ if (callback?.kind !== 'callback') {
481
+ throw new Refused(
482
+ callback?.at ?? at.at,
483
+ 'app.group takes its endpoints as a builder callback',
484
+ 'app.group({ callers }, (r) => ({ <name>: r.query({ … }) }))',
485
+ )
486
+ }
487
+ const procedures = this.#tree(callback.result, at, 'endpoints', (leaf) => this.#procedure(leaf, 'endpoints', accessDeclaration))
488
+ return { groups: [{ callers: rpcCallers(options.get('callers'), at), unknownOptions: optionKeys(options, 'rpc') }], procedures }
489
+ }
490
+ if (value?.kind !== 'object') {
491
+ throw new Refused(
492
+ value?.at ?? owner.at,
493
+ `a ${value === undefined ? 'missing value' : describeKind(value)} where a group stands`,
494
+ 'app.group(…), or { <name>: <group> }',
495
+ )
496
+ }
497
+ const groups: ReadGroup[] = []
498
+ const procedures: Record<string, Tree<ProcedureDeclaration<Schema>>> = {}
499
+ for (const [name, entry] of value.entries) {
500
+ const read = this.#groups(entry, owner)
501
+ groups.push(...read.groups)
502
+ procedures[name] = read.procedures
503
+ }
504
+ return { groups, procedures }
505
+ }
506
+
507
+ #tree<Leaf>(value: LiteralValue | undefined, owner: BuilderValue, kit: Kit, leaf: (builder: BuilderValue) => Leaf): Tree<Leaf> {
508
+ if (value?.kind !== 'object') {
509
+ throw new Refused(value?.at ?? owner.at, 'procedures are not an object', `{ <name>: ${kitName(kit)}.query({ … }), <group>: { … } }`)
510
+ }
511
+ const tree: Record<string, Leaf | Tree<Leaf>> = {}
512
+ for (const [name, node] of value.entries) {
513
+ if (node.kind === 'builder') {
514
+ tree[name] = leaf({ name: node.name, kit: node.kit, args: node.args, at: node.at })
515
+ } else if (node.kind === 'object') {
516
+ tree[name] = this.#tree(node, owner, kit, leaf)
517
+ } else {
518
+ throw new Refused(
519
+ node.at,
520
+ `procedure '${name}' is a ${describeKind(node)}`,
521
+ `${kitName(kit)}.query({ … }), ${kitName(kit)}.mutation({ … }) or a group { … }`,
522
+ )
523
+ }
524
+ }
525
+ return tree
526
+ }
527
+
528
+ #procedure<Access>(
529
+ builder: BuilderValue,
530
+ kit: Kit,
531
+ access: (value: LiteralValue | undefined, at: BuilderValue) => Access,
532
+ ): ProcedureDeclaration<Schema, Access> {
533
+ const call = `${kitName(builder.kit)}.${builder.name}`
534
+ if (builder.kit !== kit || (builder.name !== 'query' && builder.name !== 'mutation')) {
535
+ throw new Refused(builder.at, `${call}(…) is not a procedure here`, `${kitName(kit)}.query({ … }) or ${kitName(kit)}.mutation({ … })`)
536
+ }
537
+ const type: ProcedureType = builder.name
538
+ const [definition] = args(builder, call, 1, 1)
539
+ const options = builderOptions(definition, builder, call)
540
+ const input = options.get('input')
541
+ return {
542
+ '~kind': 'procedure',
543
+ type,
544
+ input: input === undefined || input.kind === 'null' ? null : this.#schema(input, builder, 'input'),
545
+ output: this.#output(options.get('output'), builder),
546
+ access: access(options.get('access'), builder),
547
+ ...(kit === 'endpoints'
548
+ ? { declared: declared(options), unknownOptions: kitOptionKeys(options, 'procedure') }
549
+ : { unknownOptions: optionKeys(options, 'procedure') }),
550
+ }
551
+ }
552
+
553
+ // ── Sections ────────────────────────────────────────────────────────────────────────────────
554
+
555
+ #files(value: LiteralValue, form: Form): FileCollection<string> {
556
+ const at =
557
+ surfaceBuilder(form === 'kit' && value.kind === 'builder' && value.kit === 'shell' ? asSurface(value) : value, ['files'], 'c.files({ … })').value
558
+ const [collection] = args(at, 'c.files', 1, 1)
559
+ const options = builderOptions(collection, at, 'c.files')
560
+ const link = options.get('link')
561
+ const scan = options.get('scan')
562
+ return {
563
+ kind: 'files',
564
+ owner: text(options.get('owner'), at, 'owner'),
565
+ read: text(options.get('read'), at, 'read'),
566
+ write: text(options.get('write'), at, 'write'),
567
+ delete: text(options.get('delete'), at, 'delete'),
568
+ maxBytes: numeric(options.get('maxBytes'), at, 'maxBytes'),
569
+ types: texts(options.get('types'), at, 'types'),
570
+ maxPerOwner: optionalNumber(options.get('maxPerOwner'), 'maxPerOwner'),
571
+ link: link === undefined ? undefined : fileLink(link, at),
572
+ scan: scan === undefined ? undefined : boolean(scan, 'scan'),
573
+ unknownOptions: optionKeys(options, 'files'),
574
+ }
575
+ }
576
+
577
+ #cron(value: LiteralValue): CronJob<string, string> {
578
+ const at = surfaceBuilder(value, ['cron'], "c.cron('<schedule>', { … })").value
579
+ const [schedule, optionsValue] = args(at, 'c.cron', 2, 2)
580
+ const options = builderOptions(optionsValue, at, 'c.cron')
581
+ return {
582
+ kind: 'cron',
583
+ schedule: text(schedule, at, 'the schedule'),
584
+ actions: texts(options.get('actions'), at, 'actions'),
585
+ scope: text(options.get('scope'), at, 'scope'),
586
+ timeout: optionalText(options.get('timeout'), 'timeout'),
587
+ retries: optionalNumber(options.get('retries'), 'retries'),
588
+ unknownOptions: optionKeys(options, 'cron'),
589
+ }
590
+ }
591
+
592
+ /** A job of the kit: a const of `app.cron(schedule, { … })`, whose `.handle(…)` the slice removed. */
593
+ #kitCron(value: LiteralValue): CronJob<string, string> {
594
+ if (value.kind !== 'builder' || value.kit !== 'app' || value.name !== 'cron') {
595
+ throw new Refused(value.at, `a ${describeKind(value)} where a job stands`, "a const of app.cron('<schedule>', { … })")
596
+ }
597
+ const job = this.#cron(asSurface(value))
598
+ const options = builderOptions(value.args[1], { name: value.name, kit: value.kit, args: value.args, at: value.at }, 'app.cron')
599
+ return { ...job, declared: declared(options), unknownOptions: kitOptionKeys(options, 'cron') }
600
+ }
601
+
602
+ /** An export of the kit: a const of `app.export({ …, procedures: (e) => ({ … }) })`. */
603
+ #kitExport(value: LiteralValue): Export<QueryTree> {
604
+ if (value.kind !== 'builder' || value.kit !== 'app' || value.name !== 'export') {
605
+ throw new Refused(value.at, `a ${describeKind(value)} where an export stands`, 'a const of app.export({ … })')
606
+ }
607
+ const at = { name: value.name, kit: value.kit, args: value.args, at: value.at }
608
+ const [definition] = args(at, 'app.export', 1, 1)
609
+ const options = builderOptions(definition, at, 'app.export')
610
+ const callback = options.get('procedures')
611
+ if (callback?.kind !== 'callback') {
612
+ throw new Refused(callback?.at ?? at.at, 'app.export needs procedures as a builder callback', 'procedures: (e) => ({ <name>: e.query({ … }) })')
613
+ }
614
+ return {
615
+ kind: 'export',
616
+ version: numeric(options.get('version'), at, 'version'),
617
+ consumers: texts(options.get('consumers'), at, 'consumers'),
618
+ audience: text(options.get('audience'), at, 'audience'),
619
+ procedures: this.#tree(callback.result, at, 'endpoints', (leaf) => {
620
+ const procedure = this.#procedure(leaf, 'endpoints', exportAccessDeclaration)
621
+ if (procedure.type !== 'query') {
622
+ throw new Refused(leaf.at, 'an export serves queries only', 'e.query')
623
+ }
624
+ return { ...procedure, type: procedure.type }
625
+ }),
626
+ unknownOptions: optionKeys(options, 'export'),
627
+ }
628
+ }
629
+
630
+ #export(value: LiteralValue): Export<QueryTree> {
631
+ const at = surfaceBuilder(value, ['export'], 'c.export({ … })').value
632
+ const [definition] = args(at, 'c.export', 1, 1)
633
+ const options = builderOptions(definition, at, 'c.export')
634
+ return {
635
+ kind: 'export',
636
+ version: numeric(options.get('version'), at, 'version'),
637
+ consumers: texts(options.get('consumers'), at, 'consumers'),
638
+ audience: text(options.get('audience'), at, 'audience'),
639
+ procedures: this.#tree(options.get('procedures'), at, 'surface', (leaf) => {
640
+ const procedure = this.#procedure(leaf, 'surface', exportAccessDeclaration)
641
+ if (procedure.type !== 'query') {
642
+ throw new Refused(leaf.at, 'an export serves queries only', 'c.query')
643
+ }
644
+ return { ...procedure, type: procedure.type }
645
+ }),
646
+ unknownOptions: optionKeys(options, 'export'),
647
+ }
648
+ }
649
+ }
650
+
651
+ // ── Builders and their options ──────────────────────────────────────────────────────────────────
652
+
653
+ interface BuilderValue {
654
+ readonly name: string
655
+ readonly kit: Kit
656
+ readonly args: readonly LiteralValue[]
657
+ readonly at: Located
658
+ }
659
+
660
+ function surfaceBuilder<const Name extends string>(
661
+ value: LiteralValue,
662
+ names: readonly Name[],
663
+ allowed: string,
664
+ ): { readonly name: Name; readonly value: BuilderValue } {
665
+ const name = value.kind === 'builder' && value.kit === 'surface' ? names.find((known) => known === value.name) : undefined
666
+ if (value.kind !== 'builder' || name === undefined) {
667
+ throw new Refused(value.at, `a ${describeKind(value)} where a builder call stands`, allowed)
668
+ }
669
+ return { name, value: { name: value.name, kit: value.kit, args: value.args, at: value.at } }
670
+ }
671
+
672
+ function args(
673
+ builder: BuilderValue | Extract<LiteralValue, { kind: 'contract' | 'kit-contract' | 'attachment' }>,
674
+ call: string,
675
+ min: number,
676
+ max: number,
677
+ ): readonly (LiteralValue | undefined)[] {
678
+ if (builder.args.length < min || builder.args.length > max) {
679
+ throw new Refused(
680
+ builder.at,
681
+ `${call} takes ${min === max ? min : `${min} to ${max}`} arguments, not ${builder.args.length}`,
682
+ `${call}(…) as its type declares`,
683
+ )
684
+ }
685
+ return Array.from({ length: max }, (_, index) => builder.args[index])
686
+ }
687
+
688
+ /** A builder's options object; its keys are not checked here, `optionKeys` records the unknown ones. */
689
+ function builderOptions(value: LiteralValue | undefined, at: Owner, call: string): Entries {
690
+ if (value?.kind !== 'object') {
691
+ throw new Refused(value?.at ?? at.at, `${call} takes an options object`, `${call}(…, { … })`)
692
+ }
693
+ return value.entries
694
+ }
695
+
696
+ function optionKeys(options: Entries, builder: Builder): string[] {
697
+ return unknownOptions(Object.fromEntries([...options.keys()].map((key) => [key, true])), builder)
698
+ }
699
+
700
+ function kitOptionKeys(options: Entries, builder: Builder): string[] {
701
+ return kitUnknownOptions(Object.fromEntries([...options.keys()].map((key) => [key, true])), builder)
702
+ }
703
+
704
+ /** What a site of the kit declares, copied as `declaredOf` copies it; `buildArtifact` checks it. */
705
+ function declared(options: Entries): DeclaredDeclaration {
706
+ return declaredOf({
707
+ sql: plain(options.get('sql')),
708
+ unscoped: plain(options.get('unscoped')),
709
+ connect: plain(options.get('connect')),
710
+ issues: plain(options.get('issues')),
711
+ })
712
+ }
713
+
714
+ /** A literal as the plain value the evaluated module holds; a declared field holds no schema or builder. */
715
+ function plain(value: LiteralValue | undefined): unknown {
716
+ if (value === undefined) {
717
+ return undefined
718
+ }
719
+ switch (value.kind) {
720
+ case 'string':
721
+ case 'number':
722
+ case 'boolean':
723
+ return value.value
724
+ case 'null':
725
+ return null
726
+ case 'array':
727
+ return value.items.map(plain)
728
+ case 'object':
729
+ return Object.fromEntries([...value.entries].map(([key, entry]) => [key, plain(entry)]))
730
+ default:
731
+ throw new Refused(value.at, `a ${describeKind(value)} in a declared field`, DECLARED_ALLOWED)
732
+ }
733
+ }
734
+
735
+ const DECLARED_ALLOWED = "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>'"
736
+
737
+ /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
738
+ const asSurface = (builder: BuilderValue): LiteralValue => ({
739
+ kind: 'builder',
740
+ kit: 'surface',
741
+ name: builder.name,
742
+ args: builder.args,
743
+ at: builder.at,
744
+ })
745
+
746
+ interface ReadGroup {
747
+ readonly callers: readonly [RpcCaller, ...RpcCaller[]]
748
+ readonly unknownOptions: readonly string[]
749
+ }
750
+
751
+ const sameCallers = (left: readonly string[], right: readonly string[]): boolean =>
752
+ left.length === right.length && left.every((caller, index) => caller === right[index])
753
+
754
+ /**
755
+ * The kit's imports from `defineApp`'s options: each snapshot's identity, the procedures it calls, its deadline;
756
+ * `undefined` without options, where the contract has no imports section.
757
+ */
758
+ function kitImports(options: LiteralValue | undefined): Record<string, KitImportDeclaration> | undefined {
759
+ if (options === undefined) {
760
+ return undefined
761
+ }
762
+ const imports = strictFields(options, "defineApp's options", ['imports'], []).get('imports')
763
+ return Object.fromEntries([...entries(imports, options, 'imports')].map(([name, value]) => {
764
+ const where = `import '${name}'`
765
+ const declaration = strictFields(value, where, ['snapshot', 'procedures'], ['timeoutMs'])
766
+ const snapshotValue = declaration.get('snapshot')
767
+ const snapshot = entries(snapshotValue, value, 'snapshot')
768
+ const owner = snapshotValue ?? value
769
+ const timeoutMs = optionalNumber(declaration.get('timeoutMs'), 'timeoutMs')
770
+ return [name, {
771
+ app: text(snapshot.get('app'), owner, 'the snapshot app'),
772
+ export: text(snapshot.get('export'), owner, 'the snapshot export'),
773
+ version: numeric(snapshot.get('version'), owner, 'the snapshot version'),
774
+ digest: text(snapshot.get('digest'), owner, 'the snapshot digest'),
775
+ procedures: texts(declaration.get('procedures'), value, 'procedures'),
776
+ ...(timeoutMs === undefined ? {} : { timeoutMs }),
777
+ }]
778
+ }))
779
+ }
780
+
781
+ const SECTIONS: ReadonlySet<string> = new Set(SURFACE_SECTIONS)
782
+
783
+ function isSection(name: string): boolean {
784
+ return SECTIONS.has(name)
785
+ }
786
+
787
+ // ── Plain fields ────────────────────────────────────────────────────────────────────────────────
788
+
789
+ type Owner = BuilderValue | LiteralValue
790
+
791
+ function entries(value: LiteralValue | undefined, owner: Owner, field: string): Entries {
792
+ if (value?.kind !== 'object') {
793
+ throw new Refused(value?.at ?? owner.at, `${field} is not an object`, `${field}: { … }`)
794
+ }
795
+ return value.entries
796
+ }
797
+
798
+ /** An object whose keys are exactly `required` plus any of `optional`. */
799
+ function strictFields(value: LiteralValue, where: string, required: readonly string[], optional: readonly string[]): Entries {
800
+ if (value.kind !== 'object') {
801
+ throw new Refused(value.at, `${where} is a ${describeKind(value)}`, `${where} as an object literal`)
802
+ }
803
+ const allowed = [...required, ...optional]
804
+ for (const [key, entry] of value.entries) {
805
+ if (!allowed.includes(key)) {
806
+ throw new Refused(entry.at, `'${key}' is not a field of ${where}`, `the fields ${allowed.join(', ')}`)
807
+ }
808
+ }
809
+ for (const key of required) {
810
+ if (!value.entries.has(key)) {
811
+ throw new Refused(value.at, `${where} has no '${key}'`, `the fields ${allowed.join(', ')}`)
812
+ }
813
+ }
814
+ return value.entries
815
+ }
816
+
817
+ function text(value: LiteralValue | undefined, owner: Owner, field: string): string {
818
+ if (value?.kind !== 'string') {
819
+ throw new Refused(
820
+ value?.at ?? owner.at,
821
+ value === undefined ? `${field} is missing` : `${field} is a ${describeKind(value)}`,
822
+ `${field} as a string`,
823
+ )
824
+ }
825
+ return value.value
826
+ }
827
+
828
+ /** The vocabulary's `locale`: one of the languages IAM speaks. */
829
+ function localeOf(value: LiteralValue, owner: Owner): Locale {
830
+ const locale = text(value, owner, 'locale')
831
+ if (!isLocale(locale)) {
832
+ throw new Refused(value.at, `locale is '${locale}'`, LOCALES.map((allowed) => `locale: '${allowed}'`).join(' or '))
833
+ }
834
+ return locale
835
+ }
836
+
837
+ /** A role's `external`, which only `true` is. */
838
+ function externalOf(value: LiteralValue): true {
839
+ if (!boolean(value, 'external')) {
840
+ throw new Refused(value.at, 'external is false', 'external: true, or no external')
841
+ }
842
+ return true
843
+ }
844
+
845
+ /** A dimension's `directory`, which only `'labels'` is. */
846
+ function directoryOf(value: LiteralValue, owner: Owner): 'labels' {
847
+ const directory = text(value, owner, 'directory')
848
+ if (directory !== 'labels') {
849
+ throw new Refused(value.at, `directory is '${directory}'`, "directory: 'labels'")
850
+ }
851
+ return directory
852
+ }
853
+
854
+ function optionalText(value: LiteralValue | undefined, field: string): string | undefined {
855
+ return value === undefined ? undefined : text(value, value, field)
856
+ }
857
+
858
+ function texts(value: LiteralValue | undefined, owner: Owner, field: string): string[] {
859
+ if (value?.kind !== 'array') {
860
+ throw new Refused(value?.at ?? owner.at, value === undefined ? `${field} is missing` : `${field} is a ${describeKind(value)}`, `${field}: ['…']`)
861
+ }
862
+ return value.items.map((item) => text(item, item, `an item of ${field}`))
863
+ }
864
+
865
+ function numeric(value: LiteralValue | undefined, owner: Owner, field: string): number {
866
+ if (value?.kind !== 'number') {
867
+ throw new Refused(
868
+ value?.at ?? owner.at,
869
+ value === undefined ? `${field} is missing` : `${field} is a ${describeKind(value)}`,
870
+ `${field} as a number`,
871
+ )
872
+ }
873
+ return value.value
874
+ }
875
+
876
+ function optionalNumber(value: LiteralValue | undefined, field: string): number | undefined {
877
+ return value === undefined ? undefined : numeric(value, value, field)
878
+ }
879
+
880
+ function boolean(value: LiteralValue, field: string): boolean {
881
+ if (value.kind !== 'boolean') {
882
+ throw new Refused(value.at, `${field} is a ${describeKind(value)}`, `${field}: true or false`)
883
+ }
884
+ return value.value
885
+ }
886
+
887
+ /** A collection's `link`: `true` or `false`, or the link mounts it names; the build refuses an empty list. */
888
+ function fileLink(value: LiteralValue, owner: Owner): boolean | string[] {
889
+ if (value.kind === 'boolean') return value.value
890
+ if (value.kind !== 'array') throw new Refused(value.at, `link is a ${describeKind(value)}`, "link: true, or link: ['<link mount>']")
891
+ return texts(value, owner, 'link')
892
+ }
893
+
894
+ function schema(value: LiteralValue | undefined, owner: Owner, field: string): Schema {
895
+ if (value?.kind !== 'schema') {
896
+ throw new Refused(
897
+ value?.at ?? owner.at,
898
+ value === undefined ? `${field} is missing` : `${field} is a ${describeKind(value)}`,
899
+ `${field}: z.<schema>`,
900
+ )
901
+ }
902
+ return value.schema
903
+ }
904
+
905
+ function isRpcCaller(caller: string): caller is RpcCaller {
906
+ return caller === 'human' || caller === 'machine'
907
+ }
908
+
909
+ function rpcCallers(value: LiteralValue | undefined, at: BuilderValue): readonly [RpcCaller, ...RpcCaller[]] {
910
+ const [first, ...rest] = texts(value, at, 'callers')
911
+ const allowed = "callers: ['human'] or ['machine']; another application reaches only an export"
912
+ if (first === undefined) {
913
+ throw new Refused(value?.at ?? at.at, 'callers is empty', allowed)
914
+ }
915
+ const callers: RpcCaller[] = []
916
+ for (const caller of [first, ...rest]) {
917
+ if (!isRpcCaller(caller)) {
918
+ throw new Refused(value?.at ?? at.at, `'${caller}' is not a caller of an RPC mount`, allowed)
919
+ }
920
+ callers.push(caller)
921
+ }
922
+ const [head, ...tail] = callers
923
+ if (head === undefined) {
924
+ throw new Refused(at.at, 'callers is empty', allowed)
925
+ }
926
+ return [head, ...tail]
927
+ }
928
+
929
+ // ── Access ──────────────────────────────────────────────────────────────────────────────────────
930
+
931
+ function accessFields(value: LiteralValue | undefined, at: BuilderValue, allowed: string): Entries {
932
+ if (value?.kind !== 'object') {
933
+ throw new Refused(value?.at ?? at.at, value === undefined ? 'access is missing' : `access is a ${describeKind(value)}`, allowed)
934
+ }
935
+ return value.entries
936
+ }
937
+
938
+ function hasKeys(fields: Entries, keys: readonly string[]): boolean {
939
+ return fields.size === keys.length && keys.every((key) => fields.has(key))
940
+ }
941
+
942
+ function isMember(fields: Entries): boolean {
943
+ const member = fields.get('member')
944
+ return hasKeys(fields, ['member']) && member?.kind === 'boolean' && member.value
945
+ }
946
+
947
+ /** `{ action, app: true }`: `app` is the literal `true`, as `buildArtifact` reads it. */
948
+ function isApp(fields: Entries): boolean {
949
+ const app = fields.get('app')
950
+ return hasKeys(fields, ['action', 'app']) && app?.kind === 'boolean' && app.value
951
+ }
952
+
953
+ /** The one access form the object spells, with exactly its keys, as `buildArtifact` reads it. */
954
+ function accessDeclaration(value: LiteralValue | undefined, at: BuilderValue): AccessDeclaration {
955
+ const fields = accessFields(value, at, ACCESS_ALLOWED)
956
+ const field = (key: string): string => text(fields.get(key), value ?? at, `access.${key}`)
957
+ if (isMember(fields)) {
958
+ return { member: true }
959
+ }
960
+ if (hasKeys(fields, ['action', 'over'])) {
961
+ return { action: field('action'), over: field('over') }
962
+ }
963
+ if (hasKeys(fields, ['action', 'in', 'from'])) {
964
+ return { action: field('action'), in: field('in'), from: field('from') }
965
+ }
966
+ if (hasKeys(fields, ['action', 'on', 'from'])) {
967
+ return { action: field('action'), on: field('on'), from: field('from') }
968
+ }
969
+ if (hasKeys(fields, ['action', 'creates'])) {
970
+ return { action: field('action'), creates: field('creates') }
971
+ }
972
+ if (isApp(fields)) {
973
+ return { action: field('action'), app: true }
974
+ }
975
+ throw new Refused(value?.at ?? at.at, 'access is not one access form', ACCESS_ALLOWED)
976
+ }
977
+
978
+ /**
979
+ * An export procedure names its action in a dimension: the consumer's key holds exactly the actions, so `member` would
980
+ * hold none, and a v1 export declares one dimension, which `app` names none of.
981
+ */
982
+ function exportAccessDeclaration(value: LiteralValue | undefined, at: BuilderValue): ExportAccessDeclaration {
983
+ const access = accessDeclaration(value, at)
984
+ if ('member' in access) {
985
+ throw new Refused(value?.at ?? at.at, 'an export procedure names its action', '{ action, over } (or in, on, creates)')
986
+ }
987
+ if ('app' in access) {
988
+ throw new Refused(value?.at ?? at.at, 'an export procedure reads in one dimension', '{ action, over } (or in, on)')
989
+ }
990
+ return access
991
+ }
992
+
993
+ function linkAccessDeclaration(value: LiteralValue | undefined, at: BuilderValue): LinkAccessDeclaration {
994
+ const fields = accessFields(value, at, "{ action: <one of the link's grants> }")
995
+ if (!hasKeys(fields, ['action'])) {
996
+ throw new Refused(value?.at ?? at.at, 'access is not a link access', "{ action: <one of the link's grants> }")
997
+ }
998
+ return { action: text(fields.get('action'), value ?? at, 'access.action') }
999
+ }
1000
+
1001
+ const SPA_ACCESS_ALLOWED = '{ member: true }, { action, over }, { action, app: true } or { public: true }'
1002
+
1003
+ function spaAccessDeclaration(value: LiteralValue | undefined, at: BuilderValue): SpaAccessDeclaration {
1004
+ const fields = accessFields(value, at, SPA_ACCESS_ALLOWED)
1005
+ if (isMember(fields)) {
1006
+ return { member: true }
1007
+ }
1008
+ const open = fields.get('public')
1009
+ if (hasKeys(fields, ['public']) && open?.kind === 'boolean' && open.value) {
1010
+ return { public: true }
1011
+ }
1012
+ if (hasKeys(fields, ['action', 'over'])) {
1013
+ return { action: text(fields.get('action'), value ?? at, 'access.action'), over: text(fields.get('over'), value ?? at, 'access.over') }
1014
+ }
1015
+ if (isApp(fields)) {
1016
+ return { action: text(fields.get('action'), value ?? at, 'access.action'), app: true }
1017
+ }
1018
+ throw new Refused(value?.at ?? at.at, 'access is not an SPA access', SPA_ACCESS_ALLOWED)
1019
+ }
1020
+
1021
+ // ── Imports and CSP ─────────────────────────────────────────────────────────────────────────────
1022
+
1023
+ function importDeclaration(name: string, value: LiteralValue): ImportDeclaration {
1024
+ const where = `import '${name}'`
1025
+ const fields = strictFields(value, where, ['app', 'export', 'version', 'digest', 'procedures', 'usedBy'], ['timeoutMs'])
1026
+ return {
1027
+ app: text(fields.get('app'), value, 'app'),
1028
+ export: text(fields.get('export'), value, 'export'),
1029
+ version: numeric(fields.get('version'), value, 'version'),
1030
+ digest: text(fields.get('digest'), value, 'digest'),
1031
+ procedures: texts(fields.get('procedures'), value, 'procedures'),
1032
+ usedBy: texts(fields.get('usedBy'), value, 'usedBy'),
1033
+ timeoutMs: optionalNumber(fields.get('timeoutMs'), 'timeoutMs'),
1034
+ }
1035
+ }
1036
+
1037
+ /** A form's `rate`, as `buildArtifact` reads it: per-minute counts, each optional. */
1038
+ function formRate(value: LiteralValue | undefined): { perClient?: number; perForm?: number } | undefined {
1039
+ if (value === undefined) {
1040
+ return undefined
1041
+ }
1042
+ const fields = strictFields(value, 'rate', [], ['perClient', 'perForm'])
1043
+ const perClient = optionalNumber(fields.get('perClient'), 'perClient')
1044
+ const perForm = optionalNumber(fields.get('perForm'), 'perForm')
1045
+ return { ...(perClient === undefined ? {} : { perClient }), ...(perForm === undefined ? {} : { perForm }) }
1046
+ }
1047
+
1048
+ /** A form's `challenge`: a provider of the closed list and the names of the application variables with its secret and site key. */
1049
+ function formChallenge(value: LiteralValue | undefined): { provider: 'turnstile'; secret: string; siteKey?: string } | undefined {
1050
+ if (value === undefined) {
1051
+ return undefined
1052
+ }
1053
+ const fields = strictFields(value, 'challenge', ['provider', 'secret'], ['siteKey'])
1054
+ const provider = fields.get('provider')
1055
+ if (provider?.kind !== 'string' || provider.value !== 'turnstile') {
1056
+ throw new Refused(provider?.at ?? value.at, 'challenge needs a known provider', "provider: 'turnstile'")
1057
+ }
1058
+ const secret = text(fields.get('secret'), value, 'secret')
1059
+ const siteKey = fields.get('siteKey')
1060
+ return siteKey === undefined ? { provider: provider.value, secret } : { provider: provider.value, secret, siteKey: text(siteKey, value, 'siteKey') }
1061
+ }
1062
+
1063
+ function cspDeclaration(value: LiteralValue): CspDeclaration {
1064
+ const fields = strictFields(value, 'csp', [], ['connectSrc', 'imgSrc', 'frameAncestors', 'scriptSrc', 'frameSrc', 'styleSrc', 'fontSrc'])
1065
+ const sources = (key: string): CspSource[] | undefined => {
1066
+ const list = fields.get(key)
1067
+ if (list === undefined) {
1068
+ return undefined
1069
+ }
1070
+ if (list.kind !== 'array') {
1071
+ throw new Refused(list.at, `csp ${key} is a ${describeKind(list)}`, `${key}: [{ origin: 'https://…', purpose: '…' }]`)
1072
+ }
1073
+ return list.items.map((item) => {
1074
+ const source = strictFields(item, `a csp ${key} source`, ['origin', 'purpose'], [])
1075
+ return { origin: text(source.get('origin'), item, 'origin'), purpose: text(source.get('purpose'), item, 'purpose') }
1076
+ })
1077
+ }
1078
+ return {
1079
+ connectSrc: sources('connectSrc'),
1080
+ imgSrc: sources('imgSrc'),
1081
+ frameAncestors: sources('frameAncestors'),
1082
+ scriptSrc: sources('scriptSrc'),
1083
+ frameSrc: sources('frameSrc'),
1084
+ styleSrc: sources('styleSrc'),
1085
+ fontSrc: sources('fontSrc'),
1086
+ }
1087
+ }