@fabrika/check 0.6.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +6 -6
- package/src/check.ts +96 -8
- package/src/contract.ts +2 -2
- package/src/finding.ts +3 -1
- package/src/lockfile.ts +47 -0
- package/src/packed.ts +4 -1
- package/src/reader/surface.ts +171 -123
- package/src/reader/value.ts +72 -0
- package/src/rules/identity.ts +1 -1
- package/src/rules/literal.ts +51 -6
- package/src/rules/migrations.ts +286 -40
- package/src/rules/packages.ts +4 -9
- package/src/rules/runtime.ts +54 -6
- package/src/rules/structure.ts +3 -2
- package/src/scaffold-sample.ts +3 -0
- package/src/scaffold.ts +87 -42
- package/src/slice.ts +9 -3
package/src/rules/literal.ts
CHANGED
|
@@ -6,14 +6,40 @@ import { isRelativeSpecifier } from '../layout'
|
|
|
6
6
|
/**
|
|
7
7
|
* What a call root builds. `surface` is the parameter of a `defineContract` callback (`c`, `l`); `app` is
|
|
8
8
|
* `defineApp`, `kit` a const it returned, `shell` the parameter of `app.contract`'s callback and `endpoints` that of
|
|
9
|
-
* a group's, a link's or an export's; `attachment` is the output `attachment({ … })
|
|
9
|
+
* a group's, a link's or an export's; `attachment` is the output `attachment({ … })`, `file` a file field or output;
|
|
10
|
+
* `value` is a schema the package exports, read as it is (`WebhookSecret`).
|
|
10
11
|
*/
|
|
11
|
-
export type BuilderKind =
|
|
12
|
+
export type BuilderKind =
|
|
13
|
+
| 'zod'
|
|
14
|
+
| 'contract'
|
|
15
|
+
| 'vocabulary'
|
|
16
|
+
| 'tables'
|
|
17
|
+
| 'surface'
|
|
18
|
+
| 'app'
|
|
19
|
+
| 'kit'
|
|
20
|
+
| 'shell'
|
|
21
|
+
| 'endpoints'
|
|
22
|
+
| 'attachment'
|
|
23
|
+
| 'redirect'
|
|
24
|
+
| 'file'
|
|
25
|
+
| 'value'
|
|
26
|
+
| 'token'
|
|
27
|
+
| 'signedToken'
|
|
12
28
|
|
|
13
29
|
/** The only imported names a literal module may use: the builders the platform reads without executing them. */
|
|
14
30
|
export const BUILDER_IMPORTS: Readonly<Record<string, Readonly<Record<string, BuilderKind>>>> = {
|
|
15
31
|
'zod/v4': { z: 'zod', '*': 'zod' },
|
|
16
|
-
'@fabrika/app/contract': {
|
|
32
|
+
'@fabrika/app/contract': {
|
|
33
|
+
defineContract: 'contract',
|
|
34
|
+
defineVocabulary: 'vocabulary',
|
|
35
|
+
defineApp: 'app',
|
|
36
|
+
attachment: 'attachment',
|
|
37
|
+
redirect: 'redirect',
|
|
38
|
+
file: 'file',
|
|
39
|
+
WebhookSecret: 'value',
|
|
40
|
+
token: 'token',
|
|
41
|
+
signedToken: 'signedToken',
|
|
42
|
+
},
|
|
17
43
|
'@fabrika/db/tables': { defineTables: 'tables' },
|
|
18
44
|
}
|
|
19
45
|
|
|
@@ -23,11 +49,11 @@ export const BUILDER_IMPORTS: Readonly<Record<string, Readonly<Record<string, Bu
|
|
|
23
49
|
*/
|
|
24
50
|
const SERVER_ENTRY_OF: Readonly<Record<string, string>> = { '@fabrika/db': '@fabrika/db/tables' }
|
|
25
51
|
|
|
26
|
-
const SURFACE_BUILDERS = new Set(['rpc', 'query', 'mutation', 'link', 'spa', 'health', '
|
|
52
|
+
const SURFACE_BUILDERS = new Set(['rpc', 'query', 'mutation', 'link', 'spa', 'health', 'webhook', 'files', 'cron', 'export'])
|
|
27
53
|
/** The methods of the kit `defineApp` returns. */
|
|
28
54
|
export const KIT_BUILDERS: ReadonlySet<string> = new Set(['group', 'contract', 'cron', 'webhook', 'link', 'export'])
|
|
29
55
|
/** The builders of `app.contract`'s callback: the mounts that take no handler, and `rpc`, which mounts groups. */
|
|
30
|
-
export const SHELL_BUILDERS: ReadonlySet<string> = new Set(['rpc', 'spa', 'health', '
|
|
56
|
+
export const SHELL_BUILDERS: ReadonlySet<string> = new Set(['rpc', 'spa', 'health', 'files'])
|
|
31
57
|
/** The builders of a group's, a link's and an export's callback. */
|
|
32
58
|
export const ENDPOINT_BUILDERS: ReadonlySet<string> = new Set(['query', 'mutation'])
|
|
33
59
|
|
|
@@ -307,7 +333,7 @@ const shapeProblem = (kind: BuilderKind, root: AstNode, links: readonly Link[]):
|
|
|
307
333
|
case 'app':
|
|
308
334
|
return links.length === 1 && calls === 1
|
|
309
335
|
? undefined
|
|
310
|
-
: { node: root, message: 'defineApp used other than as one call', allowed: 'defineApp(vocabulary, tables, { imports })' }
|
|
336
|
+
: { node: root, message: 'defineApp used other than as one call', allowed: 'defineApp(vocabulary, tables, { imports, tokens })' }
|
|
311
337
|
case 'contract':
|
|
312
338
|
return links.length === 1 && calls === 1
|
|
313
339
|
? undefined
|
|
@@ -320,6 +346,24 @@ const shapeProblem = (kind: BuilderKind, root: AstNode, links: readonly Link[]):
|
|
|
320
346
|
return links.length === 1 && calls === 1
|
|
321
347
|
? undefined
|
|
322
348
|
: { node: root, message: 'attachment used other than as one call', allowed: "attachment({ format: 'csv', filename, row, maxBytes })" }
|
|
349
|
+
case 'redirect':
|
|
350
|
+
return links.length === 1 && calls === 1
|
|
351
|
+
? undefined
|
|
352
|
+
: { node: root, message: 'redirect used other than as one call', allowed: "redirect() or redirect({ origins: ['https://…'] })" }
|
|
353
|
+
case 'file':
|
|
354
|
+
return links.length === 1 && calls === 1
|
|
355
|
+
? undefined
|
|
356
|
+
: { node: root, message: 'file used other than as one call', allowed: "file('<kind>')" }
|
|
357
|
+
case 'value':
|
|
358
|
+
return { node: root, message: `${identifierName(root) ?? 'the schema'} used other than as it is`, allowed: 'output: WebhookSecret' }
|
|
359
|
+
case 'token':
|
|
360
|
+
return links.length === 1 && calls === 1
|
|
361
|
+
? undefined
|
|
362
|
+
: { node: root, message: 'token used other than as one call', allowed: 'token(Claims, { maxDays: 400 })' }
|
|
363
|
+
case 'signedToken':
|
|
364
|
+
return links.length === 1 && calls === 1
|
|
365
|
+
? undefined
|
|
366
|
+
: { node: root, message: 'signedToken used other than as one call', allowed: "signedToken('<purpose>')" }
|
|
323
367
|
case 'tables':
|
|
324
368
|
return calls === links.length && (calls === 1 || calls === 2)
|
|
325
369
|
? undefined
|
|
@@ -373,6 +417,7 @@ const readModule = (module: ParsedModule, graph: ModuleGraph, findings: Finding[
|
|
|
373
417
|
|
|
374
418
|
const checkIdentifier = (node: AstNode, scope: Scope, dependencies: string[]): void => {
|
|
375
419
|
const name = identifierName(node) ?? ''
|
|
420
|
+
if (builders.get(name) === 'value') return
|
|
376
421
|
if (scope.has(name) || builders.has(name) || isKitName(graph, module, name)) {
|
|
377
422
|
return fail(node, `'${name}' used as a value`, `${name}.<builder>(…) calls only`)
|
|
378
423
|
}
|
package/src/rules/migrations.ts
CHANGED
|
@@ -1,4 +1,15 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
afterName,
|
|
3
|
+
closingParenthesis,
|
|
4
|
+
isPunct,
|
|
5
|
+
nameText,
|
|
6
|
+
objectNameAt,
|
|
7
|
+
skipWords,
|
|
8
|
+
splitAtCommas,
|
|
9
|
+
type SqlToken,
|
|
10
|
+
topLevelStatements,
|
|
11
|
+
upperWord,
|
|
12
|
+
} from '@fabrika/platform-node/sql'
|
|
2
13
|
import type { Finding } from '../finding'
|
|
3
14
|
import { MIGRATIONS_DIR } from '../layout'
|
|
4
15
|
|
|
@@ -32,56 +43,291 @@ export const checkMigrationNames = (paths: readonly string[]): Finding[] => {
|
|
|
32
43
|
return findings
|
|
33
44
|
}
|
|
34
45
|
|
|
46
|
+
/** A declared file column: `table.column` holds files of `kind`. */
|
|
47
|
+
export interface FileColumn {
|
|
48
|
+
readonly table: string
|
|
49
|
+
readonly column: string
|
|
50
|
+
readonly kind: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const FILES_TABLE = 'fabrika_files'
|
|
54
|
+
const TABLE_CONSTRAINTS = new Set(['CONSTRAINT', 'FOREIGN', 'UNIQUE', 'PRIMARY', 'CHECK', 'EXCLUDE', 'LIKE'])
|
|
55
|
+
|
|
56
|
+
/** What the migrations, in order, declare of each `table.column`: a foreign key to `fabrika_files`, and the indexes it leads. */
|
|
57
|
+
interface FileColumnDdl {
|
|
58
|
+
readonly references: Set<string>
|
|
59
|
+
readonly indexes: { readonly name: string | undefined; readonly key: string }[]
|
|
60
|
+
readonly created: Map<string, { readonly path: string; readonly line: number }>
|
|
61
|
+
}
|
|
62
|
+
|
|
35
63
|
/**
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
64
|
+
* Every declared file column needs a foreign key to `fabrika_files (id)`, which keeps the sweep from deleting a file a
|
|
65
|
+
* row references, and an index it leads, which the sweep's reference check and each file deletion read. Only what a
|
|
66
|
+
* migration creates counts: a `REFERENCES fabrika_files` on the column or a one-column foreign key, and a `CREATE
|
|
67
|
+
* INDEX` without `WHERE`, a `UNIQUE` or a `PRIMARY KEY` whose first column it is, minus a later `DROP INDEX`.
|
|
40
68
|
*/
|
|
41
|
-
export const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
69
|
+
export const checkFileColumnMigrations = (files: ReadonlyMap<string, string>, columns: readonly FileColumn[]): Finding[] => {
|
|
70
|
+
if (columns.length === 0) {
|
|
71
|
+
return []
|
|
72
|
+
}
|
|
73
|
+
const ddl: FileColumnDdl = { references: new Set(), indexes: [], created: new Map() }
|
|
45
74
|
const migrations = [...files.entries()]
|
|
46
|
-
.filter(
|
|
47
|
-
([path]) => path.startsWith(MIGRATIONS_DIR) && path.endsWith('.sql'),
|
|
48
|
-
)
|
|
75
|
+
.filter(([path]) => path.startsWith(MIGRATIONS_DIR) && path.endsWith('.sql'))
|
|
49
76
|
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
if (
|
|
54
|
-
fileTableScanReady(
|
|
55
|
-
migrations.map(([, sql]) => sql),
|
|
56
|
-
table,
|
|
57
|
-
) !== false
|
|
58
|
-
) {
|
|
59
|
-
continue
|
|
77
|
+
for (const [path, sql] of migrations) {
|
|
78
|
+
for (const statement of topLevelStatements(sql)) {
|
|
79
|
+
readFileColumnDdl(path, statement.tokens, statement.line, ddl)
|
|
60
80
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
81
|
+
}
|
|
82
|
+
const indexed = new Set(ddl.indexes.map((index) => index.key))
|
|
83
|
+
const findings: Finding[] = []
|
|
84
|
+
for (const { table, column, kind } of columns) {
|
|
85
|
+
const key = `${table}.${column}`
|
|
86
|
+
const at = ddl.created.get(table) ?? { path: MIGRATIONS_DIR, line: 1 }
|
|
87
|
+
const missing = [
|
|
88
|
+
ddl.references.has(key) ? undefined : `no migration makes it a foreign key to ${FILES_TABLE} (id)`,
|
|
89
|
+
indexed.has(key) ? undefined : 'no migration creates an index it leads',
|
|
90
|
+
].filter((reason) => reason !== undefined)
|
|
91
|
+
if (missing.length === 0) continue
|
|
66
92
|
findings.push({
|
|
67
|
-
file: path,
|
|
68
|
-
line,
|
|
93
|
+
file: at.path,
|
|
94
|
+
line: at.line,
|
|
69
95
|
column: 1,
|
|
70
96
|
severity: 'refusal',
|
|
71
|
-
rule: 'file-
|
|
72
|
-
message:
|
|
73
|
-
allowed:
|
|
74
|
-
`a new migration holding fileScanSql('${name}') of @fabrika/db, exactly as it writes it: ALTER TABLE ${table} DROP CONSTRAINT IF EXISTS …, ADD CONSTRAINT ${table}_status CHECK (…), ADD COLUMN object_version TEXT, …`,
|
|
97
|
+
rule: 'file-column-migration',
|
|
98
|
+
message: `${key} holds files of kind '${kind}', and ${missing.join(', and ')}`,
|
|
99
|
+
allowed: `${column} uuid references ${FILES_TABLE} (id) in a migration, and create index ${table}_${column} on ${table} (${column})`,
|
|
75
100
|
})
|
|
76
101
|
}
|
|
77
102
|
return findings
|
|
78
103
|
}
|
|
79
104
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
'
|
|
85
|
-
|
|
86
|
-
|
|
105
|
+
function readFileColumnDdl(path: string, tokens: readonly SqlToken[], line: number, ddl: FileColumnDdl): void {
|
|
106
|
+
const verb = upperWord(tokens[0])
|
|
107
|
+
const object = upperWord(tokens[1])
|
|
108
|
+
if (verb === 'CREATE' && object === 'TABLE') {
|
|
109
|
+
const at = skipWords(tokens, 2, 'IF', 'NOT', 'EXISTS')
|
|
110
|
+
const table = objectNameAt(tokens, at)?.name
|
|
111
|
+
const open = afterName(tokens, at)
|
|
112
|
+
const close = open === undefined ? undefined : closingParenthesis(tokens, open)
|
|
113
|
+
if (table === undefined || open === undefined || close === undefined) return
|
|
114
|
+
ddl.created.set(table, { path, line })
|
|
115
|
+
for (const element of splitAtCommas(tokens.slice(open + 1, close))) {
|
|
116
|
+
readTableElement(table, element, ddl)
|
|
117
|
+
}
|
|
118
|
+
} else if (verb === 'ALTER' && object === 'TABLE') {
|
|
119
|
+
const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
|
|
120
|
+
const table = objectNameAt(tokens, at)?.name
|
|
121
|
+
const end = afterName(tokens, at)
|
|
122
|
+
if (table === undefined || end === undefined) return
|
|
123
|
+
for (const action of splitAtCommas(tokens.slice(end))) {
|
|
124
|
+
if (upperWord(action[0]) !== 'ADD') continue
|
|
125
|
+
readTableElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), ddl)
|
|
126
|
+
}
|
|
127
|
+
} else if (verb === 'CREATE' && (object === 'INDEX' || (object === 'UNIQUE' && upperWord(tokens[2]) === 'INDEX'))) {
|
|
128
|
+
readIndex(tokens.slice(object === 'UNIQUE' ? 3 : 2), ddl)
|
|
129
|
+
} else if (verb === 'DROP' && object === 'INDEX') {
|
|
130
|
+
const at = skipWords(tokens, skipWords(tokens, 2, 'CONCURRENTLY'), 'IF', 'EXISTS')
|
|
131
|
+
const dropped = new Set(splitAtCommas(tokens.slice(at)).map((part) => objectNameAt(part, 0)?.name))
|
|
132
|
+
const kept = ddl.indexes.filter((index) => index.name === undefined || !dropped.has(index.name))
|
|
133
|
+
ddl.indexes.splice(0, ddl.indexes.length, ...kept)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** A column definition, or a table constraint: what it says of a file column of `table`. */
|
|
138
|
+
function readTableElement(table: string, element: readonly SqlToken[], ddl: FileColumnDdl): void {
|
|
139
|
+
const head = upperWord(element[0])
|
|
140
|
+
if (head !== undefined && TABLE_CONSTRAINTS.has(head)) {
|
|
141
|
+
readTableConstraint(table, head === 'CONSTRAINT' ? element.slice(2) : element, ddl)
|
|
142
|
+
return
|
|
143
|
+
}
|
|
144
|
+
const column = nameText(element[0])
|
|
145
|
+
if (column === undefined) return
|
|
146
|
+
const key = `${table}.${column}`
|
|
147
|
+
const rest = element.slice(1)
|
|
148
|
+
if (referencesFiles(rest)) ddl.references.add(key)
|
|
149
|
+
if (depthZeroWords(rest).some((word) => word === 'UNIQUE' || word === 'PRIMARY')) ddl.indexes.push({ name: undefined, key })
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function readTableConstraint(table: string, constraint: readonly SqlToken[], ddl: FileColumnDdl): void {
|
|
153
|
+
const kind = upperWord(constraint[0])
|
|
154
|
+
const open = kind === 'FOREIGN' || kind === 'PRIMARY'
|
|
155
|
+
? 2
|
|
156
|
+
: kind === 'UNIQUE'
|
|
157
|
+
? afterNullsClause(constraint)
|
|
158
|
+
: undefined
|
|
159
|
+
const list = open === undefined ? undefined : columnList(constraint, open)
|
|
160
|
+
const [first] = list?.columns ?? []
|
|
161
|
+
if (list === undefined || first === undefined) return
|
|
162
|
+
if (kind !== 'FOREIGN') {
|
|
163
|
+
ddl.indexes.push({ name: undefined, key: `${table}.${first}` })
|
|
164
|
+
} else if (list.columns.length === 1 && referencesFiles(constraint.slice(list.end))) {
|
|
165
|
+
ddl.references.add(`${table}.${first}`)
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The index past `UNIQUE [NULLS [NOT] DISTINCT]`. */
|
|
170
|
+
function afterNullsClause(constraint: readonly SqlToken[]): number {
|
|
171
|
+
const notDistinct = skipWords(constraint, 1, 'NULLS', 'NOT', 'DISTINCT')
|
|
172
|
+
return notDistinct === 1 ? skipWords(constraint, 1, 'NULLS', 'DISTINCT') : notDistinct
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** `[name] ON [ONLY] table [USING method] (first, …)`, after `CREATE [UNIQUE] INDEX`; a partial index serves no reference check. */
|
|
176
|
+
function readIndex(tokens: readonly SqlToken[], ddl: FileColumnDdl): void {
|
|
177
|
+
let at = skipWords(tokens, skipWords(tokens, 0, 'CONCURRENTLY'), 'IF', 'NOT', 'EXISTS')
|
|
178
|
+
const name = upperWord(tokens[at]) === 'ON' ? undefined : objectNameAt(tokens, at)?.name
|
|
179
|
+
at = name === undefined ? at : (afterName(tokens, at) ?? at)
|
|
180
|
+
if (upperWord(tokens[at]) !== 'ON') return
|
|
181
|
+
at = skipWords(tokens, at + 1, 'ONLY')
|
|
182
|
+
const table = objectNameAt(tokens, at)?.name
|
|
183
|
+
const after = afterName(tokens, at)
|
|
184
|
+
if (table === undefined || after === undefined) return
|
|
185
|
+
const list = columnList(tokens, upperWord(tokens[after]) === 'USING' ? after + 2 : after)
|
|
186
|
+
const [first] = list?.columns ?? []
|
|
187
|
+
if (list === undefined || first === undefined || depthZeroWords(tokens.slice(list.end)).includes('WHERE')) return
|
|
188
|
+
ddl.indexes.push({ name, key: `${table}.${first}` })
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** The leading names of a parenthesized list at `open` (an expression has none), and the index past it. */
|
|
192
|
+
function columnList(
|
|
193
|
+
tokens: readonly SqlToken[],
|
|
194
|
+
open: number,
|
|
195
|
+
): { readonly columns: readonly (string | undefined)[]; readonly end: number } | undefined {
|
|
196
|
+
const close = isPunct(tokens[open], '(') ? closingParenthesis(tokens, open) : undefined
|
|
197
|
+
if (close === undefined) return undefined
|
|
198
|
+
const columns = splitAtCommas(tokens.slice(open + 1, close)).map((part) => (isPunct(part[1], '(') ? undefined : nameText(part[0])))
|
|
199
|
+
return { columns, end: close + 1 }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** `REFERENCES fabrika_files` or `REFERENCES fabrika_files (id)` among `tokens`, at parenthesis depth 0. */
|
|
203
|
+
function referencesFiles(tokens: readonly SqlToken[]): boolean {
|
|
204
|
+
let depth = 0
|
|
205
|
+
for (let index = 0; index < tokens.length; index++) {
|
|
206
|
+
const token = tokens[index]
|
|
207
|
+
if (isPunct(token, '(')) depth++
|
|
208
|
+
else if (isPunct(token, ')')) depth--
|
|
209
|
+
if (depth !== 0 || upperWord(token) !== 'REFERENCES') continue
|
|
210
|
+
const target = objectNameAt(tokens, index + 1)
|
|
211
|
+
const after = afterName(tokens, index + 1)
|
|
212
|
+
if (target === undefined || after === undefined || target.qualifier !== undefined || target.name !== FILES_TABLE) return false
|
|
213
|
+
return !isPunct(tokens[after], '(') || (nameText(tokens[after + 1]) === 'id' && isPunct(tokens[after + 2], ')'))
|
|
214
|
+
}
|
|
215
|
+
return false
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function depthZeroWords(tokens: readonly SqlToken[]): string[] {
|
|
219
|
+
const words: string[] = []
|
|
220
|
+
let depth = 0
|
|
221
|
+
for (const token of tokens) {
|
|
222
|
+
if (isPunct(token, '(')) depth++
|
|
223
|
+
else if (isPunct(token, ')')) depth--
|
|
224
|
+
const word = upperWord(token)
|
|
225
|
+
if (depth === 0 && word !== undefined) words.push(word)
|
|
226
|
+
}
|
|
227
|
+
return words
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** An `insert(values, { onConflict: { columns } })` the source makes, with the finding it gets when no index fits. */
|
|
231
|
+
export interface ConflictInsert {
|
|
232
|
+
readonly table: string
|
|
233
|
+
readonly columns: readonly string[]
|
|
234
|
+
readonly finding: Finding
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* `onConflict.columns` must name a unique index the migrations create, or Postgres refuses the insert at run time: the
|
|
239
|
+
* set of columns of a `UNIQUE` or `PRIMARY KEY` constraint, or of a `CREATE UNIQUE INDEX` without `WHERE` or expression,
|
|
240
|
+
* minus a later `DROP INDEX`. Order does not matter, as for Postgres. Only a table `src/db/tables.ts` declares is
|
|
241
|
+
* checked: another receiver of `insert` is no table of the data layer.
|
|
242
|
+
*/
|
|
243
|
+
export const checkConflictIndexes = (
|
|
244
|
+
files: ReadonlyMap<string, string>,
|
|
245
|
+
tables: ReadonlySet<string>,
|
|
246
|
+
inserts: readonly ConflictInsert[],
|
|
247
|
+
): Finding[] => {
|
|
248
|
+
const checked = inserts.filter((insert) => tables.has(insert.table))
|
|
249
|
+
if (checked.length === 0) {
|
|
250
|
+
return []
|
|
251
|
+
}
|
|
252
|
+
const unique: UniqueIndex[] = []
|
|
253
|
+
const migrations = [...files.entries()]
|
|
254
|
+
.filter(([path]) => path.startsWith(MIGRATIONS_DIR) && path.endsWith('.sql'))
|
|
255
|
+
.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))
|
|
256
|
+
for (const [, sql] of migrations) {
|
|
257
|
+
for (const statement of topLevelStatements(sql)) {
|
|
258
|
+
readUniqueIndexes(statement.tokens, unique)
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
const keyOf = (columns: readonly string[]): string => [...new Set(columns)].sort().join(',')
|
|
262
|
+
const present = new Set(unique.map((index) => `${index.table}(${keyOf(index.columns)})`))
|
|
263
|
+
return checked.filter((insert) => !present.has(`${insert.table}(${keyOf(insert.columns)})`)).map((insert) => insert.finding)
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
interface UniqueIndex {
|
|
267
|
+
readonly name: string | undefined
|
|
268
|
+
readonly table: string
|
|
269
|
+
readonly columns: readonly string[]
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function readUniqueIndexes(tokens: readonly SqlToken[], unique: UniqueIndex[]): void {
|
|
273
|
+
const verb = upperWord(tokens[0])
|
|
274
|
+
const object = upperWord(tokens[1])
|
|
275
|
+
if (verb === 'CREATE' && object === 'TABLE') {
|
|
276
|
+
const at = skipWords(tokens, 2, 'IF', 'NOT', 'EXISTS')
|
|
277
|
+
const table = objectNameAt(tokens, at)?.name
|
|
278
|
+
const open = afterName(tokens, at)
|
|
279
|
+
const close = open === undefined ? undefined : closingParenthesis(tokens, open)
|
|
280
|
+
if (table === undefined || open === undefined || close === undefined) return
|
|
281
|
+
for (const element of splitAtCommas(tokens.slice(open + 1, close))) {
|
|
282
|
+
readUniqueElement(table, element, unique)
|
|
283
|
+
}
|
|
284
|
+
} else if (verb === 'ALTER' && object === 'TABLE') {
|
|
285
|
+
const at = skipWords(tokens, skipWords(tokens, 2, 'IF', 'EXISTS'), 'ONLY')
|
|
286
|
+
const table = objectNameAt(tokens, at)?.name
|
|
287
|
+
const end = afterName(tokens, at)
|
|
288
|
+
if (table === undefined || end === undefined) return
|
|
289
|
+
for (const action of splitAtCommas(tokens.slice(end))) {
|
|
290
|
+
if (upperWord(action[0]) !== 'ADD') continue
|
|
291
|
+
readUniqueElement(table, action.slice(skipWords(action, skipWords(action, 1, 'COLUMN'), 'IF', 'NOT', 'EXISTS')), unique)
|
|
292
|
+
}
|
|
293
|
+
} else if (verb === 'CREATE' && object === 'UNIQUE' && upperWord(tokens[2]) === 'INDEX') {
|
|
294
|
+
const rest = tokens.slice(3)
|
|
295
|
+
let at = skipWords(rest, skipWords(rest, 0, 'CONCURRENTLY'), 'IF', 'NOT', 'EXISTS')
|
|
296
|
+
const name = upperWord(rest[at]) === 'ON' ? undefined : objectNameAt(rest, at)?.name
|
|
297
|
+
at = name === undefined ? at : (afterName(rest, at) ?? at)
|
|
298
|
+
if (upperWord(rest[at]) !== 'ON') return
|
|
299
|
+
at = skipWords(rest, at + 1, 'ONLY')
|
|
300
|
+
const table = objectNameAt(rest, at)?.name
|
|
301
|
+
const after = afterName(rest, at)
|
|
302
|
+
if (table === undefined || after === undefined) return
|
|
303
|
+
const list = columnList(rest, upperWord(rest[after]) === 'USING' ? after + 2 : after)
|
|
304
|
+
const columns = list?.columns.filter((column) => column !== undefined) ?? []
|
|
305
|
+
if (list === undefined || columns.length !== list.columns.length || depthZeroWords(rest.slice(list.end)).includes('WHERE')) return
|
|
306
|
+
unique.push({ name, table, columns })
|
|
307
|
+
} else if (verb === 'DROP' && object === 'INDEX') {
|
|
308
|
+
const at = skipWords(tokens, skipWords(tokens, 2, 'CONCURRENTLY'), 'IF', 'EXISTS')
|
|
309
|
+
const dropped = new Set(splitAtCommas(tokens.slice(at)).map((part) => objectNameAt(part, 0)?.name))
|
|
310
|
+
const kept = unique.filter((index) => index.name === undefined || !dropped.has(index.name))
|
|
311
|
+
unique.splice(0, unique.length, ...kept)
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** A column with `UNIQUE` or `PRIMARY KEY`, or a `UNIQUE (…)` or `PRIMARY KEY (…)` table constraint. */
|
|
316
|
+
function readUniqueElement(table: string, element: readonly SqlToken[], unique: UniqueIndex[]): void {
|
|
317
|
+
const head = upperWord(element[0])
|
|
318
|
+
if (head !== undefined && TABLE_CONSTRAINTS.has(head)) {
|
|
319
|
+
const constraint = head === 'CONSTRAINT' ? element.slice(2) : element
|
|
320
|
+
const kind = upperWord(constraint[0])
|
|
321
|
+
const open = kind === 'PRIMARY' ? 2 : kind === 'UNIQUE' ? afterNullsClause(constraint) : undefined
|
|
322
|
+
const list = open === undefined ? undefined : columnList(constraint, open)
|
|
323
|
+
const columns = list?.columns.filter((column) => column !== undefined) ?? []
|
|
324
|
+
if (list !== undefined && columns.length > 0 && columns.length === list.columns.length) {
|
|
325
|
+
unique.push({ name: undefined, table, columns })
|
|
326
|
+
}
|
|
327
|
+
return
|
|
328
|
+
}
|
|
329
|
+
const column = nameText(element[0])
|
|
330
|
+
if (column !== undefined && depthZeroWords(element.slice(1)).some((word) => word === 'UNIQUE' || word === 'PRIMARY')) {
|
|
331
|
+
unique.push({ name: undefined, table, columns: [column] })
|
|
332
|
+
}
|
|
87
333
|
}
|
package/src/rules/packages.ts
CHANGED
|
@@ -8,18 +8,17 @@ import { posix } from 'node:path'
|
|
|
8
8
|
import { type AstNode, child, staticString } from '../ast'
|
|
9
9
|
import type { Finding, Report } from '../finding'
|
|
10
10
|
import { parseJsonc } from '../jsonc'
|
|
11
|
+
import { EXACT_VERSION, LOCKFILE, lockfileEntry, lockfilePackages } from '../lockfile'
|
|
11
12
|
import type { PackedSet } from '../packed'
|
|
12
13
|
import { isKey, parseToml } from '../toml'
|
|
13
14
|
import { BUNFIG_FILE, isTrustedSpecifier } from '../trust'
|
|
14
15
|
|
|
15
|
-
export const LOCKFILE = 'bun.lock'
|
|
16
16
|
export const NPMRC_FILE = '.npmrc'
|
|
17
17
|
|
|
18
18
|
const REPLACEMENT_FIELDS = ['patchedDependencies', 'overrides', 'resolutions'] as const
|
|
19
19
|
const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'] as const
|
|
20
20
|
/** An exact version or a caret/tilde range of one: what `bun add` writes for a registry package. */
|
|
21
21
|
const REGISTRY_RANGE = /^[~^]?\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
|
|
22
|
-
const EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
|
|
23
22
|
|
|
24
23
|
const REGISTRY_ALLOWED = 'a registry version of the package, such as "^1.2.3", resolved by bun install from the npm registry'
|
|
25
24
|
|
|
@@ -112,19 +111,15 @@ function checkManifest(path: string, text: string, finding: Finder, packed: Pack
|
|
|
112
111
|
}
|
|
113
112
|
|
|
114
113
|
function checkLockfile(text: string, finding: Finder, packed: PackedSet | undefined): void {
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
if (!isRecord(packages)) {
|
|
114
|
+
const packages = lockfilePackages(text)
|
|
115
|
+
if (packages === null) {
|
|
118
116
|
finding(LOCKFILE, '', `${LOCKFILE} has no packages the check can read`, 'a bun.lock written by bun install')
|
|
119
117
|
return
|
|
120
118
|
}
|
|
121
119
|
for (const [key, entry] of Object.entries(packages)) {
|
|
122
120
|
const name = lockfilePackage(key)
|
|
123
121
|
if (!isTrustedSpecifier(name)) continue
|
|
124
|
-
const
|
|
125
|
-
const registry = Array.isArray(entry) ? entry[1] : undefined
|
|
126
|
-
const integrity = Array.isArray(entry) ? entry.at(-1) : undefined
|
|
127
|
-
const version = typeof resolution === 'string' && resolution.startsWith(`${name}@`) ? resolution.slice(name.length + 1) : ''
|
|
122
|
+
const { version, registry, integrity } = lockfileEntry(name, entry)
|
|
128
123
|
// Bun records a tarball as `<name>@<path>`, its dependencies and the sha512 of its bytes, with no registry.
|
|
129
124
|
if (isPackedTarball(packed, name, version) && integrity === packed?.packages.get(name)?.integrity) continue
|
|
130
125
|
if (!EXACT_VERSION.test(version) || registry !== '' || typeof integrity !== 'string' || !integrity.startsWith('sha512-')) {
|
package/src/rules/runtime.ts
CHANGED
|
@@ -28,6 +28,12 @@ export interface SourceContext {
|
|
|
28
28
|
readonly rawSql: ReadonlySet<string>
|
|
29
29
|
/** A module under `src/` that is not a test: it reaches no global object and no `Bun` at all. */
|
|
30
30
|
readonly isServerModule: boolean
|
|
31
|
+
/** A `fetch` of an absolute URL: refused once the contract shows that no site declares its origin in `egress`. */
|
|
32
|
+
readonly absoluteFetch: (node: AstNode, target: string) => void
|
|
33
|
+
/** A `ctx.url('<endpoint id>', …)` with a literal id: refused once the contract shows that it names no procedure. */
|
|
34
|
+
readonly appUrl: (node: AstNode, endpoint: string) => void
|
|
35
|
+
/** A `<table>.insert(values, { onConflict: { columns } })`: refused once the migrations show no unique index of them. */
|
|
36
|
+
readonly conflictInsert: (node: AstNode, table: string, columns: readonly string[]) => void
|
|
31
37
|
}
|
|
32
38
|
|
|
33
39
|
/** The global objects and `Bun`: a server module reaches the platform through the framework only. */
|
|
@@ -127,14 +133,53 @@ const LOCAL_SCHEMES = /^(?:data|blob):/i
|
|
|
127
133
|
const checkFetch = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
|
128
134
|
const target = staticPrefix(invokedArgument(node, path, 'fetch'))
|
|
129
135
|
if (target === undefined || !ABSOLUTE_URL.test(target) || LOCAL_SCHEMES.test(target)) return
|
|
130
|
-
context.
|
|
131
|
-
node,
|
|
132
|
-
'cross-app-fetch',
|
|
133
|
-
`fetch to the absolute origin '${target}' is a hand-written integration`,
|
|
134
|
-
'a same-origin path to a declared endpoint, or another application through a connector import',
|
|
135
|
-
)
|
|
136
|
+
context.absoluteFetch(node, target)
|
|
136
137
|
}
|
|
137
138
|
|
|
139
|
+
/** `ctx.url('<endpoint id>', …)`, also on a `ctx` reached through a member (`args.ctx.url`). */
|
|
140
|
+
const checkAppUrl = (node: AstNode, context: SourceContext): void => {
|
|
141
|
+
const callee = child(node, 'callee')
|
|
142
|
+
const path = callee === undefined ? undefined : memberPath(callee)
|
|
143
|
+
if (path === undefined || path.length < 2 || path[path.length - 1] !== 'url' || path[path.length - 2] !== 'ctx') return
|
|
144
|
+
const endpoint = staticString(argumentAt(node, 0))
|
|
145
|
+
if (endpoint !== undefined) context.appUrl(node, endpoint)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* `<…>.<table>.insert(values, { onConflict: { columns: ['a', 'b'] } })` with literal columns: the receiver's last name
|
|
150
|
+
* is the table, as `ctx.db.<…>.<table>` names it. Anything else (an alias, computed columns) is the runtime's to refuse.
|
|
151
|
+
*/
|
|
152
|
+
const checkConflictInsert = (node: AstNode, context: SourceContext): void => {
|
|
153
|
+
const callee = child(node, 'callee')
|
|
154
|
+
const path = callee === undefined ? undefined : memberSuffix(callee)
|
|
155
|
+
const table = path !== undefined && path.length >= 2 && path[path.length - 1] === 'insert' ? path[path.length - 2] : undefined
|
|
156
|
+
const options = argumentAt(node, 1)
|
|
157
|
+
if (table === undefined || options?.type !== 'ObjectExpression') return
|
|
158
|
+
const onConflict = propertyValue(options, 'onConflict')
|
|
159
|
+
const columns = onConflict?.type === 'ObjectExpression' ? propertyValue(onConflict, 'columns') : undefined
|
|
160
|
+
if (columns?.type !== 'ArrayExpression') return
|
|
161
|
+
const names = children(columns, 'elements').map((element) => (element === null ? undefined : staticString(unwrap(element))))
|
|
162
|
+
const literal = names.filter((name): name is string => name !== undefined)
|
|
163
|
+
if (literal.length > 0 && literal.length === names.length) context.conflictInsert(node, table, literal)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** The value of an object literal's property `name`, written with a static key. */
|
|
167
|
+
const propertyValue = (object: AstNode, name: string): AstNode | undefined => {
|
|
168
|
+
for (const property of children(object, 'properties')) {
|
|
169
|
+
if (property?.type === 'Property' && staticKey(property, 'key') === name) {
|
|
170
|
+
const value = child(property, 'value')
|
|
171
|
+
return value === undefined ? undefined : unwrap(value)
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
return undefined
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The finding of a `fetch` of an absolute URL whose origin no site of the contract declares. */
|
|
178
|
+
export const crossAppFetchMessage = (target: string): { readonly message: string; readonly allowed: string } => ({
|
|
179
|
+
message: `fetch to the absolute origin '${target}' is a hand-written integration`,
|
|
180
|
+
allowed: "a same-origin path to a declared endpoint, another application through a connector import, or egress: ['<origin>'] on the site",
|
|
181
|
+
})
|
|
182
|
+
|
|
138
183
|
const checkDynamicCode = (node: AstNode, path: readonly string[], context: SourceContext): void => {
|
|
139
184
|
const isConstructor = pathIs(path, 'Function') || pathIs(path, 'Function', 'call') || pathIs(path, 'Function', 'apply')
|
|
140
185
|
if (isConstructor && (node.type === 'CallExpression' || node.type === 'NewExpression')) {
|
|
@@ -293,10 +338,13 @@ const checkCall = (node: AstNode, ancestors: readonly AstNode[], context: Source
|
|
|
293
338
|
const callee = child(node, 'callee')
|
|
294
339
|
const path = callee === undefined ? undefined : globalPath(callee)
|
|
295
340
|
if (node.type === 'CallExpression') checkIndirectLoad(node, path, context)
|
|
341
|
+
// A data-layer handle is reached through calls (`ctx.db.app('…')`), so its insert has no global path.
|
|
342
|
+
if (node.type === 'CallExpression') checkConflictInsert(node, context)
|
|
296
343
|
if (path === undefined) return
|
|
297
344
|
checkDynamicCode(node, path, context)
|
|
298
345
|
if (node.type !== 'CallExpression') return
|
|
299
346
|
checkFetch(node, path, context)
|
|
347
|
+
checkAppUrl(node, context)
|
|
300
348
|
checkConsole(node, path, ancestors, context)
|
|
301
349
|
checkPrototypeCall(node, path, context)
|
|
302
350
|
const [name] = path
|
package/src/rules/structure.ts
CHANGED
|
@@ -130,17 +130,18 @@ const isDataPackage = (specifier: string): boolean => specifier === '@fabrika/db
|
|
|
130
130
|
/** The framework modules logic and queries may import; the rest of `@fabrika/*` is the framework's own composition. */
|
|
131
131
|
const LAYER_PACKAGES: ReadonlySet<string> = new Set(['@fabrika/app', '@fabrika/db'])
|
|
132
132
|
|
|
133
|
-
/** The framework modules an SPA loads: the typed client, its React hooks
|
|
133
|
+
/** The framework modules an SPA loads: the typed client, its React hooks, the component kit and its challenge widget. */
|
|
134
134
|
const SPA_PACKAGES: ReadonlySet<string> = new Set([
|
|
135
135
|
'@fabrika/app/client',
|
|
136
136
|
'@fabrika/app/react',
|
|
137
137
|
'@fabrika/ui',
|
|
138
|
+
'@fabrika/ui/challenge',
|
|
138
139
|
'@fabrika/ui/styles.css',
|
|
139
140
|
'@fabrika/ui/theme.css',
|
|
140
141
|
])
|
|
141
142
|
|
|
142
143
|
const SPA_ALLOWED =
|
|
143
|
-
'@fabrika/app/client, @fabrika/app/react, @fabrika/ui, fabrika.contract.ts, src/schemas.ts, modules under src/shared/ and modules under web/; a type-only import of anything else'
|
|
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'
|
|
144
145
|
|
|
145
146
|
const isSchemaModule = (path: string): boolean => path === SCHEMAS_FILE || path.startsWith(SCHEMAS_DIR)
|
|
146
147
|
|
package/src/scaffold-sample.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// A fixed input that a schema shape admits, written into a generated test as a literal. Deterministic, so the checker
|
|
2
2
|
// regenerates the same text; `undefined` when the scaffold cannot build one (a pattern, contradictory bounds).
|
|
3
3
|
|
|
4
|
+
import { GENERATED_FILE_PREFIX } from '@fabrika/app/contract'
|
|
4
5
|
import type { NumberShape, SchemaShape, StringShape } from '@fabrika/auth-core'
|
|
5
6
|
|
|
6
7
|
export type Sample = null | boolean | number | string | readonly Sample[] | { readonly [key: string]: Sample }
|
|
@@ -81,6 +82,8 @@ export function sample(shape: SchemaShape): Sample | undefined {
|
|
|
81
82
|
const items = shape.items.map(sample)
|
|
82
83
|
return items.every((item) => item !== undefined) ? items.filter((item) => item !== undefined) : undefined
|
|
83
84
|
}
|
|
85
|
+
case 'file':
|
|
86
|
+
return `${GENERATED_FILE_PREFIX}${shape.kind}`
|
|
84
87
|
case 'object': {
|
|
85
88
|
const entries: [string, Sample][] = []
|
|
86
89
|
for (const [name, inner] of Object.entries(shape.fields).sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0))) {
|