@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
package/src/contract.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  import { type AnyContract, compileContract } from '@fabrika/app/contract'
6
6
  import type { ContractArtifact, TablePolicyArtifact } from '@fabrika/auth-core'
7
7
  import { type TablePolicies, tablePolicies, type Tables } from '@fabrika/db/tables'
8
- import { importedSpecifiers, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
8
+ import { child, children, importedSpecifiers, nodeCount, nodeDepth, type ParsedModule, utf8Bytes } from './ast'
9
9
  import { type Finding, formatFinding } from './finding'
10
10
  import { ModuleGraph } from './graph'
11
11
  import { CONTRACT_EXPORT, CONTRACT_FILE, isRelativeSpecifier, isSourceFile, resolveRelative, TABLES_FILE } from './layout'
@@ -19,6 +19,7 @@ import { parseShellModule } from './slice'
19
19
  import { checkTrustedResolution } from './trust'
20
20
 
21
21
  export { ContractError } from '@fabrika/app/contract'
22
+ export { accessTables } from '@fabrika/db/tables'
22
23
  export { type Finding, formatFinding } from './finding'
23
24
  export { contractReaderInputs } from './inputs'
24
25
  export { CONTRACT_FILE, MIGRATIONS_DIR, TABLES_FILE } from './layout'
@@ -160,21 +161,34 @@ export function contractModules(graph: ModuleGraph, entry: ParsedModule): Parsed
160
161
  return [...reached.values()]
161
162
  }
162
163
 
163
- /** The source and syntax-depth limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
164
+ /** The source and syntax limits of `CONTRACT_LIMITS` over the modules of one entry (the contract or the tables). */
164
165
  function sourceBudget(modules: readonly ParsedModule[], entry = CONTRACT_FILE): Finding[] {
165
166
  const findings: Finding[] = []
166
167
  const bytes = modules.reduce((total, module) => total + module.bytes, 0)
167
168
  if (bytes > CONTRACT_LIMITS.sourceBytes) {
168
169
  findings.push(overBudget(entry, `${entry} and its modules are ${bytes} bytes, over ${CONTRACT_LIMITS.sourceBytes}`))
169
170
  }
171
+ let nodes = 0
170
172
  for (const module of modules) {
173
+ if (module.bytes > CONTRACT_LIMITS.moduleBytes) {
174
+ findings.push(overBudget(module.file, moduleTooLarge(module.bytes)))
175
+ }
171
176
  if (nodeDepth(module.program) > CONTRACT_LIMITS.astDepth) {
172
177
  findings.push(overBudget(module.file, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`))
173
178
  }
179
+ nodes += heldNodes(module)
180
+ }
181
+ if (nodes > CONTRACT_LIMITS.astNodes) {
182
+ findings.push(overBudget(entry, `${entry} and its modules hold ${nodes} syntax nodes, over the budget of ${CONTRACT_LIMITS.astNodes}`))
174
183
  }
175
184
  return findings
176
185
  }
177
186
 
187
+ const moduleTooLarge = (bytes: number): string => `the module is ${bytes} bytes, over ${CONTRACT_LIMITS.moduleBytes} for one module`
188
+
189
+ /** The syntax nodes the reader holds of a module: all but its top-level type declarations. */
190
+ const heldNodes = (module: ParsedModule): number => nodeCount(withoutTypeDeclarations(module).program)
191
+
178
192
  function overBudget(file: string, message: string): Finding {
179
193
  return {
180
194
  file,
@@ -192,8 +206,8 @@ type ParsedGraph = { readonly ok: true; readonly graph: ModuleGraph } | { readon
192
206
  /**
193
207
  * Parses `entry` (`fabrika.contract.ts` or `src/db/tables.ts`) and the modules its imports reach among `files`, and
194
208
  * nothing else; each module as its shell slice, so an import only a handler uses is never followed. Every candidate of an import is parsed, so that `rules/literal.ts` sees an ambiguous or directory
195
- * import; the size limit holds before a module is parsed and the depth limit right after, before any recursive rule
196
- * walks it.
209
+ * import; the byte limits hold before a module is parsed, and the depth and node limits right after, before any
210
+ * recursive rule walks it.
197
211
  */
198
212
  function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): ParsedGraph {
199
213
  const modules = new Map<string, ParsedModule>()
@@ -202,13 +216,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
202
216
  return { ok: false, findings: [missingFile(entry)] }
203
217
  }
204
218
  let bytes = 0
219
+ let nodes = 0
205
220
  const queue = [entry]
206
221
  for (let path = queue.shift(); path !== undefined; path = queue.shift()) {
207
222
  const text = files.get(path)
208
223
  if (modules.has(path) || text === undefined || !isSourceFile(path)) {
209
224
  continue
210
225
  }
211
- bytes += utf8Bytes(text)
226
+ const moduleBytes = utf8Bytes(text)
227
+ if (moduleBytes > CONTRACT_LIMITS.moduleBytes) {
228
+ return { ok: false, findings: [overBudget(path, moduleTooLarge(moduleBytes))] }
229
+ }
230
+ bytes += moduleBytes
212
231
  if (bytes > CONTRACT_LIMITS.sourceBytes) {
213
232
  return { ok: false, findings: [overBudget(path, `${entry} and its modules are over ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
214
233
  }
@@ -228,7 +247,12 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
228
247
  if (nodeDepth(parsed.module.program) > CONTRACT_LIMITS.astDepth) {
229
248
  return { ok: false, findings: [overBudget(path, `the syntax nests deeper than ${CONTRACT_LIMITS.astDepth} levels`)] }
230
249
  }
231
- modules.set(path, parsed.module)
250
+ const held = withoutTypeDeclarations(parsed.module)
251
+ nodes += nodeCount(held.program)
252
+ if (nodes > CONTRACT_LIMITS.astNodes) {
253
+ return { ok: false, findings: [overBudget(path, `${entry} and its modules hold over ${CONTRACT_LIMITS.astNodes} syntax nodes`)] }
254
+ }
255
+ modules.set(path, held)
232
256
  for (const specifier of importedSpecifiers(parsed.module)) {
233
257
  const resolution = isRelativeSpecifier(specifier) ? resolveRelative((candidate) => files.has(candidate), path, specifier) : undefined
234
258
  if (resolution?.kind === 'file') {
@@ -241,6 +265,18 @@ function parseSourceGraph(files: ReadonlyMap<string, string>, entry: string): Pa
241
265
  return findings.length > 0 ? { ok: false, findings } : { ok: true, graph: new ModuleGraph(modules) }
242
266
  }
243
267
 
268
+ /** Top-level type declarations: the module index binds no name to them, and the literal rule passes over them. */
269
+ const TYPE_DECLARATIONS = new Set(['TSTypeAliasDeclaration', 'TSInterfaceDeclaration'])
270
+
271
+ /** The module without its top-level type declarations, which the reader would otherwise hold until it is done. */
272
+ function withoutTypeDeclarations(module: ParsedModule): ParsedModule {
273
+ const body = children(module.program, 'body').filter((statement) => {
274
+ const declaration = statement?.type === 'ExportNamedDeclaration' ? child(statement, 'declaration') : statement
275
+ return declaration === null || declaration === undefined || !TYPE_DECLARATIONS.has(declaration.type)
276
+ })
277
+ return { ...module, program: { ...module.program, body } }
278
+ }
279
+
244
280
  function missingFile(file: string): Finding {
245
281
  return {
246
282
  file,
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
+ }
package/src/finding.ts CHANGED
@@ -22,34 +22,41 @@ export const REFUSAL_RULE_IDS = [
22
22
  'cross-app-fetch',
23
23
  'url-endpoint',
24
24
  'on-conflict-index',
25
+ 'access-view-key',
25
26
  'key-literal',
26
27
  'client-identity',
27
28
  'sensitive-log',
28
29
  'unsafe-html',
29
30
  'dynamic-code',
30
31
  'migration-name',
32
+ 'migration-refused',
33
+ 'backup-schema',
34
+ 'migration-edited',
31
35
  'file-column-migration',
32
- 'crontab',
33
36
  'package-replacement',
34
37
  'skipped-test',
35
38
  'test-without-assertion',
36
- 'generated-test-hash',
37
39
  'mock-module',
38
- 'endpoint-fixture',
39
40
  'spa-server-import',
40
41
  'layer-import',
41
- 'generated-test-import',
42
42
  'shared-import',
43
+ 'tool-import',
44
+ 'cloudflare-scan',
45
+ 'cloudflare-job-segment',
46
+ 'cloudflare-current-timestamp',
47
+ 'cloudflare-framework-name',
48
+ 'cloudflare-view-trigger',
43
49
  ] as const
44
50
 
45
51
  /** Rules that report a step out of the application architecture. */
46
52
  export const STRUCTURE_HINT_RULE_IDS = ['logic-data-access', 'cross-slice-queries', 'handler-location', 'data-access-location'] as const
47
53
 
48
54
  /**
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.
55
+ * Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
56
+ * `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
57
+ * Cloudflare mutation that waits for an outside call inside the object's transaction.
51
58
  */
52
- export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external'] as const
59
+ export const HINT_RULE_IDS = [...STRUCTURE_HINT_RULE_IDS, 'sql-undeclared', 'member-admits-external', 'cloudflare-held-call'] as const
53
60
 
54
61
  export const RULE_IDS = [...REFUSAL_RULE_IDS, ...HINT_RULE_IDS] as const
55
62
 
package/src/index.ts CHANGED
@@ -1,15 +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 } from './layout'
5
+ export { readMigrationBase } from './migration-base'
4
6
  export { type PackedSet, type PackedTarball, readPackedSet } from './packed'
5
- export { GENERATED_TEST_HEADER, generatedTestHeader } from './rules/tests'
6
- export {
7
- ENDPOINT_ACCESS_TEST,
8
- ENDPOINT_FIXTURES_FILE,
9
- type GeneratedTest,
10
- generatedTests,
11
- missingEndpointFixtures,
12
- POLICY_TESTS_DIR,
13
- policyTestPath,
14
- scaffoldInputs,
15
- } from './scaffold'
7
+ export type { MigrationBase } from './rules/migration-history'
package/src/inputs.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  // Which files of an application the static reader needs. Control reads a commit file by file, and the reader cannot
2
2
  // tell a missing file from one it was not given, so the caller asks here until nothing is missing. Worker-safe.
3
3
 
4
- import { importedSpecifiers } from './ast'
4
+ import { importedSpecifiers, utf8Bytes } from './ast'
5
5
  import { parseJsonc } from './jsonc'
6
6
  import { CONTRACT_FILE, isRelativeSpecifier, isSourceFile, joinRelative, resolveRelative, TABLES_FILE } from './layout'
7
+ import { CONTRACT_LIMITS } from './limits'
7
8
  import { parseShellModule } from './slice'
8
9
  import { BUNFIG_FILE } from './trust'
9
10
 
@@ -49,7 +50,8 @@ export function contractReaderInputs(files: ReadonlyMap<string, string>, exists:
49
50
  want(path)
50
51
  continue
51
52
  }
52
- const parsed = isSourceFile(path) ? parseShellModule(path, text).parsed : undefined
53
+ // A module over the limit is not parsed here: the reader refuses it, and its own parse would be the peak.
54
+ const parsed = isSourceFile(path) && utf8Bytes(text) <= CONTRACT_LIMITS.moduleBytes ? parseShellModule(path, text).parsed : undefined
53
55
  if (parsed?.ok !== true) continue
54
56
  for (const specifier of importedSpecifiers(parsed.module)) {
55
57
  if (!isRelativeSpecifier(specifier)) continue
package/src/layout.ts CHANGED
@@ -1,20 +1,18 @@
1
+ import { children, type ParsedModule, positionOf } from './ast'
2
+
1
3
  /** Where an application keeps what the checker reads. Paths are relative to the application root. */
2
4
  export const CONTRACT_FILE = 'fabrika.contract.ts'
5
+ /** The provider-authored application config, whose `defineApp` names the provider. */
6
+ export const CONFIG_FILE = 'fabrika.config.ts'
3
7
  /** The named export of the contract module that holds `defineContract(…)`. */
4
8
  export const CONTRACT_EXPORT = 'contract'
5
9
  export const TABLES_FILE = 'src/db/tables.ts'
6
10
  /** The named export of the tables module that holds `defineTables(…)(…)`. */
7
11
  export const TABLES_EXPORT = 'tables'
8
12
  export const GENERATED_ENTRY_FILE = 'fabrika/entry.generated.ts'
13
+ /** Where a Cloudflare deploy stages the SPA mounts' built files (`@fabrika/provider-cloudflare`): build output, never source. */
14
+ export const STAGED_ASSETS_DIR = 'fabrika/assets/'
9
15
  export const MIGRATIONS_DIR = 'db/migrations/'
10
- /** Where `fabrika db test-scaffold` writes the policy isolation tests, `<table>.policy-isolation.test.ts`. */
11
- export const POLICY_TESTS_DIR = 'src/db/__tests__/'
12
- export const POLICY_TEST_SUFFIX = '.policy-isolation.test.ts'
13
- /** The generated endpoint access tests; they import `src/app.ts`, whose default export they boot. */
14
- export const ENDPOINT_ACCESS_TEST = 'src/__tests__/endpoint-access.test.ts'
15
- /** The inputs the author gives the endpoint access tests where the scaffold cannot sample one; read, never run. */
16
- export const ENDPOINT_FIXTURES_FILE = 'src/__tests__/endpoint-access.fixtures.ts'
17
- export const ZEROPS_FILES = ['zerops.yaml', 'zerops.yml'] as const
18
16
 
19
17
  /** The application architecture (docs/reference/application-architecture.md): where each layer's code lives. */
20
18
  export const VOCABULARY_FILE = 'src/vocabulary.ts'
@@ -22,9 +20,12 @@ export const APP_KIT_FILE = 'src/app-kit.ts'
22
20
  /** The shared zod schemas the shell and the SPA import: one module, or a directory of them once it grows. */
23
21
  export const SCHEMAS_FILE = 'src/schemas.ts'
24
22
  export const SCHEMAS_DIR = 'src/schemas/'
25
- /** Pure code the SPA and every slice may import: it loads nothing but `zod/v4` and other modules of its own directory. */
23
+ /**
24
+ * Pure code the SPA and every slice may import: it loads nothing but `zod/v4`, `@fabrika/app/schema` and other modules of
25
+ * its own directory.
26
+ */
26
27
  export const SHARED_DIR = 'src/shared/'
27
- /** `src/db/`: the tables, the generated schema and their generated tests; never a slice. */
28
+ /** `src/db/`: the tables and the generated schema; never a slice. */
28
29
  export const DATABASE_DIR = 'src/db/'
29
30
  /** A slice is a directory `src/<slice>/` that holds these modules, each optional. */
30
31
  export const SLICE_ENDPOINTS_FILE = 'endpoints.ts'
@@ -33,6 +34,11 @@ export const SLICE_QUERIES_FILE = 'queries.ts'
33
34
  export const SPA_DIR = 'web/'
34
35
  /** The server half of an application: its modules run in the application's process. */
35
36
  export const SERVER_DIR = 'src/'
37
+ /**
38
+ * A developer's tools, such as a command line over the contract: code that runs on a developer's machine and never in
39
+ * the application, so the rules for code that runs there do not apply, and no module outside it may load one.
40
+ */
41
+ export const TOOLS_DIR = 'tools/'
36
42
 
37
43
  const SOURCE_EXTENSION = /\.(?:[mc]?[jt]s|[jt]sx)$/
38
44
  const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
@@ -40,6 +46,9 @@ const TEST_FILE = /(?:^|\/)__tests__\/|\.(?:test|spec)\.[mc]?[jt]sx?$/
40
46
  /** Build output, installed packages and tool state are not application source and are never read. */
41
47
  export const isIgnoredSegment = (segment: string): boolean => segment === 'node_modules' || segment === 'dist' || segment.startsWith('.')
42
48
 
49
+ /** Whether the checker skips `path` (relative to the root): under a skipped segment, or the staged SPA files. */
50
+ export const isSkippedPath = (path: string): boolean => path.split('/').some(isIgnoredSegment) || path.startsWith(STAGED_ASSETS_DIR)
51
+
43
52
  export const isSourceFile = (path: string): boolean => SOURCE_EXTENSION.test(path)
44
53
 
45
54
  export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
@@ -47,14 +56,34 @@ export const isTestFile = (path: string): boolean => TEST_FILE.test(path)
47
56
  /** A module that runs in the application's server process: under `src/`, not a test. */
48
57
  export const isServerModule = (path: string): boolean => path.startsWith(SERVER_DIR) && !isTestFile(path)
49
58
 
59
+ /** A module under `tools/`, tests included. */
60
+ export const isToolModule = (path: string): boolean => path.startsWith(TOOLS_DIR)
61
+
50
62
  export const isJsonFile = (path: string): boolean => path.endsWith('.json')
51
63
 
64
+ const GENERATED_NAME = /\.(?:gen|generated)\.(?:[mc]?[jt]s|[jt]sx)$/
65
+ const GENERATED_MARKER = /@generated|auto-generated/i
66
+
67
+ /**
68
+ * A module a generator writes: named `<name>.gen.<ext>` or `<name>.generated.<ext>`, opening with a comment on its first
69
+ * line, before any statement, that says so (`@generated` or `auto-generated`, in any case). The rules about how source
70
+ * is written do not apply to it; every rule about what it does still does.
71
+ */
72
+ export const isGeneratedModule = (path: string, module: Pick<ParsedModule, 'program' | 'comments'>): boolean => {
73
+ const [header] = module.comments
74
+ if (!GENERATED_NAME.test(path) || header === undefined || header.position.line !== 1 || !GENERATED_MARKER.test(header.text)) return false
75
+ const [statement] = children(module.program, 'body')
76
+ if (statement === undefined || statement === null) return true
77
+ const start = positionOf(statement)
78
+ return header.position.line < start.line || (header.position.line === start.line && header.position.column < start.column)
79
+ }
80
+
52
81
  /** Whether the checker reads this file at all. */
53
82
  export const isCheckedFile = (path: string): boolean => {
54
83
  // The registry configuration and the lockfile decide what a trusted package name installs.
55
84
  if (path === '.npmrc' || path === 'bun.lock') return true
56
- if (path.split('/').some(isIgnoredSegment)) return false
57
- return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR) || ZEROPS_FILES.some((name) => name === path)
85
+ if (isSkippedPath(path)) return false
86
+ return isSourceFile(path) || isJsonFile(path) || path.startsWith(MIGRATIONS_DIR)
58
87
  || path === 'bunfig.toml'
59
88
  }
60
89
 
package/src/limits.ts CHANGED
@@ -4,12 +4,22 @@
4
4
  * step runs.
5
5
  */
6
6
  export const CONTRACT_LIMITS = {
7
- /** UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. */
8
- sourceBytes: 512 * 1024,
7
+ /**
8
+ * UTF-8 bytes of `fabrika.contract.ts` and every module it imports, together. Control reads them in a Cloudflare
9
+ * Worker, whose isolate has 128 MB; handler bodies are sliced out before the parse, so they cost bytes, not nodes.
10
+ */
11
+ sourceBytes: 4 * 1024 * 1024,
12
+ /** UTF-8 bytes of one module: its own parse is the peak while it is read, and a dense one needs up to 340 times it. */
13
+ moduleBytes: 512 * 1024,
14
+ /**
15
+ * Syntax nodes the reader holds over each graph (the contract's, the tables'), top-level type declarations left out.
16
+ * At this, `sourceBytes` and `schemaNodes` together, Control's read needs a 95 MB heap of its 128 MB isolate.
17
+ */
18
+ astNodes: 400_000,
9
19
  /** Nesting of syntax nodes in one module; the contracts in this repository reach 25. */
10
20
  astDepth: 128,
11
21
  /** Schema nodes once every shared schema is expanded where the contract uses it, over the whole contract. */
12
- schemaNodes: 20_000,
22
+ schemaNodes: 60_000,
13
23
  /** Nesting of one schema: objects, arrays, unions and wrappers. */
14
24
  schemaDepth: 32,
15
25
  } as const
@@ -0,0 +1,85 @@
1
+ // The migrations `migration-edited` compares the tree with: those of the merge base of HEAD and the remote's default
2
+ // branch, read with git. Only the bin reads them; a caller with the files of a commit (Control, a deploy build) has no
3
+ // history to compare with, and the runner's checksum stays the real check.
4
+
5
+ import { MIGRATIONS_DIR } from './layout'
6
+ import type { MigrationBase } from './rules/migration-history'
7
+
8
+ /** What the default base is looked up as, in order, when the bin is given no `--base`. */
9
+ const DEFAULT_REFS = ['origin/main', 'origin/master']
10
+
11
+ interface GitResult {
12
+ readonly ok: boolean
13
+ readonly stdout: Uint8Array
14
+ }
15
+
16
+ const git = async (root: string, args: readonly string[], stdin?: string): Promise<GitResult> => {
17
+ const input = stdin === undefined ? 'ignore' : new TextEncoder().encode(stdin)
18
+ const child = Bun.spawn(['git', '-C', root, ...args], { stdin: input, stdout: 'pipe', stderr: 'ignore' })
19
+ const [code, stdout] = await Promise.all([child.exited, new Response(child.stdout).arrayBuffer()])
20
+ return { ok: code === 0, stdout: new Uint8Array(stdout) }
21
+ }
22
+
23
+ const text = (bytes: Uint8Array): string => new TextDecoder().decode(bytes).trim()
24
+
25
+ /** The remote's default branch: `origin/HEAD` where the clone recorded it, else the first of `DEFAULT_REFS` that exists. */
26
+ const defaultRef = async (root: string): Promise<string | null> => {
27
+ const head = await git(root, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD'])
28
+ if (head.ok && text(head.stdout) !== '') return text(head.stdout)
29
+ for (const ref of DEFAULT_REFS) {
30
+ if ((await git(root, ['rev-parse', '--verify', '-q', `${ref}^{commit}`])).ok) return ref
31
+ }
32
+ return null
33
+ }
34
+
35
+ /** Each regular file directly in `db/migrations/` at `commit`, by its blob id. */
36
+ const migrationBlobs = async (root: string, commit: string): Promise<Map<string, string> | null> => {
37
+ const listed = await git(root, ['ls-tree', '-z', commit, '--', MIGRATIONS_DIR])
38
+ if (!listed.ok) return null
39
+ const blobs = new Map<string, string>()
40
+ for (const entry of new TextDecoder().decode(listed.stdout).split('\0')) {
41
+ const match = /^(100644|100755) blob ([0-9a-f]+)\t(.+)$/.exec(entry)
42
+ if (match?.[2] !== undefined && match[3] !== undefined && match[3].endsWith('.sql')) blobs.set(match[3], match[2])
43
+ }
44
+ return blobs
45
+ }
46
+
47
+ /** The blobs' texts, through one `git cat-file --batch`: each answer is `<id> blob <size>\n<bytes>\n`. */
48
+ const blobTexts = async (root: string, blobs: ReadonlyMap<string, string>): Promise<Map<string, string> | null> => {
49
+ if (blobs.size === 0) return new Map()
50
+ const ids = [...blobs.values()]
51
+ const batch = await git(root, ['cat-file', '--batch'], ids.map((id) => `${id}\n`).join(''))
52
+ if (!batch.ok) return null
53
+ const decoder = new TextDecoder()
54
+ const texts = new Map<string, string>()
55
+ let offset = 0
56
+ for (const id of ids) {
57
+ const end = batch.stdout.indexOf(10, offset)
58
+ const header = /^([0-9a-f]+) blob (\d+)$/.exec(decoder.decode(batch.stdout.subarray(offset, end)))
59
+ if (end < 0 || header?.[1] !== id || header[2] === undefined) return null
60
+ const size = Number(header[2])
61
+ texts.set(id, decoder.decode(batch.stdout.subarray(end + 1, end + 1 + size)))
62
+ offset = end + 1 + size + 1
63
+ }
64
+ return new Map([...blobs].map(([path, id]) => [path, texts.get(id) ?? '']))
65
+ }
66
+
67
+ /**
68
+ * The migrations at the merge base of HEAD and `ref` (the remote's default branch when omitted), compared against
69
+ * the merge base so that migrations the default branch added since the branch forked are not read as deleted.
70
+ * `null` when `root` is in no git work tree; `{ skipped }` when it is but the base cannot be read.
71
+ */
72
+ export const readMigrationBase = async (root: string, ref?: string): Promise<MigrationBase | { readonly skipped: string } | null> => {
73
+ if (!(await git(root, ['rev-parse', '--is-inside-work-tree'])).ok) return null
74
+ const named = ref ?? (await defaultRef(root))
75
+ if (named === null) return { skipped: `no origin/HEAD, ${DEFAULT_REFS.join(' or ')} to compare the migrations with; pass --base <ref>` }
76
+ if (named.startsWith('-') || !(await git(root, ['rev-parse', '--verify', '-q', `${named}^{commit}`])).ok) {
77
+ return { skipped: `${named} names no commit` }
78
+ }
79
+ const mergeBase = await git(root, ['merge-base', 'HEAD', named])
80
+ if (!mergeBase.ok) return { skipped: `HEAD and ${named} share no commit this clone holds` }
81
+ const blobs = await migrationBlobs(root, text(mergeBase.stdout))
82
+ const files = blobs === null ? null : await blobTexts(root, blobs)
83
+ if (files === null) return { skipped: `the migrations of ${named} cannot be read` }
84
+ return { ref: named, files }
85
+ }