@fabrika/check 0.0.0-stage → 0.4.0

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,49 @@
1
1
  {
2
- "name": "@fabrika/check",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@fabrika/check",
3
+ "version": "0.4.0",
4
+ "type": "module",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/contember/fabrika-platform.git",
8
+ "directory": "packages/check"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "bin": {
14
+ "fabrika-check": "./src/cli.ts"
15
+ },
16
+ "files": [
17
+ "src",
18
+ "!src/**/__tests__/**"
19
+ ],
20
+ "exports": {
21
+ ".": {
22
+ "bun": "./src/index.ts",
23
+ "types": "./src/index.ts",
24
+ "default": "./src/index.ts"
25
+ },
26
+ "./contract": {
27
+ "bun": "./src/contract.ts",
28
+ "types": "./src/contract.ts",
29
+ "default": "./src/contract.ts"
30
+ },
31
+ "./bun-plugin": {
32
+ "bun": "./src/bun-plugin.ts",
33
+ "types": "./src/bun-plugin.ts",
34
+ "default": "./src/bun-plugin.ts"
35
+ }
36
+ },
37
+ "scripts": {
38
+ "typecheck": "tsc --noEmit",
39
+ "test": "bun test"
40
+ },
41
+ "dependencies": {
42
+ "@babel/parser": "8.0.7",
43
+ "@fabrika/app": "^0.4.0",
44
+ "@fabrika/auth-core": "^0.4.0",
45
+ "@fabrika/db": "^0.4.0",
46
+ "@fabrika/platform-node": "^0.4.0",
47
+ "zod": "^3.25.76"
48
+ }
49
+ }
package/src/ast.ts ADDED
@@ -0,0 +1,268 @@
1
+ import { parse, type ParserPlugin } from '@babel/parser'
2
+
3
+ /** An ESTree node as `@babel/parser` returns it with the `estree` plugin, read structurally. */
4
+ export interface AstNode {
5
+ readonly type: string
6
+ readonly [key: string]: unknown
7
+ }
8
+
9
+ export interface Position {
10
+ readonly line: number
11
+ readonly column: number
12
+ }
13
+
14
+ export interface Comment {
15
+ readonly text: string
16
+ readonly position: Position
17
+ }
18
+
19
+ export interface ParsedModule {
20
+ readonly file: string
21
+ readonly program: AstNode
22
+ readonly comments: readonly Comment[]
23
+ /** The UTF-8 size of the source text. */
24
+ readonly bytes: number
25
+ }
26
+
27
+ export type ParseResult = { readonly ok: true; readonly module: ParsedModule } | {
28
+ readonly ok: false
29
+ readonly message: string
30
+ readonly position: Position
31
+ }
32
+
33
+ const NON_CHILD_KEYS = new Set(['loc', 'range', 'start', 'end', 'extra', 'leadingComments', 'trailingComments', 'innerComments'])
34
+
35
+ const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> => typeof value === 'object' && value !== null
36
+
37
+ export const isNode = (value: unknown): value is AstNode => isRecord(value) && typeof value['type'] === 'string'
38
+
39
+ /** Whether the source wraps a node in parentheses, which the parser records beside the node rather than as one. */
40
+ export const isParenthesized = (node: AstNode): boolean => {
41
+ const extra = node['extra']
42
+ return isRecord(extra) && extra['parenthesized'] === true
43
+ }
44
+
45
+ export const child = (node: AstNode, key: string): AstNode | undefined => {
46
+ const value = node[key]
47
+ return isNode(value) ? value : undefined
48
+ }
49
+
50
+ /** The nodes of an array property; holes (`[a, , b]`) come back as `null`. */
51
+ export const children = (node: AstNode, key: string): readonly (AstNode | null)[] => {
52
+ const value = node[key]
53
+ return Array.isArray(value) ? value.map((item) => (isNode(item) ? item : null)) : []
54
+ }
55
+
56
+ export const stringField = (node: AstNode, key: string): string | undefined => {
57
+ const value = node[key]
58
+ return typeof value === 'string' ? value : undefined
59
+ }
60
+
61
+ /** The name of an `Identifier`, or `undefined` for any other node. */
62
+ export const identifierName = (node: AstNode | undefined): string | undefined => (node?.type === 'Identifier' ? stringField(node, 'name') : undefined)
63
+
64
+ /** The text of a node whose value is a fixed string: a string `Literal`, or a template with no `${…}`. */
65
+ export const staticString = (node: AstNode | undefined): string | undefined => {
66
+ if (node?.type === 'Literal') {
67
+ const value = node['value']
68
+ return typeof value === 'string' ? value : undefined
69
+ }
70
+ if (node?.type !== 'TemplateLiteral' || children(node, 'expressions').length > 0) return undefined
71
+ const quasi = children(node, 'quasis')[0]
72
+ return quasi ? templateText(quasi).cooked : undefined
73
+ }
74
+
75
+ /** A `TemplateElement`'s source text and its decoded value (`undefined` for an invalid escape in a tagged template). */
76
+ export const templateText = (element: AstNode): { readonly raw: string; readonly cooked: string | undefined } => {
77
+ const value = element['value']
78
+ if (!isRecord(value)) return { raw: '', cooked: undefined }
79
+ const raw = typeof value['raw'] === 'string' ? value['raw'] : ''
80
+ return { raw, cooked: typeof value['cooked'] === 'string' ? value['cooked'] : undefined }
81
+ }
82
+
83
+ /** A property or member key read statically: `a.b`, `a['b']`, ``a[`b`]``, `{ b: … }`, `{ 'b': … }`. */
84
+ export const staticKey = (node: AstNode, keyField: 'property' | 'key'): string | undefined => {
85
+ const key = child(node, keyField)
86
+ if (node['computed'] === true) return staticString(key)
87
+ return identifierName(key) ?? staticString(key)
88
+ }
89
+
90
+ /** The static property names at the end of a member chain, whatever its root: `load().db.sql.raw` → `['db', 'sql', 'raw']`. */
91
+ export const memberSuffix = (node: AstNode): readonly string[] => {
92
+ const names: string[] = []
93
+ let current = unwrap(node)
94
+ while (current.type === 'MemberExpression') {
95
+ const name = staticKey(current, 'property')
96
+ const object = child(current, 'object')
97
+ if (name === undefined || object === undefined) break
98
+ names.unshift(name)
99
+ current = unwrap(object)
100
+ }
101
+ return names
102
+ }
103
+
104
+ /** `as const` and `<const>x` fix a literal's type; they assert nothing. */
105
+ export const isConstAssertion = (node: AstNode): boolean => {
106
+ const type = child(node, 'typeAnnotation')
107
+ return type?.type === 'TSTypeReference' && identifierName(child(type, 'typeName')) === 'const'
108
+ }
109
+
110
+ /** Strips the wrappers that do not change which value an expression denotes. */
111
+ export const unwrap = (node: AstNode): AstNode => {
112
+ let current = node
113
+ while (current.type === 'ChainExpression' || current.type === 'TSNonNullExpression' || current.type === 'ParenthesizedExpression') {
114
+ const inner = child(current, 'expression')
115
+ if (inner === undefined) return current
116
+ current = inner
117
+ }
118
+ return current
119
+ }
120
+
121
+ /** `a.b.c` as `['a', 'b', 'c']`; `undefined` when a link is computed or the root is not an identifier. */
122
+ export const memberPath = (node: AstNode): readonly string[] | undefined => {
123
+ const current = unwrap(node)
124
+ const root = identifierName(current)
125
+ if (root !== undefined) return [root]
126
+ if (current.type === 'MetaProperty') return ['import.meta']
127
+ if (current.type !== 'MemberExpression') return undefined
128
+ const object = child(current, 'object')
129
+ const property = staticKey(current, 'property')
130
+ if (object === undefined || property === undefined) return undefined
131
+ const base = memberPath(object)
132
+ return base === undefined ? undefined : [...base, property]
133
+ }
134
+
135
+ const TYPE_POSITION_EXCEPTIONS = new Set([
136
+ 'TSAsExpression',
137
+ 'TSSatisfiesExpression',
138
+ 'TSNonNullExpression',
139
+ 'TSTypeAssertion',
140
+ 'TSInstantiationExpression',
141
+ ])
142
+
143
+ /** Whether an `Identifier` denotes a runtime value here, rather than a property name, a key, a label or a type. */
144
+ export const isValueReference = (node: AstNode, parent: AstNode | undefined): boolean => {
145
+ if (parent === undefined) return true
146
+ const computed = parent['computed'] === true
147
+ switch (parent.type) {
148
+ case 'MemberExpression':
149
+ return parent['object'] === node || computed
150
+ case 'Property':
151
+ return parent['value'] === node || computed || parent['shorthand'] === true
152
+ case 'PropertyDefinition':
153
+ case 'MethodDefinition':
154
+ case 'TSPropertySignature':
155
+ return parent['value'] === node || computed
156
+ case 'ImportSpecifier':
157
+ case 'ImportDefaultSpecifier':
158
+ case 'ImportNamespaceSpecifier':
159
+ case 'ExportSpecifier':
160
+ case 'LabeledStatement':
161
+ case 'BreakStatement':
162
+ case 'ContinueStatement':
163
+ case 'MetaProperty':
164
+ return false
165
+ default:
166
+ return !parent.type.startsWith('TS') || TYPE_POSITION_EXCEPTIONS.has(parent.type)
167
+ }
168
+ }
169
+
170
+ export const positionOf = (node: AstNode): Position => {
171
+ const loc = node['loc']
172
+ if (isRecord(loc)) {
173
+ const start = loc['start']
174
+ if (isRecord(start) && typeof start['line'] === 'number' && typeof start['column'] === 'number') {
175
+ return { line: start['line'], column: start['column'] + 1 }
176
+ }
177
+ }
178
+ return { line: 1, column: 1 }
179
+ }
180
+
181
+ /** Visits every node below `root`, depth first, with the chain of its ancestors (nearest last); `'skip'` prunes a subtree. */
182
+ export const walk = (root: AstNode, visit: (node: AstNode, ancestors: readonly AstNode[]) => 'skip' | undefined | void): void => {
183
+ const ancestors: AstNode[] = []
184
+ const enter = (node: AstNode): void => {
185
+ if (visit(node, ancestors) === 'skip') return
186
+ ancestors.push(node)
187
+ for (const [key, value] of Object.entries(node)) {
188
+ if (NON_CHILD_KEYS.has(key)) continue
189
+ if (isNode(value)) enter(value)
190
+ else if (Array.isArray(value)) {
191
+ for (const item of value) if (isNode(item)) enter(item)
192
+ }
193
+ }
194
+ ancestors.pop()
195
+ }
196
+ enter(root)
197
+ }
198
+
199
+ const pluginsFor = (file: string): ParserPlugin[] => {
200
+ if (file.endsWith('.d.ts') || file.endsWith('.d.mts') || file.endsWith('.d.cts')) return [['typescript', { dts: true }], 'estree']
201
+ if (file.endsWith('.tsx')) return ['typescript', 'jsx', 'estree']
202
+ if (file.endsWith('.jsx')) return ['jsx', 'estree']
203
+ if (/\.[mc]?ts$/.test(file)) return ['typescript', 'estree']
204
+ return ['estree']
205
+ }
206
+
207
+ const readComments = (value: unknown): Comment[] => {
208
+ if (!Array.isArray(value)) return []
209
+ const comments: Comment[] = []
210
+ for (const item of value) {
211
+ if (!isNode(item)) continue
212
+ const text = stringField(item, 'value')
213
+ if (text !== undefined) comments.push({ text, position: positionOf(item) })
214
+ }
215
+ return comments
216
+ }
217
+
218
+ const syntaxErrorPosition = (error: unknown): Position => {
219
+ if (isRecord(error)) {
220
+ const loc = error['loc']
221
+ if (isRecord(loc) && typeof loc['line'] === 'number' && typeof loc['column'] === 'number') return { line: loc['line'], column: loc['column'] + 1 }
222
+ }
223
+ return { line: 1, column: 1 }
224
+ }
225
+
226
+ export const utf8Bytes = (text: string): number => new TextEncoder().encode(text).byteLength
227
+
228
+ /** The nesting depth of the tree below `root`, measured without recursion, so a deep tree cannot exhaust the stack. */
229
+ export const nodeDepth = (root: AstNode): number => {
230
+ let deepest = 0
231
+ const pending: [AstNode, number][] = [[root, 1]]
232
+ for (let entry = pending.pop(); entry !== undefined; entry = pending.pop()) {
233
+ const [node, depth] = entry
234
+ deepest = Math.max(deepest, depth)
235
+ for (const [key, value] of Object.entries(node)) {
236
+ if (NON_CHILD_KEYS.has(key)) continue
237
+ if (isNode(value)) pending.push([value, depth + 1])
238
+ else if (Array.isArray(value)) {
239
+ for (const item of value) if (isNode(item)) pending.push([item, depth + 1])
240
+ }
241
+ }
242
+ }
243
+ return deepest
244
+ }
245
+
246
+ export const parseModule = (file: string, text: string): ParseResult => {
247
+ try {
248
+ const ast = parse(text, { sourceType: 'module', sourceFilename: file, plugins: pluginsFor(file) })
249
+ const program: unknown = ast.program
250
+ if (!isNode(program)) return { ok: false, message: 'the parser returned no program', position: { line: 1, column: 1 } }
251
+ return { ok: true, module: { file, program, comments: readComments(ast.comments), bytes: utf8Bytes(text) } }
252
+ } catch (error) {
253
+ const message = error instanceof Error ? (error.message.split('\n')[0] ?? error.message) : 'unparseable source'
254
+ return { ok: false, message, position: syntaxErrorPosition(error) }
255
+ }
256
+ }
257
+
258
+ /** The sources of a module's import and re-export declarations; `rules/literal.ts` decides which of them are allowed. */
259
+ export const importedSpecifiers = (module: ParsedModule): string[] => {
260
+ const specifiers: string[] = []
261
+ for (const statement of children(module.program, 'body')) {
262
+ const source = statement === null ? undefined : staticString(child(statement, 'source'))
263
+ if (source !== undefined && statement?.['importKind'] !== 'type' && statement?.['exportKind'] !== 'type') {
264
+ specifiers.push(source)
265
+ }
266
+ }
267
+ return specifiers
268
+ }
@@ -0,0 +1,63 @@
1
+ // @fabrika/check/bun-plugin — a Bun build of the SPA that imports `fabrika.contract.ts` without its handlers. The
2
+ // typed client needs the contract's values (its paths and output schemas), never a handler or what only a handler
3
+ // imports. The plugin reads the shell graph as Control does, refuses the build when the reader refuses it, and loads
4
+ // each shell module as its slice; every other module loads as it is.
5
+
6
+ import type { BunPlugin, Loader } from 'bun'
7
+ import { readFileSync, realpathSync, statSync } from 'node:fs'
8
+ import { join, resolve } from 'node:path'
9
+ import { contractReaderInputs, readContract } from './contract'
10
+ import { CONTRACT_FILE, isSourceFile } from './layout'
11
+ import { shellSlice } from './slice'
12
+
13
+ const SOURCE_EXTENSION = String.raw`\.(?:[mc]?[jt]s|[jt]sx)$`
14
+
15
+ /** The application's own modules under `root`, outside `node_modules`: every extension the reader reads. */
16
+ const applicationModules = (root: string): RegExp =>
17
+ new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\/](?!(?:.*[\\/])?node_modules[\\/]).*${SOURCE_EXTENSION}`)
18
+
19
+ export interface ShellSliceOptions {
20
+ /** The application's root, where `fabrika.contract.ts` lies; the working directory by default. */
21
+ readonly root?: string
22
+ }
23
+
24
+ /**
25
+ * Loads every module of the application's shell graph as its slice: no `.handle(…)`, and no import only a handler
26
+ * used. The build fails with the reader's findings when the static reader refuses the shell.
27
+ */
28
+ export function shellSlicePlugin(options: ShellSliceOptions = {}): BunPlugin {
29
+ return {
30
+ name: 'fabrika-shell-slice',
31
+ setup(build) {
32
+ const root = realpathSync(resolve(options.root ?? process.cwd()))
33
+ let shell: ReadonlyMap<string, string> | undefined
34
+ build.onLoad({ filter: applicationModules(root) }, (args) => {
35
+ shell ??= shellModules(root)
36
+ return { contents: shell.get(args.path) ?? readFileSync(args.path, 'utf8'), loader: loaderOf(args.path) }
37
+ })
38
+ },
39
+ }
40
+ }
41
+
42
+ export default shellSlicePlugin()
43
+
44
+ const isFile = (path: string): boolean => statSync(path, { throwIfNoEntry: false })?.isFile() === true
45
+
46
+ /** The shell modules under `root`, by absolute path, as their slices; none without a `fabrika.contract.ts` there. */
47
+ function shellModules(root: string): ReadonlyMap<string, string> {
48
+ if (!isFile(join(root, CONTRACT_FILE))) return new Map()
49
+ const files = new Map<string, string>()
50
+ for (;;) {
51
+ const missing = contractReaderInputs(files, (path) => isFile(join(root, path)))
52
+ if (missing.length === 0) break
53
+ for (const path of missing) files.set(path, readFileSync(join(root, path), 'utf8'))
54
+ }
55
+ readContract(files)
56
+ return new Map([...files].filter(([path]) => isSourceFile(path)).map(([path, text]) => [join(root, path), shellSlice(path, text).text]))
57
+ }
58
+
59
+ function loaderOf(path: string): Loader {
60
+ if (path.endsWith('.tsx')) return 'tsx'
61
+ if (path.endsWith('.jsx')) return 'jsx'
62
+ return /\.[mc]?ts$/.test(path) ? 'ts' : 'js'
63
+ }
package/src/check.ts ADDED
@@ -0,0 +1,183 @@
1
+ import { readdir, readFile } from 'node:fs/promises'
2
+ import { join } from 'node:path'
3
+ import { type ParsedModule, parseModule, walk } from './ast'
4
+ import { contractModules, readContractModule } from './contract'
5
+ import { compareFindings, type Finding, reporter } from './finding'
6
+ import { ModuleGraph } from './graph'
7
+ import {
8
+ CONTRACT_FILE,
9
+ GENERATED_ENTRY_FILE,
10
+ isCheckedFile,
11
+ isIgnoredSegment,
12
+ isJsonFile,
13
+ isServerModule,
14
+ isSourceFile,
15
+ isTestFile,
16
+ TABLES_FILE,
17
+ ZEROPS_FILES,
18
+ } from './layout'
19
+ import type { PackedSet } from './packed'
20
+ import { type ModuleReference, moduleReferences } from './references'
21
+ import { type ImportMappings, readImportMappings } from './resolution'
22
+ import { checkContractRead } from './rules/contract'
23
+ import { checkCrontab, contractJobs } from './rules/crontab'
24
+ import { checkFrameworkWrite, trustedBindings } from './rules/framework'
25
+ import { checkClientIdentity } from './rules/identity'
26
+ import { checkGeneratedTests } from './rules/isolation'
27
+ import { checkJsonStrings } from './rules/json'
28
+ import { checkLiteralGraph } from './rules/literal'
29
+ import { checkMigrationNames, checkScanMigrations } from './rules/migrations'
30
+ import { checkModuleReferences } from './rules/modules'
31
+ import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
32
+ import { checkRuntimeNode, rawSqlBindings } from './rules/runtime'
33
+ import { checkStructureNode, checkStructureReferences, structurePlace } from './rules/structure'
34
+ import { checkGeneratedTest, checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
35
+ import { checkComments, checkTypeNode } from './rules/types'
36
+ import { moduleSlice, sliceFinding } from './slice'
37
+ import { BUNFIG_FILE, checkTrustedResolution } from './trust'
38
+
39
+ export interface CheckInput {
40
+ /** The application's root directory. */
41
+ readonly root: string
42
+ /** The application's files keyed by path relative to `root` with `/` separators; read from disk under `root` when omitted. */
43
+ readonly files?: ReadonlyMap<string, string>
44
+ /** A local pack whose tarballs `package-replacement` accepts (`fabrika-check --packed`); a deploy build gives none. */
45
+ readonly packed?: PackedSet
46
+ }
47
+
48
+ export interface ApplicationTree {
49
+ readonly files: ReadonlyMap<string, string>
50
+ /** Symbolic links outside the skipped directories; the checker does not follow them. */
51
+ readonly links: readonly string[]
52
+ }
53
+
54
+ /** Every file the checker reads, by relative path, and the symbolic links it refuses to follow. */
55
+ export const readApplicationTree = async (root: string): Promise<ApplicationTree> => {
56
+ const files = new Map<string, string>()
57
+ const links: string[] = []
58
+ const visit = async (relativeDirectory: string): Promise<void> => {
59
+ const entries = await readdir(join(root, relativeDirectory), { withFileTypes: true })
60
+ for (const entry of entries.sort((left, right) => left.name.localeCompare(right.name))) {
61
+ const path = relativeDirectory === '' ? entry.name : `${relativeDirectory}/${entry.name}`
62
+ if (isIgnoredSegment(entry.name) && !isCheckedFile(path)) continue
63
+ if (entry.isSymbolicLink()) links.push(path)
64
+ else if (entry.isDirectory()) await visit(path)
65
+ else if (entry.isFile() && isCheckedFile(path)) files.set(path, await readFile(join(root, path), 'utf8'))
66
+ }
67
+ }
68
+ await visit('')
69
+ return { files, links }
70
+ }
71
+
72
+ const checkSourceModule = async (
73
+ module: ParsedModule,
74
+ references: readonly ModuleReference[],
75
+ text: string,
76
+ mappings: ImportMappings,
77
+ files: ReadonlyMap<string, string>,
78
+ findings: Finding[],
79
+ ): Promise<void> => {
80
+ const exists = (path: string): boolean => files.has(path)
81
+ const report = reporter(module.file, findings)
82
+ const isGeneratedEntry = module.file === GENERATED_ENTRY_FILE
83
+ const isTest = isTestFile(module.file)
84
+ const context = { report, isGeneratedEntry, rawSql: rawSqlBindings(module.program), isServerModule: isServerModule(module.file) }
85
+ const trusted = trustedBindings(module.file, module.program, mappings)
86
+ const place = structurePlace(module.file, isGeneratedEntry)
87
+ walk(module.program, (node, ancestors) => {
88
+ checkRuntimeNode(node, ancestors, context)
89
+ checkFrameworkWrite(node, ancestors, trusted, report)
90
+ checkTypeNode(node, report)
91
+ checkAmbientModule(node, report)
92
+ if (isTest) checkTestNode(node, ancestors, report)
93
+ checkMockModule(node, module.file, files, report)
94
+ checkStructureNode(place, node, report)
95
+ })
96
+ checkComments(module.comments, report)
97
+ checkModuleReferences(module.file, references, mappings, exists, report, isGeneratedEntry, isTest)
98
+ await checkGeneratedTest(text, module.comments, report)
99
+ }
100
+
101
+ /** `module` as its shell slice (itself when it holds no colocated handler), and the `.handle(…)` forms it refused. */
102
+ const shellModule = (module: ParsedModule, text: string): { readonly module: ParsedModule; readonly refusals: readonly Finding[] } => {
103
+ const slice = moduleSlice(module, text)
104
+ const refusals = slice.refusals.map((refusal) => sliceFinding(module, refusal))
105
+ const parsed = slice.text === text ? undefined : parseModule(module.file, slice.text)
106
+ return { module: parsed?.ok === true ? parsed.module : module, refusals }
107
+ }
108
+
109
+ /** Runs every rule over one application and returns the findings in file, line and column order. */
110
+ export const checkApplication = async (input: CheckInput): Promise<Finding[]> => {
111
+ const tree: ApplicationTree = input.files === undefined ? await readApplicationTree(input.root) : { files: input.files, links: [] }
112
+ const findings: Finding[] = []
113
+ const modules = new Map<string, ParsedModule>()
114
+ const references = new Map<string, readonly ModuleReference[]>()
115
+ const checkedPaths = [...tree.files.keys()].filter(isCheckedFile).sort()
116
+ const mappings = readImportMappings(tree.files)
117
+ const trust = checkTrustedResolution(tree.files)
118
+ findings.push(...trust)
119
+ findings.push(...checkPackageReplacement(tree.files, input.packed))
120
+
121
+ for (const link of tree.links) {
122
+ findings.push({
123
+ file: link,
124
+ line: 1,
125
+ column: 1,
126
+ severity: 'refusal',
127
+ rule: 'unchecked-import',
128
+ message: 'a symbolic link, which the checker does not follow',
129
+ allowed: 'a regular file or directory inside the application',
130
+ })
131
+ }
132
+ for (const path of checkedPaths) {
133
+ const text = tree.files.get(path) ?? ''
134
+ if (isJsonFile(path)) checkJsonStrings(text, reporter(path, findings))
135
+ if (!isSourceFile(path)) continue
136
+ const parsed = parseModule(path, text)
137
+ if (!parsed.ok) {
138
+ reporter(path, findings)(parsed.position, 'parse-error', parsed.message, 'source the TypeScript parser accepts')
139
+ continue
140
+ }
141
+ modules.set(path, parsed.module)
142
+ const referencesOfModule = moduleReferences(parsed.module.program)
143
+ references.set(path, referencesOfModule)
144
+ await checkSourceModule(parsed.module, referencesOfModule, text, mappings, tree.files, findings)
145
+ }
146
+ const structure = { files: tree.files, mappings, referencesOf: (path: string) => references.get(path) ?? [] }
147
+ for (const path of modules.keys()) {
148
+ checkStructureReferences(structure, structurePlace(path, path === GENERATED_ENTRY_FILE), reporter(path, findings))
149
+ }
150
+
151
+ // The contract rules read each module's shell slice: a colocated handler, and what only it uses, is application
152
+ // code, which the rules above checked in full.
153
+ const shell = new Map([...modules].map(([path, module]) => [path, shellModule(module, tree.files.get(path) ?? '')]))
154
+ const graph = new ModuleGraph(new Map([...shell].map(([path, slice]) => [path, slice.module])))
155
+ const contract = graph.module(CONTRACT_FILE)
156
+ const tables = graph.module(TABLES_FILE)
157
+ const shellGraph = new Set(
158
+ [contract, tables].flatMap((entry) => (entry === undefined ? [] : contractModules(graph, entry))).map((module) => module.file),
159
+ )
160
+ const literal = [
161
+ ...[...shellGraph].flatMap((path) => shell.get(path)?.refusals ?? []),
162
+ ...checkLiteralGraph([CONTRACT_FILE, TABLES_FILE], graph),
163
+ ]
164
+ findings.push(...literal)
165
+ const contractRead = contract !== undefined && literal.length === 0 ? checkContractRead(graph) : []
166
+ findings.push(...contractRead)
167
+ for (const module of contract === undefined ? [] : contractModules(graph, contract)) findings.push(...checkClientIdentity(module, graph))
168
+ findings.push(...(await checkGeneratedTests(tree.files, literal.length === 0 && trust.length === 0 && contractRead.length === 0)))
169
+ findings.push(...checkMigrationNames(checkedPaths))
170
+ const read = contract !== undefined && literal.length === 0 && contractRead.length === 0 ? readContractModule(graph) : undefined
171
+ if (read?.ok === true) {
172
+ const scanning = Object.entries(read.contract.surface.files ?? {}).filter(([, collection]) => collection.scan === true).map(([name]) => name)
173
+ findings.push(...checkScanMigrations(tree.files, scanning))
174
+ }
175
+ const bunfig = tree.files.get(BUNFIG_FILE)
176
+ if (bunfig !== undefined) findings.push(...checkTestSuiteConfig(bunfig))
177
+ const jobs = contract === undefined ? [] : contractJobs(contract, graph)
178
+ for (const name of ZEROPS_FILES) {
179
+ const text = tree.files.get(name)
180
+ if (text !== undefined) findings.push(...checkCrontab(name, text, jobs))
181
+ }
182
+ return findings.sort(compareFindings)
183
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,88 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { readFile } from 'node:fs/promises'
4
+ import { resolve } from 'node:path'
5
+ import { checkApplication } from './check'
6
+ import { type Finding, formatFinding } from './finding'
7
+ import { type PackedSet, readPackedSet } from './packed'
8
+
9
+ const USAGE = `fabrika-check — the application checker
10
+
11
+ Usage:
12
+ fabrika-check [--packed <release-manifest.json>] [<root>]
13
+
14
+ Checks the application in <root> (default: the current directory) and prints one line per finding:
15
+ <file>:<line>:<column> <rule> <message> (allowed form: <what to write instead>)
16
+
17
+ --packed accepts the tarballs of a local pack (bun scripts/release.ts pack --local) in place of registry versions:
18
+ file: specifiers and overrides of its @fabrika/* packages, and their lockfile entries, when each tarball's bytes
19
+ match the sha512 the manifest records. Only a local or dogfood setup passes it; the platform build never does.
20
+
21
+ A refusal fails the check. A hint, printed under its own heading after the refusals, reports a step out of the
22
+ application architecture and does not fail it.
23
+
24
+ Exit status: 0 with no refusals, 1 with a refusal, 2 on a usage or read error.
25
+ There is no suppression syntax; a finding is fixed in the code.
26
+ `
27
+
28
+ const HINTS_HEADING = 'Hints — the application architecture; they do not fail the check:'
29
+
30
+ const count = (amount: number, noun: string): string => `${amount} ${noun}${amount === 1 ? '' : 's'}`
31
+
32
+ interface Arguments {
33
+ readonly root: string | undefined
34
+ readonly packed: string | undefined
35
+ }
36
+
37
+ /** The root and the `--packed` manifest, or the first argument the checker does not take. */
38
+ const parseArguments = (argv: readonly string[]): Arguments | { readonly unexpected: string } => {
39
+ let root: string | undefined
40
+ let packed: string | undefined
41
+ for (let index = 0; index < argv.length; index++) {
42
+ const argument = argv[index] ?? ''
43
+ if (argument === '--packed' && packed === undefined && argv[index + 1] !== undefined) packed = argv[++index]
44
+ else if (argument.startsWith('--packed=') && packed === undefined) packed = argument.slice('--packed='.length)
45
+ else if (argument.startsWith('-') || root !== undefined) return { unexpected: argument }
46
+ else root = argument
47
+ }
48
+ return { root, packed }
49
+ }
50
+
51
+ const main = async (argv: readonly string[]): Promise<number> => {
52
+ if (argv.includes('--help') || argv.includes('-h')) {
53
+ console.log(USAGE)
54
+ return 0
55
+ }
56
+ const parsed = parseArguments(argv)
57
+ if ('unexpected' in parsed) {
58
+ console.error(`fabrika-check: unexpected argument '${parsed.unexpected}'\n\n${USAGE}`)
59
+ return 2
60
+ }
61
+ const root = resolve(parsed.root ?? '.')
62
+ let packed: PackedSet | undefined
63
+ if (parsed.packed !== undefined) {
64
+ try {
65
+ packed = await readPackedSet(root, await readFile(resolve(parsed.packed), 'utf8'))
66
+ } catch (error) {
67
+ console.error(`fabrika-check: cannot read the packed set ${parsed.packed}: ${error instanceof Error ? error.message : 'unknown error'}`)
68
+ return 2
69
+ }
70
+ console.error(`fabrika-check: accepting the tarballs of the local pack ${packed.version}, which no deploy build does`)
71
+ }
72
+ let findings: Finding[]
73
+ try {
74
+ findings = await checkApplication({ root, packed })
75
+ } catch (error) {
76
+ console.error(`fabrika-check: cannot read ${root}: ${error instanceof Error ? error.message : 'unknown error'}`)
77
+ return 2
78
+ }
79
+ const refusals = findings.filter((finding) => finding.severity === 'refusal')
80
+ const hints = findings.filter((finding) => finding.severity === 'hint')
81
+ for (const finding of refusals) console.log(formatFinding(finding))
82
+ if (hints.length > 0) console.log(HINTS_HEADING)
83
+ for (const finding of hints) console.log(formatFinding(finding))
84
+ console.error(`fabrika-check: ${count(refusals.length, 'refusal')}, ${count(hints.length, 'hint')}`)
85
+ return refusals.length === 0 ? 0 : 1
86
+ }
87
+
88
+ process.exitCode = await main(process.argv.slice(2))