@fabrika/check 0.9.0-dev.2 → 0.9.0-dev.21

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 (61) hide show
  1. package/package.json +7 -7
  2. package/src/ast.ts +69 -6
  3. package/src/check.ts +148 -44
  4. package/src/cli.ts +34 -8
  5. package/src/contract.ts +42 -6
  6. package/src/dialect.ts +29 -0
  7. package/src/finding.ts +14 -7
  8. package/src/index.ts +4 -12
  9. package/src/inputs.ts +4 -2
  10. package/src/layout.ts +41 -12
  11. package/src/limits.ts +13 -3
  12. package/src/migration-base.ts +85 -0
  13. package/src/reader/schema.ts +42 -512
  14. package/src/reader/surface.ts +43 -5
  15. package/src/reader/value.ts +18 -6
  16. package/src/resolution.ts +2 -2
  17. package/src/rules/cloudflare.ts +59 -0
  18. package/src/rules/compile.ts +32 -0
  19. package/src/rules/framework.ts +2 -2
  20. package/src/rules/literal.ts +3 -1
  21. package/src/rules/migration-history.ts +70 -0
  22. package/src/rules/migrations.ts +248 -9
  23. package/src/rules/modules.ts +9 -3
  24. package/src/rules/platform-migrations.ts +100 -0
  25. package/src/rules/runtime.ts +45 -14
  26. package/src/rules/structure.ts +38 -18
  27. package/src/rules/tests.ts +9 -60
  28. package/src/rules/types.ts +17 -16
  29. package/src/source-maps.ts +2 -0
  30. package/src/trust.ts +8 -4
  31. package/types/src/ast.d.ts +6 -0
  32. package/types/src/check.d.ts +3 -0
  33. package/types/src/contract.d.ts +1 -0
  34. package/types/src/dialect.d.ts +8 -0
  35. package/types/src/finding.d.ts +6 -5
  36. package/types/src/index.d.ts +4 -3
  37. package/types/src/layout.d.ts +25 -10
  38. package/types/src/limits.d.ts +12 -2
  39. package/types/src/migration-base.d.ts +9 -0
  40. package/types/src/reader/schema.d.ts +5 -2
  41. package/types/src/reader/value.d.ts +2 -2
  42. package/types/src/rules/cloudflare.d.ts +9 -0
  43. package/types/src/rules/compile.d.ts +7 -0
  44. package/types/src/rules/framework.d.ts +1 -1
  45. package/types/src/rules/migration-history.d.ts +12 -0
  46. package/types/src/rules/migrations.d.ts +28 -0
  47. package/types/src/rules/platform-migrations.d.ts +15 -0
  48. package/types/src/rules/runtime.d.ts +7 -2
  49. package/types/src/rules/structure.d.ts +11 -4
  50. package/types/src/rules/tests.d.ts +6 -14
  51. package/types/src/rules/types.d.ts +2 -0
  52. package/src/endpoint-fixtures.ts +0 -221
  53. package/src/rules/crontab.ts +0 -147
  54. package/src/rules/isolation.ts +0 -79
  55. package/src/scaffold-sample.ts +0 -111
  56. package/src/scaffold.ts +0 -650
  57. package/types/src/endpoint-fixtures.d.ts +0 -36
  58. package/types/src/rules/crontab.d.ts +0 -15
  59. package/types/src/rules/isolation.d.ts +0 -18
  60. package/types/src/scaffold-sample.d.ts +0 -8
  61. package/types/src/scaffold.d.ts +0 -28
@@ -18,6 +18,7 @@ import {
18
18
  type ExportAccessDeclaration,
19
19
  type FileKind,
20
20
  type ImportDeclaration,
21
+ isPath,
21
22
  type KitImportDeclaration,
22
23
  kitImportsSection,
23
24
  kitUnknownOptions,
@@ -31,11 +32,13 @@ import {
31
32
  type SpaAccessDeclaration,
32
33
  type Surface,
33
34
  SURFACE_SECTIONS,
35
+ type TerminalDeclaration,
34
36
  type TokenPurpose,
35
37
  type TokenPurposes,
36
38
  unknownOptions,
37
39
  type Vocabulary,
38
40
  } from '@fabrika/app/contract'
41
+ import { DataObject } from '@fabrika/app/schema'
39
42
  import {
40
43
  type CspSource,
41
44
  isLocale,
@@ -79,7 +82,7 @@ const CONTRACT_ALLOWED = 'export const contract = app.contract((c) => ({ … }))
79
82
  /** Which builders a surface is written with: `defineContract`'s `c`, or the staged kit's (`app.*` and its `c`). */
80
83
  type Form = 'surface' | 'kit'
81
84
  const ACCESS_ALLOWED =
82
- '{ member: true }, { action, over }, { action, in, from }, { action, on, from }, { action, creates }, { action, app: true }, { capabilities: { <name>: … } } or { public: true }'
85
+ "{ member: true }, { action, over }, { action, in, from }, { action, on, from }, { action, creates }, { action, app: true }, { anyOf: ['<action>', …], app: true }, { capabilities: { <name>: … } } or { public: true }"
83
86
  const CAPABILITY_ALLOWED = '{ action, over }, { action, in, from } or { action, on, from }'
84
87
 
85
88
  type Entries = ReadonlyMap<string, LiteralValue>
@@ -180,7 +183,7 @@ class SurfaceReader {
180
183
  const [definition] = args(value, 'attachment', 1, 1)
181
184
  const options = builderOptions(definition, value, 'attachment')
182
185
  const row = this.#schema(options.get('row'), value, 'row')
183
- if (!(row instanceof z.ZodObject)) {
186
+ if (!(row instanceof z.ZodObject || row instanceof DataObject)) {
184
187
  throw new Refused(options.get('row')?.at ?? value.at, 'the row is not an object schema', 'row: z.strictObject({ … })')
185
188
  }
186
189
  const maxRows = optionalNumber(options.get('maxRows'), 'maxRows')
@@ -213,13 +216,17 @@ class SurfaceReader {
213
216
  'mail',
214
217
  'members',
215
218
  'directory',
219
+ 'terminal',
220
+ 'relations',
216
221
  ])
222
+ const relations = fields.get('relations')
217
223
  const locale = fields.get('locale')
218
224
  const displayName = fields.get('displayName')
219
225
  const mail = fields.get('mail')
220
226
  const members = fields.get('members')
221
227
  const memberFields = members === undefined ? undefined : strictFields(members, 'the vocabulary members', ['manage', 'list'], [])
222
228
  const directory = fields.get('directory')
229
+ const terminal = fields.get('terminal')
223
230
  return {
224
231
  app: text(fields.get('app'), value, 'app'),
225
232
  ...(locale === undefined ? {} : { locale: localeOf(locale, value) }),
@@ -229,9 +236,17 @@ class SurfaceReader {
229
236
  ? {}
230
237
  : { members: { manage: text(memberFields.get('manage'), value, 'manage'), list: text(memberFields.get('list'), value, 'list') } }),
231
238
  ...(directory === undefined ? {} : { directory: directoryOf(directory, value) }),
239
+ ...(terminal === undefined ? {} : { terminal: terminalOf(terminal) }),
232
240
  dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
233
241
  actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
234
242
  roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
243
+ ...(relations === undefined
244
+ ? {}
245
+ : {
246
+ relations: this.#each(entries(relations, value, 'relations'), (name, relation) => ({
247
+ dimension: text(strictFields(relation, `relation '${name}'`, ['dimension'], []).get('dimension'), relation, 'dimension'),
248
+ })),
249
+ }),
235
250
  }
236
251
  }
237
252
 
@@ -278,16 +293,18 @@ class SurfaceReader {
278
293
  }
279
294
 
280
295
  #role(name: string, value: LiteralValue): RoleDef<string, string, string> {
281
- const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external'])
296
+ const fields = strictFields(value, `role '${name}'`, ['grants'], ['member', 'external', 'via'])
282
297
  const member = fields.get('member')
283
298
  const memberFields = member === undefined ? undefined : strictFields(member, `role '${name}' member`, ['scope', 'assignableBy'], [])
284
299
  const external = fields.get('external')
300
+ const via = fields.get('via')
285
301
  return {
286
302
  grants: texts(fields.get('grants'), value, 'grants'),
287
303
  member: memberFields === undefined
288
304
  ? undefined
289
305
  : { scope: text(memberFields.get('scope'), value, 'scope'), assignableBy: texts(memberFields.get('assignableBy'), value, 'assignableBy') },
290
306
  ...(external === undefined ? {} : { external: externalOf(external) }),
307
+ ...(via === undefined ? {} : { via: this.#each(entries(via, value, 'via'), (_, actions) => texts(actions, value, 'via')) }),
291
308
  }
292
309
  }
293
310
 
@@ -592,7 +609,7 @@ class SurfaceReader {
592
609
  // ── Sections ────────────────────────────────────────────────────────────────────────────────
593
610
 
594
611
  /**
595
- * `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes` and `scan` is unknown, as the kit
612
+ * `c.files({ … })`: a kind of stored file. Every option but `types`, `maxBytes`, `scan` and `inline` is unknown, as the kit
596
613
  * records it, so `buildArtifact` refuses a file collection's `owner` in its own words.
597
614
  */
598
615
  #files(value: LiteralValue, form: Form): FileKind {
@@ -601,11 +618,13 @@ class SurfaceReader {
601
618
  const [kind] = args(at, 'c.files', 1, 1)
602
619
  const options = builderOptions(kind, at, 'c.files')
603
620
  const scan = options.get('scan')
621
+ const inline = options.get('inline')
604
622
  return {
605
623
  kind: 'file-kind',
606
624
  types: texts(options.get('types'), at, 'types'),
607
625
  maxBytes: numeric(options.get('maxBytes'), at, 'maxBytes'),
608
626
  scan: scan === undefined ? undefined : boolean(scan, 'scan'),
627
+ inline: inline === undefined ? undefined : boolean(inline, 'inline'),
609
628
  unknownOptions: optionKeys(options, 'fileKind'),
610
629
  }
611
630
  }
@@ -794,7 +813,7 @@ function plain(value: LiteralValue | undefined): unknown {
794
813
  }
795
814
 
796
815
  const DECLARED_ALLOWED =
797
- "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>']"
816
+ "sql: 'read' | 'write', unscoped: { <table>: 'read' | 'write' }, connect: ['<import>'], issues: '<link mount>', mailer: 'installation' | 'own', kicks: ['<cron job>'], binds: '<webhook>', signs: ['<token purpose>'], egress: ['https://<host>' | 'https://*.<domain>'] | 'public' (a cron job)"
798
817
 
799
818
  /** A builder of the kit read as the `defineContract` builder of the same name, which builds the same declaration. */
800
819
  const asSurface = (builder: BuilderValue): LiteralValue => ({
@@ -936,6 +955,16 @@ function directoryOf(value: LiteralValue, owner: Owner): 'labels' {
936
955
  return directory
937
956
  }
938
957
 
958
+ /** The vocabulary's `terminal: { identify: '/path' }`; `buildArtifact` checks the path itself. */
959
+ function terminalOf(value: LiteralValue): TerminalDeclaration {
960
+ const identify = strictFields(value, 'the vocabulary terminal', ['identify'], []).get('identify')
961
+ const path = text(identify, value, 'terminal.identify')
962
+ if (!isPath(path)) {
963
+ throw new Refused(identify?.at ?? value.at, `terminal.identify is '${path}'`, "terminal: { identify: '/identify' }")
964
+ }
965
+ return { identify: path }
966
+ }
967
+
939
968
  function optionalText(value: LiteralValue | undefined, field: string): string | undefined {
940
969
  return value === undefined ? undefined : text(value, value, field)
941
970
  }
@@ -1028,6 +1057,12 @@ function isApp(fields: Entries): boolean {
1028
1057
  return hasKeys(fields, ['action', 'app']) && app?.kind === 'boolean' && app.value
1029
1058
  }
1030
1059
 
1060
+ /** `{ anyOf: [...], app: true }`: `app` is the literal `true`; `buildArtifact` checks the list. */
1061
+ function isAnyOf(fields: Entries): boolean {
1062
+ const app = fields.get('app')
1063
+ return hasKeys(fields, ['anyOf', 'app']) && app?.kind === 'boolean' && app.value
1064
+ }
1065
+
1031
1066
  /** `{ public: true }`: `public` is the literal `true`. */
1032
1067
  function isPublic(fields: Entries): boolean {
1033
1068
  const open = fields.get('public')
@@ -1056,6 +1091,9 @@ function accessDeclaration(value: LiteralValue | undefined, at: BuilderValue): A
1056
1091
  if (isApp(fields)) {
1057
1092
  return { action: field('action'), app: true }
1058
1093
  }
1094
+ if (isAnyOf(fields)) {
1095
+ return { anyOf: texts(fields.get('anyOf'), value ?? at, 'access.anyOf'), app: true }
1096
+ }
1059
1097
  if (isPublic(fields)) {
1060
1098
  return { public: true }
1061
1099
  }
@@ -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 real zod schemas, `c.*` calls stay unapplied for `surface.ts`.
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: z.ZodType
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. */
@@ -83,7 +83,19 @@ type Role = { readonly callback: Kit } | { readonly procedures: Kit } | null
83
83
  const callbackKit = (kind: BuilderKind): Kit => (kind === 'shell' ? 'shell' : kind === 'endpoints' ? 'endpoints' : 'surface')
84
84
 
85
85
  /** The fields `defineVocabulary` copies from its argument, in its order. */
86
- const VOCABULARY_SECTIONS = ['app', 'dimensions', 'actions', 'roles', 'locale', 'displayName', 'mail'] as const
86
+ const VOCABULARY_SECTIONS = [
87
+ 'app',
88
+ 'dimensions',
89
+ 'actions',
90
+ 'roles',
91
+ 'relations',
92
+ 'locale',
93
+ 'displayName',
94
+ 'mail',
95
+ 'members',
96
+ 'directory',
97
+ 'terminal',
98
+ ] as const
87
99
 
88
100
  const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
89
101
 
@@ -541,7 +553,7 @@ export class ValueReader {
541
553
  return args === null ? null : { kind: 'contract', args, at: located }
542
554
  }
543
555
 
544
- /** `z.<factory>(…)` or `z.iso.<format>(…)`, then `.<method>(…)` links, each applied to a real zod schema. */
556
+ /** `z.<factory>(…)` or `z.iso.<format>(…)`, then `.<method>(…)` links, each checked against zod as it is applied. */
545
557
  #zodChain(located: Located, links: readonly Link[], scope: Scope): LiteralValue | null {
546
558
  const isIso = links[0]?.kind === 'member' && links[0].name === 'iso'
547
559
  const steps = this.#steps(located, links, isIso ? 1 : 0)
@@ -583,7 +595,7 @@ export class ValueReader {
583
595
  return null
584
596
  }
585
597
  }
586
- let schema: z.ZodType | undefined = receiver?.schema
598
+ let schema: ReadSchema | undefined = receiver?.schema
587
599
  let size: SchemaSize = receiver === null ? { nodes: 0, depth: 0 } : { nodes: receiver.nodes, depth: receiver.depth }
588
600
  for (const step of steps) {
589
601
  const at = { module: located.module, node: step.call }
package/src/resolution.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { isBuiltin } from 'node:module'
2
2
  import { z } from 'zod/v4'
3
3
  import { parseJsonc } from './jsonc'
4
- import { isIgnoredSegment, isRelativeSpecifier, joinRelative, resolveRelative } from './layout'
4
+ import { isRelativeSpecifier, isSkippedPath, joinRelative, resolveRelative } from './layout'
5
5
 
6
6
  /** Pattern → targets. A target is a bare specifier, an absolute path, or `./<path from the root>` (`../…` above it). */
7
7
  type MappingTable = ReadonlyMap<string, readonly string[]>
@@ -139,7 +139,7 @@ export const readImportMappings = (files: ReadonlyMap<string, string>): ImportMa
139
139
  },
140
140
  mayExist: (target) => {
141
141
  const path = target.startsWith('/') ? undefined : joinRelative('package.json', target)
142
- if (path === undefined || path.split('/').some(isIgnoredSegment)) return true
142
+ if (path === undefined || isSkippedPath(path)) return true
143
143
  return resolveRelative((candidate) => files.has(candidate), 'package.json', `./${path}`).kind !== 'missing'
144
144
  },
145
145
  }
@@ -0,0 +1,59 @@
1
+ import { CLOUDFLARE_MAX_JOB_SEGMENT_MS } from '@fabrika/app/contract'
2
+ import { type ContractArtifact, type DeclaredEgress, PUBLIC_EGRESS } from '@fabrika/auth-core'
3
+ import type { Finding } from '../finding'
4
+ import { CONTRACT_FILE } from '../layout'
5
+
6
+ const at = (rule: 'cloudflare-scan' | 'cloudflare-job-segment', message: string, allowed: string): Finding => ({
7
+ file: CONTRACT_FILE,
8
+ line: 1,
9
+ column: 1,
10
+ severity: 'refusal',
11
+ rule,
12
+ message,
13
+ allowed,
14
+ })
15
+
16
+ /** The outside calls a site declares, as the hint names them: its `egress` origins and its `connect` imports. */
17
+ const outsideCalls = (reach: { readonly egress?: DeclaredEgress; readonly connect: readonly string[] }): string[] => [
18
+ ...(reach.egress === PUBLIC_EGRESS ? [`egress '${PUBLIC_EGRESS}'`] : (reach.egress ?? []).map((origin) => `egress ${origin}`)),
19
+ ...reach.connect.map((name) => `connect ${name}`),
20
+ ]
21
+
22
+ /**
23
+ * What an application on Cloudflare cannot declare (ADR-0065): a file kind that scans, because no scanner runs there; a
24
+ * job longer than one segment, because the object runs it inside an alarm or a request. And a hint for a mutation that
25
+ * declares an outside call: the object runs one transaction at a time, and the mutation holds it while the call waits
26
+ * (backlog 216 item 7).
27
+ */
28
+ export const checkCloudflareContract = (artifact: ContractArtifact): Finding[] => [
29
+ ...Object.entries(artifact.fileKinds ?? {}).filter(([, kind]) => kind.scan === true).map(([name]) =>
30
+ at(
31
+ 'cloudflare-scan',
32
+ `the file kind ${name} scans its files (scan: true), which an application on Cloudflare cannot: no scanner runs there`,
33
+ `c.files({ types, maxBytes }) without scan for ${name}, and no public procedure that takes its files`,
34
+ )
35
+ ),
36
+ ...Object.entries(artifact.jobs).filter(([, job]) => job.timeoutMs > CLOUDFLARE_MAX_JOB_SEGMENT_MS).map(([name, job]) =>
37
+ at(
38
+ 'cloudflare-job-segment',
39
+ `the job ${name} runs up to ${job.timeoutMs} ms, and a job segment on Cloudflare runs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} ms`,
40
+ `limits.timeoutMs at most ${CLOUDFLARE_MAX_JOB_SEGMENT_MS} for ${name}: claim a bounded batch per run, and the next run takes the rest; a Workflow for one longer run is planned (backlog 230)`,
41
+ )
42
+ ),
43
+ ...artifact.endpoints.filter((endpoint) => endpoint.kind === 'mutation').flatMap((endpoint): Finding[] => {
44
+ const reach = artifact.declared?.[endpoint.id]
45
+ const calls = reach === undefined ? [] : outsideCalls(reach)
46
+ if (calls.length === 0) return []
47
+ return [{
48
+ file: CONTRACT_FILE,
49
+ line: 1,
50
+ column: 1,
51
+ severity: 'hint',
52
+ rule: 'cloudflare-held-call',
53
+ message: `${endpoint.id} is a mutation that declares ${
54
+ calls.join(', ')
55
+ }: on Cloudflare it waits for that call inside the object's transaction, which holds the whole environment`,
56
+ allowed: "record a row and ctx.kick('<job>'); the job declares the call and makes it outside ctx.transaction",
57
+ }]
58
+ }),
59
+ ]
@@ -0,0 +1,32 @@
1
+ import { ContractError } from '@fabrika/app/contract'
2
+ import { ContractSourceError, readContractSource, readTablesDefinition } from '../contract'
3
+ import type { Finding } from '../finding'
4
+ import { CONTRACT_FILE } from '../layout'
5
+
6
+ /**
7
+ * What the reader refuses of `src/db/tables.ts`, and a contract that does not compile against its policies: Control
8
+ * reads the commit with the same calls and refuses the deploy. `readable` is false while the literal, trust or
9
+ * contract rules report the sources, so a refusal is not reported twice.
10
+ */
11
+ export const checkContractCompiles = (files: ReadonlyMap<string, string>, readable: boolean): Finding[] => {
12
+ if (!readable) return []
13
+ try {
14
+ const tables = readTablesDefinition(files)
15
+ if (files.has(CONTRACT_FILE) && tables !== null) readContractSource(files, tables)
16
+ return []
17
+ } catch (error) {
18
+ if (error instanceof ContractSourceError) return [...error.findings]
19
+ if (error instanceof ContractError) {
20
+ return error.problems.map((problem): Finding => ({
21
+ file: CONTRACT_FILE,
22
+ line: 1,
23
+ column: 1,
24
+ severity: 'refusal',
25
+ rule: 'contract',
26
+ message: problem,
27
+ allowed: 'a contract that compiles against src/db/tables.ts',
28
+ }))
29
+ }
30
+ throw error
31
+ }
32
+ }
@@ -79,7 +79,7 @@ export const trustedBindings = (file: string, program: AstNode, mappings: Import
79
79
  }
80
80
 
81
81
  /**
82
- * The trusted binding a member chain starts from (`Database.postgres`, `db['Database'].postgres` → `Database`, `db`),
82
+ * The trusted binding a member chain starts from (`Database.fromEngine`, `db['Database'].fromEngine` → `Database`, `db`),
83
83
  * when the name at `ancestors` denotes that declaration and no local that shadows it.
84
84
  */
85
85
  const trustedRoot = (
@@ -135,7 +135,7 @@ const WRITERS = new Set([
135
135
 
136
136
  /**
137
137
  * A write to a member of a value from `@fabrika/*` or `zod`: an assignment, `delete`, `++`, or a writer call on it. A
138
- * replaced `Database.postgres` receives the database URL; a patched schema changes what the contract admits. A write
138
+ * replaced `openPostgres` receives the database URL; a patched schema changes what the contract admits. A write
139
139
  * through a prototype is `prototype-assignment`'s. A local that shadows such a name is not one.
140
140
  */
141
141
  export const checkFrameworkWrite = (node: AstNode, ancestors: readonly AstNode[], bindings: TrustedBindings, report: Report): void => {
@@ -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'
@@ -0,0 +1,70 @@
1
+ // A migration that a shared branch already holds, edited, renamed or deleted in the tree being checked. Every runner
2
+ // keeps the SHA-256 of each applied file and refuses a deploy whose file changed after it ran (ADR-0017), and Control
3
+ // refuses it at the run's snapshot; neither sees history, so the checker is where the edit can be named before the push.
4
+
5
+ import type { Finding } from '../finding'
6
+ import { MIGRATIONS_DIR } from '../layout'
7
+
8
+ /** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
9
+ export interface MigrationBase {
10
+ /** How the commit is named to the author, such as `origin/main`. */
11
+ readonly ref: string
12
+ readonly files: ReadonlyMap<string, string>
13
+ }
14
+
15
+ const ALLOWED = 'the file as it is there, and the change as a new migration (bunx fabrika db new <slug>)'
16
+
17
+ const isMigration = (path: string): boolean => {
18
+ const name = path.slice(MIGRATIONS_DIR.length)
19
+ return path.startsWith(MIGRATIONS_DIR) && name.endsWith('.sql') && !name.includes('/')
20
+ }
21
+
22
+ /** Lines without a trailing carriage return: a Windows checkout's line ends are not an edit of the committed file. */
23
+ const linesOf = (sql: string): string[] => sql.split('\n').map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line))
24
+
25
+ /** The first line where `current` leaves `base`, or its last line when it only lost lines at the end. */
26
+ const firstChangedLine = (base: readonly string[], current: readonly string[]): number | null => {
27
+ const length = Math.max(base.length, current.length)
28
+ for (let index = 0; index < length; index++) {
29
+ if (base[index] !== current[index]) return Math.min(index, current.length - 1) + 1
30
+ }
31
+ return null
32
+ }
33
+
34
+ /**
35
+ * Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
36
+ * removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
37
+ */
38
+ export const checkMigrationHistory = (files: ReadonlyMap<string, string>, base: MigrationBase): Finding[] => {
39
+ const findings: Finding[] = []
40
+ for (const [path, committed] of base.files) {
41
+ if (!isMigration(path)) continue
42
+ const name = path.slice(MIGRATIONS_DIR.length)
43
+ const current = files.get(path)
44
+ if (current === undefined) {
45
+ findings.push({
46
+ file: path,
47
+ line: 1,
48
+ column: 1,
49
+ severity: 'refusal',
50
+ rule: 'migration-edited',
51
+ message:
52
+ `'${name}' is in ${base.ref} and was deleted or renamed: an environment that applied it keeps its changes, and a renamed file runs again there`,
53
+ allowed: ALLOWED,
54
+ })
55
+ continue
56
+ }
57
+ const line = firstChangedLine(linesOf(committed), linesOf(current))
58
+ if (line === null) continue
59
+ findings.push({
60
+ file: path,
61
+ line,
62
+ column: 1,
63
+ severity: 'refusal',
64
+ rule: 'migration-edited',
65
+ message: `'${name}' differs from ${base.ref}: a deploy refuses a migration that changed after it was applied, even in a comment`,
66
+ allowed: ALLOWED,
67
+ })
68
+ }
69
+ return findings
70
+ }