@fabrika/check 0.8.2 → 0.9.0-cloudflare.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/package.json +12 -11
  2. package/src/check.ts +23 -6
  3. package/src/dialect.ts +29 -0
  4. package/src/endpoint-fixtures.ts +29 -9
  5. package/src/finding.ts +7 -3
  6. package/src/index.ts +2 -1
  7. package/src/layout.ts +2 -0
  8. package/src/reader/surface.ts +15 -0
  9. package/src/rules/cloudflare.ts +58 -0
  10. package/src/rules/framework.ts +2 -2
  11. package/src/rules/isolation.ts +5 -1
  12. package/src/rules/migrations.ts +31 -0
  13. package/src/rules/modules.ts +1 -1
  14. package/src/scaffold.ts +133 -33
  15. package/types/src/ast.d.ts +65 -0
  16. package/types/src/bun-plugin.d.ts +12 -0
  17. package/types/src/check.d.ts +19 -0
  18. package/types/src/cli.d.ts +2 -0
  19. package/types/src/contract.d.ts +58 -0
  20. package/types/src/dialect.d.ts +8 -0
  21. package/types/src/endpoint-fixtures.d.ts +39 -0
  22. package/types/src/finding.d.ts +39 -0
  23. package/types/src/graph.d.ts +68 -0
  24. package/types/src/index.d.ts +7 -0
  25. package/types/src/inputs.d.ts +9 -0
  26. package/types/src/jsonc.d.ts +2 -0
  27. package/types/src/layout.d.ts +65 -0
  28. package/types/src/limits.d.ts +15 -0
  29. package/types/src/lockfile.d.ts +19 -0
  30. package/types/src/packed.d.ts +15 -0
  31. package/types/src/reader/problems.d.ts +7 -0
  32. package/types/src/reader/schema.d.ts +18 -0
  33. package/types/src/reader/surface.d.ts +5 -0
  34. package/types/src/reader/tables.d.ts +6 -0
  35. package/types/src/reader/value.d.ts +113 -0
  36. package/types/src/references.d.ts +15 -0
  37. package/types/src/resolution.d.ts +20 -0
  38. package/types/src/rules/cloudflare.d.ts +9 -0
  39. package/types/src/rules/contract.d.ts +8 -0
  40. package/types/src/rules/crontab.d.ts +15 -0
  41. package/types/src/rules/framework.d.ts +19 -0
  42. package/types/src/rules/identity.d.ts +5 -0
  43. package/types/src/rules/isolation.d.ts +18 -0
  44. package/types/src/rules/json.d.ts +3 -0
  45. package/types/src/rules/literal.d.ts +63 -0
  46. package/types/src/rules/migrations.d.ts +34 -0
  47. package/types/src/rules/modules.d.ts +12 -0
  48. package/types/src/rules/packages.d.ts +7 -0
  49. package/types/src/rules/runtime.d.ts +32 -0
  50. package/types/src/rules/structure.d.ts +36 -0
  51. package/types/src/rules/tests.d.ts +22 -0
  52. package/types/src/rules/types.d.ts +4 -0
  53. package/types/src/scaffold-sample.d.ts +8 -0
  54. package/types/src/scaffold.d.ts +34 -0
  55. package/types/src/scope.d.ts +6 -0
  56. package/types/src/slice.d.ts +30 -0
  57. package/types/src/source-maps-cli.d.ts +4 -0
  58. package/types/src/source-maps.d.ts +32 -0
  59. package/types/src/toml.d.ts +30 -0
  60. package/types/src/trust.d.ts +15 -0
  61. package/types/src/version.d.ts +2 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/check",
3
- "version": "0.8.2",
3
+ "version": "0.9.0-cloudflare.1",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -16,27 +16,28 @@
16
16
  },
17
17
  "files": [
18
18
  "src",
19
- "!src/**/__tests__/**"
19
+ "!src/**/__tests__/**",
20
+ "types"
20
21
  ],
21
22
  "exports": {
22
23
  ".": {
23
24
  "bun": "./src/index.ts",
24
- "types": "./src/index.ts",
25
+ "types": "./types/src/index.d.ts",
25
26
  "default": "./src/index.ts"
26
27
  },
27
28
  "./contract": {
28
29
  "bun": "./src/contract.ts",
29
- "types": "./src/contract.ts",
30
+ "types": "./types/src/contract.d.ts",
30
31
  "default": "./src/contract.ts"
31
32
  },
32
33
  "./bun-plugin": {
33
34
  "bun": "./src/bun-plugin.ts",
34
- "types": "./src/bun-plugin.ts",
35
+ "types": "./types/src/bun-plugin.d.ts",
35
36
  "default": "./src/bun-plugin.ts"
36
37
  },
37
38
  "./source-maps": {
38
39
  "bun": "./src/source-maps.ts",
39
- "types": "./src/source-maps.ts",
40
+ "types": "./types/src/source-maps.d.ts",
40
41
  "default": "./src/source-maps.ts"
41
42
  }
42
43
  },
@@ -46,11 +47,11 @@
46
47
  },
47
48
  "dependencies": {
48
49
  "@babel/parser": "8.0.7",
49
- "@fabrika/app": "0.8.2",
50
- "@fabrika/auth-core": "0.8.2",
51
- "@fabrika/db": "0.8.2",
52
- "@fabrika/operations-contract": "0.8.2",
53
- "@fabrika/platform-node": "0.8.2",
50
+ "@fabrika/app": "0.9.0-cloudflare.1",
51
+ "@fabrika/auth-core": "0.9.0-cloudflare.1",
52
+ "@fabrika/db": "0.9.0-cloudflare.1",
53
+ "@fabrika/operations-contract": "0.9.0-cloudflare.1",
54
+ "@fabrika/platform-node": "0.9.0-cloudflare.1",
54
55
  "zod": "^3.25.76"
55
56
  }
56
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,14 @@ 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
+ type ConflictInsert,
42
+ type FileColumn,
43
+ } from './rules/migrations'
35
44
  import { checkModuleReferences } from './rules/modules'
36
45
  import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
37
46
  import { checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
@@ -157,15 +166,18 @@ interface CompiledReach {
157
166
  readonly origins: readonly string[]
158
167
  }
159
168
 
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
169
+ /** The contract's artifact, or `null` when it does not compile, which its own rule reports. */
170
+ const compiledArtifact = (contract: AnyContract, tables: Tables<unknown, unknown> | null): ContractArtifact | null => {
163
171
  try {
164
- artifact = compileContract(contract, tables ?? {})
172
+ return compileContract(contract, tables ?? {})
165
173
  } catch (error) {
166
174
  if (error instanceof ContractError) return null
167
175
  throw error
168
176
  }
177
+ }
178
+
179
+ /** The contract's procedures and origins. */
180
+ const compiledReach = (artifact: ContractArtifact): CompiledReach => {
169
181
  const procedures = artifact.endpoints.filter((row) =>
170
182
  (row.kind === 'query' || row.kind === 'mutation' || row.kind === 'public') && row.source.kind === 'mount'
171
183
  )
@@ -254,7 +266,12 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
254
266
  findings.push(...checkMigrationNames(checkedPaths))
255
267
  const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
256
268
  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))
269
+ const artifact = read?.ok === true ? compiledArtifact(read.contract, declaredTables) : null
270
+ findings.push(...contractDependentFindings(dependent, artifact === null ? null : compiledReach(artifact)))
271
+ if (applicationDialect(tree.files) === 'sqlite') {
272
+ if (artifact !== null) findings.push(...checkCloudflareContract(artifact))
273
+ findings.push(...checkCurrentTimestampDefaults(tree.files))
274
+ }
258
275
  if (declaredTables !== null) {
259
276
  const policies = tablePolicies(declaredTables)
260
277
  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,13 @@
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.
10
+ // Read from source, never executed, within the reader's budget: `export const fixtures = { '<endpoint id>': { … } }`,
11
+ // `export const seeds = { '<endpoint id>': { <column>: <value> } }`, `export const members = { '<endpoint id>':
12
+ // ['<field>'] }` (`invitations`, `links` alike), `export const rows = { '<endpoint id>': { <field>: '<table>' } }` and
13
+ // `export const appRows = { '<endpoint id>': { <table>: { <column>: <value> } } }`, plain literals only.
11
14
  // Browser-safe.
12
15
 
13
16
  import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
@@ -22,6 +25,7 @@ export const MEMBERS_EXPORT = 'members'
22
25
  export const INVITATIONS_EXPORT = 'invitations'
23
26
  export const LINKS_EXPORT = 'links'
24
27
  export const ROWS_EXPORT = 'rows'
28
+ export const APP_ROWS_EXPORT = 'appRows'
25
29
 
26
30
  /** The exports that list, by endpoint id, the input fields the kit fills with something it holds. */
27
31
  const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT] as const
@@ -29,7 +33,7 @@ type FieldExport = (typeof FIELD_EXPORTS)[number]
29
33
  const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
30
34
 
31
35
  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"
36
+ "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' } } and export const appRows = { 'portal.guide': { guides: { active: true } } }: string keys, and strings, numbers, booleans, null, arrays and objects"
33
37
 
34
38
  type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
35
39
 
@@ -46,9 +50,11 @@ export interface EndpointFixtures {
46
50
  readonly links: Readonly<Record<string, readonly string[]>>
47
51
  /** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
48
52
  readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
53
+ /** The rows of application tables the endpoint's own case reads, by table, each with its columns, by endpoint id. */
54
+ readonly appRows: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, Sample>>>>>>
49
55
  }
50
56
 
51
- export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
57
+ export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {}, appRows: {} }
52
58
 
53
59
  const finding = (at: AstNode | undefined, message: string): Finding => {
54
60
  const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
@@ -118,7 +124,8 @@ function byId(
118
124
  const entries: Record<string, Readonly<Record<string, Sample>>> = {}
119
125
  for (const [id, entry] of Object.entries(all)) {
120
126
  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'}`)] }
127
+ const of = name === SEEDS_EXPORT ? 'columns' : name === APP_ROWS_EXPORT ? 'tables' : 'input fields'
128
+ return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${of}`)] }
122
129
  }
123
130
  entries[id] = entry
124
131
  }
@@ -173,7 +180,8 @@ export function readEndpointFixtures(
173
180
  const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
174
181
  if (
175
182
  statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
176
- || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
183
+ || (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && name !== APP_ROWS_EXPORT && !isFieldExport(name))
184
+ || read.has(name)
177
185
  || (isFieldExport(name) && fields.has(name))
178
186
  ) {
179
187
  return {
@@ -181,7 +189,7 @@ export function readEndpointFixtures(
181
189
  findings: [
182
190
  finding(
183
191
  statement ?? undefined,
184
- `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
192
+ `the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT}, ${LINKS_EXPORT}, ${ROWS_EXPORT} and ${APP_ROWS_EXPORT} = { … }, each at most once`,
185
193
  ),
186
194
  ],
187
195
  }
@@ -200,6 +208,12 @@ export function readEndpointFixtures(
200
208
  return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
201
209
  }
202
210
  }
211
+ if (name === APP_ROWS_EXPORT) {
212
+ const named = Object.entries(value.value).find(([, tables]) => Object.values(tables).some((columns) => !isSampleObject(columns)))
213
+ if (named !== undefined) {
214
+ return { ok: false, findings: [finding(child(declarator, 'init'), `the appRows of ${named[0]} give each table's row as an object of columns`)] }
215
+ }
216
+ }
203
217
  read.set(name, value.value)
204
218
  }
205
219
  return {
@@ -216,6 +230,12 @@ export function readEndpointFixtures(
216
230
  Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
217
231
  ]),
218
232
  ),
233
+ appRows: Object.fromEntries(
234
+ Object.entries(read.get(APP_ROWS_EXPORT) ?? {}).map(([id, tables]) => [
235
+ id,
236
+ Object.fromEntries(Object.entries(tables).flatMap(([table, columns]) => (isSampleObject(columns) ? [[table, columns]] : []))),
237
+ ]),
238
+ ),
219
239
  },
220
240
  }
221
241
  }
package/src/finding.ts CHANGED
@@ -40,16 +40,20 @@ export const REFUSAL_RULE_IDS = [
40
40
  'layer-import',
41
41
  'generated-test-import',
42
42
  'shared-import',
43
+ 'cloudflare-sql',
44
+ 'cloudflare-scan',
45
+ 'cloudflare-current-timestamp',
43
46
  ] as const
44
47
 
45
48
  /** Rules that report a step out of the application architecture. */
46
49
  export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
47
50
 
48
51
  /**
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.
52
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
53
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
54
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
51
55
  */
52
- export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
56
+ export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external', 'cloudflare-held-call'] as const
53
57
 
54
58
  export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
55
59
 
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,5 +1,7 @@
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'
@@ -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
  }
@@ -0,0 +1,58 @@
1
+ import type { ContractArtifact } from '@fabrika/auth-core'
2
+ import type { Finding } from '../finding'
3
+ import { CONTRACT_FILE } from '../layout'
4
+
5
+ const at = (rule: 'cloudflare-sql' | 'cloudflare-scan', message: string, allowed: string): Finding => ({
6
+ file: CONTRACT_FILE,
7
+ line: 1,
8
+ column: 1,
9
+ severity: 'refusal',
10
+ rule,
11
+ message,
12
+ allowed,
13
+ })
14
+
15
+ /** The outside calls a site declares, as the hint names them: its `egress` origins and its `connect` imports. */
16
+ const outsideCalls = (reach: { readonly egress?: readonly string[]; readonly connect: readonly string[] }): string[] => [
17
+ ...(reach.egress ?? []).map((origin) => `egress ${origin}`),
18
+ ...reach.connect.map((name) => `connect ${name}`),
19
+ ]
20
+
21
+ /**
22
+ * What an application on Cloudflare cannot declare (ADR-0065): raw SQL, because a Durable Object's SQLite has no role
23
+ * under it and the classifier reads Postgres's lexical rules; a file kind that scans, because no scanner runs there.
24
+ * And a hint for a mutation that declares an outside call: the object runs one transaction at a time, and the mutation
25
+ * holds it while the call waits (backlog 216 item 7).
26
+ */
27
+ export const checkCloudflareContract = (artifact: ContractArtifact): Finding[] => [
28
+ ...Object.entries(artifact.declared ?? {}).filter(([, reach]) => reach.sql !== null).map(([site]) =>
29
+ at(
30
+ 'cloudflare-sql',
31
+ `${site} declares sql, which an application on Cloudflare cannot run: its SQLite database has no role to bound raw SQL`,
32
+ 'ctx.db and its stores, without sql in the site options',
33
+ )
34
+ ),
35
+ ...Object.entries(artifact.fileKinds ?? {}).filter(([, kind]) => kind.scan === true).map(([name]) =>
36
+ at(
37
+ 'cloudflare-scan',
38
+ `the file kind ${name} scans its files (scan: true), which an application on Cloudflare cannot: no scanner runs there`,
39
+ `c.files({ types, maxBytes }) without scan for ${name}, and no public procedure that takes its files`,
40
+ )
41
+ ),
42
+ ...artifact.endpoints.filter((endpoint) => endpoint.kind === 'mutation').flatMap((endpoint): Finding[] => {
43
+ const reach = artifact.declared?.[endpoint.id]
44
+ const calls = reach === undefined ? [] : outsideCalls(reach)
45
+ if (calls.length === 0) return []
46
+ return [{
47
+ file: CONTRACT_FILE,
48
+ line: 1,
49
+ column: 1,
50
+ severity: 'hint',
51
+ rule: 'cloudflare-held-call',
52
+ message: `${endpoint.id} is a mutation that declares ${
53
+ calls.join(', ')
54
+ }: on Cloudflare it waits for that call inside the object's transaction, which holds the whole environment`,
55
+ allowed: "record a row and ctx.kick('<job>'); the job declares the call and makes it outside ctx.transaction",
56
+ }]
57
+ }),
58
+ ]
@@ -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) {
@@ -43,6 +43,37 @@ export const checkMigrationNames = (paths: readonly string[]): Finding[] => {
43
43
  return findings
44
44
  }
45
45
 
46
+ /** The default a SQLite timestamp column takes: the UTC ISO text every read of the table parses. */
47
+ const SQLITE_NOW_DEFAULT = "DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ', 'now'))"
48
+
49
+ /**
50
+ * On SQLite `DEFAULT CURRENT_TIMESTAMP` stores `YYYY-MM-DD HH:MM:SS`, which every read of the table refuses as
51
+ * `unexpected_row` (backlog 216 item 13). Refused with or without parentheses, at the line of `CURRENT_TIMESTAMP`.
52
+ */
53
+ export const checkCurrentTimestampDefaults = (files: ReadonlyMap<string, string>): Finding[] => {
54
+ const findings: Finding[] = []
55
+ for (const [path, sql] of files) {
56
+ if (!path.startsWith(MIGRATIONS_DIR) || !path.endsWith('.sql')) continue
57
+ for (const { tokens } of topLevelStatements(sql)) {
58
+ tokens.forEach((token, index) => {
59
+ if (upperWord(token) !== 'DEFAULT') return
60
+ const value = isPunct(tokens[index + 1], '(') ? tokens[index + 2] : tokens[index + 1]
61
+ if (value === undefined || upperWord(value) !== 'CURRENT_TIMESTAMP') return
62
+ findings.push({
63
+ file: path,
64
+ line: value.line,
65
+ column: 1,
66
+ severity: 'refusal',
67
+ rule: 'cloudflare-current-timestamp',
68
+ message: 'DEFAULT CURRENT_TIMESTAMP stores YYYY-MM-DD HH:MM:SS on SQLite, which every read of the table refuses as unexpected_row',
69
+ allowed: SQLITE_NOW_DEFAULT,
70
+ })
71
+ })
72
+ }
73
+ }
74
+ return findings
75
+ }
76
+
46
77
  /** A declared file column: `table.column` holds files of `kind`. */
47
78
  export interface FileColumn {
48
79
  readonly table: string
@@ -94,7 +94,7 @@ const ALLOWED_ENV = 'values the framework hands the handler through deps or ctx'
94
94
  * The test kits: the application's signs tokens with its own key and boots the application a second way; the
95
95
  * database's reaches tables by name and seeds rows past the data layer. Production never loads either.
96
96
  */
97
- const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing']
97
+ const TEST_KITS = ['@fabrika/app/testing', '@fabrika/app/react/testing', '@fabrika/db/testing', '@fabrika/db/testing-sqlite']
98
98
  const TEST_ONLY_ALLOWED = 'the kit in a test file (*.test.ts, *.spec.ts or a __tests__ directory) only'
99
99
 
100
100
  export const isTestKit = (specifier: string): boolean => TEST_KITS.some((kit) => specifier === kit || specifier.startsWith(`${kit}/`))