@fabrika/app 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.
Files changed (64) hide show
  1. package/package.json +14 -9
  2. package/skill/SKILL.md +2 -2
  3. package/skill/references/app-setup.md +10 -9
  4. package/skill/references/endpoint.md +8 -1
  5. package/src/build-contract-child.ts +16 -0
  6. package/src/build.ts +48 -2
  7. package/src/client/contract.ts +6 -4
  8. package/src/cloudflare/application.ts +3 -0
  9. package/src/contract/artifact-schema.ts +355 -301
  10. package/src/contract/attachment.ts +4 -3
  11. package/src/contract/compile.ts +3 -2
  12. package/src/contract/context.ts +2 -3
  13. package/src/contract/define.ts +17 -5
  14. package/src/contract/group.ts +8 -7
  15. package/src/contract/index.ts +1 -1
  16. package/src/contract/kit.ts +2 -2
  17. package/src/contract/problems.ts +4 -0
  18. package/src/contract/schema-shape.ts +14 -2
  19. package/src/contract/token.ts +4 -3
  20. package/src/from-row.ts +12 -6
  21. package/src/implement/approved.ts +57 -0
  22. package/src/implement/attachment.ts +2 -1
  23. package/src/implement/boot.ts +90 -12
  24. package/src/implement/dispatch.ts +14 -10
  25. package/src/implement/egress.ts +7 -6
  26. package/src/implement/faults.ts +1 -0
  27. package/src/implement/project.ts +3 -1
  28. package/src/implement/tokens.ts +3 -2
  29. package/src/implement/types.ts +18 -6
  30. package/src/react/hooks.ts +12 -11
  31. package/src/react/provider.tsx +2 -1
  32. package/src/react/types.ts +2 -2
  33. package/src/schema/builder.ts +146 -0
  34. package/src/schema/data-schema.ts +365 -0
  35. package/src/schema/index.ts +18 -0
  36. package/src/schema/replay.ts +623 -0
  37. package/src/testing/kit.ts +3 -3
  38. package/types/src/build-contract-child.d.ts +1 -0
  39. package/types/src/build.d.ts +16 -1
  40. package/types/src/client/contract.d.ts +3 -4
  41. package/types/src/cloudflare/application.d.ts +2 -0
  42. package/types/src/contract/artifact-schema.d.ts +8 -0
  43. package/types/src/contract/attachment.d.ts +3 -2
  44. package/types/src/contract/context.d.ts +2 -3
  45. package/types/src/contract/define.d.ts +14 -5
  46. package/types/src/contract/group.d.ts +5 -6
  47. package/types/src/contract/index.d.ts +1 -1
  48. package/types/src/contract/kit.d.ts +2 -3
  49. package/types/src/contract/problems.d.ts +1 -0
  50. package/types/src/contract/schema-shape.d.ts +3 -2
  51. package/types/src/contract/token.d.ts +3 -3
  52. package/types/src/from-row.d.ts +9 -5
  53. package/types/src/implement/approved.d.ts +11 -0
  54. package/types/src/implement/boot.d.ts +6 -0
  55. package/types/src/implement/faults.d.ts +1 -0
  56. package/types/src/implement/project.d.ts +2 -1
  57. package/types/src/implement/types.d.ts +4 -5
  58. package/types/src/react/hooks.d.ts +4 -5
  59. package/types/src/react/types.d.ts +2 -2
  60. package/types/src/schema/builder.d.ts +45 -0
  61. package/types/src/schema/data-schema.d.ts +124 -0
  62. package/types/src/schema/index.d.ts +3 -0
  63. package/types/src/schema/replay.d.ts +27 -0
  64. package/types/src/testing/kit.d.ts +2 -3
@@ -29,6 +29,7 @@ import {
29
29
  type RecordShape,
30
30
  type RowsTestArtifact,
31
31
  type SchemaShape,
32
+ SHARED_SHAPES_ENCODING,
32
33
  type StringShape,
33
34
  type TablePolicyArtifact,
34
35
  terminalIdentifyProblem,
@@ -65,77 +66,95 @@ const fileKindName = name.refine(
65
66
  /** IAM's own role keys win over an application role of the same key at resolution. */
66
67
  const roleKey = name.refine((key) => !BUILTIN_ROLE_KEYS.includes(key), 'a built-in IAM role key is not a contract role name')
67
68
 
68
- const stringShape: z.ZodType<StringShape> = z.strictObject({
69
- type: z.literal('string'),
70
- format: z.enum(['uuid', 'email', 'url', 'datetime', 'date', 'time', 'duration']).nullable(),
71
- minLength: z.int().nonnegative().nullable(),
72
- maxLength: z.int().nonnegative().nullable(),
73
- pattern: z.string().nullable(),
74
- startsWith: z.string().nullable(),
75
- endsWith: z.string().nullable(),
76
- includes: z.string().nullable(),
77
- })
69
+ /**
70
+ * The parser of a schema shape. Plain (`shared` null): every constraint present, null when unset, as `canonicalShape`
71
+ * writes it. Shared, as `encodeArtifact` writes it: a null constraint is absent, and `{ type: 'shared', index }` is the
72
+ * shape `shared[index]`, the same object wherever it is referenced. `shared` holds only the shapes parsed before, so a
73
+ * reference reaches back only, and no shape contains itself.
74
+ */
75
+ function shapeSchemaOf(shared: readonly SchemaShape[] | null): z.ZodType<SchemaShape> {
76
+ const absentIsNull = shared !== null
77
+ const nonNegative = orNull(z.int().nonnegative(), absentIsNull)
78
+ const text = orNull(z.string(), absentIsNull)
79
+ const bound = orNull(z.number(), absentIsNull)
80
+ const stringShape = z.strictObject({
81
+ type: z.literal('string'),
82
+ format: orNull(z.enum(['uuid', 'email', 'url', 'datetime', 'date', 'time', 'duration']), absentIsNull),
83
+ minLength: nonNegative,
84
+ maxLength: nonNegative,
85
+ pattern: text,
86
+ startsWith: text,
87
+ endsWith: text,
88
+ includes: text,
89
+ }) satisfies z.ZodType<StringShape>
90
+ const numberShape = z.strictObject({
91
+ type: z.literal('number'),
92
+ int: z.boolean(),
93
+ min: bound,
94
+ exclusiveMin: z.boolean(),
95
+ max: bound,
96
+ exclusiveMax: z.boolean(),
97
+ multipleOf: orNull(z.number().positive(), absentIsNull),
98
+ }) satisfies z.ZodType<NumberShape>
99
+ const forms = () =>
100
+ [
101
+ stringShape,
102
+ numberShape,
103
+ z.strictObject({ type: z.enum(['boolean', 'null']) }),
104
+ z.strictObject({ type: z.literal('literal'), value: z.union([z.string(), z.number(), z.boolean(), z.null()]) }),
105
+ z.strictObject({ type: z.literal('enum'), values: z.array(z.string()) }),
106
+ z.strictObject({ type: z.literal('array'), items: shape, minItems: nonNegative, maxItems: nonNegative }) satisfies z.ZodType<ArrayShape>,
107
+ z.strictObject({ type: z.literal('tuple'), items: z.array(shape), rest: orNull(shape, absentIsNull) }) satisfies z.ZodType<TupleShape>,
108
+ z.strictObject({ type: z.literal('record'), key: shape, value: shape }) satisfies z.ZodType<RecordShape>,
109
+ z.strictObject({ type: z.literal('object'), fields: z.record(z.string(), shape) }),
110
+ z.strictObject({ type: z.literal('optional'), inner: shape }),
111
+ z.strictObject({ type: z.literal('nullable'), inner: shape }),
112
+ z.strictObject({ type: z.literal('union'), options: z.array(shape) }),
113
+ z.strictObject({ type: z.literal('token'), purpose: name }),
114
+ z.strictObject({ type: z.literal('file'), kind: z.string().min(1) }),
115
+ ] as const
116
+ // Dispatched on `type`: one form per node, never a trial of each.
117
+ const shape: z.ZodType<SchemaShape> = shared === null
118
+ ? z.lazy(() => z.discriminatedUnion('type', forms()))
119
+ : z.lazy(() =>
120
+ z.discriminatedUnion('type', [...forms(), z.strictObject({ type: z.literal('shared'), index: z.int().nonnegative() })]).transform(
121
+ (written, context): SchemaShape => {
122
+ if (written.type !== 'shared') return written
123
+ const target = shared[written.index]
124
+ if (target === undefined) {
125
+ context.addIssue({ code: 'custom', message: `shape ${written.index} is not written before it is referenced` })
126
+ return z.NEVER
127
+ }
128
+ return target
129
+ },
130
+ )
131
+ )
132
+ return shape
133
+ }
78
134
 
79
- const numberShape: z.ZodType<NumberShape> = z.strictObject({
80
- type: z.literal('number'),
81
- int: z.boolean(),
82
- min: z.number().nullable(),
83
- exclusiveMin: z.boolean(),
84
- max: z.number().nullable(),
85
- exclusiveMax: z.boolean(),
86
- multipleOf: z.number().positive().nullable(),
87
- })
135
+ /** A constraint that is null when unset; absent stands for null where `absentIsNull`. */
136
+ function orNull<T extends z.ZodType>(schema: T, absentIsNull: boolean): z.ZodType<z.output<T> | null, z.input<T> | null | undefined> {
137
+ return absentIsNull ? schema.nullable().default(null) : schema.nullable()
138
+ }
88
139
 
89
140
  /** A `SchemaShape` read back as JSON. */
90
- export const schemaShapeSchema: z.ZodType<SchemaShape> = z.lazy(() =>
91
- z.union([
92
- stringShape,
93
- numberShape,
94
- z.strictObject({ type: z.enum(['boolean', 'null']) }),
95
- z.strictObject({ type: z.literal('literal'), value: z.union([z.string(), z.number(), z.boolean(), z.null()]) }),
96
- z.strictObject({ type: z.literal('enum'), values: z.array(z.string()) }),
97
- arrayShape,
98
- tupleShape,
99
- recordShape,
100
- z.strictObject({ type: z.literal('object'), fields: z.record(z.string(), schemaShapeSchema) }),
101
- z.strictObject({ type: z.literal('optional'), inner: schemaShapeSchema }),
102
- z.strictObject({ type: z.literal('nullable'), inner: schemaShapeSchema }),
103
- z.strictObject({ type: z.literal('union'), options: z.array(schemaShapeSchema) }),
104
- z.strictObject({ type: z.literal('token'), purpose: name }),
105
- z.strictObject({ type: z.literal('file'), kind: z.string().min(1) }),
106
- ])
107
- )
108
-
109
- const arrayShape: z.ZodType<ArrayShape> = z.lazy(() =>
110
- z.strictObject({
111
- type: z.literal('array'),
112
- items: schemaShapeSchema,
113
- minItems: z.int().nonnegative().nullable(),
114
- maxItems: z.int().nonnegative().nullable(),
115
- })
116
- )
117
-
118
- const tupleShape: z.ZodType<TupleShape> = z.lazy(() =>
119
- z.strictObject({ type: z.literal('tuple'), items: z.array(schemaShapeSchema), rest: schemaShapeSchema.nullable() })
120
- )
121
-
122
- const recordShape: z.ZodType<RecordShape> = z.lazy(() =>
123
- z.strictObject({ type: z.literal('record'), key: schemaShapeSchema, value: schemaShapeSchema })
124
- )
125
-
126
- const attachmentShape: z.ZodType<AttachmentShape> = z.strictObject({
127
- type: z.literal('attachment'),
128
- format: z.enum(['csv', 'xlsx']),
129
- filename: name,
130
- maxBytes: z.int().positive(),
131
- maxRows: z.int().positive(),
132
- columns: z.array(z.strictObject({ name: z.string(), shape: schemaShapeSchema })).min(1),
133
- })
141
+ export const schemaShapeSchema: z.ZodType<SchemaShape> = shapeSchemaOf(null)
134
142
 
135
143
  /** What a procedure answers: a schema shape, or an attachment's file. */
136
- const redirectShape = z.strictObject({ type: z.literal('redirect'), origins: z.array(z.string().startsWith('https://')) })
144
+ function outputShapeSchemaOf(shape: z.ZodType<SchemaShape>): z.ZodType<OutputShape> {
145
+ const attachmentShape: z.ZodType<AttachmentShape> = z.strictObject({
146
+ type: z.literal('attachment'),
147
+ format: z.enum(['csv', 'xlsx']),
148
+ filename: name,
149
+ maxBytes: z.int().positive(),
150
+ maxRows: z.int().positive(),
151
+ columns: z.array(z.strictObject({ name: z.string(), shape })).min(1),
152
+ })
153
+ const redirectShape = z.strictObject({ type: z.literal('redirect'), origins: z.array(z.string().startsWith('https://')) })
154
+ return z.union([shape, attachmentShape, redirectShape])
155
+ }
137
156
 
138
- export const outputShapeSchema: z.ZodType<OutputShape> = z.union([schemaShapeSchema, attachmentShape, redirectShape])
157
+ export const outputShapeSchema: z.ZodType<OutputShape> = outputShapeSchemaOf(schemaShapeSchema)
139
158
 
140
159
  const caller = z.union([z.enum(['human', 'machine', 'link']), z.templateLiteral(['app:', z.string().min(1)])])
141
160
  const rpcCaller = z.enum(['human', 'machine'])
@@ -171,79 +190,86 @@ const endpointCacheSchema = z.union([
171
190
  z.strictObject({ maxAgeSeconds: z.int().min(1).max(MAX_CACHE_AGE_SECONDS) }),
172
191
  ])
173
192
 
174
- const rowBase = {
175
- id: name,
176
- source: z.strictObject({ kind: z.enum(['mount', 'export', 'files']), name }),
177
- method: z.enum(['GET', 'POST']),
178
- path: z.string().startsWith('/'),
179
- admission: z.strictObject({ contentTypes: z.tuple([name], name), maxBytes: z.int().positive().nullable() }).nullable(),
180
- input: schemaShapeSchema.nullable(),
181
- output: outputShapeSchema.nullable(),
182
- response: z.enum(['file', 'inline-file']).optional(),
193
+ function rowBaseOf(shape: z.ZodType<SchemaShape>, output: z.ZodType<OutputShape>) {
194
+ return {
195
+ id: name,
196
+ source: z.strictObject({ kind: z.enum(['mount', 'export', 'files']), name }),
197
+ method: z.enum(['GET', 'POST']),
198
+ path: z.string().startsWith('/'),
199
+ admission: z.strictObject({ contentTypes: z.tuple([name], name), maxBytes: z.int().positive().nullable() }).nullable(),
200
+ input: shape.nullable(),
201
+ output: output.nullable(),
202
+ response: z.enum(['file', 'inline-file']).optional(),
203
+ }
183
204
  }
184
205
 
185
- const endpointRow: z.ZodType<EndpointRow> = z.union([
186
- z.strictObject({
187
- ...rowBase,
188
- kind: z.enum(['query', 'mutation', 'spa', 'upload', 'download']),
189
- callers: z.tuple([caller], caller),
190
- requirement,
191
- crossOrigin: z.literal('environment').optional(),
192
- }),
193
- z.strictObject({
194
- ...rowBase,
195
- kind: z.enum(['health', 'form', 'webhook', 'link-spa']),
196
- callers: z.tuple([]),
197
- requirement: z.null(),
198
- crossOrigin: z.enum(['environment', 'any']).optional(),
199
- authorization: z.literal('forward').optional(),
200
- }).refine((row) => row.authorization === undefined || row.kind === 'webhook', "only a webhook forwards the request's Authorization"),
201
- // A public procedure is a mount's procedure anyone calls: it admits a body and answers its output.
202
- z.strictObject({
203
- ...rowBase,
204
- kind: z.literal('public'),
205
- source: z.strictObject({ kind: z.literal('mount'), name }),
206
- output: outputShapeSchema,
207
- callers: z.tuple([]),
208
- requirement: z.null(),
209
- crossOrigin: z.enum(['environment', 'any']).optional(),
210
- cache: endpointCacheSchema.optional(),
211
- }).refine((row) => row.cache === undefined || row.method === 'GET', 'only a GET answer is cached'),
212
- // The framework's own GET that issues the ALTCHA challenge of the public procedure its source names: no body, no schemas.
213
- z.strictObject({
214
- ...rowBase,
215
- kind: z.literal('public'),
216
- source: z.strictObject({ kind: z.literal('challenge'), name }),
217
- method: z.literal('GET'),
218
- admission: z.null(),
219
- input: z.null(),
220
- output: z.null(),
221
- callers: z.tuple([]),
222
- requirement: z.null(),
223
- crossOrigin: z.enum(['environment', 'any']).optional(),
224
- }),
225
- // A public SPA is a fixed static row: GET only, no body, no schemas.
226
- z.strictObject({
227
- ...rowBase,
228
- kind: z.literal('public-spa'),
229
- method: z.literal('GET'),
230
- admission: z.null(),
231
- input: z.null(),
232
- output: z.null(),
233
- callers: z.tuple([]),
234
- requirement: z.null(),
235
- }),
236
- ]).refine(
237
- // Only a procedure answers a stored file, and exactly when its output is one.
238
- (row) => (row.response !== undefined) === (row.output?.type === 'file') && (row.response === undefined || FILE_RESPONSE_KINDS.includes(row.kind)),
239
- 'only a procedure whose output is a file answers a stored file',
240
- ).refine(
241
- // Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022).
242
- (row) =>
243
- !('crossOrigin' in row) || row.crossOrigin === undefined
244
- || (CROSS_ORIGIN_KINDS.includes(row.kind) && (row.crossOrigin !== 'any' || ANY_ORIGIN_KINDS.includes(row.kind))),
245
- 'this endpoint kind cannot be called cross-origin',
246
- )
206
+ /** An endpoint row whose schemas `shape` parses. */
207
+ function endpointRowOf(shape: z.ZodType<SchemaShape>): z.ZodType<EndpointRow> {
208
+ const output = outputShapeSchemaOf(shape)
209
+ const rowBase = rowBaseOf(shape, output)
210
+ return z.union([
211
+ z.strictObject({
212
+ ...rowBase,
213
+ kind: z.enum(['query', 'mutation', 'spa', 'upload', 'download']),
214
+ callers: z.tuple([caller], caller),
215
+ requirement,
216
+ crossOrigin: z.literal('environment').optional(),
217
+ }),
218
+ z.strictObject({
219
+ ...rowBase,
220
+ kind: z.enum(['health', 'form', 'webhook', 'link-spa']),
221
+ callers: z.tuple([]),
222
+ requirement: z.null(),
223
+ crossOrigin: z.enum(['environment', 'any']).optional(),
224
+ authorization: z.literal('forward').optional(),
225
+ }).refine((row) => row.authorization === undefined || row.kind === 'webhook', "only a webhook forwards the request's Authorization"),
226
+ // A public procedure is a mount's procedure anyone calls: it admits a body and answers its output.
227
+ z.strictObject({
228
+ ...rowBase,
229
+ kind: z.literal('public'),
230
+ source: z.strictObject({ kind: z.literal('mount'), name }),
231
+ output,
232
+ callers: z.tuple([]),
233
+ requirement: z.null(),
234
+ crossOrigin: z.enum(['environment', 'any']).optional(),
235
+ cache: endpointCacheSchema.optional(),
236
+ }).refine((row) => row.cache === undefined || row.method === 'GET', 'only a GET answer is cached'),
237
+ // The framework's own GET that issues the ALTCHA challenge of the public procedure its source names: no body, no schemas.
238
+ z.strictObject({
239
+ ...rowBase,
240
+ kind: z.literal('public'),
241
+ source: z.strictObject({ kind: z.literal('challenge'), name }),
242
+ method: z.literal('GET'),
243
+ admission: z.null(),
244
+ input: z.null(),
245
+ output: z.null(),
246
+ callers: z.tuple([]),
247
+ requirement: z.null(),
248
+ crossOrigin: z.enum(['environment', 'any']).optional(),
249
+ }),
250
+ // A public SPA is a fixed static row: GET only, no body, no schemas.
251
+ z.strictObject({
252
+ ...rowBase,
253
+ kind: z.literal('public-spa'),
254
+ method: z.literal('GET'),
255
+ admission: z.null(),
256
+ input: z.null(),
257
+ output: z.null(),
258
+ callers: z.tuple([]),
259
+ requirement: z.null(),
260
+ }),
261
+ ]).refine(
262
+ // Only a procedure answers a stored file, and exactly when its output is one.
263
+ (row) => (row.response !== undefined) === (row.output?.type === 'file') && (row.response === undefined || FILE_RESPONSE_KINDS.includes(row.kind)),
264
+ 'only a procedure whose output is a file answers a stored file',
265
+ ).refine(
266
+ // Only an RPC procedure, a public procedure and a form open to another origin, and only the anonymous two to any (ADR-0022).
267
+ (row) =>
268
+ !('crossOrigin' in row) || row.crossOrigin === undefined
269
+ || (CROSS_ORIGIN_KINDS.includes(row.kind) && (row.crossOrigin !== 'any' || ANY_ORIGIN_KINDS.includes(row.kind))),
270
+ 'this endpoint kind cannot be called cross-origin',
271
+ )
272
+ }
247
273
 
248
274
  const scopeBinding = z.discriminatedUnion('kind', [
249
275
  z.strictObject({ kind: z.literal('app') }),
@@ -406,182 +432,188 @@ const tablePolicy: z.ZodType<TablePolicyArtifact> = z.strictObject({
406
432
  ).optional(),
407
433
  })
408
434
 
409
- export const contractArtifactSchema: z.ZodType<ContractArtifact> = z.strictObject({
410
- format: z.literal(CONTRACT_FORMAT),
411
- app: name,
412
- dimensions: record(z.strictObject({
413
- in: nullableName,
414
- creator: nullableName,
415
- members: z.strictObject({ manage: action, list: action }).nullable(),
416
- directory: z.literal('labels').optional(),
417
- })),
418
- actions: z.record(action, z.string()),
419
- roles: z.record(
420
- roleKey,
421
- z.strictObject({
422
- grants: actions,
423
- member: z.strictObject({ scope: name, assignableBy: z.array(roleKey) }).nullable(),
424
- external: z.literal(true).optional(),
425
- via: record(actions.nonempty()).optional(),
426
- }).refine((role) => role.external !== true || role.member !== null, {
427
- path: ['external'],
428
- message: 'only a membership role admits external principals',
429
- }).refine((role) => role.via === undefined || role.external !== true, {
430
- path: ['via'],
431
- message: 'a relation holds actions through an internal role only, never an external one',
432
- }),
433
- ),
434
- relations: record(z.strictObject({ dimension: name })).optional(),
435
- mounts: record(mount),
436
- files: record(z.strictObject({
437
- owner: name,
438
- read: action,
439
- write: action,
440
- delete: action,
441
- maxBytes: z.int().positive(),
442
- types: names,
443
- maxPerOwner: z.int().positive().nullable(),
444
- link: z.union([z.boolean(), z.array(name).nonempty()]),
445
- scan: z.literal(true).optional(),
446
- })),
447
- fileKinds: z.record(
448
- fileKindName,
449
- z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional(), inline: z.literal(true).optional() }).refine(
450
- (kind) => kind.inline === undefined || kind.types.every((type) => inlineFileTypes('inline-file').includes(type)),
451
- 'an inline kind admits only inert images and XML documents',
452
- ),
453
- ).optional(),
454
- jobs: record(z.strictObject({
455
- schedule: name,
456
- actions,
457
- scope: scopeBinding,
458
- timeoutMs: z.int().positive().max(JOB_LIMITS.maxTimeoutMs),
459
- retries: z.int().nonnegative(),
460
- })),
461
- exports: record(z.strictObject({ version: z.int().positive(), consumers: names, audience: name })),
462
- imports: record(z.strictObject({
435
+ /** A contract artifact whose schemas `shape` parses. */
436
+ function artifactSchemaOf(shape: z.ZodType<SchemaShape>): z.ZodType<ContractArtifact> {
437
+ return z.strictObject({
438
+ format: z.literal(CONTRACT_FORMAT),
463
439
  app: name,
464
- export: name,
465
- version: z.int().positive(),
466
- digest: name,
467
- procedures: names,
468
- usedBy: names,
469
- timeoutMs: z.int().positive().nullable(),
470
- })),
471
- csp: z.strictObject({
472
- connectSrc: z.array(cspSource),
473
- imgSrc: z.array(cspSource),
474
- frameAncestors: z.array(cspSource),
475
- scriptSrc: z.array(cspSource).nonempty().optional(),
476
- frameSrc: z.array(cspSource).nonempty().optional(),
477
- styleSrc: z.array(cspSource).nonempty().optional(),
478
- fontSrc: z.array(cspSource).nonempty().optional(),
479
- workerSrc: z.tuple([z.strictObject({ origin: z.literal(WORKER_BLOB_SOURCE), purpose: z.string().min(1) })]).optional(),
480
- }),
481
- tables: record(tablePolicy),
482
- endpoints: z.array(endpointRow).superRefine((rows, context) => {
483
- for (const [index, row] of rows.entries()) {
484
- if (row.source.kind !== 'export' && row.callers.some((caller) => caller.startsWith('app:'))) {
485
- context.addIssue({ code: 'custom', path: [index, 'callers'], message: 'an app:<id> caller reaches only an export row' })
440
+ dimensions: record(z.strictObject({
441
+ in: nullableName,
442
+ creator: nullableName,
443
+ members: z.strictObject({ manage: action, list: action }).nullable(),
444
+ directory: z.literal('labels').optional(),
445
+ })),
446
+ actions: z.record(action, z.string()),
447
+ roles: z.record(
448
+ roleKey,
449
+ z.strictObject({
450
+ grants: actions,
451
+ member: z.strictObject({ scope: name, assignableBy: z.array(roleKey) }).nullable(),
452
+ external: z.literal(true).optional(),
453
+ via: record(actions.nonempty()).optional(),
454
+ }).refine((role) => role.external !== true || role.member !== null, {
455
+ path: ['external'],
456
+ message: 'only a membership role admits external principals',
457
+ }).refine((role) => role.via === undefined || role.external !== true, {
458
+ path: ['via'],
459
+ message: 'a relation holds actions through an internal role only, never an external one',
460
+ }),
461
+ ),
462
+ relations: record(z.strictObject({ dimension: name })).optional(),
463
+ mounts: record(mount),
464
+ files: record(z.strictObject({
465
+ owner: name,
466
+ read: action,
467
+ write: action,
468
+ delete: action,
469
+ maxBytes: z.int().positive(),
470
+ types: names,
471
+ maxPerOwner: z.int().positive().nullable(),
472
+ link: z.union([z.boolean(), z.array(name).nonempty()]),
473
+ scan: z.literal(true).optional(),
474
+ })),
475
+ fileKinds: z.record(
476
+ fileKindName,
477
+ z.strictObject({ types: names, maxBytes: z.int().positive(), scan: z.literal(true).optional(), inline: z.literal(true).optional() }).refine(
478
+ (kind) => kind.inline === undefined || kind.types.every((type) => inlineFileTypes('inline-file').includes(type)),
479
+ 'an inline kind admits only inert images and XML documents',
480
+ ),
481
+ ).optional(),
482
+ jobs: record(z.strictObject({
483
+ schedule: name,
484
+ actions,
485
+ scope: scopeBinding,
486
+ timeoutMs: z.int().positive().max(JOB_LIMITS.maxTimeoutMs),
487
+ retries: z.int().nonnegative(),
488
+ })),
489
+ exports: record(z.strictObject({ version: z.int().positive(), consumers: names, audience: name })),
490
+ imports: record(z.strictObject({
491
+ app: name,
492
+ export: name,
493
+ version: z.int().positive(),
494
+ digest: name,
495
+ procedures: names,
496
+ usedBy: names,
497
+ timeoutMs: z.int().positive().nullable(),
498
+ })),
499
+ csp: z.strictObject({
500
+ connectSrc: z.array(cspSource),
501
+ imgSrc: z.array(cspSource),
502
+ frameAncestors: z.array(cspSource),
503
+ scriptSrc: z.array(cspSource).nonempty().optional(),
504
+ frameSrc: z.array(cspSource).nonempty().optional(),
505
+ styleSrc: z.array(cspSource).nonempty().optional(),
506
+ fontSrc: z.array(cspSource).nonempty().optional(),
507
+ workerSrc: z.tuple([z.strictObject({ origin: z.literal(WORKER_BLOB_SOURCE), purpose: z.string().min(1) })]).optional(),
508
+ }),
509
+ tables: record(tablePolicy),
510
+ endpoints: z.array(endpointRowOf(shape)).superRefine((rows, context) => {
511
+ for (const [index, row] of rows.entries()) {
512
+ if (row.source.kind !== 'export' && row.callers.some((caller) => caller.startsWith('app:'))) {
513
+ context.addIssue({ code: 'custom', path: [index, 'callers'], message: 'an app:<id> caller reaches only an export row' })
514
+ }
515
+ if (row.source.kind === 'export' && row.requirement?.kind !== 'action') {
516
+ context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row requires an action' })
517
+ }
518
+ if (row.source.kind === 'export' && row.requirement?.kind === 'action' && row.requirement.access.form === 'app') {
519
+ context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row reads in one dimension, never app-wide' })
520
+ }
486
521
  }
487
- if (row.source.kind === 'export' && row.requirement?.kind !== 'action') {
488
- context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row requires an action' })
522
+ }),
523
+ reservedPrefixes: names,
524
+ declared: record(z.strictObject({
525
+ sql: z.enum(['read', 'write']).nullable(),
526
+ unscoped: record(z.enum(['read', 'write'])),
527
+ connect: names,
528
+ issues: nullableName,
529
+ then: name.optional(),
530
+ mailer: z.enum(JOB_MAILERS).optional(),
531
+ actions: actions.nonempty().optional(),
532
+ kicks: z.array(name).nonempty().optional(),
533
+ binds: name.optional(),
534
+ signs: z.array(name).nonempty().optional(),
535
+ egress: z.union([z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty(), z.literal(PUBLIC_EGRESS)]).optional(),
536
+ })).superRefine((declared, context) => {
537
+ for (const [site, reach] of Object.entries(declared)) {
538
+ if (reach.egress === PUBLIC_EGRESS && !site.startsWith(JOB_SITE_PREFIX)) {
539
+ context.addIssue({ code: 'custom', path: [site, 'egress'], message: "egress: 'public' belongs to a cron job, keyed by job:<name>" })
540
+ }
541
+ if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
542
+ context.addIssue({ code: 'custom', path: [site, 'actions'], message: 'workload actions belong to a public procedure, keyed by its endpoint id' })
543
+ }
489
544
  }
490
- if (row.source.kind === 'export' && row.requirement?.kind === 'action' && row.requirement.access.form === 'app') {
491
- context.addIssue({ code: 'custom', path: [index, 'requirement'], message: 'an export row reads in one dimension, never app-wide' })
545
+ }).optional(),
546
+ directories: record(z.strictObject({ dimension: name, lists: z.boolean() })).optional(),
547
+ locale: z.enum(LOCALES).optional(),
548
+ displayName: z.string().refine((value) => displayNameProblem(value) === null, 'not a display name').optional(),
549
+ mail: z.strictObject({ invitation: mailLocales('invitation'), enrollment: mailLocales('enrollment'), reset: mailLocales('reset') }).partial()
550
+ .optional(),
551
+ members: z.strictObject({ manage: action, list: action }).optional(),
552
+ directory: z.literal('labels').optional(),
553
+ terminal: z.strictObject({ identify: z.string().refine((path) => terminalIdentifyProblem(path) === null, 'not an identification path') })
554
+ .optional(),
555
+ procedures: record(z.strictObject({
556
+ rate: z.strictObject({
557
+ perClient: bucket,
558
+ perCaller: bucket,
559
+ perEndpoint: bucket,
560
+ bytesPerHour: z.int().positive().max(PROCEDURE_LIMITS.maxBytesPerHour).nullable(),
561
+ }),
562
+ challenge: procedureChallenge.nullable(),
563
+ timeoutMs: z.int().positive().max(PROCEDURE_LIMITS.maxTimeoutMs),
564
+ query: shape.optional(),
565
+ changesStateOnGet: z.literal(true).optional(),
566
+ })).optional(),
567
+ tokens: record(z.strictObject({ claims: shape, maxDays: z.int().positive().max(TOKEN_MAX_DAYS) })).optional(),
568
+ }).superRefine((artifact, context) => {
569
+ for (const row of artifact.endpoints) {
570
+ // A row answering a file of an inline kind shows it, every other row that answers a file downloads it.
571
+ if (row.output?.type === 'file' && (row.response === 'inline-file') !== (artifact.fileKinds?.[row.output.kind]?.inline === true)) {
572
+ context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${row.id}' is inline-file exactly when its file kind is inline` })
492
573
  }
493
- }
494
- }),
495
- reservedPrefixes: names,
496
- declared: record(z.strictObject({
497
- sql: z.enum(['read', 'write']).nullable(),
498
- unscoped: record(z.enum(['read', 'write'])),
499
- connect: names,
500
- issues: nullableName,
501
- then: name.optional(),
502
- mailer: z.enum(JOB_MAILERS).optional(),
503
- actions: actions.nonempty().optional(),
504
- kicks: z.array(name).nonempty().optional(),
505
- binds: name.optional(),
506
- signs: z.array(name).nonempty().optional(),
507
- egress: z.union([z.array(z.string().refine((origin) => parseEgressEntry(origin).ok)).nonempty(), z.literal(PUBLIC_EGRESS)]).optional(),
508
- })).superRefine((declared, context) => {
509
- for (const [site, reach] of Object.entries(declared)) {
510
- if (reach.egress === PUBLIC_EGRESS && !site.startsWith(JOB_SITE_PREFIX)) {
511
- context.addIssue({ code: 'custom', path: [site, 'egress'], message: "egress: 'public' belongs to a cron job, keyed by job:<name>" })
574
+ // Only the application writes a file of an inline kind: an uploaded document could render as a page.
575
+ const inline = row.input === null ? undefined : fileKindsIn(row.input).find((kind) => artifact.fileKinds?.[kind]?.inline === true)
576
+ if (inline !== undefined) {
577
+ context.addIssue({
578
+ code: 'custom',
579
+ path: ['endpoints', artifact.endpoints.indexOf(row)],
580
+ message: `'${row.id}' takes a file of the inline kind '${inline}', which only the application writes`,
581
+ })
512
582
  }
513
- if (reach.actions !== undefined && !isOwnWorkloadName('public', site)) {
514
- context.addIssue({ code: 'custom', path: [site, 'actions'], message: 'workload actions belong to a public procedure, keyed by its endpoint id' })
583
+ if (row.kind === 'public' && row.source.kind !== 'challenge' && artifact.declared?.[row.id]?.actions === undefined) {
584
+ context.addIssue({ code: 'custom', path: ['declared', row.id], message: 'a public procedure declares its workload actions' })
515
585
  }
516
586
  }
517
- }).optional(),
518
- directories: record(z.strictObject({ dimension: name, lists: z.boolean() })).optional(),
519
- locale: z.enum(LOCALES).optional(),
520
- displayName: z.string().refine((value) => displayNameProblem(value) === null, 'not a display name').optional(),
521
- mail: z.strictObject({ invitation: mailLocales('invitation'), enrollment: mailLocales('enrollment'), reset: mailLocales('reset') }).partial()
522
- .optional(),
523
- members: z.strictObject({ manage: action, list: action }).optional(),
524
- directory: z.literal('labels').optional(),
525
- terminal: z.strictObject({ identify: z.string().refine((path) => terminalIdentifyProblem(path) === null, 'not an identification path') }).optional(),
526
- procedures: record(z.strictObject({
527
- rate: z.strictObject({
528
- perClient: bucket,
529
- perCaller: bucket,
530
- perEndpoint: bucket,
531
- bytesPerHour: z.int().positive().max(PROCEDURE_LIMITS.maxBytesPerHour).nullable(),
532
- }),
533
- challenge: procedureChallenge.nullable(),
534
- timeoutMs: z.int().positive().max(PROCEDURE_LIMITS.maxTimeoutMs),
535
- query: schemaShapeSchema.optional(),
536
- changesStateOnGet: z.literal(true).optional(),
537
- })).optional(),
538
- tokens: record(z.strictObject({ claims: schemaShapeSchema, maxDays: z.int().positive().max(TOKEN_MAX_DAYS) })).optional(),
539
- }).superRefine((artifact, context) => {
540
- for (const row of artifact.endpoints) {
541
- // A row answering a file of an inline kind shows it, every other row that answers a file downloads it.
542
- if (row.output?.type === 'file' && (row.response === 'inline-file') !== (artifact.fileKinds?.[row.output.kind]?.inline === true)) {
543
- context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${row.id}' is inline-file exactly when its file kind is inline` })
587
+ // Every ALTCHA challenge has exactly its own issuer, under its action, from the procedure's origins, with its own buckets.
588
+ const rows = new Map(artifact.endpoints.map((row) => [row.id, row]))
589
+ const issuers = artifact.endpoints.filter((row) => row.source.kind === 'challenge')
590
+ for (const [id, rules] of Object.entries(artifact.procedures ?? {})) {
591
+ if (rules.challenge?.provider !== 'altcha') continue
592
+ const issuer = rows.get(challengeRowId(id))
593
+ const procedure = rows.get(id)
594
+ if (
595
+ issuer === undefined || procedure === undefined || issuer.source.kind !== 'challenge' || issuer.source.name !== id
596
+ || issuer.path !== challengePath(rules.challenge.action) || issuer.crossOrigin !== procedure.crossOrigin
597
+ || artifact.procedures?.[issuer.id]?.challenge !== null
598
+ ) {
599
+ context.addIssue({ code: 'custom', path: ['procedures', id, 'challenge'], message: 'an ALTCHA challenge has its own issuer row' })
600
+ }
544
601
  }
545
- // Only the application writes a file of an inline kind: an uploaded document could render as a page.
546
- const inline = row.input === null ? undefined : fileKindsIn(row.input).find((kind) => artifact.fileKinds?.[kind]?.inline === true)
547
- if (inline !== undefined) {
548
- context.addIssue({
549
- code: 'custom',
550
- path: ['endpoints', artifact.endpoints.indexOf(row)],
551
- message: `'${row.id}' takes a file of the inline kind '${inline}', which only the application writes`,
552
- })
602
+ for (const issuer of issuers) {
603
+ if (issuer.id !== challengeRowId(issuer.source.name) || artifact.procedures?.[issuer.source.name]?.challenge?.provider !== 'altcha') {
604
+ context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${issuer.id}' issues the challenge of no ALTCHA procedure` })
605
+ }
553
606
  }
554
- if (row.kind === 'public' && row.source.kind !== 'challenge' && artifact.declared?.[row.id]?.actions === undefined) {
555
- context.addIssue({ code: 'custom', path: ['declared', row.id], message: 'a public procedure declares its workload actions' })
607
+ if (issuers.length > 0 && !artifact.reservedPrefixes.includes(CHALLENGE_PREFIX)) {
608
+ context.addIssue({ code: 'custom', path: ['reservedPrefixes'], message: `an issuer row reserves ${CHALLENGE_PREFIX}` })
556
609
  }
557
- }
558
- // Every ALTCHA challenge has exactly its own issuer, under its action, from the procedure's origins, with its own buckets.
559
- const rows = new Map(artifact.endpoints.map((row) => [row.id, row]))
560
- const issuers = artifact.endpoints.filter((row) => row.source.kind === 'challenge')
561
- for (const [id, rules] of Object.entries(artifact.procedures ?? {})) {
562
- if (rules.challenge?.provider !== 'altcha') continue
563
- const issuer = rows.get(challengeRowId(id))
564
- const procedure = rows.get(id)
565
- if (
566
- issuer === undefined || procedure === undefined || issuer.source.kind !== 'challenge' || issuer.source.name !== id
567
- || issuer.path !== challengePath(rules.challenge.action) || issuer.crossOrigin !== procedure.crossOrigin
568
- || artifact.procedures?.[issuer.id]?.challenge !== null
569
- ) {
570
- context.addIssue({ code: 'custom', path: ['procedures', id, 'challenge'], message: 'an ALTCHA challenge has its own issuer row' })
571
- }
572
- }
573
- for (const issuer of issuers) {
574
- if (issuer.id !== challengeRowId(issuer.source.name) || artifact.procedures?.[issuer.source.name]?.challenge?.provider !== 'altcha') {
575
- context.addIssue({ code: 'custom', path: ['endpoints'], message: `'${issuer.id}' issues the challenge of no ALTCHA procedure` })
610
+ if ((artifact.csp.workerSrc !== undefined) !== issuers.length > 0) {
611
+ context.addIssue({ code: 'custom', path: ['csp', 'workerSrc'], message: 'workerSrc admits the workers of an ALTCHA challenge, and only those' })
576
612
  }
577
- }
578
- if (issuers.length > 0 && !artifact.reservedPrefixes.includes(CHALLENGE_PREFIX)) {
579
- context.addIssue({ code: 'custom', path: ['reservedPrefixes'], message: `an issuer row reserves ${CHALLENGE_PREFIX}` })
580
- }
581
- if ((artifact.csp.workerSrc !== undefined) !== issuers.length > 0) {
582
- context.addIssue({ code: 'custom', path: ['csp', 'workerSrc'], message: 'workerSrc admits the workers of an ALTCHA challenge, and only those' })
583
- }
584
- })
613
+ })
614
+ }
615
+
616
+ export const contractArtifactSchema: z.ZodType<ContractArtifact> = artifactSchemaOf(schemaShapeSchema)
585
617
 
586
618
  function mailLocales(kind: MessageKind) {
587
619
  const template = z.strictObject({ subject: z.string(), text: z.string(), html: z.string().optional() }).superRefine((value, context) => {
@@ -594,3 +626,25 @@ function mailLocales(kind: MessageKind) {
594
626
  export function parseContractArtifact(value: unknown): ContractArtifact {
595
627
  return contractArtifactSchema.parse(value)
596
628
  }
629
+
630
+ /** Whether a stored artifact is in the shared encoding, which `parseEncodedArtifact` reads, rather than plain. */
631
+ export function isEncodedArtifact(value: unknown): boolean {
632
+ return typeof value === 'object' && value !== null && 'encoding' in value
633
+ }
634
+
635
+ const encodedArtifactSchema = z.strictObject({ encoding: z.literal(SHARED_SHAPES_ENCODING), shapes: z.array(z.unknown()), artifact: z.unknown() })
636
+
637
+ /**
638
+ * Parses an artifact in the shared encoding (`encodeArtifact`): each shared shape over the shapes written before it,
639
+ * then the artifact over all of them. The result is the canonical artifact, its shared shapes one object each; throws a
640
+ * `ZodError` naming every mismatch.
641
+ */
642
+ export function parseEncodedArtifact(value: unknown): ContractArtifact {
643
+ const encoded = encodedArtifactSchema.parse(value)
644
+ const shapes: SchemaShape[] = []
645
+ const shape = shapeSchemaOf(shapes)
646
+ for (const written of encoded.shapes) {
647
+ shapes.push(shape.parse(written))
648
+ }
649
+ return artifactSchemaOf(shape).parse(encoded.artifact)
650
+ }