@fabrika/check 0.9.0-dev.4 → 0.9.0-dev.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.9.0-dev.4",
3
+ "version": "0.9.0-dev.5",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -47,11 +47,11 @@
47
47
  },
48
48
  "dependencies": {
49
49
  "@babel/parser": "8.0.7",
50
- "@fabrika/app": "0.9.0-dev.4",
51
- "@fabrika/auth-core": "0.9.0-dev.4",
52
- "@fabrika/db": "0.9.0-dev.4",
53
- "@fabrika/operations-contract": "0.9.0-dev.4",
54
- "@fabrika/platform-node": "0.9.0-dev.4",
50
+ "@fabrika/app": "0.9.0-dev.5",
51
+ "@fabrika/auth-core": "0.9.0-dev.5",
52
+ "@fabrika/db": "0.9.0-dev.5",
53
+ "@fabrika/operations-contract": "0.9.0-dev.5",
54
+ "@fabrika/platform-node": "0.9.0-dev.5",
55
55
  "zod": "^3.25.76"
56
56
  }
57
57
  }
package/src/check.ts CHANGED
@@ -5,6 +5,7 @@ import { readdir, readFile } from 'node:fs/promises'
5
5
  import { join } from 'node:path'
6
6
  import { type AstNode, type ParsedModule, parseModule, walk } from './ast'
7
7
  import { contractModules, readContractModule } from './contract'
8
+ import { applicationDialect } from './dialect'
8
9
  import { compareFindings, type Finding, reporter } from './finding'
9
10
  import { ModuleGraph } from './graph'
10
11
  import {
@@ -24,6 +25,7 @@ import { ReaderProblems } from './reader/problems'
24
25
  import { readTablesValue } from './reader/tables'
25
26
  import { type ModuleReference, moduleReferences } from './references'
26
27
  import { type ImportMappings, readImportMappings } from './resolution'
28
+ import { checkCloudflareContract } from './rules/cloudflare'
27
29
  import { checkContractRead } from './rules/contract'
28
30
  import { checkCrontab, contractJobs } from './rules/crontab'
29
31
  import { checkFrameworkWrite, trustedBindings } from './rules/framework'
@@ -31,7 +33,15 @@ import { checkClientIdentity } from './rules/identity'
31
33
  import { checkGeneratedTests } from './rules/isolation'
32
34
  import { checkJsonStrings } from './rules/json'
33
35
  import { checkLiteralGraph } from './rules/literal'
34
- import { checkConflictIndexes, checkFileColumnMigrations, checkMigrationNames, type ConflictInsert, type FileColumn } from './rules/migrations'
36
+ import {
37
+ checkConflictIndexes,
38
+ checkCurrentTimestampDefaults,
39
+ checkFileColumnMigrations,
40
+ checkMigrationNames,
41
+ checkSqliteFrameworkNames,
42
+ type ConflictInsert,
43
+ type FileColumn,
44
+ } from './rules/migrations'
35
45
  import { checkModuleReferences } from './rules/modules'
36
46
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
37
47
  import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
@@ -157,15 +167,18 @@ interface CompiledReach {
157
167
  readonly origins: readonly string[]
158
168
  }
159
169
 
160
- /** The contract's procedures and origins, or `null` when it does not compile, which its own rule reports. */
161
- const compiledReach = (contract: AnyContract, tables: Tables<unknown, unknown> | null): CompiledReach | null => {
162
- let artifact: ContractArtifact
170
+ /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
171
+ const compiledArtifact = (contract: AnyContract, tables: Tables<unknown, unknown> | null): ContractArtifact | null => {
163
172
  try {
164
- artifact = compileContract(contract, tables ?? {})
173
+ return compileContract(contract, tables ?? {})
165
174
  } catch (error) {
166
175
  if (error instanceof ContractError) return null
167
176
  throw error
168
177
  }
178
+ }
179
+
180
+ /** The contract's procedures and origins. */
181
+ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
169
182
  const procedures = artifact.endpoints.filter((row) =>
170
183
  (row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
171
184
  )
@@ -254,7 +267,13 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
254
267
  findings.push(...checkMigrationNames(checkedPaths))
255
268
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
256
269
  const declaredTables = tables !== undefined && literal.length === 0 ? readTablesValue(graph, tables, new ReaderProblems()) : null
257
- findings.push(...contractDependentFindings(dependent, read?.ok === true ? compiledReach(read.contract, declaredTables) : null))
270
+ const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
271
+ findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
272
+ if (applicationDialect(tree.files) === 'sqlite') {
273
+ if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
274
+ findings.push(...checkCurrentTimestampDefaults(tree.files))
275
+ findings.push(...checkSqliteFrameworkNames(tree.files))
276
+ }
258
277
  if (declaredTables !== null) {
259
278
  const policies = tablePolicies(declaredTables)
260
279
  findings.push(...checkFileColumnMigrations(tree.files, fileColumns(policies)))
package/src/dialect.ts ADDED
@@ -0,0 +1,29 @@
1
+ import { child, identifierName, parseModule } from './ast'
2
+ import { ModuleGraph, unwrapValue } from './graph'
3
+ import { CONFIG_FILE } from './layout'
4
+
5
+ /** The database an application's data layer runs on: SQLite in its Durable Object on Cloudflare (ADR-0065), else Postgres. */
6
+ export type ApplicationDialect = 'postgres' | 'sqlite'
7
+
8
+ const CLOUDFLARE_PROVIDER = '@fabrika/provider-cloudflare'
9
+
10
+ /**
11
+ * Read statically from `fabrika.config.ts`: SQLite when its default export is a call of the `defineApp` that
12
+ * `@fabrika/provider-cloudflare` exports, the config every Cloudflare application writes. Postgres otherwise,
13
+ * including without a config or when the call's origin is not static.
14
+ */
15
+ export const applicationDialect = (files: ReadonlyMap<string, string>): ApplicationDialect => {
16
+ const text = files.get(CONFIG_FILE)
17
+ if (text === undefined) return 'postgres'
18
+ const parsed = parseModule(CONFIG_FILE, text)
19
+ if (!parsed.ok) return 'postgres'
20
+ const graph = new ModuleGraph(new Map([[CONFIG_FILE, parsed.module]]))
21
+ const exported = graph.exported(parsed.module, 'default')
22
+ if (exported.kind !== 'default') return 'postgres'
23
+ const call = unwrapValue(exported.expression)
24
+ if (call.type !== 'CallExpression') return 'postgres'
25
+ const callee = identifierName(child(call, 'callee'))
26
+ if (callee === undefined) return 'postgres'
27
+ const binding = graph.binding(parsed.module, callee)
28
+ return binding.kind === 'package' && binding.specifier === CLOUDFLARE_PROVIDER && binding.imported === 'defineApp' ? 'sqlite' : 'postgres'
29
+ }
@@ -4,10 +4,19 @@
4
4
  // that name a member the handler looks up (`deals.assign`'s `ownerId`), which the kit fills with a real member;
5
5
  // `invitations` and `links` the fields that name an invitation the handler cancels or a share link it revokes, which the
6
6
  // kit fills with one it holds; `rows` the fields that name a row lying in the endpoint's object (a note's comment), by
7
- // table, which the kit seeds in each scope's object. Read from source, never executed, within the reader's budget:
8
- // `export const fixtures = { '<endpoint id>': { … } }`, `export const seeds = { '<endpoint id>': { <column>: <value> } }`,
9
- // `export const members = { '<endpoint id>': ['<field>'] }` (`invitations`, `links` alike) and
10
- // `export const rows = { '<endpoint id>': { <field>: '<table>' } }`, plain literals only.
7
+ // table, which the kit seeds in each scope's object; `appRows` the rows of application tables an endpoint's own case
8
+ // reads (the guide a link holder downloads), by table, with their columns, which the kit seeds before each leak or own
9
+ // case asks and removes once it is over; `files` the file of the repository each generated case sends in a file field
10
+ // (a package a handler inspects), by input field, relative to the application's root; `refusals` the error types of the
11
+ // 400s an endpoint's handler answers its own object with when no fixture can meet its domain rule, which the kit then
12
+ // counts as the handler's answer; `pins` known values of text columns of the row an endpoint addresses (a skill's slug a
13
+ // package must name), the own scope's, which the kit writes there instead of a marker.
14
+ // Read from source, never executed, within the reader's budget: `export const fixtures = { '<endpoint id>': { … } }`,
15
+ // `export const seeds = { '<endpoint id>': { <column>: <value> } }`, `export const members = { '<endpoint id>':
16
+ // ['<field>'] }` (`invitations`, `links` alike), `export const rows = { '<endpoint id>': { <field>: '<table>' } }` and
17
+ // `export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }`, `export const files = { '<endpoint
18
+ // id>': { <field>: '<path>' } }`, `export const refusals = { '<endpoint id>': ['<error type>'] }` and `export const pins
19
+ // = { '<endpoint id>': { <column>: '<value>' } }`, plain literals only.
11
20
  // Browser-safe.
12
21
 
13
22
  import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
@@ -22,14 +31,18 @@ export const MEMBERS_EXPORT = 'members'
22
31
  export const INVITATIONS_EXPORT = 'invitations'
23
32
  export const LINKS_EXPORT = 'links'
24
33
  export const ROWS_EXPORT = 'rows'
34
+ export const APP_ROWS_EXPORT = 'appRows'
35
+ export const FILES_EXPORT = 'files'
36
+ export const REFUSALS_EXPORT = 'refusals'
37
+ export const PINS_EXPORT = 'pins'
25
38
 
26
- /** The exports that list, by endpoint id, the input fields the kit fills with something it holds. */
27
- const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT] as const
39
+ /** The exports that list strings by endpoint id: the input fields the kit fills with something it holds, and the refusals. */
40
+ const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT, REFUSALS_EXPORT] as const
28
41
  type FieldExport = (typeof FIELD_EXPORTS)[number]
29
42
  const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
30
43
 
31
44
  const ALLOWED =
32
- "export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] } and export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
45
+ "export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] }, export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }, export const appRows = { 'portal.guide': { guides: { active: true } } }, export const files = { 'api.skills.publish': { package: 'src/__tests__/fixtures/skill.zip' } }, export const refusals = { 'api.skills.publish': ['skill_frontmatter'] } and export const pins = { 'api.skills.publish': { slug: 'sample-skill' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
33
46
 
34
47
  type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
35
48
 
@@ -46,9 +59,35 @@ export interface EndpointFixtures {
46
59
  readonly links: Readonly<Record<string, readonly string[]>>
47
60
  /** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
48
61
  readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
62
+ /** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
63
+ readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>
64
+ /** The file each case sends in a file field, a path relative to the application's root, by input field, by endpoint id. */
65
+ readonly files: Readonly<Record<string, Readonly<Record<string, string>>>>
66
+ /** The error types of the 400s an endpoint's handler may answer its own object with, by endpoint id. */
67
+ readonly refusals: Readonly<Record<string, readonly string[]>>
68
+ /** The own scope's value of each pinned text column of the row the endpoint addresses, by endpoint id. */
69
+ readonly pins: Readonly<Record<string, Readonly<Record<string, string>>>>
49
70
  }
50
71
 
51
- export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
72
+ export const NO_FIXTURES: EndpointFixtures = {
73
+ inputs: {},
74
+ seeds: {},
75
+ members: {},
76
+ invitations: {},
77
+ links: {},
78
+ rows: {},
79
+ appRows: {},
80
+ files: {},
81
+ refusals: {},
82
+ pins: {},
83
+ }
84
+
85
+ /**
86
+ * Whether `path` may name a file fixture: relative to the application's root, `/`-separated, and each segment of
87
+ * letters, digits, `_`, `-` and `.` that starts with neither `.` nor `-`, so it never leaves the root, names no dotfile and
88
+ * reads the same as a URL path.
89
+ */
90
+ export const isFixtureFilePath = (path: string): boolean => /^[A-Za-z0-9_][A-Za-z0-9._-]*(\/[A-Za-z0-9_][A-Za-z0-9._-]*)*$/.test(path)
52
91
 
53
92
  const finding = (at: AstNode | undefined, message: string): Finding => {
54
93
  const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
@@ -118,14 +157,15 @@ function byId(
118
157
  const entries: Record<string, Readonly<Record<string, Sample>>> = {}
119
158
  for (const [id, entry] of Object.entries(all)) {
120
159
  if (!isSampleObject(entry)) {
121
- return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${name === SEEDS_EXPORT ? 'columns' : 'input fields'}`)] }
160
+ const of = name === SEEDS_EXPORT ? 'columns' : name === APP_ROWS_EXPORT ? 'tables' : 'input fields'
161
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${of}`)] }
122
162
  }
123
163
  entries[id] = entry
124
164
  }
125
165
  return { ok: true, value: entries }
126
166
  }
127
167
 
128
- /** `export const <members, invitations or links> = { '<endpoint id>': ['<field>', …] }`, read into field lists. */
168
+ /** `export const <members, invitations, links or refusals> = { '<endpoint id>': ['<field>', …] }`, read into lists. */
129
169
  function fieldsById(
130
170
  declarator: AstNode,
131
171
  name: FieldExport,
@@ -142,13 +182,23 @@ function fieldsById(
142
182
  const entries: Record<string, readonly string[]> = {}
143
183
  for (const [id, fields] of Object.entries(value.value)) {
144
184
  if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
145
- return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of input field names`)] }
185
+ const of = name === REFUSALS_EXPORT ? 'error types' : 'input field names'
186
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of ${of}`)] }
146
187
  }
147
188
  entries[id] = fields.filter((field) => typeof field === 'string')
148
189
  }
149
190
  return { ok: true, value: entries }
150
191
  }
151
192
 
193
+ /** Each entry's string values, by endpoint id: what `rows`, `files` and `pins` hold once checked. */
194
+ const stringsById = (byIdValue: ById): Readonly<Record<string, Readonly<Record<string, string>>>> =>
195
+ Object.fromEntries(
196
+ Object.entries(byIdValue).map(([id, named]) => [
197
+ id,
198
+ Object.fromEntries(Object.entries(named).flatMap(([key, item]) => (typeof item === 'string' ? [[key, item]] : []))),
199
+ ]),
200
+ )
201
+
152
202
  /** The fixtures of `files`, by endpoint id; none without the file. */
153
203
  export function readEndpointFixtures(
154
204
  files: ReadonlyMap<string, string>,
@@ -173,7 +223,9 @@ export function readEndpointFixtures(
173
223
  const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
174
224
  if (
175
225
  statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
176
- || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
226
+ || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT && name !== FILES_EXPORT
227
+ && name !== PINS_EXPORT && !isFieldExport(name))
228
+ || read.has(name)
177
229
  || (isFieldExport(name) && fields.has(name))
178
230
  ) {
179
231
  return {
@@ -181,7 +233,7 @@ export function readEndpointFixtures(
181
233
  findings: [
182
234
  finding(
183
235
  statement ?? undefined,
184
- `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
236
+ `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT}, ${LINKS_EXPORT}, ${ROWS_EXPORT}, ${APP_ROWS_EXPORT}, ${FILES_EXPORT}, ${REFUSALS_EXPORT} and ${PINS_EXPORT} = { … }, each at most once`,
185
237
  ),
186
238
  ],
187
239
  }
@@ -200,6 +252,26 @@ export function readEndpointFixtures(
200
252
  return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
201
253
  }
202
254
  }
255
+ if (name === FILES_EXPORT) {
256
+ const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((path) => typeof path !== 'string'))
257
+ if (named !== undefined) {
258
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the files of ${named[0]} name each field's file as a path string`)] }
259
+ }
260
+ }
261
+ if (name === PINS_EXPORT) {
262
+ const named = Object.entries(value.value).find(([, columns]) =>
263
+ Object.values(columns).some((pinned) => typeof pinned !== 'string' || pinned === '')
264
+ )
265
+ if (named !== undefined) {
266
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the pins of ${named[0]} give each column a non-empty string`)] }
267
+ }
268
+ }
269
+ if (name === APP_ROWS_EXPORT) {
270
+ const named = Object.entries(value.value).find(([, tables]) => Object.values(tables).some((columns) => !isSampleObject(columns)))
271
+ if (named !== undefined) {
272
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the appRows of ${named[0]} give each table's row as an object of columns`)] }
273
+ }
274
+ }
203
275
  read.set(name, value.value)
204
276
  }
205
277
  return {
@@ -210,12 +282,26 @@ export function readEndpointFixtures(
210
282
  members: fields.get(MEMBERS_EXPORT) ?? {},
211
283
  invitations: fields.get(INVITATIONS_EXPORT) ?? {},
212
284
  links: fields.get(LINKS_EXPORT) ?? {},
285
+ refusals: fields.get(REFUSALS_EXPORT) ?? {},
213
286
  rows: Object.fromEntries(
214
287
  Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
215
288
  id,
216
289
  Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
217
290
  ]),
218
291
  ),
292
+ appRows: Object.fromEntries(
293
+ Object.entries(read.get(APP_ROWS_EXPORT) ?? {}).map(([id, tables]) => [
294
+ id,
295
+ Object.fromEntries(Object.entries(tables).flatMap(([table, columns]) => (isSampleObject(columns) ? [[table, columns]] : []))),
296
+ ]),
297
+ ),
298
+ pins: stringsById(read.get(PINS_EXPORT) ?? {}),
299
+ files: Object.fromEntries(
300
+ Object.entries(read.get(FILES_EXPORT) ?? {}).map(([id, named]) => [
301
+ id,
302
+ Object.fromEntries(Object.entries(named).flatMap(([field, path]) => (typeof path === 'string' ? [[field, path]] : []))),
303
+ ]),
304
+ ),
219
305
  },
220
306
  }
221
307
  }
package/src/finding.ts CHANGED
@@ -40,16 +40,21 @@ export const REFUSAL_RULE_IDS = [
40
40
  'layer-import',
41
41
  'generated-test-import',
42
42
  'shared-import',
43
+ 'cloudflare-scan',
44
+ 'cloudflare-job-segment',
45
+ 'cloudflare-current-timestamp',
46
+ 'cloudflare-framework-name',
43
47
  ] as const
44
48
 
45
49
  /** Rules that report a step out of the application architecture. */
46
50
  export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
47
51
 
48
52
  /**
49
- * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, and a
50
- * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization.
53
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
54
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
55
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
51
56
  */
52
- export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
57
+ export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external', 'cloudflare-held-call'] as const
53
58
 
54
59
  export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
55
60
 
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export { type ApplicationTree, checkApplication, type CheckInput, readApplicationTree } from './check'
2
+ export { type ApplicationDialect, applicationDialect } from './dialect'
2
3
  export { type Finding, formatFinding, RULE_IDS, type RuleId } from './finding'
3
- export { CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
4
+ export { CONFIG_FILE, CONTRACT_FILE, GENERATED_ENTRY_FILE, MIGRATIONS_DIR, TABLES_FILE, ZEROPS_FILES } from './layout'
4
5
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
5
6
  export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
6
7
  export {
package/src/layout.ts CHANGED
@@ -1,11 +1,15 @@
1
1
  /** Where an application keeps what the checker reads. Paths are relative to the application root. */
2
2
  export const CONTRACT_FILE = 'fabrika.contract.ts'
3
+ /** The provider-authored application config, whose `defineApp` names the provider. */
4
+ export const CONFIG_FILE = 'fabrika.config.ts'
3
5
  /** The named export of the contract module that holds `defineContract(…)`. */
4
6
  export const CONTRACT_EXPORT = 'contract'
5
7
  export const TABLES_FILE = 'src/db/tables.ts'
6
8
  /** The named export of the tables module that holds `defineTables(…)(…)`. */
7
9
  export const TABLES_EXPORT = 'tables'
8
10
  export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
11
+ /** Where a Cloudflare deploy stages the SPA mounts' built files (`@fabrika/provider-cloudflare`): build output, never source. */
12
+ export const STAGED_ASSETS_DIR = 'fabrika/assets/'
9
13
  export const MIGRATIONS_DIR = 'db/migrations/'
10
14
  /** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
11
15
  export const POLICY_TESTS_DIR = 'src/db/__tests__/'
@@ -40,6 +44,9 @@ const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
40
44
  /** Build output, installed packages and tool state are not application source and are never read. */
41
45
  export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
42
46
 
47
+ /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
48
+ export const isSkippedPath = (path: string): boolean => path.split('/').some(isIgnoredSegment) || path.startsWith(STAGED_ASSETS_DIR)
49
+
43
50
  export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
44
51
 
45
52
  export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
@@ -53,7 +60,7 @@ export const isJsonFile = (path: string): boolean => path.endsWith('.json')
53
60
  export const isCheckedFile = (path: string): boolean => {
54
61
  // The registry configuration and the lockfile decide what a trusted package name installs.
55
62
  if (path === '.npmrc' || path === 'bun.lock') return true
56
- if (path.split('/').some(isIgnoredSegment)) return false
63
+ if (isSkippedPath(path)) return false
57
64
  return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR) || ZEROPS_FILES.some((name) => name === path)
58
65
  || path === 'bunfig.toml'
59
66
  }
@@ -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,6 +32,7 @@ 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,
@@ -213,6 +215,7 @@ class SurfaceReader {
213
215
  'mail',
214
216
  'members',
215
217
  'directory',
218
+ 'terminal',
216
219
  ])
217
220
  const locale = fields.get('locale')
218
221
  const displayName = fields.get('displayName')
@@ -220,6 +223,7 @@ class SurfaceReader {
220
223
  const members = fields.get('members')
221
224
  const memberFields = members === undefined ? undefined : strictFields(members, 'the vocabulary members', ['manage', 'list'], [])
222
225
  const directory = fields.get('directory')
226
+ const terminal = fields.get('terminal')
223
227
  return {
224
228
  app: text(fields.get('app'), value, 'app'),
225
229
  ...(locale === undefined ? {} : { locale: localeOf(locale, value) }),
@@ -229,6 +233,7 @@ class SurfaceReader {
229
233
  ? {}
230
234
  : { members: { manage: text(memberFields.get('manage'), value, 'manage'), list: text(memberFields.get('list'), value, 'list') } }),
231
235
  ...(directory === undefined ? {} : { directory: directoryOf(directory, value) }),
236
+ ...(terminal === undefined ? {} : { terminal: terminalOf(terminal) }),
232
237
  dimensions: this.#each(entries(fields.get('dimensions'), value, 'dimensions'), (name, dimension) => this.#dimension(name, dimension)),
233
238
  actions: this.#each(entries(fields.get('actions'), value, 'actions'), (_, description) => text(description, description, 'an action description')),
234
239
  roles: this.#each(entries(fields.get('roles'), value, 'roles'), (name, role) => this.#role(name, role)),
@@ -936,6 +941,16 @@ function directoryOf(value: LiteralValue, owner: Owner): 'labels' {
936
941
  return directory
937
942
  }
938
943
 
944
+ /** The vocabulary's `terminal: { identify: '/path' }`; `buildArtifact` checks the path itself. */
945
+ function terminalOf(value: LiteralValue): TerminalDeclaration {
946
+ const identify = strictFields(value, 'the vocabulary terminal', ['identify'], []).get('identify')
947
+ const path = text(identify, value, 'terminal.identify')
948
+ if (!isPath(path)) {
949
+ throw new Refused(identify?.at ?? value.at, `terminal.identify is '${path}'`, "terminal: { identify: '/identify' }")
950
+ }
951
+ return { identify: path }
952
+ }
953
+
939
954
  function optionalText(value: LiteralValue | undefined, field: string): string | undefined {
940
955
  return value === undefined ? undefined : text(value, value, field)
941
956
  }
@@ -83,7 +83,7 @@ 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 = ['app', 'dimensions', 'actions', 'roles', 'locale', 'displayName', 'mail', 'members', 'directory', 'terminal'] as const
87
87
 
88
88
  const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
89
89
 
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 } 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?: readonly string[]; readonly connect: readonly string[] }): string[] => [
18
+ ...(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
+ ]
@@ -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 => {
@@ -33,7 +33,11 @@ export const expectedGeneratedTests = async (
33
33
  > => {
34
34
  try {
35
35
  const inputs = scaffoldInputs(files)
36
- return { ok: true, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
36
+ return {
37
+ ok: true,
38
+ tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures, inputs.dialect),
39
+ missing: missingEndpointFixtures(inputs),
40
+ }
37
41
  } catch (error) {
38
42
  if (error instanceof ContractSourceError) return { ok: false, findings: error.findings }
39
43
  if (error instanceof ContractError) {