@fabrika/check 0.9.0-dev.3 → 0.9.0-dev.31
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 +12 -7
- package/src/ast.ts +69 -18
- package/src/bun-plugin.ts +4 -27
- package/src/check.ts +157 -44
- package/src/cli.ts +34 -8
- package/src/contract.ts +68 -11
- package/src/dialect.ts +29 -0
- package/src/finding.ts +21 -8
- package/src/graph.ts +49 -12
- package/src/index.ts +4 -12
- package/src/inputs.ts +5 -2
- package/src/layout.ts +41 -12
- package/src/limits.ts +15 -5
- package/src/migration-base.ts +85 -0
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +48 -7
- package/src/reader/value.ts +41 -8
- package/src/references.ts +16 -1
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +59 -0
- package/src/rules/compile.ts +32 -0
- package/src/rules/contract.ts +3 -2
- package/src/rules/framework.ts +2 -2
- package/src/rules/identity.ts +6 -9
- package/src/rules/literal.ts +42 -9
- package/src/rules/migration-history.ts +70 -0
- package/src/rules/migrations.ts +248 -9
- package/src/rules/modules.ts +9 -3
- package/src/rules/platform-migrations.ts +100 -0
- package/src/rules/runtime.ts +45 -14
- package/src/rules/structure.ts +172 -19
- package/src/rules/tests.ts +9 -60
- package/src/rules/types.ts +17 -16
- package/src/shell-modules.ts +53 -0
- package/src/slice.ts +6 -5
- package/src/source-maps.ts +2 -0
- package/src/trust.ts +8 -4
- package/src/vite-plugin.ts +65 -0
- package/types/src/ast.d.ts +6 -2
- package/types/src/check.d.ts +3 -0
- package/types/src/contract.d.ts +13 -1
- package/types/src/dialect.d.ts +8 -0
- package/types/src/finding.d.ts +7 -6
- package/types/src/graph.d.ts +12 -2
- package/types/src/index.d.ts +4 -3
- package/types/src/layout.d.ts +25 -10
- package/types/src/limits.d.ts +14 -4
- package/types/src/migration-base.d.ts +9 -0
- package/types/src/reader/schema.d.ts +5 -2
- package/types/src/reader/value.d.ts +3 -3
- package/types/src/references.d.ts +6 -1
- package/types/src/rules/cloudflare.d.ts +9 -0
- package/types/src/rules/compile.d.ts +7 -0
- package/types/src/rules/framework.d.ts +1 -1
- package/types/src/rules/literal.d.ts +1 -1
- package/types/src/rules/migration-history.d.ts +12 -0
- package/types/src/rules/migrations.d.ts +28 -0
- package/types/src/rules/platform-migrations.d.ts +15 -0
- package/types/src/rules/runtime.d.ts +7 -2
- package/types/src/rules/structure.d.ts +18 -4
- package/types/src/rules/tests.d.ts +6 -14
- package/types/src/rules/types.d.ts +2 -0
- package/types/src/shell-modules.d.ts +7 -0
- package/types/src/slice.d.ts +8 -2
- package/types/src/vite-plugin.d.ts +27 -0
- package/src/endpoint-fixtures.ts +0 -221
- package/src/rules/crontab.ts +0 -147
- package/src/rules/isolation.ts +0 -79
- package/src/scaffold-sample.ts +0 -111
- package/src/scaffold.ts +0 -650
- package/types/src/endpoint-fixtures.d.ts +0 -36
- package/types/src/rules/crontab.d.ts +0 -15
- package/types/src/rules/isolation.d.ts +0 -18
- package/types/src/scaffold-sample.d.ts +0 -8
- package/types/src/scaffold.d.ts +0 -28
package/src/rules/structure.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { isBuiltin } from 'node:module'
|
|
2
|
-
import { type AstNode, child, identifierName, staticKey } from '../ast'
|
|
3
|
-
import { 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,
|
|
7
7
|
isRelativeSpecifier,
|
|
8
8
|
isSourceFile,
|
|
9
9
|
isTestFile,
|
|
10
|
+
isToolModule,
|
|
10
11
|
resolveRelative,
|
|
11
12
|
SCHEMAS_DIR,
|
|
12
13
|
SCHEMAS_FILE,
|
|
@@ -18,11 +19,11 @@ import {
|
|
|
18
19
|
} from '../layout'
|
|
19
20
|
import type { ModuleReference } from '../references'
|
|
20
21
|
import { type ImportMappings, mappedTargets } from '../resolution'
|
|
22
|
+
import { declaringScope } from '../scope'
|
|
21
23
|
import { isTestKit } from './modules'
|
|
22
|
-
import { isGeneratedTestPath } from './tests'
|
|
23
24
|
|
|
24
|
-
/** The rules of the application architecture (docs/reference/application-architecture.md):
|
|
25
|
-
export const STRUCTURE_RULE_IDS = ['spa-server-import', 'layer-import', '
|
|
25
|
+
/** The rules of the application architecture (docs/reference/application-architecture.md): three refusals and the hints. */
|
|
26
|
+
export const STRUCTURE_RULE_IDS = ['spa-server-import', 'layer-import', 'shared-import', ...STRUCTURE_HINT_RULE_IDS] as const
|
|
26
27
|
|
|
27
28
|
type SlicePart = 'endpoints' | 'logic' | 'queries'
|
|
28
29
|
|
|
@@ -57,13 +58,16 @@ export interface StructurePlace {
|
|
|
57
58
|
readonly part: SlicePart | undefined
|
|
58
59
|
/** A test or the generated entrypoint: the structure hints do not apply to it. */
|
|
59
60
|
readonly exempt: boolean
|
|
61
|
+
/** A generated module (`isGeneratedModule`): the hints do not apply to it, the refusals do. */
|
|
62
|
+
readonly generated: boolean
|
|
60
63
|
}
|
|
61
64
|
|
|
62
|
-
export const structurePlace = (file: string, isGeneratedEntry: boolean): StructurePlace => ({
|
|
65
|
+
export const structurePlace = (file: string, isGeneratedEntry: boolean, generated: boolean): StructurePlace => ({
|
|
63
66
|
file,
|
|
64
67
|
slice: sliceOf(file),
|
|
65
68
|
part: slicePart(file),
|
|
66
69
|
exempt: isGeneratedEntry || isTestFile(file),
|
|
70
|
+
generated,
|
|
67
71
|
})
|
|
68
72
|
|
|
69
73
|
/** What the structure rules read beyond one module: every module's references, and how Bun resolves them. */
|
|
@@ -128,12 +132,13 @@ const runtimeClosure = (graph: StructureGraph, start: Targets, descend: (path: s
|
|
|
128
132
|
const isDataPackage = (specifier: string): boolean => specifier === '@fabrika/db' || specifier.startsWith('@fabrika/db/')
|
|
129
133
|
|
|
130
134
|
/** The framework modules logic and queries may import; the rest of `@fabrika/*` is the framework's own composition. */
|
|
131
|
-
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/db'])
|
|
135
|
+
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/app/schema', '@fabrika/db'])
|
|
132
136
|
|
|
133
137
|
/** The framework modules an SPA loads: the typed client, its React hooks, the component kit and its challenge widget. */
|
|
134
138
|
const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
135
139
|
'@fabrika/app/client',
|
|
136
140
|
'@fabrika/app/react',
|
|
141
|
+
'@fabrika/app/schema',
|
|
137
142
|
'@fabrika/ui',
|
|
138
143
|
'@fabrika/ui/challenge',
|
|
139
144
|
'@fabrika/ui/styles.css',
|
|
@@ -141,7 +146,7 @@ const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
|
141
146
|
])
|
|
142
147
|
|
|
143
148
|
const SPA_ALLOWED =
|
|
144
|
-
'@fabrika/app/client, @fabrika/app/react, @fabrika/ui, @fabrika/ui/challenge, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
149
|
+
'@fabrika/app/client, @fabrika/app/react, @fabrika/app/schema, @fabrika/ui, @fabrika/ui/challenge, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
145
150
|
|
|
146
151
|
const isSchemaModule = (path: string): boolean => path === SCHEMAS_FILE || path.startsWith(SCHEMAS_DIR)
|
|
147
152
|
|
|
@@ -168,18 +173,18 @@ const checkSpaReference = (graph: StructureGraph, reference: ModuleReference, ta
|
|
|
168
173
|
if (server !== undefined) report(reference.node, 'spa-server-import', viaMessage(reference, server, 'server code', 'the SPA'), SPA_ALLOWED)
|
|
169
174
|
}
|
|
170
175
|
|
|
171
|
-
/** The
|
|
172
|
-
const
|
|
176
|
+
/** The packages shared code loads, zod's schemas either way; everything else it needs is in other modules of `src/shared/`. */
|
|
177
|
+
const SHARED_PACKAGES: ReadonlySet<string> = new Set(['zod/v4', '@fabrika/app/schema'])
|
|
173
178
|
|
|
174
179
|
/** A shared module runs in the SPA and in every slice, so it loads nothing either side lacks. */
|
|
175
180
|
const checkSharedReference = (reference: ModuleReference, targets: Targets, report: Report): void => {
|
|
176
|
-
const outside = targets.packages.find((specifier) => specifier
|
|
181
|
+
const outside = targets.packages.find((specifier) => !SHARED_PACKAGES.has(specifier)) ?? targets.files.find((path) => !isSharedModule(path))
|
|
177
182
|
if (outside === undefined) return
|
|
178
183
|
report(
|
|
179
184
|
reference.node,
|
|
180
185
|
'shared-import',
|
|
181
186
|
viaMessage(reference, outside, 'outside src/shared/', 'shared code'),
|
|
182
|
-
'zod/v4 and other modules under src/shared/; a type-only import of anything else',
|
|
187
|
+
'zod/v4, @fabrika/app/schema and other modules under src/shared/; a type-only import of anything else',
|
|
183
188
|
)
|
|
184
189
|
}
|
|
185
190
|
|
|
@@ -221,23 +226,171 @@ const checkSliceReference = (place: StructurePlace, reference: ModuleReference,
|
|
|
221
226
|
)
|
|
222
227
|
}
|
|
223
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
|
+
|
|
361
|
+
/**
|
|
362
|
+
* A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
|
|
363
|
+
* load by its name, past `tool-import`, which judges the files an import resolves to.
|
|
364
|
+
*/
|
|
365
|
+
export const checkToolPackages = (paths: readonly string[]): Finding[] =>
|
|
366
|
+
paths.filter((path) => isToolModule(path) && path.endsWith('/package.json')).map((path) => ({
|
|
367
|
+
file: path,
|
|
368
|
+
line: 1,
|
|
369
|
+
column: 1,
|
|
370
|
+
severity: 'refusal',
|
|
371
|
+
rule: 'tool-import',
|
|
372
|
+
message: `'${path}' makes a developer's tool a package, which the application could load by its name`,
|
|
373
|
+
allowed: "tools/ without a package.json: a tool's dependencies go in the root package.json",
|
|
374
|
+
}))
|
|
375
|
+
|
|
224
376
|
/** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
|
|
225
377
|
export const checkStructureReferences = (graph: StructureGraph, place: StructurePlace, report: Report): void => {
|
|
226
378
|
for (const reference of graph.referencesOf(place.file)) {
|
|
227
379
|
const targets = referenceTargets(graph, place.file, reference.specifier)
|
|
228
|
-
if (
|
|
380
|
+
if (reference.typeOnly) continue
|
|
381
|
+
const tool = isToolModule(place.file) ? undefined : targets.files.find(isToolModule)
|
|
382
|
+
if (tool !== undefined) {
|
|
229
383
|
report(
|
|
230
384
|
reference.node,
|
|
231
|
-
'
|
|
232
|
-
`'${reference.specifier}'
|
|
233
|
-
'a
|
|
385
|
+
'tool-import',
|
|
386
|
+
`'${reference.specifier}' loads ${tool}, a developer's tool, which nothing outside tools/ loads`,
|
|
387
|
+
'what the application and a tool share under src/ (pure code in src/shared/), imported by the tool',
|
|
234
388
|
)
|
|
235
389
|
}
|
|
236
|
-
if (reference.typeOnly) continue
|
|
237
390
|
if (place.file.startsWith(SPA_DIR) && !place.exempt) checkSpaReference(graph, reference, targets, report)
|
|
238
391
|
if (isSharedModule(place.file) && !place.exempt) checkSharedReference(reference, targets, report)
|
|
239
392
|
if (isLayerModule(place.file)) checkLayerReference(graph, place, reference, targets, report)
|
|
240
|
-
if (place.exempt) continue
|
|
393
|
+
if (place.exempt || place.generated) continue
|
|
241
394
|
if (place.part === 'logic') checkLogicReference(reference, targets, report)
|
|
242
395
|
else if (place.slice !== undefined) checkSliceReference(place, reference, targets, report)
|
|
243
396
|
}
|
|
@@ -276,7 +429,7 @@ const dataAccess = (node: AstNode): string | undefined => {
|
|
|
276
429
|
|
|
277
430
|
/** The architecture's hints at one node: a handler outside `endpoints.ts`, data access outside `endpoints.ts`/`queries.ts`. */
|
|
278
431
|
export const checkStructureNode = (place: StructurePlace, node: AstNode, report: Report): void => {
|
|
279
|
-
if (place.exempt) return
|
|
432
|
+
if (place.exempt || place.generated) return
|
|
280
433
|
const handle = handledProcedure(node)?.handle
|
|
281
434
|
if (handle !== undefined && place.part !== 'endpoints') {
|
|
282
435
|
report(
|
package/src/rules/tests.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { type AstNode, child, children,
|
|
1
|
+
import { type AstNode, child, children, identifierName, memberPath, memberSuffix, staticString, walk } from '../ast'
|
|
2
2
|
import type { Finding, Report } from '../finding'
|
|
3
|
-
import { ENDPOINT_ACCESS_TEST, isRelativeSpecifier, joinRelative, POLICY_TEST_SUFFIX, POLICY_TESTS_DIR, resolveRelative } from '../layout'
|
|
4
3
|
import { declaringScope } from '../scope'
|
|
5
4
|
import { isKey, parseToml } from '../toml'
|
|
6
5
|
import { BUNFIG_FILE } from '../trust'
|
|
@@ -33,7 +32,7 @@ const isAssertionCall = (node: AstNode): boolean => {
|
|
|
33
32
|
const path = memberPath(callee)
|
|
34
33
|
const [root] = path ?? []
|
|
35
34
|
const last = path?.[path.length - 1]
|
|
36
|
-
return root !== undefined && root !== 'expect' && (
|
|
35
|
+
return root !== undefined && root !== 'expect' && (root.startsWith('assert') || (last !== undefined && ASSERTION_NAME.test(last)))
|
|
37
36
|
}
|
|
38
37
|
|
|
39
38
|
/** Whether a test body runs an assertion; a nested function counts only where it is called or passed to a call. */
|
|
@@ -107,50 +106,12 @@ export const checkTestNode = (node: AstNode, ancestors: readonly AstNode[], repo
|
|
|
107
106
|
}
|
|
108
107
|
}
|
|
109
108
|
|
|
110
|
-
/** The first line of a test written by `fabrika db test-scaffold`, followed by the SHA-256 of everything after that line. */
|
|
111
|
-
export const GENERATED_TEST_HEADER = '// @generated by fabrika db test-scaffold sha256:'
|
|
112
|
-
const GENERATED_TEST_MARKER = '// @generated by fabrika db test-scaffold'
|
|
113
|
-
|
|
114
|
-
const sha256 = async (text: string): Promise<string> => {
|
|
115
|
-
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
|
|
116
|
-
return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('')
|
|
117
|
-
}
|
|
118
|
-
|
|
119
|
-
/** The header `fabrika db test-scaffold` puts on a generated test with this body. */
|
|
120
|
-
export const generatedTestHeader = async (body: string): Promise<string> => `${GENERATED_TEST_HEADER}${await sha256(body)}`
|
|
121
|
-
|
|
122
|
-
export const checkGeneratedTest = async (text: string, comments: readonly Comment[], report: Report): Promise<void> => {
|
|
123
|
-
if (!text.startsWith(GENERATED_TEST_MARKER)) {
|
|
124
|
-
const misplaced = comments.find((comment) => comment.text.includes(GENERATED_TEST_MARKER.slice('// '.length)))
|
|
125
|
-
if (misplaced !== undefined) {
|
|
126
|
-
report(
|
|
127
|
-
misplaced.position,
|
|
128
|
-
'generated-test-hash',
|
|
129
|
-
'the generated-test header is not the first line of the file',
|
|
130
|
-
'the file as fabrika db test-scaffold wrote it',
|
|
131
|
-
)
|
|
132
|
-
}
|
|
133
|
-
return
|
|
134
|
-
}
|
|
135
|
-
const newline = text.indexOf('\n')
|
|
136
|
-
const header = newline === -1 ? text : text.slice(0, newline)
|
|
137
|
-
const body = newline === -1 ? '' : text.slice(newline + 1)
|
|
138
|
-
if (header === (await generatedTestHeader(body))) return
|
|
139
|
-
report(
|
|
140
|
-
{ line: 1, column: 1 },
|
|
141
|
-
'generated-test-hash',
|
|
142
|
-
'this generated test differs from what fabrika db test-scaffold wrote',
|
|
143
|
-
'the file as generated; rerun fabrika db test-scaffold after a table change',
|
|
144
|
-
)
|
|
145
|
-
}
|
|
146
|
-
|
|
147
109
|
/** `[test]` keys that pick other test files, skip some, or let a failing test pass on a later attempt. */
|
|
148
110
|
const SUITE_NARROWING_TEST_KEYS = ['root', 'pathIgnorePatterns', 'retry'] as const
|
|
149
111
|
|
|
150
112
|
/**
|
|
151
|
-
* The `bunfig.toml` of an application must not narrow its own suite
|
|
152
|
-
*
|
|
153
|
-
* subset is reported by the trust rules.
|
|
113
|
+
* The `bunfig.toml` of an application must not narrow its own suite, which the platform build runs. A file outside the
|
|
114
|
+
* TOML subset is reported by the trust rules.
|
|
154
115
|
*/
|
|
155
116
|
export const checkTestSuiteConfig = (text: string): Finding[] => {
|
|
156
117
|
const document = parseToml(text)
|
|
@@ -174,35 +135,23 @@ export const checkTestSuiteConfig = (text: string): Finding[] => {
|
|
|
174
135
|
return findings
|
|
175
136
|
}
|
|
176
137
|
|
|
177
|
-
/** Whether `path` is a file the scaffold generates: a policy isolation test, the endpoint access test, or one with the header. */
|
|
178
|
-
export const isGeneratedTestPath = (path: string, files: ReadonlyMap<string, string>): boolean =>
|
|
179
|
-
path === ENDPOINT_ACCESS_TEST || (path.startsWith(POLICY_TESTS_DIR) && path.endsWith(POLICY_TEST_SUFFIX))
|
|
180
|
-
|| (files.get(path)?.startsWith(GENERATED_TEST_MARKER) ?? false)
|
|
181
|
-
|
|
182
138
|
/**
|
|
183
|
-
* `mock.module(…)` of the test runner
|
|
184
|
-
*
|
|
139
|
+
* `mock.module(…)` of the test runner or a framework package would let application code replace what the test kit runs
|
|
140
|
+
* on; a computed specifier could name either. Refused anywhere in the application.
|
|
185
141
|
*/
|
|
186
|
-
export const checkMockModule = (node: AstNode,
|
|
142
|
+
export const checkMockModule = (node: AstNode, report: Report): void => {
|
|
187
143
|
if (node.type !== 'CallExpression') return
|
|
188
144
|
const callee = child(node, 'callee')
|
|
189
145
|
if (callee === undefined || callee.type !== 'MemberExpression') return
|
|
190
146
|
const suffix = memberPath(callee) ?? memberSuffix(callee)
|
|
191
147
|
if (suffix.length < 2 || suffix[suffix.length - 1] !== 'module' || suffix[suffix.length - 2] !== 'mock') return
|
|
192
|
-
const allowed = 'mock.module of an application module
|
|
148
|
+
const allowed = 'mock.module of an application module, with a literal specifier'
|
|
193
149
|
const specifier = staticString(children(node, 'arguments')[0] ?? undefined)
|
|
194
150
|
if (specifier === undefined) {
|
|
195
151
|
report(node, 'mock-module', 'mock.module with a computed specifier could replace the test runner or the framework', allowed)
|
|
196
152
|
return
|
|
197
153
|
}
|
|
198
154
|
if (specifier === 'bun:test' || specifier.startsWith('@fabrika/')) {
|
|
199
|
-
report(node, 'mock-module', `mock.module('${specifier}') replaces what the
|
|
200
|
-
return
|
|
201
|
-
}
|
|
202
|
-
if (!isRelativeSpecifier(specifier)) return
|
|
203
|
-
const resolved = resolveRelative((path) => files.has(path), file, specifier)
|
|
204
|
-
const targets = resolved.kind === 'file' ? [resolved.path] : resolved.kind === 'missing' ? [joinRelative(file, specifier) ?? ''] : resolved.paths
|
|
205
|
-
if (targets.some((target) => isGeneratedTestPath(target, files))) {
|
|
206
|
-
report(node, 'mock-module', `mock.module('${specifier}') replaces a generated test`, allowed)
|
|
155
|
+
report(node, 'mock-module', `mock.module('${specifier}') replaces what the test kit runs on`, allowed)
|
|
207
156
|
}
|
|
208
157
|
}
|
package/src/rules/types.ts
CHANGED
|
@@ -17,6 +17,7 @@ const admitsAnyString = (type: AstNode): boolean => {
|
|
|
17
17
|
const referencedName = (typeName: AstNode | undefined): string | undefined =>
|
|
18
18
|
typeName?.type === 'TSQualifiedName' ? identifierName(child(typeName, 'right')) : identifierName(typeName)
|
|
19
19
|
|
|
20
|
+
/** `type-assertion` and `any-type`: how a module's own source is written, which a generated module is not held to. */
|
|
20
21
|
export const checkTypeNode = (node: AstNode, report: Report): void => {
|
|
21
22
|
switch (node.type) {
|
|
22
23
|
case 'TSAsExpression':
|
|
@@ -27,22 +28,22 @@ export const checkTypeNode = (node: AstNode, report: Report): void => {
|
|
|
27
28
|
return
|
|
28
29
|
case 'TSAnyKeyword':
|
|
29
30
|
report(node, 'any-type', '`any` switches type checking off', 'the concrete type, or `unknown` narrowed by a check')
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const checkCapabilityNode = (node: AstNode, report: Report): void => {
|
|
35
|
+
if (node.type !== 'TSTypeReference') return
|
|
36
|
+
const name = referencedName(child(node, 'typeName'))
|
|
37
|
+
if (name === undefined || !CAPABILITIES.has(name)) return
|
|
38
|
+
const typeArguments = child(node, 'typeArguments')
|
|
39
|
+
const parameters = typeArguments === undefined ? [] : children(typeArguments, 'params')
|
|
40
|
+
if (parameters.some((parameter) => parameter !== null && admitsAnyString(parameter))) {
|
|
41
|
+
report(
|
|
42
|
+
node,
|
|
43
|
+
'capability-widening',
|
|
44
|
+
`${name}<string, …> widens a capability to any dimension or action`,
|
|
45
|
+
`${name}<'<dimension>', '<action>'> with literal names`,
|
|
46
|
+
)
|
|
46
47
|
}
|
|
47
48
|
}
|
|
48
49
|
|
|
@@ -0,0 +1,53 @@
|
|
|
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. The SPA's slice of the module that
|
|
3
|
+
// declares the table policies has `tables = {}`: the client never reads them, and their parse would load with them.
|
|
4
|
+
|
|
5
|
+
import { readFileSync, statSync } from 'node:fs'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { parseModule } from './ast'
|
|
8
|
+
import { contractReaderInputs, readContract, readTablesDeclaration, type TablesDeclaration } from './contract'
|
|
9
|
+
import { CONTRACT_FILE, isSourceFile } from './layout'
|
|
10
|
+
import { moduleSlice, shellSlice } from './slice'
|
|
11
|
+
|
|
12
|
+
const SOURCE_EXTENSION = String.raw`\.(?:[mc]?[jt]s|[jt]sx)$`
|
|
13
|
+
|
|
14
|
+
/** The application's own modules under `root`, outside `node_modules`: every extension the reader reads. */
|
|
15
|
+
export const applicationModules = (root: string): RegExp =>
|
|
16
|
+
new RegExp(`^${root.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\/](?!(?:.*[\\/])?node_modules[\\/]).*${SOURCE_EXTENSION}`)
|
|
17
|
+
|
|
18
|
+
const isFile = (path: string): boolean => statSync(path, { throwIfNoEntry: false })?.isFile() === true
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The shell modules under `root`, by absolute path, as their slices; none without a `fabrika.contract.ts` there.
|
|
22
|
+
* Throws the reader's refusal when the static reader refuses the shell or the table policies.
|
|
23
|
+
*/
|
|
24
|
+
export function shellModules(root: string): ReadonlyMap<string, string> {
|
|
25
|
+
if (!isFile(join(root, CONTRACT_FILE))) return new Map()
|
|
26
|
+
const files = new Map<string, string>()
|
|
27
|
+
for (;;) {
|
|
28
|
+
const missing = contractReaderInputs(files, (path) => isFile(join(root, path)))
|
|
29
|
+
if (missing.length === 0) break
|
|
30
|
+
for (const path of missing) files.set(path, readFileSync(join(root, path), 'utf8'))
|
|
31
|
+
}
|
|
32
|
+
readContract(files)
|
|
33
|
+
// The policies are refused here as the platform refuses them, instead of by `defineTables` in the browser.
|
|
34
|
+
const tables = readTablesDeclaration(files)
|
|
35
|
+
return new Map(
|
|
36
|
+
[...files]
|
|
37
|
+
.filter(([path]) => isSourceFile(path))
|
|
38
|
+
.map(([path, text]) => [join(root, path), path === tables?.file ? withoutPolicies(path, text, tables) : shellSlice(path, text).text]),
|
|
39
|
+
)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The slice of the module that declares the policies, its `defineTables(…)(…)` call and what only the call imports
|
|
44
|
+
* blanked, `{}` in the call's place. `defineApp` reads of `tables` only that it is given.
|
|
45
|
+
*/
|
|
46
|
+
function withoutPolicies(path: string, text: string, tables: TablesDeclaration): string {
|
|
47
|
+
const slice = shellSlice(path, text).text
|
|
48
|
+
const parsed = parseModule(path, slice)
|
|
49
|
+
// The reader has just read the policies from this slice.
|
|
50
|
+
if (!parsed.ok) throw new Error(`${path}: the slice the policies were read from does not parse`)
|
|
51
|
+
const blanked = moduleSlice(parsed.module, slice, [tables.call]).text
|
|
52
|
+
return `${blanked.slice(0, tables.call.start)}{}${blanked.slice(tables.call.start + 2)}`
|
|
53
|
+
}
|
package/src/slice.ts
CHANGED
|
@@ -26,14 +26,14 @@ import type { Finding } from './finding'
|
|
|
26
26
|
/** Builders whose result takes `.handle(handler)`: an endpoint of a group, a link or an export, a job and a webhook. */
|
|
27
27
|
const HANDLED_BUILDERS = new Set(['query', 'mutation', 'cron', 'webhook'])
|
|
28
28
|
|
|
29
|
-
interface Range {
|
|
29
|
+
export interface Range {
|
|
30
30
|
readonly start: number
|
|
31
31
|
readonly end: number
|
|
32
32
|
}
|
|
33
33
|
|
|
34
34
|
const isFunction = (node: AstNode | null | undefined): boolean => node?.type === 'ArrowFunctionExpression' || node?.type === 'FunctionExpression'
|
|
35
35
|
|
|
36
|
-
const offsets = (node: AstNode): Range | undefined => {
|
|
36
|
+
export const offsets = (node: AstNode): Range | undefined => {
|
|
37
37
|
const start = node['start']
|
|
38
38
|
const end = node['end']
|
|
39
39
|
return typeof start === 'number' && typeof end === 'number' ? { start, end } : undefined
|
|
@@ -245,10 +245,11 @@ export interface ShellSlice {
|
|
|
245
245
|
|
|
246
246
|
/**
|
|
247
247
|
* The slice of one parsed module: `module`'s text with every `.handle(…)` and everything only the handlers used
|
|
248
|
-
* blanked. A module without a handler comes back unchanged.
|
|
248
|
+
* blanked. A module without a handler comes back unchanged. Each range of `removed` goes as a handler does, with what
|
|
249
|
+
* only it uses.
|
|
249
250
|
*/
|
|
250
|
-
export function moduleSlice(module: ParsedModule, text: string): ShellSlice {
|
|
251
|
-
const handles: Range[] = []
|
|
251
|
+
export function moduleSlice(module: ParsedModule, text: string, removed: readonly Range[] = []): ShellSlice {
|
|
252
|
+
const handles: Range[] = [...removed]
|
|
252
253
|
const refusals: SliceRefusal[] = []
|
|
253
254
|
const visit = (node: AstNode): 'skip' | undefined => {
|
|
254
255
|
const site = handleSite(node)
|
package/src/source-maps.ts
CHANGED
|
@@ -144,6 +144,8 @@ export async function uploadSourceMaps(
|
|
|
144
144
|
},
|
|
145
145
|
body: artifact.body,
|
|
146
146
|
signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS),
|
|
147
|
+
// The bearer and the map must never reach a redirect target; a 3xx is not ok below.
|
|
148
|
+
redirect: 'manual',
|
|
147
149
|
})
|
|
148
150
|
if (response.ok) uploaded++
|
|
149
151
|
else incomplete = true
|
package/src/trust.ts
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
import type { Finding } from './finding'
|
|
6
6
|
import { parseJsonc } from './jsonc'
|
|
7
|
-
import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, joinRelative } from './layout'
|
|
7
|
+
import { isIgnoredSegment, isRelativeSpecifier, isSourceFile, isToolModule, joinRelative } from './layout'
|
|
8
8
|
import { isKey, parseToml } from './toml'
|
|
9
9
|
|
|
10
10
|
/** Packages whose exports the reader trusts by name, and the packages they rely on. */
|
|
@@ -141,11 +141,15 @@ function checkTsconfig(path: string, text: string, files: ReadonlyMap<string, st
|
|
|
141
141
|
}
|
|
142
142
|
}
|
|
143
143
|
|
|
144
|
-
/**
|
|
144
|
+
/**
|
|
145
|
+
* A test preload must be a checked application file: a skipped or generated one runs unchecked during the build, and a
|
|
146
|
+
* developer's tool is not checked as application code.
|
|
147
|
+
*/
|
|
145
148
|
const isCheckedTestPreload = (target: string): boolean => {
|
|
146
149
|
if (!target.startsWith('./')) return false
|
|
147
150
|
const segments = target.slice(2).split('/')
|
|
148
|
-
return segments[0] !== 'fabrika' &&
|
|
151
|
+
return segments[0] !== 'fabrika' && !isToolModule(target.slice(2))
|
|
152
|
+
&& segments.every((segment) => segment !== '' && segment !== '..' && !isIgnoredSegment(segment))
|
|
149
153
|
&& isSourceFile(target)
|
|
150
154
|
}
|
|
151
155
|
|
|
@@ -180,7 +184,7 @@ function checkBunfig(text: string, report: (needle: string, message: string, all
|
|
|
180
184
|
report(
|
|
181
185
|
at(entry.line),
|
|
182
186
|
'a test preload outside the checked application files runs unchecked in the platform build',
|
|
183
|
-
"'./<path>' of a source file the checker reads, outside fabrika/, dist/, node_modules/ and dot directories",
|
|
187
|
+
"'./<path>' of a source file the checker reads, outside fabrika/, tools/, dist/, node_modules/ and dot directories",
|
|
184
188
|
)
|
|
185
189
|
}
|
|
186
190
|
}
|
|
@@ -0,0 +1,65 @@
|
|
|
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/`, and the SPA loads
|
|
57
|
+
// no module only the table policies import, which the next read checks again.
|
|
58
|
+
for (const file of shell.keys()) this.addWatchFile(file)
|
|
59
|
+
return { code }
|
|
60
|
+
},
|
|
61
|
+
watchChange() {
|
|
62
|
+
shell = undefined
|
|
63
|
+
},
|
|
64
|
+
}
|
|
65
|
+
}
|