@fabrika/check 0.9.0-dev.23 → 0.9.0-dev.27
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 +11 -6
- package/src/bun-plugin.ts +4 -27
- package/src/check.ts +2 -1
- package/src/contract.ts +2 -2
- package/src/finding.ts +7 -1
- package/src/graph.ts +49 -12
- package/src/reader/surface.ts +5 -2
- package/src/reader/value.ts +23 -2
- package/src/rules/contract.ts +3 -2
- package/src/rules/identity.ts +6 -9
- package/src/rules/literal.ts +39 -8
- package/src/rules/structure.ts +135 -2
- package/src/shell-modules.ts +32 -0
- package/src/vite-plugin.ts +64 -0
- package/types/src/contract.d.ts +1 -1
- package/types/src/finding.d.ts +3 -3
- package/types/src/graph.d.ts +12 -2
- package/types/src/reader/value.d.ts +1 -1
- package/types/src/rules/literal.d.ts +1 -1
- package/types/src/rules/structure.d.ts +8 -1
- package/types/src/shell-modules.d.ts +7 -0
- package/types/src/vite-plugin.d.ts +27 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/check",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.27",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -35,6 +35,11 @@
|
|
|
35
35
|
"types": "./types/src/bun-plugin.d.ts",
|
|
36
36
|
"default": "./src/bun-plugin.ts"
|
|
37
37
|
},
|
|
38
|
+
"./vite-plugin": {
|
|
39
|
+
"bun": "./src/vite-plugin.ts",
|
|
40
|
+
"types": "./types/src/vite-plugin.d.ts",
|
|
41
|
+
"default": "./src/vite-plugin.ts"
|
|
42
|
+
},
|
|
38
43
|
"./source-maps": {
|
|
39
44
|
"bun": "./src/source-maps.ts",
|
|
40
45
|
"types": "./types/src/source-maps.d.ts",
|
|
@@ -47,11 +52,11 @@
|
|
|
47
52
|
},
|
|
48
53
|
"dependencies": {
|
|
49
54
|
"@babel/parser": "8.0.7",
|
|
50
|
-
"@fabrika/app": "0.9.0-dev.
|
|
51
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
52
|
-
"@fabrika/db": "0.9.0-dev.
|
|
53
|
-
"@fabrika/operations-contract": "0.9.0-dev.
|
|
54
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
55
|
+
"@fabrika/app": "0.9.0-dev.27",
|
|
56
|
+
"@fabrika/auth-core": "0.9.0-dev.27",
|
|
57
|
+
"@fabrika/db": "0.9.0-dev.27",
|
|
58
|
+
"@fabrika/operations-contract": "0.9.0-dev.27",
|
|
59
|
+
"@fabrika/platform-node": "0.9.0-dev.27",
|
|
55
60
|
"zod": "^3.25.76"
|
|
56
61
|
}
|
|
57
62
|
}
|
package/src/bun-plugin.ts
CHANGED
|
@@ -1,20 +1,12 @@
|
|
|
1
1
|
// @fabrika/check/bun-plugin — a Bun build of the SPA that imports `fabrika.contract.ts` without its handlers. The
|
|
2
2
|
// typed client needs the contract's values (its paths and output schemas), never a handler or what only a handler
|
|
3
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.
|
|
4
|
+
// each shell module as its slice; every other module loads as it is. `@fabrika/check/vite-plugin` is the same for Vite.
|
|
5
5
|
|
|
6
6
|
import type { BunPlugin, Loader } from 'bun'
|
|
7
|
-
import { readFileSync, realpathSync
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
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}`)
|
|
7
|
+
import { readFileSync, realpathSync } from 'node:fs'
|
|
8
|
+
import { resolve } from 'node:path'
|
|
9
|
+
import { applicationModules, shellModules } from './shell-modules'
|
|
18
10
|
|
|
19
11
|
export interface ShellSliceOptions {
|
|
20
12
|
/** The application's root, where `fabrika.contract.ts` lies; the working directory by default. */
|
|
@@ -41,21 +33,6 @@ export function shellSlicePlugin(options: ShellSliceOptions = {}): BunPlugin {
|
|
|
41
33
|
|
|
42
34
|
export default shellSlicePlugin()
|
|
43
35
|
|
|
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
36
|
function loaderOf(path: string): Loader {
|
|
60
37
|
if (path.endsWith('.tsx')) return 'tsx'
|
|
61
38
|
if (path.endsWith('.jsx')) return 'jsx'
|
package/src/check.ts
CHANGED
|
@@ -50,7 +50,7 @@ import { checkModuleReferences } from './rules/modules'
|
|
|
50
50
|
import { checkAmbientModule, checkPackageReplacement } from './rules/packages'
|
|
51
51
|
import { checkBackupPlan, checkMigrationClassification } from './rules/platform-migrations'
|
|
52
52
|
import { checkKeyLiteralNode, checkRuntimeNode, crossAppFetchMessage, rawSqlBindings } from './rules/runtime'
|
|
53
|
-
import { checkStructureNode, checkStructureReferences, checkToolPackages, structurePlace } from './rules/structure'
|
|
53
|
+
import { checkSingleSliceQueries, checkStructureNode, checkStructureReferences, checkToolPackages, structurePlace } from './rules/structure'
|
|
54
54
|
import { checkMockModule, checkTestNode, checkTestSuiteConfig } from './rules/tests'
|
|
55
55
|
import { checkCapabilityNode, checkComments, checkTypeNode } from './rules/types'
|
|
56
56
|
import { moduleSlice, sliceFinding } from './slice'
|
|
@@ -334,6 +334,7 @@ export const checkApplication = async (input: CheckInput): Promise<Finding[]> =>
|
|
|
334
334
|
for (const path of modules.keys()) {
|
|
335
335
|
checkStructureReferences(structure, structurePlace(path, path === GENERATED_ENTRY_FILE, generated.has(path)), reporter(path, findings))
|
|
336
336
|
}
|
|
337
|
+
findings.push(...checkSingleSliceQueries(structure, new Map([...modules].map(([path, module]) => [path, module.program]))))
|
|
337
338
|
|
|
338
339
|
// The contract rules read each module's shell slice: a colocated handler, and what only it uses, is application
|
|
339
340
|
// code, which the rules above checked in full.
|
package/src/contract.ts
CHANGED
|
@@ -142,7 +142,7 @@ export function readContractModule(graph: ModuleGraph): ContractRead {
|
|
|
142
142
|
return contract === null || problems.findings.length > 0 ? { ok: false, findings: problems.findings } : { ok: true, contract }
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
-
/** The contract module and every module its value imports reach. */
|
|
145
|
+
/** The contract module and every module its value imports and re-exports reach. */
|
|
146
146
|
export function contractModules(graph: ModuleGraph, entry: ParsedModule): ParsedModule[] {
|
|
147
147
|
const reached = new Map<string, ParsedModule>()
|
|
148
148
|
const queue = [entry]
|
|
@@ -151,7 +151,7 @@ export function contractModules(graph: ModuleGraph, entry: ParsedModule): Parsed
|
|
|
151
151
|
continue
|
|
152
152
|
}
|
|
153
153
|
reached.set(module.file, module)
|
|
154
|
-
for (const imported of graph.
|
|
154
|
+
for (const imported of graph.links(module)) {
|
|
155
155
|
const target = graph.resolve(module.file, imported.specifier)
|
|
156
156
|
if (target !== undefined) {
|
|
157
157
|
queue.push(target)
|
package/src/finding.ts
CHANGED
|
@@ -49,7 +49,13 @@ export const REFUSAL_RULE_IDS = [
|
|
|
49
49
|
] as const
|
|
50
50
|
|
|
51
51
|
/** Rules that report a step out of the application architecture. */
|
|
52
|
-
export const STRUCTURE_HINT_RULE_IDS = [
|
|
52
|
+
export const STRUCTURE_HINT_RULE_IDS = [
|
|
53
|
+
'logic-data-access',
|
|
54
|
+
'cross-slice-queries',
|
|
55
|
+
'single-slice-queries',
|
|
56
|
+
'handler-location',
|
|
57
|
+
'data-access-location',
|
|
58
|
+
] as const
|
|
53
59
|
|
|
54
60
|
/**
|
|
55
61
|
* Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
|
package/src/graph.ts
CHANGED
|
@@ -41,6 +41,8 @@ interface ModuleIndex {
|
|
|
41
41
|
readonly imports: ReadonlyMap<string, ImportBinding>
|
|
42
42
|
/** Exported name → the local name it exports, or the default export's expression. */
|
|
43
43
|
readonly exports: ReadonlyMap<string, string | AstNode>
|
|
44
|
+
/** `export { x as y } from './m'`: the exported name (`local`) → the module and the name it takes from it. */
|
|
45
|
+
readonly reexports: ReadonlyMap<string, ImportBinding>
|
|
44
46
|
}
|
|
45
47
|
|
|
46
48
|
const importedName = (specifier: AstNode): string => {
|
|
@@ -55,6 +57,7 @@ const indexModule = (module: ParsedModule): ModuleIndex => {
|
|
|
55
57
|
const others = new Set<string>()
|
|
56
58
|
const imports = new Map<string, ImportBinding>()
|
|
57
59
|
const exports = new Map<string, string | AstNode>()
|
|
60
|
+
const reexports = new Map<string, ImportBinding>()
|
|
58
61
|
for (const statement of children(module.program, 'body')) {
|
|
59
62
|
if (statement === null) continue
|
|
60
63
|
if (statement.type === 'ImportDeclaration') {
|
|
@@ -73,13 +76,17 @@ const indexModule = (module: ParsedModule): ModuleIndex => {
|
|
|
73
76
|
continue
|
|
74
77
|
}
|
|
75
78
|
const isExport = statement.type === 'ExportNamedDeclaration'
|
|
76
|
-
|
|
79
|
+
const source = isExport ? staticString(child(statement, 'source')) : undefined
|
|
80
|
+
if (isExport && stringField(statement, 'exportKind') !== 'type') {
|
|
77
81
|
for (const item of children(statement, 'specifiers')) {
|
|
78
82
|
if (item === null || stringField(item, 'exportKind') === 'type') continue
|
|
79
|
-
const
|
|
83
|
+
const localNode = child(item, 'local')
|
|
84
|
+
const local = identifierName(localNode) ?? staticString(localNode)
|
|
80
85
|
const exported = child(item, 'exported')
|
|
81
86
|
const name = identifierName(exported) ?? staticString(exported)
|
|
82
|
-
if (local
|
|
87
|
+
if (local === undefined || name === undefined) continue
|
|
88
|
+
if (source === undefined) exports.set(name, local)
|
|
89
|
+
else reexports.set(name, { local: name, specifier: source, imported: local, node: item })
|
|
83
90
|
}
|
|
84
91
|
}
|
|
85
92
|
const declaration = isExport ? child(statement, 'declaration') : statement
|
|
@@ -103,7 +110,7 @@ const indexModule = (module: ParsedModule): ModuleIndex => {
|
|
|
103
110
|
}
|
|
104
111
|
if (isExport) { for (const name of declared) exports.set(name, name) }
|
|
105
112
|
}
|
|
106
|
-
return { consts, others, imports, exports }
|
|
113
|
+
return { consts, others, imports, exports, reexports }
|
|
107
114
|
}
|
|
108
115
|
|
|
109
116
|
/** Erased wrappers: `x satisfies T`, `x as const`, parentheses. */
|
|
@@ -143,6 +150,12 @@ export class ModuleGraph {
|
|
|
143
150
|
return resolveRelative((path) => this.#modules.has(path), from, specifier)
|
|
144
151
|
}
|
|
145
152
|
|
|
153
|
+
/** What a module loads by name: its value imports and its re-exports. */
|
|
154
|
+
links(module: ParsedModule): readonly ImportBinding[] {
|
|
155
|
+
const index = this.index(module)
|
|
156
|
+
return [...index.imports.values(), ...index.reexports.values()]
|
|
157
|
+
}
|
|
158
|
+
|
|
146
159
|
/** The checked module a relative specifier names; none when two candidates compete, the index of a directory import. */
|
|
147
160
|
resolve(from: string, specifier: string): ParsedModule | undefined {
|
|
148
161
|
if (!isRelativeSpecifier(specifier)) return undefined
|
|
@@ -169,7 +182,17 @@ export class ModuleGraph {
|
|
|
169
182
|
|
|
170
183
|
/** What an exported name of `module` denotes. */
|
|
171
184
|
exported(module: ParsedModule, name: string, seen: ReadonlySet<string> = new Set()): Binding {
|
|
172
|
-
const
|
|
185
|
+
const index = this.index(module)
|
|
186
|
+
const reexported = index.reexports.get(name)
|
|
187
|
+
if (reexported !== undefined) {
|
|
188
|
+
const key = `${module.file}#export ${name}`
|
|
189
|
+
if (seen.has(key)) return { kind: 'unresolved', reason: `'${name}' is re-exported in a cycle` }
|
|
190
|
+
if (!isRelativeSpecifier(reexported.specifier)) return { kind: 'package', specifier: reexported.specifier, imported: reexported.imported }
|
|
191
|
+
const target = this.resolve(module.file, reexported.specifier)
|
|
192
|
+
if (target === undefined) return { kind: 'unresolved', reason: `unresolved module '${reexported.specifier}'` }
|
|
193
|
+
return this.exported(target, reexported.imported, new Set([...seen, key]))
|
|
194
|
+
}
|
|
195
|
+
const exported = index.exports.get(name)
|
|
173
196
|
if (exported === undefined) return { kind: 'unresolved', reason: `'${module.file}' does not export '${name}'` }
|
|
174
197
|
if (typeof exported !== 'string') return { kind: 'default', module, expression: exported }
|
|
175
198
|
return this.binding(module, exported, seen)
|
|
@@ -194,13 +217,27 @@ export class ModuleGraph {
|
|
|
194
217
|
}
|
|
195
218
|
}
|
|
196
219
|
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
|
|
220
|
+
/**
|
|
221
|
+
* The entries of an object literal by key, in the order the object holds them, as evaluating it would build them: a
|
|
222
|
+
* spread of a value that resolves to an object literal contributes its entries, and a later key overrides an earlier
|
|
223
|
+
* one. A computed key, a method and a spread of anything else are not followed.
|
|
224
|
+
*/
|
|
225
|
+
export const objectEntries = (graph: ModuleGraph, located: Located, depth = 0): ReadonlyMap<string, Located> => {
|
|
226
|
+
const entries = new Map<string, Located>()
|
|
227
|
+
if (located.node.type !== 'ObjectExpression' || depth > 32) return entries
|
|
200
228
|
for (const property of children(located.node, 'properties')) {
|
|
201
|
-
if (property?.type
|
|
202
|
-
|
|
203
|
-
|
|
229
|
+
if (property?.type === 'SpreadElement') {
|
|
230
|
+
const argument = child(property, 'argument')
|
|
231
|
+
const spread = argument === undefined ? undefined : graph.resolveValue({ module: located.module, node: argument })
|
|
232
|
+
if (spread !== undefined) { for (const [key, value] of objectEntries(graph, spread, depth + 1)) entries.set(key, value) }
|
|
233
|
+
continue
|
|
234
|
+
}
|
|
235
|
+
const key = property?.type === 'Property' && property['computed'] !== true ? staticKey(property, 'key') : undefined
|
|
236
|
+
const value = property === null || key === undefined ? undefined : child(property, 'value')
|
|
237
|
+
if (key !== undefined && value !== undefined) entries.set(key, { module: located.module, node: value })
|
|
204
238
|
}
|
|
205
|
-
return
|
|
239
|
+
return entries
|
|
206
240
|
}
|
|
241
|
+
|
|
242
|
+
/** The value of `key` in an object literal, read statically through `objectEntries`. */
|
|
243
|
+
export const propertyValue = (graph: ModuleGraph, located: Located, key: string): Located | undefined => objectEntries(graph, located).get(key)
|
package/src/reader/surface.ts
CHANGED
|
@@ -833,6 +833,9 @@ interface ReadGroup {
|
|
|
833
833
|
const sameCallers = (left: readonly string[], right: readonly string[]): boolean =>
|
|
834
834
|
left.length === right.length && left.every((caller, index) => caller === right[index])
|
|
835
835
|
|
|
836
|
+
/** `defineApp`'s option fields. `caller` (`ctx.caller`) is the runtime's alone: the artifact carries nothing of it. */
|
|
837
|
+
const KIT_OPTIONS = ['imports', 'tokens', 'caller']
|
|
838
|
+
|
|
836
839
|
/**
|
|
837
840
|
* The kit's imports from `defineApp`'s options: each snapshot's identity, the procedures it calls, its deadline;
|
|
838
841
|
* `undefined` without options, where the contract has no imports section.
|
|
@@ -841,7 +844,7 @@ function kitImports(options: LiteralValue | undefined): Record<string, KitImport
|
|
|
841
844
|
if (options === undefined) {
|
|
842
845
|
return undefined
|
|
843
846
|
}
|
|
844
|
-
const imports = strictFields(options, "defineApp's options", [],
|
|
847
|
+
const imports = strictFields(options, "defineApp's options", [], KIT_OPTIONS).get('imports')
|
|
845
848
|
if (imports === undefined) {
|
|
846
849
|
return undefined
|
|
847
850
|
}
|
|
@@ -865,7 +868,7 @@ function kitImports(options: LiteralValue | undefined): Record<string, KitImport
|
|
|
865
868
|
|
|
866
869
|
/** The token purposes of `defineApp`'s options, each `token(Claims, { maxDays })`; `undefined` without any. */
|
|
867
870
|
function kitTokens(options: LiteralValue | undefined): TokenPurposes | undefined {
|
|
868
|
-
const tokens = options === undefined ? undefined : strictFields(options, "defineApp's options", [],
|
|
871
|
+
const tokens = options === undefined ? undefined : strictFields(options, "defineApp's options", [], KIT_OPTIONS).get('tokens')
|
|
869
872
|
if (options === undefined || tokens === undefined) {
|
|
870
873
|
return undefined
|
|
871
874
|
}
|
package/src/reader/value.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { file, signedToken, WebhookSecret } from '@fabrika/app/contract'
|
|
5
5
|
import type { z } from 'zod/v4'
|
|
6
6
|
import { type AstNode, child, children, identifierName, isConstAssertion, type ParsedModule, staticKey } from '../ast'
|
|
7
|
-
import type
|
|
7
|
+
import { type Located, type ModuleGraph, unwrapValue } from '../graph'
|
|
8
8
|
import { CONTRACT_LIMITS } from '../limits'
|
|
9
9
|
import {
|
|
10
10
|
BUILDER_IMPORTS,
|
|
@@ -98,6 +98,7 @@ const VOCABULARY_SECTIONS = [
|
|
|
98
98
|
] as const
|
|
99
99
|
|
|
100
100
|
const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, null, the c.* and z.* builders, and const imports of such values'
|
|
101
|
+
const ALLOWED_SPREAD = "a spread of a const whose value is an object literal (this module's or a named import), or the entries written out"
|
|
101
102
|
|
|
102
103
|
export class ValueReader {
|
|
103
104
|
readonly #graph: ModuleGraph
|
|
@@ -256,13 +257,19 @@ export class ValueReader {
|
|
|
256
257
|
continue
|
|
257
258
|
}
|
|
258
259
|
const at = { module: located.module, node: property }
|
|
260
|
+
if (property.type === 'SpreadElement') {
|
|
261
|
+
const spread = this.#spread(at, scope)
|
|
262
|
+
if (spread === null) complete = false
|
|
263
|
+
else for (const [key, value] of spread) entries.set(key, value)
|
|
264
|
+
continue
|
|
265
|
+
}
|
|
259
266
|
const key = staticKey(property, 'key')
|
|
260
267
|
const value = child(property, 'value')
|
|
261
268
|
if (
|
|
262
269
|
property.type !== 'Property' || property['computed'] === true || property['kind'] !== 'init' || property['method'] === true
|
|
263
270
|
|| key === undefined || key === '__proto__' || value === undefined
|
|
264
271
|
) {
|
|
265
|
-
this.#problems.add(at, 'a
|
|
272
|
+
this.#problems.add(at, 'a computed key, method or __proto__ key', 'a plain or quoted key with a literal value')
|
|
266
273
|
complete = false
|
|
267
274
|
continue
|
|
268
275
|
}
|
|
@@ -277,6 +284,20 @@ export class ValueReader {
|
|
|
277
284
|
return complete ? { kind: 'object', entries, at: located } : null
|
|
278
285
|
}
|
|
279
286
|
|
|
287
|
+
/** The entries `{ ...x }` copies: those of an object literal, in place or a const's (`rules/literal.ts`' spread). */
|
|
288
|
+
#spread(at: Located, scope: Scope): ReadonlyMap<string, LiteralValue> | null {
|
|
289
|
+
const argument = child(at.node, 'argument')
|
|
290
|
+
const value = argument === undefined ? undefined : unwrapValue(argument)
|
|
291
|
+
const target = value === undefined ? undefined : this.#graph.resolveValue({ module: at.module, node: value })
|
|
292
|
+
const read = value === undefined || target?.node.type !== 'ObjectExpression'
|
|
293
|
+
? undefined
|
|
294
|
+
: this.#read({ module: at.module, node: value }, scope, null)
|
|
295
|
+
if (read === null) return null
|
|
296
|
+
if (read?.kind === 'object') return read.entries
|
|
297
|
+
this.#problems.add(at, 'spread of a value that is not a constant object literal', ALLOWED_SPREAD)
|
|
298
|
+
return null
|
|
299
|
+
}
|
|
300
|
+
|
|
280
301
|
#identifier(located: Located, scope: Scope): LiteralValue | null {
|
|
281
302
|
const name = identifierName(located.node) ?? ''
|
|
282
303
|
const builder = this.#builderOf(located.module, name)
|
package/src/rules/contract.ts
CHANGED
|
@@ -20,8 +20,9 @@ export const checkContractRead = (graph: ModuleGraph): Finding[] => {
|
|
|
20
20
|
return [...read.findings]
|
|
21
21
|
}
|
|
22
22
|
const module = graph.module(CONTRACT_FILE)
|
|
23
|
-
const binding = module === undefined ? undefined : graph.
|
|
24
|
-
|
|
23
|
+
const binding = module === undefined ? undefined : graph.exported(module, CONTRACT_EXPORT)
|
|
24
|
+
// A contract declared in another module (an import or a re-export) is reported at this file's start.
|
|
25
|
+
const at = binding?.kind === 'const' && binding.module === module && binding.init !== undefined ? positionOf(binding.init) : { line: 1, column: 1 }
|
|
25
26
|
try {
|
|
26
27
|
return memberAdmitsExternal(describeContract(read.contract), at)
|
|
27
28
|
} catch (error) {
|
package/src/rules/identity.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AstNode, child, children, type ParsedModule, staticKey, walk } from '../ast'
|
|
2
2
|
import { type Finding, reporter } from '../finding'
|
|
3
|
-
import { type Located, type ModuleGraph, propertyValue } from '../graph'
|
|
3
|
+
import { type Located, type ModuleGraph, objectEntries, propertyValue } from '../graph'
|
|
4
4
|
|
|
5
5
|
const IDENTITY_FIELDS = new Set([
|
|
6
6
|
'userId',
|
|
@@ -35,10 +35,7 @@ const schemaFields = (located: Located, graph: ModuleGraph, depth = 0): Readonly
|
|
|
35
35
|
if (method === undefined || !argument) return fields
|
|
36
36
|
if (SHAPE_METHODS.has(method)) {
|
|
37
37
|
const shape = graph.resolveValue({ module: value.module, node: argument })
|
|
38
|
-
for (const
|
|
39
|
-
const key = property === null ? undefined : staticKey(property, 'key')
|
|
40
|
-
if (key !== undefined) fields.add(key)
|
|
41
|
-
}
|
|
38
|
+
for (const key of shape === undefined ? [] : objectEntries(graph, shape).keys()) fields.add(key)
|
|
42
39
|
} else if (MERGE_METHODS.has(method)) add({ module: value.module, node: argument })
|
|
43
40
|
return fields
|
|
44
41
|
}
|
|
@@ -46,8 +43,8 @@ const schemaFields = (located: Located, graph: ModuleGraph, depth = 0): Readonly
|
|
|
46
43
|
/** The field an `in`/`on` access form takes from the input; the framework removes it and checks the caller's access to it. */
|
|
47
44
|
const checkedField = (access: Located | undefined, graph: ModuleGraph): string | undefined => {
|
|
48
45
|
const value = access === undefined ? undefined : graph.resolveValue(access)
|
|
49
|
-
if (value === undefined || (propertyValue(value, 'in') === undefined && propertyValue(value, 'on') === undefined)) return undefined
|
|
50
|
-
const from = propertyValue(value, 'from')
|
|
46
|
+
if (value === undefined || (propertyValue(graph, value, 'in') === undefined && propertyValue(graph, value, 'on') === undefined)) return undefined
|
|
47
|
+
const from = propertyValue(graph, value, 'from')
|
|
51
48
|
return from === undefined ? undefined : graph.resolveString(from)
|
|
52
49
|
}
|
|
53
50
|
|
|
@@ -61,9 +58,9 @@ export const checkClientIdentity = (contract: ParsedModule, graph: ModuleGraph):
|
|
|
61
58
|
for (const argument of children(node, 'arguments')) {
|
|
62
59
|
if (argument === null) continue
|
|
63
60
|
const options = graph.resolveValue({ module: contract, node: argument })
|
|
64
|
-
const input = options === undefined ? undefined : propertyValue(options, 'input')
|
|
61
|
+
const input = options === undefined ? undefined : propertyValue(graph, options, 'input')
|
|
65
62
|
if (options === undefined || input === undefined) continue
|
|
66
|
-
const checked = checkedField(propertyValue(options, 'access'), graph)
|
|
63
|
+
const checked = checkedField(propertyValue(graph, options, 'access'), graph)
|
|
67
64
|
const at: AstNode = input.module === contract ? input.node : argument
|
|
68
65
|
for (const field of schemaFields(input, graph)) {
|
|
69
66
|
if (!IDENTITY_FIELDS.has(field) || field === checked) continue
|
package/src/rules/literal.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AstNode, child, children, identifierName, isConstAssertion, type ParsedModule, staticKey, staticString, stringField } from '../ast'
|
|
2
2
|
import { type Finding, type Report, reporter } from '../finding'
|
|
3
|
-
import type
|
|
3
|
+
import { type Binding, type ModuleGraph, unwrapValue } from '../graph'
|
|
4
4
|
import { isRelativeSpecifier } from '../layout'
|
|
5
5
|
|
|
6
6
|
/**
|
|
@@ -165,6 +165,7 @@ const ALLOWED_VALUE = 'object and array literals, strings, numbers, booleans, nu
|
|
|
165
165
|
const ALLOWED_SCHEMA = 'a schema of the supported z subset (packages/check/CLAUDE.md): strict objects, no transforms, refinements or pipes'
|
|
166
166
|
const ALLOWED_CALLBACK =
|
|
167
167
|
'a function only as a builder callback: defineContract(…, (c) => ({ … })), app.contract((c) => ({ … })), app.group(…, (r) => ({ … })), procedures: (l) => ({ … }) of a link or an export, and the handler of .handle(…)'
|
|
168
|
+
const ALLOWED_SPREAD = "a spread of a const whose value is an object literal (this module's or a named import), or the entries written out"
|
|
168
169
|
const ALLOWED_IMPORT =
|
|
169
170
|
'z from zod/v4 or @fabrika/app/schema, defineContract, defineVocabulary or defineApp from @fabrika/app/contract, defineTables from @fabrika/db/tables, or a literal const of the application'
|
|
170
171
|
|
|
@@ -527,7 +528,7 @@ const readModule = (module: ParsedModule, graph: ModuleGraph, findings: Finding[
|
|
|
527
528
|
for (const property of children(node, 'properties')) {
|
|
528
529
|
if (property === null) continue
|
|
529
530
|
if (property.type === 'SpreadElement') {
|
|
530
|
-
|
|
531
|
+
checkObjectSpread(property, scope, dependencies)
|
|
531
532
|
continue
|
|
532
533
|
}
|
|
533
534
|
if (property['computed'] === true) {
|
|
@@ -549,6 +550,23 @@ const readModule = (module: ParsedModule, graph: ModuleGraph, findings: Finding[
|
|
|
549
550
|
}
|
|
550
551
|
}
|
|
551
552
|
|
|
553
|
+
/**
|
|
554
|
+
* `{ ...Base }`: a spread of an object literal, written in place or as a const of this module or an imported one (through
|
|
555
|
+
* `as const`, `satisfies` and parentheses), whose entries the reader copies as evaluating it would.
|
|
556
|
+
*/
|
|
557
|
+
const checkObjectSpread = (spread: AstNode, scope: Scope, dependencies: string[]): void => {
|
|
558
|
+
const argument = child(spread, 'argument')
|
|
559
|
+
const value = argument === undefined ? undefined : unwrapValue(argument)
|
|
560
|
+
if (value?.type === 'ObjectExpression') return checkObject(value, scope, dependencies)
|
|
561
|
+
const name = identifierName(value)
|
|
562
|
+
if (value === undefined || name === undefined) return fail(spread, 'spread of a value that is not a constant object', ALLOWED_SPREAD)
|
|
563
|
+
const before = reported
|
|
564
|
+
checkIdentifier(value, scope, dependencies)
|
|
565
|
+
if (reported !== before) return
|
|
566
|
+
const resolved = graph.resolveValue({ module, node: value })
|
|
567
|
+
if (resolved?.node.type !== 'ObjectExpression') fail(spread, `spread of '${name}', which is not a constant object literal`, ALLOWED_SPREAD)
|
|
568
|
+
}
|
|
569
|
+
|
|
552
570
|
const checkExpression = (node: AstNode, scope: Scope, dependencies: string[]): void => {
|
|
553
571
|
switch (node.type) {
|
|
554
572
|
case 'Literal':
|
|
@@ -617,8 +635,17 @@ const readModule = (module: ParsedModule, graph: ModuleGraph, findings: Finding[
|
|
|
617
635
|
const declaration = statement.type === 'ExportNamedDeclaration' ? (child(statement, 'declaration') ?? statement) : statement
|
|
618
636
|
if (declaration.type === 'TSTypeAliasDeclaration' || declaration.type === 'TSInterfaceDeclaration') continue
|
|
619
637
|
if (declaration.type === 'ExportNamedDeclaration') {
|
|
620
|
-
|
|
621
|
-
|
|
638
|
+
// A relative re-export is checked with the imports (`checkLiteralGraph`), as its binding. Bun erases one whose
|
|
639
|
+
// every specifier is a type, and evaluates the source of `export {} from`, as of `import {} from`.
|
|
640
|
+
const source = staticString(child(declaration, 'source'))
|
|
641
|
+
if (source !== undefined) {
|
|
642
|
+
const specifiers = children(declaration, 'specifiers').filter((item): item is AstNode => item !== null)
|
|
643
|
+
const erased = stringField(declaration, 'exportKind') === 'type'
|
|
644
|
+
|| (specifiers.length > 0 && specifiers.every((item) => stringField(item, 'exportKind') === 'type'))
|
|
645
|
+
if (!erased && specifiers.length === 0) fail(declaration, `side-effect re-export of '${source}'`, 'named imports of literal consts')
|
|
646
|
+
else if (!erased && !isRelativeSpecifier(source)) {
|
|
647
|
+
fail(declaration, `re-export from the package '${source}'`, 'import the builder in the module that uses it')
|
|
648
|
+
}
|
|
622
649
|
continue
|
|
623
650
|
}
|
|
624
651
|
for (const item of children(declaration, 'specifiers')) {
|
|
@@ -665,7 +692,7 @@ export const checkLiteralGraph = (entries: readonly string[], graph: ModuleGraph
|
|
|
665
692
|
for (let module = queue.shift(); module !== undefined; module = queue.shift()) {
|
|
666
693
|
if (summaries.has(module.file)) continue
|
|
667
694
|
summaries.set(module.file, readModule(module, graph, findings))
|
|
668
|
-
for (const binding of graph.
|
|
695
|
+
for (const binding of graph.links(module)) {
|
|
669
696
|
const target = graph.resolve(module.file, binding.specifier)
|
|
670
697
|
if (target !== undefined) queue.push(target)
|
|
671
698
|
}
|
|
@@ -709,7 +736,11 @@ export const checkLiteralGraph = (entries: readonly string[], graph: ModuleGraph
|
|
|
709
736
|
for (const name of summary.consts.keys()) {
|
|
710
737
|
isLiteral(name === 'default' ? graph.exported(summary.module, 'default') : graph.binding(summary.module, name))
|
|
711
738
|
}
|
|
712
|
-
|
|
739
|
+
const index = graph.index(summary.module)
|
|
740
|
+
for (const imported of graph.links(summary.module)) {
|
|
741
|
+
const reexport = index.reexports.get(imported.local) === imported
|
|
742
|
+
// A package re-export is refused at its declaration (`readModule`).
|
|
743
|
+
if (reexport && !isRelativeSpecifier(imported.specifier)) continue
|
|
713
744
|
if (!isRelativeSpecifier(imported.specifier)) {
|
|
714
745
|
const browserSafe = SERVER_ENTRY_OF[imported.specifier]
|
|
715
746
|
if (browserSafe !== undefined && BUILDER_IMPORTS[browserSafe]?.[imported.imported] !== undefined) {
|
|
@@ -741,7 +772,7 @@ export const checkLiteralGraph = (entries: readonly string[], graph: ModuleGraph
|
|
|
741
772
|
)
|
|
742
773
|
continue
|
|
743
774
|
}
|
|
744
|
-
const binding = graph.binding(summary.module, imported.local)
|
|
775
|
+
const binding = reexport ? graph.exported(summary.module, imported.local) : graph.binding(summary.module, imported.local)
|
|
745
776
|
if (binding.kind === 'unresolved') summary.report(imported.node, 'literal', binding.reason, 'a named import of a const the module exports')
|
|
746
777
|
else if (!isLiteral(binding) && !refusedInPlace(binding)) {
|
|
747
778
|
summary.report(
|
|
@@ -761,7 +792,7 @@ const reportImportCycles = (summaries: ReadonlyMap<string, LiteralSummary>, grap
|
|
|
761
792
|
const state = new Map<string, 'visiting' | 'done'>()
|
|
762
793
|
const visit = (summary: LiteralSummary): void => {
|
|
763
794
|
state.set(summary.module.file, 'visiting')
|
|
764
|
-
for (const imported of graph.
|
|
795
|
+
for (const imported of graph.links(summary.module)) {
|
|
765
796
|
const target = graph.resolve(summary.module.file, imported.specifier)
|
|
766
797
|
const next = target === undefined ? undefined : summaries.get(target.file)
|
|
767
798
|
if (next === undefined) continue
|
package/src/rules/structure.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { isBuiltin } from 'node:module'
|
|
2
|
-
import { type AstNode, child, identifierName, staticKey } from '../ast'
|
|
3
|
-
import { type Finding, type Report, STRUCTURE_HINT_RULE_IDS } from '../finding'
|
|
2
|
+
import { type AstNode, child, children, identifierName, isValueReference, staticKey, staticString, stringField, unwrap, walk } from '../ast'
|
|
3
|
+
import { type Finding, type Report, reporter, STRUCTURE_HINT_RULE_IDS } from '../finding'
|
|
4
4
|
import {
|
|
5
5
|
CONTRACT_FILE,
|
|
6
6
|
DATABASE_DIR,
|
|
@@ -19,6 +19,7 @@ import {
|
|
|
19
19
|
} from '../layout'
|
|
20
20
|
import type { ModuleReference } from '../references'
|
|
21
21
|
import { type ImportMappings, mappedTargets } from '../resolution'
|
|
22
|
+
import { declaringScope } from '../scope'
|
|
22
23
|
import { isTestKit } from './modules'
|
|
23
24
|
|
|
24
25
|
/** The rules of the application architecture (docs/reference/application-architecture.md): three refusals and the hints. */
|
|
@@ -225,6 +226,138 @@ const checkSliceReference = (place: StructurePlace, reference: ModuleReference,
|
|
|
225
226
|
)
|
|
226
227
|
}
|
|
227
228
|
|
|
229
|
+
/** A top-level function of a module: its local name, its declaration, and the node a finding points at. */
|
|
230
|
+
interface TopLevelFunction {
|
|
231
|
+
readonly local: string
|
|
232
|
+
readonly declaration: AstNode
|
|
233
|
+
readonly at: AstNode
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
const isFunctionValue = (node: AstNode | undefined): boolean => {
|
|
237
|
+
const value = node === undefined ? undefined : unwrap(node)
|
|
238
|
+
return value?.type === 'ArrowFunctionExpression' || value?.type === 'FunctionExpression'
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** `function f() {}` and `const f = () => …` (or a function expression) at the top level, by local name. */
|
|
242
|
+
const topLevelFunctions = (statement: AstNode): readonly TopLevelFunction[] => {
|
|
243
|
+
if (statement.type === 'FunctionDeclaration') {
|
|
244
|
+
const id = child(statement, 'id')
|
|
245
|
+
const local = identifierName(id)
|
|
246
|
+
return local === undefined || id === undefined ? [] : [{ local, declaration: statement, at: id }]
|
|
247
|
+
}
|
|
248
|
+
if (statement.type !== 'VariableDeclaration') return []
|
|
249
|
+
return children(statement, 'declarations').flatMap((declarator) => {
|
|
250
|
+
const id = declarator === null ? undefined : child(declarator, 'id')
|
|
251
|
+
const local = identifierName(id)
|
|
252
|
+
if (declarator === null || id === undefined || local === undefined || !isFunctionValue(child(declarator, 'init'))) return []
|
|
253
|
+
return [{ local, declaration: declarator, at: id }]
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The functions a module exports by name: `export function`, `export const f = () => …`, `export { f as g }` of one. */
|
|
258
|
+
const exportedFunctions = (program: AstNode): ReadonlyMap<string, TopLevelFunction> => {
|
|
259
|
+
const statements = children(program, 'body').filter((statement): statement is AstNode => statement !== null)
|
|
260
|
+
const declared = new Map<string, TopLevelFunction>()
|
|
261
|
+
for (const statement of statements) {
|
|
262
|
+
const declaration = statement.type === 'ExportNamedDeclaration' ? child(statement, 'declaration') : statement
|
|
263
|
+
for (const fn of declaration === undefined ? [] : topLevelFunctions(declaration)) declared.set(fn.local, fn)
|
|
264
|
+
}
|
|
265
|
+
const exported = new Map<string, TopLevelFunction>()
|
|
266
|
+
for (const statement of statements) {
|
|
267
|
+
if (statement.type !== 'ExportNamedDeclaration' || stringField(statement, 'exportKind') === 'type') continue
|
|
268
|
+
const declaration = child(statement, 'declaration')
|
|
269
|
+
if (declaration !== undefined) {
|
|
270
|
+
for (const fn of topLevelFunctions(declaration)) exported.set(fn.local, fn)
|
|
271
|
+
continue
|
|
272
|
+
}
|
|
273
|
+
if (child(statement, 'source') !== undefined) continue
|
|
274
|
+
for (const specifier of children(statement, 'specifiers')) {
|
|
275
|
+
if (specifier === null || stringField(specifier, 'exportKind') === 'type') continue
|
|
276
|
+
const fn = declared.get(identifierName(child(specifier, 'local')) ?? '')
|
|
277
|
+
const name = identifierName(child(specifier, 'exported')) ?? staticString(child(specifier, 'exported'))
|
|
278
|
+
if (fn !== undefined && name !== undefined) exported.set(name, { ...fn, at: specifier })
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
return exported
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** Whether `node` is the name a declaration binds: `const f = …`, `function f() {}`. */
|
|
285
|
+
const isDeclaredName = (node: AstNode, parent: AstNode): boolean =>
|
|
286
|
+
(parent.type === 'VariableDeclarator' || parent.type === 'FunctionDeclaration') && child(parent, 'id') === node
|
|
287
|
+
|
|
288
|
+
/** Which of the top-level functions (local name → declaration) the module's own code uses as a value, outside its own declaration. */
|
|
289
|
+
const usedWithin = (program: AstNode, declarations: ReadonlyMap<string, AstNode>): ReadonlySet<string> => {
|
|
290
|
+
const used = new Set<string>()
|
|
291
|
+
walk(program, (node, ancestors) => {
|
|
292
|
+
const name = identifierName(node)
|
|
293
|
+
const declaration = name === undefined ? undefined : declarations.get(name)
|
|
294
|
+
const parent = ancestors.at(-1)
|
|
295
|
+
if (name === undefined || declaration === undefined || parent === undefined || isDeclaredName(node, parent)) return
|
|
296
|
+
if (!isValueReference(node, parent) || declaringScope(name, ancestors) !== program || ancestors.includes(declaration)) return
|
|
297
|
+
used.add(name)
|
|
298
|
+
})
|
|
299
|
+
return used
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* `single-slice-queries`: a function of `src/<a>/queries.ts` that exactly one other slice `src/<b>/` uses belongs in
|
|
304
|
+
* `src/<b>/queries.ts`. A caller is any module but a test, and a use is a named import or re-export; a function
|
|
305
|
+
* exported under two names is one function. A module outside every slice, and a whole-module load (`import *`,
|
|
306
|
+
* `export *`) from another slice, which names no function, leave every function they reach where it is.
|
|
307
|
+
*/
|
|
308
|
+
export const checkSingleSliceQueries = (graph: StructureGraph, programs: ReadonlyMap<string, AstNode>): Finding[] => {
|
|
309
|
+
// Who loads each queries module: the importer's slice (`undefined` outside every slice) and the names it takes.
|
|
310
|
+
const loads = new Map<string, { readonly slice: string | undefined; readonly names: readonly string[] }[]>()
|
|
311
|
+
for (const importer of programs.keys()) {
|
|
312
|
+
if (isTestFile(importer)) continue
|
|
313
|
+
for (const reference of graph.referencesOf(importer)) {
|
|
314
|
+
if (reference.typeOnly) continue
|
|
315
|
+
for (const target of referenceTargets(graph, importer, reference.specifier).files) {
|
|
316
|
+
if (target === importer || slicePart(target) !== 'queries') continue
|
|
317
|
+
const into = loads.get(target) ?? []
|
|
318
|
+
into.push({ slice: sliceOf(importer), names: reference.names })
|
|
319
|
+
loads.set(target, into)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const findings: Finding[] = []
|
|
324
|
+
for (const [file, program] of programs) {
|
|
325
|
+
const slice = sliceOf(file)
|
|
326
|
+
if (slicePart(file) !== 'queries' || slice === undefined) continue
|
|
327
|
+
const exported = exportedFunctions(program)
|
|
328
|
+
// Each function's callers, by its local name: the slices that use it, and `unjudged` once a use names no slice.
|
|
329
|
+
const callers = new Map([...exported.values()].map((fn) => [fn.local, { slices: new Set<string>(), unjudged: false }]))
|
|
330
|
+
const use = (local: string | undefined, caller: string | undefined): void => {
|
|
331
|
+
const entry = local === undefined ? undefined : callers.get(local)
|
|
332
|
+
if (entry === undefined) return
|
|
333
|
+
if (caller === undefined) entry.unjudged = true
|
|
334
|
+
else entry.slices.add(caller)
|
|
335
|
+
}
|
|
336
|
+
const within = usedWithin(program, new Map([...exported.values()].map((fn) => [fn.local, fn.declaration])))
|
|
337
|
+
for (const local of within) use(local, slice)
|
|
338
|
+
for (const load of loads.get(file) ?? []) {
|
|
339
|
+
if (load.names.includes('*')) {
|
|
340
|
+
for (const local of callers.keys()) use(local, load.slice === slice ? slice : undefined)
|
|
341
|
+
} else {
|
|
342
|
+
for (const name of load.names) use(exported.get(name)?.local, load.slice)
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
const report = reporter(file, findings)
|
|
346
|
+
for (const [name, fn] of exported) {
|
|
347
|
+
const entry = callers.get(fn.local)
|
|
348
|
+
const [only, ...rest] = entry?.slices ?? []
|
|
349
|
+
if (entry === undefined || entry.unjudged || only === undefined || rest.length > 0 || only === slice) continue
|
|
350
|
+
report(
|
|
351
|
+
fn.at,
|
|
352
|
+
'single-slice-queries',
|
|
353
|
+
`'${name}' of ${file} is used only by the slice '${only}'`,
|
|
354
|
+
`the function in src/${only}/queries.ts, with the helpers only it uses; ${file} keeps what two or more slices use`,
|
|
355
|
+
)
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return findings
|
|
359
|
+
}
|
|
360
|
+
|
|
228
361
|
/**
|
|
229
362
|
* A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
|
|
230
363
|
* load by its name, past `tool-import`, which judges the files an import resolves to.
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// The application's shell graph read from disk as Control reads it from a commit, each module as its slice: what both
|
|
2
|
+
// SPA build plugins (`bun-plugin.ts`, `vite-plugin.ts`) load in place of the files.
|
|
3
|
+
|
|
4
|
+
import { readFileSync, statSync } from 'node:fs'
|
|
5
|
+
import { join } from 'node:path'
|
|
6
|
+
import { contractReaderInputs, readContract } from './contract'
|
|
7
|
+
import { CONTRACT_FILE, isSourceFile } from './layout'
|
|
8
|
+
import { shellSlice } from './slice'
|
|
9
|
+
|
|
10
|
+
const SOURCE_EXTENSION = String.raw`\.(?:[mc]?[jt]s|[jt]sx)$`
|
|
11
|
+
|
|
12
|
+
/** The application's own modules under `root`, outside `node_modules`: every extension the reader reads. */
|
|
13
|
+
export const applicationModules = (root: string): RegExp =>
|
|
14
|
+
new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\/](?!(?:.*[\\/])?node_modules[\\/]).*${SOURCE_EXTENSION}`)
|
|
15
|
+
|
|
16
|
+
const isFile = (path: string): boolean => statSync(path, { throwIfNoEntry: false })?.isFile() === true
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The shell modules under `root`, by absolute path, as their slices; none without a `fabrika.contract.ts` there.
|
|
20
|
+
* Throws the reader's refusal when the static reader refuses the shell.
|
|
21
|
+
*/
|
|
22
|
+
export function shellModules(root: string): ReadonlyMap<string, string> {
|
|
23
|
+
if (!isFile(join(root, CONTRACT_FILE))) return new Map()
|
|
24
|
+
const files = new Map<string, string>()
|
|
25
|
+
for (;;) {
|
|
26
|
+
const missing = contractReaderInputs(files, (path) => isFile(join(root, path)))
|
|
27
|
+
if (missing.length === 0) break
|
|
28
|
+
for (const path of missing) files.set(path, readFileSync(join(root, path), 'utf8'))
|
|
29
|
+
}
|
|
30
|
+
readContract(files)
|
|
31
|
+
return new Map([...files].filter(([path]) => isSourceFile(path)).map(([path, text]) => [join(root, path), shellSlice(path, text).text]))
|
|
32
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// @fabrika/check/vite-plugin — a Vite build (or dev server) of the SPA that imports `fabrika.contract.ts` without its
|
|
2
|
+
// handlers, as `@fabrika/check/bun-plugin` does for `Bun.build`. It loads each module of the shell graph as its slice
|
|
3
|
+
// and leaves every other module to Vite; the build fails when the static reader refuses the shell. The package ships
|
|
4
|
+
// TypeScript, so the Vite that loads this plugin runs on Bun (`bun --bun vite build`).
|
|
5
|
+
|
|
6
|
+
import { realpathSync } from 'node:fs'
|
|
7
|
+
import { basename, resolve } from 'node:path'
|
|
8
|
+
import { CONTRACT_FILE } from './layout'
|
|
9
|
+
import { applicationModules, shellModules } from './shell-modules'
|
|
10
|
+
|
|
11
|
+
export interface ShellSliceOptions {
|
|
12
|
+
/** The application's root, where `fabrika.contract.ts` lies; the working directory by default. */
|
|
13
|
+
readonly root?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** What the plugin uses of Vite's plugin context. */
|
|
17
|
+
export interface WatchContext {
|
|
18
|
+
addWatchFile(id: string): void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The part of Vite's `Plugin` this plugin implements; a value of it goes into `plugins` as it is. */
|
|
22
|
+
export interface ShellSliceVitePlugin {
|
|
23
|
+
readonly name: string
|
|
24
|
+
readonly enforce: 'pre'
|
|
25
|
+
/**
|
|
26
|
+
* A shell module's slice, its file watched; `null` leaves the module to Vite's own load. Throws for a
|
|
27
|
+
* `fabrika.contract.ts` that is not the root's: Vite would bundle it, handlers included.
|
|
28
|
+
*/
|
|
29
|
+
load(this: WatchContext, id: string): { readonly code: string } | null
|
|
30
|
+
/** Any change of a watched file: the next load reads the shell graph again. */
|
|
31
|
+
watchChange(): void
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Loads every module of the application's shell graph as its slice: no `.handle(…)`, and no import only a handler
|
|
36
|
+
* used. The build fails with the reader's findings when the static reader refuses the shell.
|
|
37
|
+
*/
|
|
38
|
+
export function shellSlicePlugin(options: ShellSliceOptions = {}): ShellSliceVitePlugin {
|
|
39
|
+
const root = realpathSync(resolve(options.root ?? process.cwd()))
|
|
40
|
+
const modules = applicationModules(root)
|
|
41
|
+
let shell: ReadonlyMap<string, string> | undefined
|
|
42
|
+
return {
|
|
43
|
+
name: 'fabrika-shell-slice',
|
|
44
|
+
enforce: 'pre',
|
|
45
|
+
load(id) {
|
|
46
|
+
// Vite's id is the file's real path, with a query for a variant (`?raw`, `?url`), which gets the slice too.
|
|
47
|
+
const path = id.split('?', 1)[0] ?? id
|
|
48
|
+
const contract = basename(path) === CONTRACT_FILE
|
|
49
|
+
if (!contract && !modules.test(path)) return null
|
|
50
|
+
shell ??= shellModules(root)
|
|
51
|
+
const code = shell.get(path)
|
|
52
|
+
if (code === undefined && contract) {
|
|
53
|
+
throw new Error(`${path} is not the contract of the plugin's root ${root}: pass shellSlicePlugin({ root }) the application's root`)
|
|
54
|
+
}
|
|
55
|
+
if (code === undefined) return null
|
|
56
|
+
// Vite watches only its root and the files it loads itself; the shell lies beside `web/`.
|
|
57
|
+
this.addWatchFile(path)
|
|
58
|
+
return { code }
|
|
59
|
+
},
|
|
60
|
+
watchChange() {
|
|
61
|
+
shell = undefined
|
|
62
|
+
},
|
|
63
|
+
}
|
|
64
|
+
}
|
package/types/src/contract.d.ts
CHANGED
|
@@ -55,5 +55,5 @@ export type ContractRead = {
|
|
|
55
55
|
};
|
|
56
56
|
/** Reads the `contract` export of a graph whose contract modules already pass the literal rule. */
|
|
57
57
|
export declare function readContractModule(graph: ModuleGraph): ContractRead;
|
|
58
|
-
/** The contract module and every module its value imports reach. */
|
|
58
|
+
/** The contract module and every module its value imports and re-exports reach. */
|
|
59
59
|
export declare function contractModules(graph: ModuleGraph, entry: ParsedModule): ParsedModule[];
|
package/types/src/finding.d.ts
CHANGED
|
@@ -2,14 +2,14 @@ import type { AstNode, Position } from './ast';
|
|
|
2
2
|
/** Rules whose finding fails the check: the framework's forms and platform integrity. */
|
|
3
3
|
export declare const REFUSAL_RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "access-view-key", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "package-replacement", "skipped-test", "test-without-assertion", "mock-module", "spa-server-import", "layer-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "cloudflare-view-trigger"];
|
|
4
4
|
/** Rules that report a step out of the application architecture. */
|
|
5
|
-
export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
|
|
5
|
+
export declare const STRUCTURE_HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "single-slice-queries", "handler-location", "data-access-location"];
|
|
6
6
|
/**
|
|
7
7
|
* Rules whose findings never fail the check: the architecture's, a `ctx.sql` its site does not declare, a
|
|
8
8
|
* `{ member: true }` endpoint of a contract whose external role admits people from outside the organization, and a
|
|
9
9
|
* Cloudflare mutation that waits for an outside call inside the object's transaction.
|
|
10
10
|
*/
|
|
11
|
-
export declare const HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
|
|
12
|
-
export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "access-view-key", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "package-replacement", "skipped-test", "test-without-assertion", "mock-module", "spa-server-import", "layer-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "cloudflare-view-trigger", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
|
|
11
|
+
export declare const HINT_RULE_IDS: readonly ["logic-data-access", "cross-slice-queries", "single-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
|
|
12
|
+
export declare const RULE_IDS: readonly ["parse-error", "literal", "contract", "forbidden-import", "test-only-import", "unchecked-import", "forbidden-global", "raw-sql", "type-assertion", "any-type", "suppression-comment", "capability-widening", "prototype-assignment", "framework-write", "env-read", "public-env", "cross-app-fetch", "url-endpoint", "on-conflict-index", "access-view-key", "key-literal", "client-identity", "sensitive-log", "unsafe-html", "dynamic-code", "migration-name", "migration-refused", "backup-schema", "migration-edited", "file-column-migration", "package-replacement", "skipped-test", "test-without-assertion", "mock-module", "spa-server-import", "layer-import", "shared-import", "tool-import", "cloudflare-scan", "cloudflare-job-segment", "cloudflare-current-timestamp", "cloudflare-framework-name", "cloudflare-view-trigger", "logic-data-access", "cross-slice-queries", "single-slice-queries", "handler-location", "data-access-location", "sql-undeclared", "member-admits-external", "cloudflare-held-call"];
|
|
13
13
|
export type RefusalRuleId = (typeof REFUSAL_RULE_IDS)[number];
|
|
14
14
|
export type HintRuleId = (typeof HINT_RULE_IDS)[number];
|
|
15
15
|
export type RuleId = (typeof RULE_IDS)[number];
|
package/types/src/graph.d.ts
CHANGED
|
@@ -41,6 +41,8 @@ interface ModuleIndex {
|
|
|
41
41
|
readonly imports: ReadonlyMap<string, ImportBinding>;
|
|
42
42
|
/** Exported name → the local name it exports, or the default export's expression. */
|
|
43
43
|
readonly exports: ReadonlyMap<string, string | AstNode>;
|
|
44
|
+
/** `export { x as y } from './m'`: the exported name (`local`) → the module and the name it takes from it. */
|
|
45
|
+
readonly reexports: ReadonlyMap<string, ImportBinding>;
|
|
44
46
|
}
|
|
45
47
|
/** Erased wrappers: `x satisfies T`, `x as const`, parentheses. */
|
|
46
48
|
export declare const unwrapValue: (node: AstNode) => AstNode;
|
|
@@ -52,6 +54,8 @@ export declare class ModuleGraph {
|
|
|
52
54
|
index(module: ParsedModule): ModuleIndex;
|
|
53
55
|
/** How a relative specifier resolves among the checked modules. */
|
|
54
56
|
resolution(from: string, specifier: string): Resolution;
|
|
57
|
+
/** What a module loads by name: its value imports and its re-exports. */
|
|
58
|
+
links(module: ParsedModule): readonly ImportBinding[];
|
|
55
59
|
/** The checked module a relative specifier names; none when two candidates compete, the index of a directory import. */
|
|
56
60
|
resolve(from: string, specifier: string): ParsedModule | undefined;
|
|
57
61
|
/** What `name` denotes in `module`; an import is followed to the exporting module's declaration. */
|
|
@@ -63,6 +67,12 @@ export declare class ModuleGraph {
|
|
|
63
67
|
/** The fixed string a value resolves to. */
|
|
64
68
|
resolveString(located: Located): string | undefined;
|
|
65
69
|
}
|
|
66
|
-
/**
|
|
67
|
-
|
|
70
|
+
/**
|
|
71
|
+
* The entries of an object literal by key, in the order the object holds them, as evaluating it would build them: a
|
|
72
|
+
* spread of a value that resolves to an object literal contributes its entries, and a later key overrides an earlier
|
|
73
|
+
* one. A computed key, a method and a spread of anything else are not followed.
|
|
74
|
+
*/
|
|
75
|
+
export declare const objectEntries: (graph: ModuleGraph, located: Located, depth?: number) => ReadonlyMap<string, Located>;
|
|
76
|
+
/** The value of `key` in an object literal, read statically through `objectEntries`. */
|
|
77
|
+
export declare const propertyValue: (graph: ModuleGraph, located: Located, key: string) => Located | undefined;
|
|
68
78
|
export {};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type AstNode, type ParsedModule } from '../ast';
|
|
2
|
-
import type
|
|
2
|
+
import { type Located, type ModuleGraph } from '../graph';
|
|
3
3
|
import type { ReaderProblems } from './problems';
|
|
4
4
|
import { type ReadSchema } from './schema';
|
|
5
5
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type AstNode, type ParsedModule } from '../ast';
|
|
2
2
|
import { type Finding } from '../finding';
|
|
3
|
-
import type
|
|
3
|
+
import { type ModuleGraph } from '../graph';
|
|
4
4
|
/**
|
|
5
5
|
* What a call root builds. `surface` is the parameter of a `defineContract` callback (`c`, `l`); `app` is
|
|
6
6
|
* `defineApp`, `kit` a const it returned, `shell` the parameter of `app.contract`'s callback and `endpoints` that of
|
|
@@ -3,7 +3,7 @@ import { type Finding, type Report } from '../finding';
|
|
|
3
3
|
import type { ModuleReference } from '../references';
|
|
4
4
|
import { type ImportMappings } from '../resolution';
|
|
5
5
|
/** The rules of the application architecture (docs/reference/application-architecture.md): three refusals and the hints. */
|
|
6
|
-
export declare const STRUCTURE_RULE_IDS: readonly ["spa-server-import", "layer-import", "shared-import", "logic-data-access", "cross-slice-queries", "handler-location", "data-access-location"];
|
|
6
|
+
export declare const STRUCTURE_RULE_IDS: readonly ["spa-server-import", "layer-import", "shared-import", "logic-data-access", "cross-slice-queries", "single-slice-queries", "handler-location", "data-access-location"];
|
|
7
7
|
type SlicePart = 'endpoints' | 'logic' | 'queries';
|
|
8
8
|
/** Where a module sits in the architecture, which decides what it may import and call. */
|
|
9
9
|
export interface StructurePlace {
|
|
@@ -22,6 +22,13 @@ export interface StructureGraph {
|
|
|
22
22
|
readonly mappings: ImportMappings;
|
|
23
23
|
readonly referencesOf: (path: string) => readonly ModuleReference[];
|
|
24
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* `single-slice-queries`: a function of `src/<a>/queries.ts` that exactly one other slice `src/<b>/` uses belongs in
|
|
27
|
+
* `src/<b>/queries.ts`. A caller is any module but a test, and a use is a named import or re-export; a function
|
|
28
|
+
* exported under two names is one function. A module outside every slice, and a whole-module load (`import *`,
|
|
29
|
+
* `export *`) from another slice, which names no function, leave every function they reach where it is.
|
|
30
|
+
*/
|
|
31
|
+
export declare const checkSingleSliceQueries: (graph: StructureGraph, programs: ReadonlyMap<string, AstNode>) => Finding[];
|
|
25
32
|
/**
|
|
26
33
|
* A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
|
|
27
34
|
* load by its name, past `tool-import`, which judges the files an import resolves to.
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** The application's own modules under `root`, outside `node_modules`: every extension the reader reads. */
|
|
2
|
+
export declare const applicationModules: (root: string) => RegExp;
|
|
3
|
+
/**
|
|
4
|
+
* The shell modules under `root`, by absolute path, as their slices; none without a `fabrika.contract.ts` there.
|
|
5
|
+
* Throws the reader's refusal when the static reader refuses the shell.
|
|
6
|
+
*/
|
|
7
|
+
export declare function shellModules(root: string): ReadonlyMap<string, string>;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export interface ShellSliceOptions {
|
|
2
|
+
/** The application's root, where `fabrika.contract.ts` lies; the working directory by default. */
|
|
3
|
+
readonly root?: string;
|
|
4
|
+
}
|
|
5
|
+
/** What the plugin uses of Vite's plugin context. */
|
|
6
|
+
export interface WatchContext {
|
|
7
|
+
addWatchFile(id: string): void;
|
|
8
|
+
}
|
|
9
|
+
/** The part of Vite's `Plugin` this plugin implements; a value of it goes into `plugins` as it is. */
|
|
10
|
+
export interface ShellSliceVitePlugin {
|
|
11
|
+
readonly name: string;
|
|
12
|
+
readonly enforce: 'pre';
|
|
13
|
+
/**
|
|
14
|
+
* A shell module's slice, its file watched; `null` leaves the module to Vite's own load. Throws for a
|
|
15
|
+
* `fabrika.contract.ts` that is not the root's: Vite would bundle it, handlers included.
|
|
16
|
+
*/
|
|
17
|
+
load(this: WatchContext, id: string): {
|
|
18
|
+
readonly code: string;
|
|
19
|
+
} | null;
|
|
20
|
+
/** Any change of a watched file: the next load reads the shell graph again. */
|
|
21
|
+
watchChange(): void;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Loads every module of the application's shell graph as its slice: no `.handle(…)`, and no import only a handler
|
|
25
|
+
* used. The build fails with the reader's findings when the static reader refuses the shell.
|
|
26
|
+
*/
|
|
27
|
+
export declare function shellSlicePlugin(options?: ShellSliceOptions): ShellSliceVitePlugin;
|