@fabrika/check 0.9.0-dev.2 → 0.9.0-dev.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -7
- package/src/ast.ts +69 -6
- package/src/check.ts +148 -44
- package/src/cli.ts +34 -8
- package/src/contract.ts +42 -6
- package/src/dialect.ts +29 -0
- package/src/finding.ts +14 -7
- package/src/index.ts +4 -12
- package/src/inputs.ts +4 -2
- package/src/layout.ts +41 -12
- package/src/limits.ts +13 -3
- package/src/migration-base.ts +85 -0
- package/src/reader/schema.ts +42 -512
- package/src/reader/surface.ts +43 -5
- package/src/reader/value.ts +18 -6
- package/src/resolution.ts +2 -2
- package/src/rules/cloudflare.ts +59 -0
- package/src/rules/compile.ts +32 -0
- package/src/rules/framework.ts +2 -2
- package/src/rules/literal.ts +3 -1
- 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 +38 -18
- package/src/rules/tests.ts +9 -60
- package/src/rules/types.ts +17 -16
- package/src/source-maps.ts +2 -0
- package/src/trust.ts +8 -4
- package/types/src/ast.d.ts +6 -0
- package/types/src/check.d.ts +3 -0
- package/types/src/contract.d.ts +1 -0
- package/types/src/dialect.d.ts +8 -0
- package/types/src/finding.d.ts +6 -5
- package/types/src/index.d.ts +4 -3
- package/types/src/layout.d.ts +25 -10
- package/types/src/limits.d.ts +12 -2
- 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 +2 -2
- 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/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 +11 -4
- package/types/src/rules/tests.d.ts +6 -14
- package/types/src/rules/types.d.ts +2 -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
|
@@ -12,7 +12,7 @@ export type TrustedBindings = ReadonlyMap<string, readonly TrustedBinding[]>;
|
|
|
12
12
|
export declare const trustedBindings: (file: string, program: AstNode, mappings: ImportMappings) => TrustedBindings;
|
|
13
13
|
/**
|
|
14
14
|
* A write to a member of a value from `@fabrika/*` or `zod`: an assignment, `delete`, `++`, or a writer call on it. A
|
|
15
|
-
* replaced `
|
|
15
|
+
* replaced `openPostgres` receives the database URL; a patched schema changes what the contract admits. A write
|
|
16
16
|
* through a prototype is `prototype-assignment`'s. A local that shadows such a name is not one.
|
|
17
17
|
*/
|
|
18
18
|
export declare const checkFrameworkWrite: (node: AstNode, ancestors: readonly AstNode[], bindings: TrustedBindings, report: Report) => void;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { Finding } from '../finding';
|
|
2
|
+
/** The migrations of `db/migrations` at the commit the tree is compared with, by path relative to the root. */
|
|
3
|
+
export interface MigrationBase {
|
|
4
|
+
/** How the commit is named to the author, such as `origin/main`. */
|
|
5
|
+
readonly ref: string;
|
|
6
|
+
readonly files: ReadonlyMap<string, string>;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Each migration of `base` that the tree changed (at its first changed line) or no longer holds. A file renamed is one
|
|
10
|
+
* removed and one new, and the new one would run again where the old one ran, so the removal is what is reported.
|
|
11
|
+
*/
|
|
12
|
+
export declare const checkMigrationHistory: (files: ReadonlyMap<string, string>, base: MigrationBase) => Finding[];
|
|
@@ -1,6 +1,22 @@
|
|
|
1
1
|
import type { Finding } from '../finding';
|
|
2
2
|
/** Migration file names sort by creation time, so parallel worktrees never claim the same name. */
|
|
3
3
|
export declare const checkMigrationNames: (paths: readonly string[]) => Finding[];
|
|
4
|
+
/**
|
|
5
|
+
* On SQLite `DEFAULT CURRENT_TIMESTAMP` stores `YYYY-MM-DD HH:MM:SS`, which every read of the table refuses as
|
|
6
|
+
* `unexpected_row` (backlog 216 item 13). Refused with or without parentheses, at the line of `CURRENT_TIMESTAMP`.
|
|
7
|
+
*/
|
|
8
|
+
export declare const checkCurrentTimestampDefaults: (files: ReadonlyMap<string, string>) => Finding[];
|
|
9
|
+
/**
|
|
10
|
+
* On SQLite an application migration runs verbatim, with no name rule, so a view or a trigger over a framework table
|
|
11
|
+
* would reach what `ctx.sql`'s name rule keeps it from. Every `fabrika_*` name is refused (any case, quoted, bracketed,
|
|
12
|
+
* or as a string SQLite may read as a name) but `fabrika_files` right after `REFERENCES`, a file column's foreign key.
|
|
13
|
+
*/
|
|
14
|
+
export declare const checkSqliteFrameworkNames: (files: ReadonlyMap<string, string>) => Finding[];
|
|
15
|
+
/**
|
|
16
|
+
* A view is read-only (ADR-0072); on SQLite an INSTEAD OF trigger would make a view writable, so it is refused. SQLite
|
|
17
|
+
* takes INSTEAD OF only on a view, so the timing alone, written before the trigger's `ON`, names one.
|
|
18
|
+
*/
|
|
19
|
+
export declare const checkSqliteViewTriggers: (files: ReadonlyMap<string, string>) => Finding[];
|
|
4
20
|
/** A declared file column: `table.column` holds files of `kind`. */
|
|
5
21
|
export interface FileColumn {
|
|
6
22
|
readonly table: string;
|
|
@@ -27,3 +43,15 @@ export interface ConflictInsert {
|
|
|
27
43
|
* checked: another receiver of `insert` is no table of the data layer.
|
|
28
44
|
*/
|
|
29
45
|
export declare const checkConflictIndexes: (files: ReadonlyMap<string, string>, tables: ReadonlySet<string>, inserts: readonly ConflictInsert[]) => Finding[];
|
|
46
|
+
/** A table that names an access view under `key` (ADR-0076). */
|
|
47
|
+
export interface AccessKey {
|
|
48
|
+
readonly table: string;
|
|
49
|
+
readonly key: string;
|
|
50
|
+
readonly views: readonly string[];
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A table that names an access view needs its key unique on its own, or the view's `row` names several rows at once
|
|
54
|
+
* (ADR-0076 section 1). A view as the target keeps its key unique by its SQL; any other name no migration creates as a
|
|
55
|
+
* table is refused, so a statement the reader does not follow fails closed.
|
|
56
|
+
*/
|
|
57
|
+
export declare const checkAccessViewKeys: (files: ReadonlyMap<string, string>, keys: readonly AccessKey[]) => Finding[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type MigrationDialect } from '@fabrika/platform-node/sql';
|
|
2
|
+
import type { Finding } from '../finding';
|
|
3
|
+
/**
|
|
4
|
+
* Every statement Control's classifier refuses, at its file and line, against the application's access tables and in its
|
|
5
|
+
* dialect. Control refuses a deploy whose new migration holds
|
|
6
|
+
* one (`migrations-refused`), and its run log names neither, so this is where the author finds it. Every file is
|
|
7
|
+
* checked, applied or not: the checker does not know which an environment holds.
|
|
8
|
+
*/
|
|
9
|
+
export declare const checkMigrationClassification: (files: ReadonlyMap<string, string>, appId: string, accessTables: readonly string[], dialect: MigrationDialect) => Finding[];
|
|
10
|
+
/**
|
|
11
|
+
* On Cloudflare, the backup's refusal of the migrated schema (`planOpsDump`), at the newest migration that names the
|
|
12
|
+
* table. Every migration deploy backs the environment up first, so a schema the backup refuses blocks every migration
|
|
13
|
+
* after the one that made it. A migration set that does not apply is codegen's to report, so it finds nothing here.
|
|
14
|
+
*/
|
|
15
|
+
export declare const checkBackupPlan: (files: ReadonlyMap<string, string>) => Promise<Finding[]>;
|
|
@@ -8,8 +8,11 @@ export interface SourceContext {
|
|
|
8
8
|
readonly rawSql: ReadonlySet<string>;
|
|
9
9
|
/** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
|
|
10
10
|
readonly isServerModule: boolean;
|
|
11
|
-
/**
|
|
12
|
-
|
|
11
|
+
/**
|
|
12
|
+
* A `fetch` of an absolute URL, by its static prefix and, for a template whose first label alone is interpolated, its
|
|
13
|
+
* authority with that label as `*`: refused once the contract shows that no site declares its origin in `egress`.
|
|
14
|
+
*/
|
|
15
|
+
readonly absoluteFetch: (node: AstNode, target: string, labelled: string | undefined) => void;
|
|
13
16
|
/** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
|
|
14
17
|
readonly appUrl: (node: AstNode, endpoint: string) => void;
|
|
15
18
|
/** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
|
|
@@ -28,5 +31,7 @@ export declare const crossAppFetchMessage: (target: string) => {
|
|
|
28
31
|
};
|
|
29
32
|
/** Whether an expression reaches a prototype: through `.prototype`, `.__proto__` or `Object.getPrototypeOf(…)`. */
|
|
30
33
|
export declare const touchesPrototype: (node: AstNode | undefined) => boolean;
|
|
34
|
+
/** `key-literal` over a string or a template's text: also the one rule of this module a developer's tool is held to. */
|
|
35
|
+
export declare const checkKeyLiteralNode: (node: AstNode, report: Report) => void;
|
|
31
36
|
/** The rules that read one node at a time, for every source file. */
|
|
32
37
|
export declare const checkRuntimeNode: (node: AstNode, ancestors: readonly AstNode[], context: SourceContext) => void;
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { type AstNode } from '../ast';
|
|
2
|
-
import { type Report } from '../finding';
|
|
2
|
+
import { type Finding, type Report } from '../finding';
|
|
3
3
|
import type { ModuleReference } from '../references';
|
|
4
4
|
import { type ImportMappings } from '../resolution';
|
|
5
|
-
/** The rules of the application architecture (docs/reference/application-architecture.md):
|
|
6
|
-
export declare const STRUCTURE_RULE_IDS: readonly ["spa-server-import", "layer-import", "
|
|
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"];
|
|
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 {
|
|
@@ -12,14 +12,21 @@ export interface StructurePlace {
|
|
|
12
12
|
readonly part: SlicePart | undefined;
|
|
13
13
|
/** A test or the generated entrypoint: the structure hints do not apply to it. */
|
|
14
14
|
readonly exempt: boolean;
|
|
15
|
+
/** A generated module (`isGeneratedModule`): the hints do not apply to it, the refusals do. */
|
|
16
|
+
readonly generated: boolean;
|
|
15
17
|
}
|
|
16
|
-
export declare const structurePlace: (file: string, isGeneratedEntry: boolean) => StructurePlace;
|
|
18
|
+
export declare const structurePlace: (file: string, isGeneratedEntry: boolean, generated: boolean) => StructurePlace;
|
|
17
19
|
/** What the structure rules read beyond one module: every module's references, and how Bun resolves them. */
|
|
18
20
|
export interface StructureGraph {
|
|
19
21
|
readonly files: ReadonlyMap<string, string>;
|
|
20
22
|
readonly mappings: ImportMappings;
|
|
21
23
|
readonly referencesOf: (path: string) => readonly ModuleReference[];
|
|
22
24
|
}
|
|
25
|
+
/**
|
|
26
|
+
* A `package.json` under `tools/` makes a tool a package, which a workspace or a `file:` dependency lets the application
|
|
27
|
+
* load by its name, past `tool-import`, which judges the files an import resolves to.
|
|
28
|
+
*/
|
|
29
|
+
export declare const checkToolPackages: (paths: readonly string[]) => Finding[];
|
|
23
30
|
/** The architecture's rules over one module's imports, re-exports and loads, as Bun resolves them for that module. */
|
|
24
31
|
export declare const checkStructureReferences: (graph: StructureGraph, place: StructurePlace, report: Report) => void;
|
|
25
32
|
/** A `<x>.<builder>(…).handle(…)` call: the builder's name, its call (whose arguments hold the options) and `.handle`. */
|
|
@@ -1,22 +1,14 @@
|
|
|
1
|
-
import { type AstNode
|
|
1
|
+
import { type AstNode } from '../ast';
|
|
2
2
|
import type { Finding, Report } from '../finding';
|
|
3
3
|
/** For test files: every test runs, and every test asserts. */
|
|
4
4
|
export declare const checkTestNode: (node: AstNode, ancestors: readonly AstNode[], report: Report) => void;
|
|
5
|
-
/** The first line of a test written by `fabrika db test-scaffold`, followed by the SHA-256 of everything after that line. */
|
|
6
|
-
export declare const GENERATED_TEST_HEADER = "// @generated by fabrika db test-scaffold sha256:";
|
|
7
|
-
/** The header `fabrika db test-scaffold` puts on a generated test with this body. */
|
|
8
|
-
export declare const generatedTestHeader: (body: string) => Promise<string>;
|
|
9
|
-
export declare const checkGeneratedTest: (text: string, comments: readonly Comment[], report: Report) => Promise<void>;
|
|
10
5
|
/**
|
|
11
|
-
* The `bunfig.toml` of an application must not narrow its own suite
|
|
12
|
-
*
|
|
13
|
-
* subset is reported by the trust rules.
|
|
6
|
+
* The `bunfig.toml` of an application must not narrow its own suite, which the platform build runs. A file outside the
|
|
7
|
+
* TOML subset is reported by the trust rules.
|
|
14
8
|
*/
|
|
15
9
|
export declare const checkTestSuiteConfig: (text: string) => Finding[];
|
|
16
|
-
/** Whether `path` is a file the scaffold generates: a policy isolation test, the endpoint access test, or one with the header. */
|
|
17
|
-
export declare const isGeneratedTestPath: (path: string, files: ReadonlyMap<string, string>) => boolean;
|
|
18
10
|
/**
|
|
19
|
-
* `mock.module(…)` of the test runner
|
|
20
|
-
*
|
|
11
|
+
* `mock.module(…)` of the test runner or a framework package would let application code replace what the test kit runs
|
|
12
|
+
* on; a computed specifier could name either. Refused anywhere in the application.
|
|
21
13
|
*/
|
|
22
|
-
export declare const checkMockModule: (node: AstNode,
|
|
14
|
+
export declare const checkMockModule: (node: AstNode, report: Report) => void;
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type AstNode, type Comment } from '../ast';
|
|
2
2
|
import type { Report } from '../finding';
|
|
3
|
+
/** `type-assertion` and `any-type`: how a module's own source is written, which a generated module is not held to. */
|
|
3
4
|
export declare const checkTypeNode: (node: AstNode, report: Report) => void;
|
|
5
|
+
export declare const checkCapabilityNode: (node: AstNode, report: Report) => void;
|
|
4
6
|
export declare const checkComments: (comments: readonly Comment[], report: Report) => void;
|
package/src/endpoint-fixtures.ts
DELETED
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
// `src/__tests__/endpoint-access.fixtures.ts`: what an application's author gives the endpoint access tests. `fixtures`
|
|
2
|
-
// are the inputs the scaffold cannot sample (a `regex`); `seeds` are the state of the row an endpoint addresses, which
|
|
3
|
-
// its precondition needs (`deals.reopen` reopens only a won deal: `{ stage: 'won' }`); `members` are the input fields
|
|
4
|
-
// that name a member the handler looks up (`deals.assign`'s `ownerId`), which the kit fills with a real member;
|
|
5
|
-
// `invitations` and `links` the fields that name an invitation the handler cancels or a share link it revokes, which the
|
|
6
|
-
// kit fills with one it holds; `rows` the fields that name a row lying in the endpoint's object (a note's comment), by
|
|
7
|
-
// table, which the kit seeds in each scope's object. Read from source, never executed, within the reader's budget:
|
|
8
|
-
// `export const fixtures = { '<endpoint id>': { … } }`, `export const seeds = { '<endpoint id>': { <column>: <value> } }`,
|
|
9
|
-
// `export const members = { '<endpoint id>': ['<field>'] }` (`invitations`, `links` alike) and
|
|
10
|
-
// `export const rows = { '<endpoint id>': { <field>: '<table>' } }`, plain literals only.
|
|
11
|
-
// Browser-safe.
|
|
12
|
-
|
|
13
|
-
import { type AstNode, child, children, identifierName, nodeDepth, parseModule, positionOf, staticKey, staticString } from './ast'
|
|
14
|
-
import type { Finding } from './finding'
|
|
15
|
-
import { ENDPOINT_FIXTURES_FILE } from './layout'
|
|
16
|
-
import { CONTRACT_LIMITS } from './limits'
|
|
17
|
-
import type { Sample } from './scaffold-sample'
|
|
18
|
-
|
|
19
|
-
export const FIXTURES_EXPORT = 'fixtures'
|
|
20
|
-
export const SEEDS_EXPORT = 'seeds'
|
|
21
|
-
export const MEMBERS_EXPORT = 'members'
|
|
22
|
-
export const INVITATIONS_EXPORT = 'invitations'
|
|
23
|
-
export const LINKS_EXPORT = 'links'
|
|
24
|
-
export const ROWS_EXPORT = 'rows'
|
|
25
|
-
|
|
26
|
-
/** The exports that list, by endpoint id, the input fields the kit fills with something it holds. */
|
|
27
|
-
const FIELD_EXPORTS = [MEMBERS_EXPORT, INVITATIONS_EXPORT, LINKS_EXPORT] as const
|
|
28
|
-
type FieldExport = (typeof FIELD_EXPORTS)[number]
|
|
29
|
-
const isFieldExport = (name: string | undefined): name is FieldExport => FIELD_EXPORTS.some((field) => field === name)
|
|
30
|
-
|
|
31
|
-
const ALLOWED =
|
|
32
|
-
"export const fixtures = { 'api.notes.get': { id: '…' } }, export const seeds = { 'api.deals.reopen': { stage: 'won' } }, export const members = { 'api.deals.assign': ['ownerId'] }, export const invitations = { 'api.members.cancel': ['invitationId'] }, export const links = { 'api.notes.unshare': ['linkId'] } and export const rows = { 'api.notes.editComment': { commentId: 'note_comments' } }: string keys, and strings, numbers, booleans, null, arrays and objects"
|
|
33
|
-
|
|
34
|
-
type ById = Readonly<Record<string, Readonly<Record<string, Sample>>>>
|
|
35
|
-
|
|
36
|
-
export interface EndpointFixtures {
|
|
37
|
-
/** The input each endpoint's cases send, by endpoint id. */
|
|
38
|
-
readonly inputs: ById
|
|
39
|
-
/** The columns of the row each endpoint addresses, as both scopes' rows are seeded, by endpoint id. */
|
|
40
|
-
readonly seeds: ById
|
|
41
|
-
/** The input fields that name a member of the endpoint's member directory, by endpoint id. */
|
|
42
|
-
readonly members: Readonly<Record<string, readonly string[]>>
|
|
43
|
-
/** The input fields that name an invitation the endpoint cancels, by endpoint id. */
|
|
44
|
-
readonly invitations: Readonly<Record<string, readonly string[]>>
|
|
45
|
-
/** The input fields that name a share link the endpoint revokes, by endpoint id. */
|
|
46
|
-
readonly links: Readonly<Record<string, readonly string[]>>
|
|
47
|
-
/** The input fields that name a row lying in the endpoint's object, with that row's table, by endpoint id. */
|
|
48
|
-
readonly rows: Readonly<Record<string, Readonly<Record<string, string>>>>
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export const NO_FIXTURES: EndpointFixtures = { inputs: {}, seeds: {}, members: {}, invitations: {}, links: {}, rows: {} }
|
|
52
|
-
|
|
53
|
-
const finding = (at: AstNode | undefined, message: string): Finding => {
|
|
54
|
-
const { line, column } = at === undefined ? { line: 1, column: 1 } : positionOf(at)
|
|
55
|
-
return { file: ENDPOINT_FIXTURES_FILE, line, column, severity: 'refusal', rule: 'endpoint-fixture', message, allowed: ALLOWED }
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export function isSampleObject(value: Sample): value is { readonly [key: string]: Sample } {
|
|
59
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
/** A plain literal value, or the node that is not one. */
|
|
63
|
-
function literal(
|
|
64
|
-
node: AstNode | undefined,
|
|
65
|
-
): { readonly ok: true; readonly value: Sample } | { readonly ok: false; readonly at: AstNode | undefined } {
|
|
66
|
-
if (node === undefined) return { ok: false, at: node }
|
|
67
|
-
if (node.type === 'Literal') {
|
|
68
|
-
const value = node['value']
|
|
69
|
-
if (value === null || typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
|
|
70
|
-
return { ok: true, value }
|
|
71
|
-
}
|
|
72
|
-
return { ok: false, at: node }
|
|
73
|
-
}
|
|
74
|
-
if (node.type === 'TemplateLiteral') {
|
|
75
|
-
const text = staticString(node)
|
|
76
|
-
return text === undefined ? { ok: false, at: node } : { ok: true, value: text }
|
|
77
|
-
}
|
|
78
|
-
if (node.type === 'UnaryExpression' && node['operator'] === '-') {
|
|
79
|
-
const inner = literal(child(node, 'argument'))
|
|
80
|
-
return inner.ok && typeof inner.value === 'number' ? { ok: true, value: -inner.value } : { ok: false, at: node }
|
|
81
|
-
}
|
|
82
|
-
if (node.type === 'ArrayExpression') {
|
|
83
|
-
const items: Sample[] = []
|
|
84
|
-
for (const element of children(node, 'elements')) {
|
|
85
|
-
const item = literal(element ?? undefined)
|
|
86
|
-
if (!item.ok) return item
|
|
87
|
-
items.push(item.value)
|
|
88
|
-
}
|
|
89
|
-
return { ok: true, value: items }
|
|
90
|
-
}
|
|
91
|
-
if (node.type === 'ObjectExpression') {
|
|
92
|
-
const entries: [string, Sample][] = []
|
|
93
|
-
for (const property of children(node, 'properties')) {
|
|
94
|
-
if (property?.type !== 'Property' || property['computed'] === true || property['method'] === true) return { ok: false, at: property ?? node }
|
|
95
|
-
const key = staticKey(property, 'key')
|
|
96
|
-
if (key === undefined || key === '__proto__') return { ok: false, at: property }
|
|
97
|
-
const value = literal(child(property, 'value'))
|
|
98
|
-
if (!value.ok) return value
|
|
99
|
-
entries.push([key, value.value])
|
|
100
|
-
}
|
|
101
|
-
return { ok: true, value: Object.fromEntries(entries) }
|
|
102
|
-
}
|
|
103
|
-
return { ok: false, at: node }
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
/** One `export const <name> = { '<endpoint id>': { … } }`, read into an object of objects. */
|
|
107
|
-
function byId(
|
|
108
|
-
declarator: AstNode,
|
|
109
|
-
name: string,
|
|
110
|
-
): { readonly ok: true; readonly value: ById } | { readonly ok: false; readonly findings: readonly Finding[] } {
|
|
111
|
-
const init = child(declarator, 'init')
|
|
112
|
-
const value = literal(init)
|
|
113
|
-
if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
|
|
114
|
-
const all = value.value
|
|
115
|
-
if (!isSampleObject(all)) {
|
|
116
|
-
return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
|
|
117
|
-
}
|
|
118
|
-
const entries: Record<string, Readonly<Record<string, Sample>>> = {}
|
|
119
|
-
for (const [id, entry] of Object.entries(all)) {
|
|
120
|
-
if (!isSampleObject(entry)) {
|
|
121
|
-
return { ok: false, findings: [finding(init, `the ${name} of ${id} is not an object of ${name === SEEDS_EXPORT ? 'columns' : 'input fields'}`)] }
|
|
122
|
-
}
|
|
123
|
-
entries[id] = entry
|
|
124
|
-
}
|
|
125
|
-
return { ok: true, value: entries }
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
/** `export const <members, invitations or links> = { '<endpoint id>': ['<field>', …] }`, read into field lists. */
|
|
129
|
-
function fieldsById(
|
|
130
|
-
declarator: AstNode,
|
|
131
|
-
name: FieldExport,
|
|
132
|
-
): { readonly ok: true; readonly value: Readonly<Record<string, readonly string[]>> } | {
|
|
133
|
-
readonly ok: false
|
|
134
|
-
readonly findings: readonly Finding[]
|
|
135
|
-
} {
|
|
136
|
-
const init = child(declarator, 'init')
|
|
137
|
-
const value = literal(init)
|
|
138
|
-
if (!value.ok) return { ok: false, findings: [finding(value.at, 'not a plain literal')] }
|
|
139
|
-
if (!isSampleObject(value.value)) {
|
|
140
|
-
return { ok: false, findings: [finding(init, `the ${name} are an object keyed by endpoint id`)] }
|
|
141
|
-
}
|
|
142
|
-
const entries: Record<string, readonly string[]> = {}
|
|
143
|
-
for (const [id, fields] of Object.entries(value.value)) {
|
|
144
|
-
if (!Array.isArray(fields) || fields.length === 0 || !fields.every((field) => typeof field === 'string')) {
|
|
145
|
-
return { ok: false, findings: [finding(init, `the ${name} of ${id} is not a list of input field names`)] }
|
|
146
|
-
}
|
|
147
|
-
entries[id] = fields.filter((field) => typeof field === 'string')
|
|
148
|
-
}
|
|
149
|
-
return { ok: true, value: entries }
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
/** The fixtures of `files`, by endpoint id; none without the file. */
|
|
153
|
-
export function readEndpointFixtures(
|
|
154
|
-
files: ReadonlyMap<string, string>,
|
|
155
|
-
): { readonly ok: true; readonly fixtures: EndpointFixtures } | { readonly ok: false; readonly findings: readonly Finding[] } {
|
|
156
|
-
const text = files.get(ENDPOINT_FIXTURES_FILE)
|
|
157
|
-
if (text === undefined) return { ok: true, fixtures: NO_FIXTURES }
|
|
158
|
-
if (new TextEncoder().encode(text).byteLength > CONTRACT_LIMITS.sourceBytes) {
|
|
159
|
-
return { ok: false, findings: [finding(undefined, `the fixtures exceed ${CONTRACT_LIMITS.sourceBytes} bytes`)] }
|
|
160
|
-
}
|
|
161
|
-
const parsed = parseModule(ENDPOINT_FIXTURES_FILE, text)
|
|
162
|
-
if (!parsed.ok) return { ok: false, findings: [finding(undefined, parsed.message)] }
|
|
163
|
-
const program = parsed.module.program
|
|
164
|
-
if (nodeDepth(program) > CONTRACT_LIMITS.astDepth) {
|
|
165
|
-
return { ok: false, findings: [finding(undefined, `the fixtures nest deeper than ${CONTRACT_LIMITS.astDepth}`)] }
|
|
166
|
-
}
|
|
167
|
-
const read = new Map<string, ById>()
|
|
168
|
-
const fields = new Map<FieldExport, Readonly<Record<string, readonly string[]>>>()
|
|
169
|
-
for (const statement of children(program, 'body')) {
|
|
170
|
-
const declaration = statement === null ? undefined : child(statement, 'declaration')
|
|
171
|
-
const declarators = declaration?.type === 'VariableDeclaration' && declaration['kind'] === 'const' ? children(declaration, 'declarations') : []
|
|
172
|
-
const declarator = declarators.length === 1 ? declarators[0] : undefined
|
|
173
|
-
const name = declarator === null || declarator === undefined ? undefined : identifierName(child(declarator, 'id'))
|
|
174
|
-
if (
|
|
175
|
-
statement?.type !== 'ExportNamedDeclaration' || declarator === null || declarator === undefined
|
|
176
|
-
|| (name !== FIXTURES_EXPORT && name !== SEEDS_EXPORT && name !== ROWS_EXPORT && !isFieldExport(name)) || read.has(name)
|
|
177
|
-
|| (isFieldExport(name) && fields.has(name))
|
|
178
|
-
) {
|
|
179
|
-
return {
|
|
180
|
-
ok: false,
|
|
181
|
-
findings: [
|
|
182
|
-
finding(
|
|
183
|
-
statement ?? undefined,
|
|
184
|
-
`the file holds export const ${FIXTURES_EXPORT}, ${SEEDS_EXPORT}, ${MEMBERS_EXPORT}, ${INVITATIONS_EXPORT} and ${LINKS_EXPORT} = { … }, each at most once`,
|
|
185
|
-
),
|
|
186
|
-
],
|
|
187
|
-
}
|
|
188
|
-
}
|
|
189
|
-
if (isFieldExport(name)) {
|
|
190
|
-
const listed = fieldsById(declarator, name)
|
|
191
|
-
if (!listed.ok) return listed
|
|
192
|
-
fields.set(name, listed.value)
|
|
193
|
-
continue
|
|
194
|
-
}
|
|
195
|
-
const value = byId(declarator, name)
|
|
196
|
-
if (!value.ok) return value
|
|
197
|
-
if (name === ROWS_EXPORT) {
|
|
198
|
-
const named = Object.entries(value.value).find(([, fields]) => Object.values(fields).some((table) => typeof table !== 'string'))
|
|
199
|
-
if (named !== undefined) {
|
|
200
|
-
return { ok: false, findings: [finding(child(declarator, 'init'), `the rows of ${named[0]} name each field's table as a string`)] }
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
read.set(name, value.value)
|
|
204
|
-
}
|
|
205
|
-
return {
|
|
206
|
-
ok: true,
|
|
207
|
-
fixtures: {
|
|
208
|
-
inputs: read.get(FIXTURES_EXPORT) ?? {},
|
|
209
|
-
seeds: read.get(SEEDS_EXPORT) ?? {},
|
|
210
|
-
members: fields.get(MEMBERS_EXPORT) ?? {},
|
|
211
|
-
invitations: fields.get(INVITATIONS_EXPORT) ?? {},
|
|
212
|
-
links: fields.get(LINKS_EXPORT) ?? {},
|
|
213
|
-
rows: Object.fromEntries(
|
|
214
|
-
Object.entries(read.get(ROWS_EXPORT) ?? {}).map(([id, named]) => [
|
|
215
|
-
id,
|
|
216
|
-
Object.fromEntries(Object.entries(named).flatMap(([field, table]) => (typeof table === 'string' ? [[field, table]] : []))),
|
|
217
|
-
]),
|
|
218
|
-
),
|
|
219
|
-
},
|
|
220
|
-
}
|
|
221
|
-
}
|
package/src/rules/crontab.ts
DELETED
|
@@ -1,147 +0,0 @@
|
|
|
1
|
-
import { z } from 'zod/v4'
|
|
2
|
-
import { type AstNode, child, children, type ParsedModule, staticKey, walk } from '../ast'
|
|
3
|
-
import type { Finding } from '../finding'
|
|
4
|
-
import { type Located, type ModuleGraph, unwrapValue } from '../graph'
|
|
5
|
-
|
|
6
|
-
export interface ContractJob {
|
|
7
|
-
readonly name: string
|
|
8
|
-
/** `undefined` when the contract's schedule is not a static string. */
|
|
9
|
-
readonly schedule: string | undefined
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Every `<name>: c.cron('<schedule>', { … })` in the contract, and every `<name>` there that names a const of the
|
|
14
|
-
* kit's `app.cron('<schedule>', { … })`; the schedule is resolved through literal consts.
|
|
15
|
-
*/
|
|
16
|
-
export const contractJobs = (contract: ParsedModule, graph: ModuleGraph): readonly ContractJob[] => {
|
|
17
|
-
const jobs: ContractJob[] = []
|
|
18
|
-
const cronSchedule = (located: Located): string | undefined => {
|
|
19
|
-
const first = children(located.node, 'arguments')[0]
|
|
20
|
-
return first ? graph.resolveString({ module: located.module, node: first }) : undefined
|
|
21
|
-
}
|
|
22
|
-
walk(contract.program, (node, ancestors) => {
|
|
23
|
-
if (node.type === 'Property') {
|
|
24
|
-
const value = child(node, 'value')
|
|
25
|
-
const name = staticKey(node, 'key')
|
|
26
|
-
const resolved = value !== undefined && unwrapValue(value).type === 'Identifier'
|
|
27
|
-
? graph.resolveValue({ module: contract, node: value })
|
|
28
|
-
: undefined
|
|
29
|
-
if (name !== undefined && resolved !== undefined && isCronCall(resolved.node)) jobs.push({ name, schedule: cronSchedule(resolved) })
|
|
30
|
-
return
|
|
31
|
-
}
|
|
32
|
-
if (!isCronCall(node)) return
|
|
33
|
-
const property = [...ancestors].reverse().find((ancestor) => {
|
|
34
|
-
const value = ancestor.type === 'Property' ? child(ancestor, 'value') : undefined
|
|
35
|
-
return value !== undefined && unwrapValue(value) === node
|
|
36
|
-
})
|
|
37
|
-
const name = property === undefined ? undefined : staticKey(property, 'key')
|
|
38
|
-
if (name !== undefined) jobs.push({ name, schedule: cronSchedule({ module: contract, node }) })
|
|
39
|
-
})
|
|
40
|
-
return jobs
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
const isCronCall = (node: AstNode): boolean => {
|
|
44
|
-
const callee = node.type === 'CallExpression' ? child(node, 'callee') : undefined
|
|
45
|
-
return callee?.type === 'MemberExpression' && staticKey(callee, 'property') === 'cron'
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
const crontabEntrySchema = z.object({
|
|
49
|
-
timing: z.string().optional(),
|
|
50
|
-
command: z.string().optional(),
|
|
51
|
-
allContainers: z.boolean().optional(),
|
|
52
|
-
})
|
|
53
|
-
|
|
54
|
-
const zeropsYamlSchema = z.object({
|
|
55
|
-
zerops: z.array(
|
|
56
|
-
z.object({
|
|
57
|
-
setup: z.string(),
|
|
58
|
-
run: z.object({ start: z.string().optional(), crontab: z.array(crontabEntrySchema).optional() }).optional(),
|
|
59
|
-
}),
|
|
60
|
-
),
|
|
61
|
-
})
|
|
62
|
-
|
|
63
|
-
const JOB_COMMAND = /^fabrika job run (\S+)$/
|
|
64
|
-
/** A lone `&`, `nohup`, `setsid` or `disown` starts a process beside the server, outside every job rule. */
|
|
65
|
-
const BACKGROUND_PROCESS = /(?:^|[^&])&(?:[^&]|$)|\b(?:nohup|setsid|disown)\b/
|
|
66
|
-
|
|
67
|
-
/** The line of the first occurrence of `needle`, or 1. */
|
|
68
|
-
const lineOf = (text: string, needle: string, after = 0): number => {
|
|
69
|
-
const index = text.indexOf(needle, after)
|
|
70
|
-
return index === -1 ? 1 : text.slice(0, index).split('\n').length
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
/** Each setup that runs the application carries exactly the contract's jobs as crontab entries, and nothing else. */
|
|
74
|
-
export const checkCrontab = (file: string, text: string, jobs: readonly ContractJob[]): Finding[] => {
|
|
75
|
-
const findings: Finding[] = []
|
|
76
|
-
const finding = (line: number, message: string, allowed: string) =>
|
|
77
|
-
findings.push({ file, line, column: 1, severity: 'refusal', rule: 'crontab', message, allowed })
|
|
78
|
-
let document: unknown
|
|
79
|
-
try {
|
|
80
|
-
document = Bun.YAML.parse(text)
|
|
81
|
-
} catch {
|
|
82
|
-
finding(1, `${file} is not valid YAML`, 'a zerops.yaml that parses')
|
|
83
|
-
return findings
|
|
84
|
-
}
|
|
85
|
-
const parsed = zeropsYamlSchema.safeParse(document)
|
|
86
|
-
if (!parsed.success) {
|
|
87
|
-
const issue = parsed.error.issues[0]
|
|
88
|
-
finding(
|
|
89
|
-
1,
|
|
90
|
-
`${file} does not have the zerops.yaml shape at '${issue?.path.join('.') ?? ''}'`,
|
|
91
|
-
'zerops: [{ setup, run: { start, crontab: [{ timing, command, allContainers }] } }]',
|
|
92
|
-
)
|
|
93
|
-
return findings
|
|
94
|
-
}
|
|
95
|
-
const byName = new Map(jobs.map((job) => [job.name, job]))
|
|
96
|
-
for (const setup of parsed.data.zerops) {
|
|
97
|
-
const { run } = setup
|
|
98
|
-
if (run === undefined) continue
|
|
99
|
-
const setupLine = lineOf(text, `setup: ${setup.setup}`)
|
|
100
|
-
const crontabLine = lineOf(text, 'crontab:', text.indexOf(`setup: ${setup.setup}`))
|
|
101
|
-
if (run.start !== undefined && BACKGROUND_PROCESS.test(run.start)) {
|
|
102
|
-
finding(
|
|
103
|
-
lineOf(text, run.start),
|
|
104
|
-
`run.start of '${setup.setup}' starts a background process`,
|
|
105
|
-
'one server process in run.start; background work is a job in the contract (c.cron)',
|
|
106
|
-
)
|
|
107
|
-
}
|
|
108
|
-
const scheduled = new Set<string>()
|
|
109
|
-
for (const entry of run.crontab ?? []) {
|
|
110
|
-
const line = entry.command === undefined ? crontabLine : lineOf(text, entry.command)
|
|
111
|
-
const name = JOB_COMMAND.exec(entry.command ?? '')?.[1]
|
|
112
|
-
const job = name === undefined ? undefined : byName.get(name)
|
|
113
|
-
if (job === undefined) {
|
|
114
|
-
finding(
|
|
115
|
-
line,
|
|
116
|
-
`crontab entry '${entry.command ?? ''}' is not a job of the contract`,
|
|
117
|
-
'fabrika job run <name> for a c.cron job declared in fabrika.contract.ts',
|
|
118
|
-
)
|
|
119
|
-
continue
|
|
120
|
-
}
|
|
121
|
-
if (scheduled.has(job.name)) finding(line, `job '${job.name}' has a second crontab entry`, 'one crontab entry per job')
|
|
122
|
-
scheduled.add(job.name)
|
|
123
|
-
if (job.schedule === undefined) {
|
|
124
|
-
finding(line, `the contract's schedule of job '${job.name}' is not a static string`, `c.cron('<cron expression>', { … }) in fabrika.contract.ts`)
|
|
125
|
-
} else if (entry.timing !== job.schedule) {
|
|
126
|
-
finding(
|
|
127
|
-
line,
|
|
128
|
-
`crontab timing '${entry.timing ?? ''}' of job '${job.name}' differs from the contract's '${job.schedule}'`,
|
|
129
|
-
`timing: '${job.schedule}'`,
|
|
130
|
-
)
|
|
131
|
-
}
|
|
132
|
-
if (entry.allContainers !== false) {
|
|
133
|
-
finding(line, `crontab entry of job '${job.name}' does not set allContainers: false`, 'allContainers: false, written explicitly')
|
|
134
|
-
}
|
|
135
|
-
}
|
|
136
|
-
for (const job of jobs) {
|
|
137
|
-
if (!scheduled.has(job.name)) {
|
|
138
|
-
finding(
|
|
139
|
-
run.crontab === undefined ? setupLine : crontabLine,
|
|
140
|
-
`job '${job.name}' has no crontab entry in '${setup.setup}'`,
|
|
141
|
-
`{ timing: '${job.schedule ?? ''}', command: 'fabrika job run ${job.name}', allContainers: false }`,
|
|
142
|
-
)
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
return findings
|
|
147
|
-
}
|
package/src/rules/isolation.ts
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import { ContractError } from '@fabrika/app/contract'
|
|
2
|
-
import { ContractSourceError } from '../contract'
|
|
3
|
-
import type { Finding } from '../finding'
|
|
4
|
-
import { CONTRACT_FILE } from '../layout'
|
|
5
|
-
import { type GeneratedTest, generatedTests, missingEndpointFixtures, scaffoldInputs } from '../scaffold'
|
|
6
|
-
import { GENERATED_TEST_HEADER, generatedTestHeader } from './tests'
|
|
7
|
-
|
|
8
|
-
const RESCAFFOLD = 'the files fabrika db test-scaffold writes for the current contract and src/db/tables.ts; run it and commit the result'
|
|
9
|
-
|
|
10
|
-
const at = (file: string, message: string): Finding => ({
|
|
11
|
-
file,
|
|
12
|
-
line: 1,
|
|
13
|
-
column: 1,
|
|
14
|
-
severity: 'refusal',
|
|
15
|
-
rule: 'generated-test-hash',
|
|
16
|
-
message,
|
|
17
|
-
allowed: RESCAFFOLD,
|
|
18
|
-
})
|
|
19
|
-
|
|
20
|
-
/** Whether the first line is a generated-test header whose hash fails: `checkGeneratedTest` reports that file already. */
|
|
21
|
-
const failsItsHash = async (text: string): Promise<boolean> => {
|
|
22
|
-
if (!text.startsWith(GENERATED_TEST_HEADER)) return false
|
|
23
|
-
const newline = text.indexOf('\n')
|
|
24
|
-
return newline === -1 || text.slice(0, newline) !== (await generatedTestHeader(text.slice(newline + 1)))
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** The tests the scaffold writes for these files, or the findings that stop it from reading them. */
|
|
28
|
-
export const expectedGeneratedTests = async (
|
|
29
|
-
files: ReadonlyMap<string, string>,
|
|
30
|
-
): Promise<
|
|
31
|
-
| { readonly ok: true; readonly tests: ReadonlyMap<string, GeneratedTest>; readonly missing: readonly Finding[] }
|
|
32
|
-
| { readonly ok: false; readonly findings: readonly Finding[] }
|
|
33
|
-
> => {
|
|
34
|
-
try {
|
|
35
|
-
const inputs = scaffoldInputs(files)
|
|
36
|
-
return { ok: true, tests: await generatedTests(inputs.policies, inputs.artifact, inputs.fixtures), missing: missingEndpointFixtures(inputs) }
|
|
37
|
-
} catch (error) {
|
|
38
|
-
if (error instanceof ContractSourceError) return { ok: false, findings: error.findings }
|
|
39
|
-
if (error instanceof ContractError) {
|
|
40
|
-
return {
|
|
41
|
-
ok: false,
|
|
42
|
-
findings: error.problems.map((problem): Finding => ({
|
|
43
|
-
file: CONTRACT_FILE,
|
|
44
|
-
line: 1,
|
|
45
|
-
column: 1,
|
|
46
|
-
severity: 'refusal',
|
|
47
|
-
rule: 'contract',
|
|
48
|
-
message: problem,
|
|
49
|
-
allowed: 'a contract that compiles against src/db/tables.ts',
|
|
50
|
-
})),
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
throw error
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/**
|
|
58
|
-
* Every generated test is byte for byte what the scaffold writes from the current contract and policies: a missing,
|
|
59
|
-
* edited or replaced one is a finding, header or not, and so is a generated test the scaffold no longer writes.
|
|
60
|
-
* `readable` is false while the literal or trust rules report the sources; otherwise what the reader refuses is
|
|
61
|
-
* reported here, so a source it cannot read does not silence the check.
|
|
62
|
-
*/
|
|
63
|
-
export const checkGeneratedTests = async (files: ReadonlyMap<string, string>, readable: boolean): Promise<Finding[]> => {
|
|
64
|
-
if (!readable) return []
|
|
65
|
-
const expected = await expectedGeneratedTests(files)
|
|
66
|
-
if (!expected.ok) return [...expected.findings]
|
|
67
|
-
const findings: Finding[] = [...expected.missing]
|
|
68
|
-
for (const [path, { text }] of expected.tests) {
|
|
69
|
-
const present = files.get(path)
|
|
70
|
-
if (present === undefined) findings.push(at(path, 'this generated test is missing'))
|
|
71
|
-
else if (present !== text && !(await failsItsHash(present))) findings.push(at(path, 'this file is not the generated test the scaffold writes here'))
|
|
72
|
-
}
|
|
73
|
-
for (const [path, text] of files) {
|
|
74
|
-
if (text.startsWith(GENERATED_TEST_HEADER) && !expected.tests.has(path)) {
|
|
75
|
-
findings.push(at(path, 'a generated test the scaffold no longer writes'))
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
return findings
|
|
79
|
-
}
|