@kerf-js/cli 0.0.0-stage → 0.1.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.
Files changed (176) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +554 -2
  3. package/bin/kerf.mjs +15 -0
  4. package/docs/async.md +50 -0
  5. package/docs/browser.md +53 -0
  6. package/docs/config.md +127 -0
  7. package/docs/core.md +30 -0
  8. package/docs/deploy.md +108 -0
  9. package/docs/design.md +106 -0
  10. package/docs/entrypoints.md +83 -0
  11. package/docs/fonts.md +118 -0
  12. package/docs/icons.md +108 -0
  13. package/docs/lists.md +25 -0
  14. package/docs/meta.md +92 -0
  15. package/docs/plugins.md +166 -0
  16. package/docs/props.md +88 -0
  17. package/docs/reactivity.md +26 -0
  18. package/docs/rules.md +39 -0
  19. package/docs/rust.md +253 -0
  20. package/docs/start-short.md +10 -0
  21. package/docs/start.md +642 -0
  22. package/docs/state.md +122 -0
  23. package/docs/style.md +82 -0
  24. package/docs/surface.md +158 -0
  25. package/docs/testing.md +81 -0
  26. package/docs/theme.md +263 -0
  27. package/docs/ui-state.md +105 -0
  28. package/docs/verify.md +61 -0
  29. package/package.json +47 -3
  30. package/src/add/config.mjs +93 -0
  31. package/src/add/errors.mjs +2 -0
  32. package/src/add/setup.mjs +88 -0
  33. package/src/add-rust.mjs +178 -0
  34. package/src/add.mjs +392 -0
  35. package/src/agents-md.mjs +240 -0
  36. package/src/alias.mjs +70 -0
  37. package/src/audit/page.mjs +313 -0
  38. package/src/audit/report.mjs +69 -0
  39. package/src/audit/utils.mjs +5 -0
  40. package/src/audit.mjs +319 -0
  41. package/src/browser/cli.mjs +53 -0
  42. package/src/browser/client.mjs +299 -0
  43. package/src/browser/commands.mjs +258 -0
  44. package/src/capture.mjs +21 -0
  45. package/src/catalog/audit.mjs +129 -0
  46. package/src/catalog/auth.mjs +40 -0
  47. package/src/catalog/compiler.mjs +337 -0
  48. package/src/catalog/contracts.mjs +18 -0
  49. package/src/catalog/database.mjs +52 -0
  50. package/src/catalog/deploy.mjs +117 -0
  51. package/src/catalog/design.mjs +159 -0
  52. package/src/catalog/forms.mjs +25 -0
  53. package/src/catalog/hydration.mjs +29 -0
  54. package/src/catalog/icons.mjs +24 -0
  55. package/src/catalog/media.mjs +163 -0
  56. package/src/catalog/metadata.mjs +116 -0
  57. package/src/catalog/plugins.mjs +228 -0
  58. package/src/catalog/realtime.mjs +195 -0
  59. package/src/catalog/rust.mjs +75 -0
  60. package/src/catalog/server-functions.mjs +100 -0
  61. package/src/catalog/state.mjs +39 -0
  62. package/src/catalog/style-groups.mjs +54 -0
  63. package/src/catalog/tests.mjs +127 -0
  64. package/src/catalog/text.mjs +200 -0
  65. package/src/catalog/ui-state.mjs +42 -0
  66. package/src/catalog.mjs +103 -0
  67. package/src/check/runtime.mjs +280 -0
  68. package/src/check.mjs +321 -0
  69. package/src/cli/authoring.mjs +213 -0
  70. package/src/cli/project.mjs +302 -0
  71. package/src/cli.mjs +340 -0
  72. package/src/config.d.ts +1 -0
  73. package/src/config.mjs +5 -0
  74. package/src/contributions.mjs +119 -0
  75. package/src/db-layer.mjs +41 -0
  76. package/src/deploy/cdn.mjs +142 -0
  77. package/src/deploy/files.mjs +266 -0
  78. package/src/deploy/fit.mjs +166 -0
  79. package/src/deploy/hosts.mjs +126 -0
  80. package/src/deploy/index/cli.mjs +20 -0
  81. package/src/deploy/index/environment.mjs +69 -0
  82. package/src/deploy/index/steps.mjs +87 -0
  83. package/src/deploy/index.mjs +387 -0
  84. package/src/deploy/needs.mjs +149 -0
  85. package/src/design-checks/accessible-names.mjs +62 -0
  86. package/src/design-checks/contrast.mjs +43 -0
  87. package/src/design-checks/csp.mjs +60 -0
  88. package/src/design-checks/files.mjs +59 -0
  89. package/src/design-checks/heading-links.mjs +61 -0
  90. package/src/design-checks/interaction.mjs +65 -0
  91. package/src/design-checks/jsx.mjs +67 -0
  92. package/src/design-checks/layout-values.mjs +68 -0
  93. package/src/design-checks/native-controls.mjs +48 -0
  94. package/src/design-checks/outline.mjs +39 -0
  95. package/src/design-checks/reporter.mjs +37 -0
  96. package/src/design-checks/rules.mjs +274 -0
  97. package/src/design-checks/values.mjs +262 -0
  98. package/src/design-checks.mjs +49 -0
  99. package/src/diag.mjs +98 -0
  100. package/src/docs.mjs +228 -0
  101. package/src/doctor.mjs +42 -0
  102. package/src/files.mjs +60 -0
  103. package/src/fix.mjs +48 -0
  104. package/src/gate/after.mjs +40 -0
  105. package/src/gate/before.mjs +54 -0
  106. package/src/gate/classify.mjs +72 -0
  107. package/src/gate/mutation.mjs +209 -0
  108. package/src/gate/resolve-cases.mjs +22 -0
  109. package/src/gate/result.mjs +63 -0
  110. package/src/gate/run.mjs +75 -0
  111. package/src/gate.mjs +178 -0
  112. package/src/index.mjs +9 -0
  113. package/src/infer/box-props.cjs +140 -0
  114. package/src/infer/core-boxes.cjs +46 -0
  115. package/src/infer/derived-writes.cjs +95 -0
  116. package/src/infer/engine/checks.cjs +193 -0
  117. package/src/infer/engine/flow.cjs +293 -0
  118. package/src/infer/engine/report.cjs +158 -0
  119. package/src/infer/engine/utils.cjs +15 -0
  120. package/src/infer/engine.cjs +265 -0
  121. package/src/infer/facts/sites.cjs +114 -0
  122. package/src/infer/facts.cjs +345 -0
  123. package/src/infer/hosts.cjs +161 -0
  124. package/src/infer/lsp.mjs +240 -0
  125. package/src/infer/session.cjs +161 -0
  126. package/src/infer/shadow.cjs +54 -0
  127. package/src/infer/worker.cjs +145 -0
  128. package/src/jsx-scan.mjs +128 -0
  129. package/src/kerf.mjs +98 -0
  130. package/src/load-config/schema.mjs +300 -0
  131. package/src/load-config.mjs +302 -0
  132. package/src/map.mjs +177 -0
  133. package/src/mcp/browser-tools.mjs +155 -0
  134. package/src/mcp.mjs +273 -0
  135. package/src/meta-table.mjs +63 -0
  136. package/src/mutate.mjs +224 -0
  137. package/src/plugin-checks.mjs +118 -0
  138. package/src/plugins.mjs +258 -0
  139. package/src/project.mjs +310 -0
  140. package/src/props-checks.mjs +64 -0
  141. package/src/props-listener.mjs +56 -0
  142. package/src/react-checks.mjs +67 -0
  143. package/src/server-state-checks.mjs +34 -0
  144. package/src/share-checks.mjs +158 -0
  145. package/src/site.mjs +46 -0
  146. package/src/slots.mjs +181 -0
  147. package/src/start/build.mjs +116 -0
  148. package/src/start/routes.mjs +38 -0
  149. package/src/start.mjs +394 -0
  150. package/src/state-checks/core-state.mjs +223 -0
  151. package/src/state-checks/modules.mjs +17 -0
  152. package/src/state-checks/scan.mjs +232 -0
  153. package/src/state-checks/server-graph.mjs +65 -0
  154. package/src/state-checks.mjs +189 -0
  155. package/src/style/find.mjs +121 -0
  156. package/src/style.mjs +327 -0
  157. package/src/surface-checks.mjs +384 -0
  158. package/src/tailwind.mjs +23 -0
  159. package/src/tasks.mjs +261 -0
  160. package/src/test-rules/context.mjs +109 -0
  161. package/src/test-rules/file-rules.mjs +279 -0
  162. package/src/test-rules/rule-helpers.mjs +244 -0
  163. package/src/test-rules/syntax.mjs +223 -0
  164. package/src/test-rules/test-rules.mjs +127 -0
  165. package/src/testdiff.mjs +219 -0
  166. package/src/tests.mjs +120 -0
  167. package/src/text-checks.mjs +332 -0
  168. package/src/tokens.mjs +33 -0
  169. package/src/trust/scan.mjs +95 -0
  170. package/src/trust.mjs +394 -0
  171. package/src/workspace.mjs +182 -0
  172. package/ts-plugin/context.js +57 -0
  173. package/ts-plugin/index.js +17 -0
  174. package/ts-plugin/mapping.js +65 -0
  175. package/ts-plugin/package.json +1 -0
  176. package/ts-plugin/proxy.js +144 -0
@@ -0,0 +1,223 @@
1
+ import { existsSync } from 'node:fs'
2
+ import ts from 'typescript'
3
+ import { local } from '../alias.mjs'
4
+
5
+ const suiteRoots = new Set(['describe', 'suite', 'fdescribe', 'xdescribe'])
6
+ const testRoots = new Set(['test', 'it', 'fit', 'xit', 'xtest', ...suiteRoots])
7
+ const exts = [
8
+ '',
9
+ '.ts',
10
+ '.tsx',
11
+ '.mts',
12
+ '.js',
13
+ '.jsx',
14
+ '.mjs',
15
+ '/index.ts',
16
+ '/index.tsx',
17
+ '/index.js',
18
+ ]
19
+
20
+ const kindOf = (file) =>
21
+ file.endsWith('.tsx')
22
+ ? ts.ScriptKind.TSX
23
+ : file.endsWith('.jsx')
24
+ ? ts.ScriptKind.JSX
25
+ : /\.[mc]?ts$/.test(file)
26
+ ? ts.ScriptKind.TS
27
+ : ts.ScriptKind.JS
28
+ export const parse = (text, file) =>
29
+ ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kindOf(file))
30
+ export const isFn = (n) =>
31
+ n && (ts.isArrowFunction(n) || ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n))
32
+ export const norm = (n) => n.getText().replace(/\s+/g, ' ').replace(/;$/, '')
33
+ export const unwrap = (n) => {
34
+ while (
35
+ n &&
36
+ (ts.isParenthesizedExpression(n) ||
37
+ ts.isAsExpression(n) ||
38
+ ts.isNonNullExpression(n) ||
39
+ ts.isAwaitExpression(n))
40
+ )
41
+ n = n.expression
42
+ return n
43
+ }
44
+
45
+ export function walk(node, visit) {
46
+ const go = (n) => {
47
+ if (visit(n) === false) return
48
+ ts.forEachChild(n, go)
49
+ }
50
+ go(node)
51
+ }
52
+
53
+ export const contains = (node, pred) => {
54
+ let hit = false
55
+ walk(node, (n) => {
56
+ if (hit) return false
57
+ if (pred(n)) hit = true
58
+ })
59
+ return hit
60
+ }
61
+
62
+ /** The identifier at the root of `a.b(…).c`, or undefined. */
63
+ export function rootName(expr) {
64
+ let n = expr
65
+ for (;;) {
66
+ n = unwrap(n)
67
+ if (
68
+ ts.isPropertyAccessExpression(n) ||
69
+ ts.isElementAccessExpression(n) ||
70
+ ts.isCallExpression(n)
71
+ )
72
+ n = n.expression
73
+ else break
74
+ }
75
+ return ts.isIdentifier(n) ? n.text : undefined
76
+ }
77
+
78
+ /** `1`, `'a'`, `null`, `[1, { a: 'b' }]`: a value with nothing behind it. */
79
+ export function isLiteral(n) {
80
+ n = unwrap(n)
81
+ if (!n) return false
82
+ if (
83
+ ts.isStringLiteral(n) ||
84
+ ts.isNumericLiteral(n) ||
85
+ ts.isBigIntLiteral(n) ||
86
+ ts.isNoSubstitutionTemplateLiteral(n) ||
87
+ ts.isRegularExpressionLiteral(n)
88
+ )
89
+ return true
90
+ if (
91
+ [ts.SyntaxKind.TrueKeyword, ts.SyntaxKind.FalseKeyword, ts.SyntaxKind.NullKeyword].includes(
92
+ n.kind,
93
+ )
94
+ )
95
+ return true
96
+ if (ts.isIdentifier(n)) return n.text === 'undefined' || n.text === 'NaN' || n.text === 'Infinity'
97
+ if (ts.isPrefixUnaryExpression(n)) return isLiteral(n.operand)
98
+ if (ts.isArrayLiteralExpression(n)) return n.elements.every(isLiteral)
99
+ if (ts.isObjectLiteralExpression(n))
100
+ return n.properties.every((p) => ts.isPropertyAssignment(p) && isLiteral(p.initializer))
101
+ return false
102
+ }
103
+
104
+ export const hasCall = (n) =>
105
+ contains(
106
+ n,
107
+ (x) =>
108
+ ts.isCallExpression(x) ||
109
+ ts.isNewExpression(x) ||
110
+ ts.isAwaitExpression(x) ||
111
+ ts.isTaggedTemplateExpression(x),
112
+ )
113
+
114
+ /** `expect(x)`, `expect.soft(x)`, `t.expect(x)`: the call that takes the subject. */
115
+ export function isSubject(call) {
116
+ const c = call.expression
117
+ if (ts.isIdentifier(c)) return c.text === 'expect'
118
+ if (!ts.isPropertyAccessExpression(c)) return false
119
+ if (c.name.text === 'expect') return true
120
+ return (
121
+ ts.isIdentifier(c.expression) &&
122
+ c.expression.text === 'expect' &&
123
+ ['soft', 'poll'].includes(c.name.text)
124
+ )
125
+ }
126
+
127
+ /** For a subject call, the matcher it ends in: `expect(x).not.toBe(1)` → { name: 'toBe', call, not: true }. */
128
+ export function matcherOf(subject) {
129
+ let cur = subject
130
+ let not = false
131
+ const mods = []
132
+ for (;;) {
133
+ const p = cur.parent
134
+ if (p && ts.isPropertyAccessExpression(p) && p.expression === cur) {
135
+ const name = p.name.text
136
+ if (p.parent && ts.isCallExpression(p.parent) && p.parent.expression === p)
137
+ return { name, node: p.name, call: p.parent, not, mods }
138
+ if (name === 'not') not = !not
139
+ mods.push(name)
140
+ cur = p
141
+ } else return null
142
+ }
143
+ }
144
+
145
+ /** Test and suite calls, with their modifiers: `test.only.each(table)('x', fn)`. */
146
+ export function testCall(call) {
147
+ // The outer call of a curried form (`test.each(t)(…)`) is the test; skip the inner one.
148
+ if (call.parent && ts.isCallExpression(call.parent) && call.parent.expression === call)
149
+ return null
150
+ const mods = []
151
+ let n = call.expression
152
+ for (;;) {
153
+ if (ts.isPropertyAccessExpression(n)) {
154
+ mods.unshift({ name: n.name.text, node: n })
155
+ n = n.expression
156
+ } else if (ts.isCallExpression(n)) n = n.expression
157
+ else break
158
+ }
159
+ if (!ts.isIdentifier(n) || !testRoots.has(n.text)) return null
160
+ const root = n.text
161
+ const fn = [...call.arguments]
162
+ .reverse()
163
+ .find((a) => ts.isArrowFunction(a) || ts.isFunctionExpression(a))
164
+ // `fit` with no test body is someone's function (@kerf-js/core/text's), not a focused test
165
+ if (root === 'fit' && !fn) return null
166
+ return { root, rootNode: n, mods, fn, suite: suiteRoots.has(root), call }
167
+ }
168
+
169
+ /** Functions (by name) whose bodies assert, in one file: local helpers and, given `imported`, what they call. */
170
+ export function assertingFunctions(sf, imported = new Set()) {
171
+ const bodies = new Map()
172
+ const add = (name, fn) => fn?.body && bodies.set(name, fn.body)
173
+ for (const st of sf.statements) {
174
+ const decl = ts.isExportDeclaration(st) ? null : st
175
+ if (decl && ts.isFunctionDeclaration(decl) && decl.name) add(decl.name.text, decl)
176
+ if (decl && ts.isVariableStatement(decl))
177
+ for (const d of decl.declarationList.declarations)
178
+ if (ts.isIdentifier(d.name) && isFn(d.initializer)) add(d.name.text, d.initializer)
179
+ }
180
+ const asserting = new Set(imported)
181
+ for (let changed = true; changed;) {
182
+ changed = false
183
+ for (const [name, body] of bodies) {
184
+ if (asserting.has(name) || !asserts(body, asserting)) continue
185
+ asserting.add(name)
186
+ changed = true
187
+ }
188
+ }
189
+ return asserting
190
+ }
191
+
192
+ /** Does this code assert? A matcher, `assert…`, `expect.assertions`, a helper named `expect…`, or a known asserting function. */
193
+ export function asserts(node, asserting) {
194
+ return contains(node, (n) => {
195
+ if (!ts.isCallExpression(n)) return false
196
+ if (isSubject(n)) return Boolean(matcherOf(n))
197
+ const c = n.expression
198
+ if (
199
+ ts.isPropertyAccessExpression(c) &&
200
+ ts.isIdentifier(c.expression) &&
201
+ c.expression.text === 'expect'
202
+ )
203
+ return true // expect.assertions(n)
204
+ const name = ts.isIdentifier(c)
205
+ ? c.text
206
+ : ts.isPropertyAccessExpression(c) && ts.isIdentifier(c.expression)
207
+ ? c.expression.text
208
+ : undefined
209
+ return Boolean(name && (/^(expect|assert)([A-Z_]|$)/.test(name) || asserting.has(name)))
210
+ })
211
+ }
212
+
213
+ export function resolveImport(fromAbs, spec) {
214
+ const base = local(fromAbs, spec)
215
+ if (!base) return null
216
+ for (const e of exts) {
217
+ const p = base + e
218
+ if (existsSync(p) && !p.endsWith('/') && (e || /\.[cm]?[jt]sx?$/.test(p))) return p
219
+ }
220
+ return null
221
+ }
222
+
223
+ export const moduleKey = (abs) => abs.replace(/(\/index)?\.[cm]?[jt]sx?$/, '')
@@ -0,0 +1,127 @@
1
+ import ts from 'typescript'
2
+ import { asserts, isSubject, matcherOf, norm, walk } from './syntax.mjs'
3
+ import { assertsWhatItSet, conditional } from './rule-helpers.mjs'
4
+
5
+ const focusRoots = { fit: 'it', fdescribe: 'describe' }
6
+ const skipRoots = { xit: 'it', xtest: 'test', xdescribe: 'describe' }
7
+
8
+ export function focusRule(t, { sf, edit, report }) {
9
+ const focus =
10
+ t.mods.find((m) => m.name === 'only') ??
11
+ (focusRoots[t.root] && { name: 'only', node: t.rootNode })
12
+ const skip =
13
+ t.mods.find((m) => m.name === 'skip') ??
14
+ (skipRoots[t.root] && { name: 'skip', node: t.rootNode })
15
+ for (const m of [focus, skip].filter(Boolean)) {
16
+ const kind = t.suite ? 'suite' : 'test'
17
+ let fix
18
+ if (m.node === t.rootNode) {
19
+ const to = focusRoots[t.root] ?? skipRoots[t.root]
20
+ fix = {
21
+ description: `Rename \`${t.root}\` to \`${to}\``,
22
+ safe: m.name === 'only',
23
+ edits: [edit(m.node.getStart(sf), m.node.getEnd(), to)],
24
+ }
25
+ report(
26
+ 'T009',
27
+ m.node,
28
+ `\`${t.root}\` ${m.name === 'only' ? 'focuses this ' + kind + ': every other test in the run is silently skipped' : 'skips this ' + kind + ': it never runs, so it proves nothing'}.`,
29
+ { fix },
30
+ )
31
+ } else {
32
+ const dot = m.node.expression.getEnd()
33
+ fix = {
34
+ description: `Remove \`.${m.name}\``,
35
+ safe: m.name === 'only',
36
+ edits: [edit(dot, m.node.getEnd(), '')],
37
+ }
38
+ report(
39
+ 'T009',
40
+ m.node.name,
41
+ m.name === 'only'
42
+ ? `\`.only\` focuses this ${kind}: every other test in the run is silently skipped.`
43
+ : `\`.skip\` turns this ${kind} off: it never runs, so it proves nothing. Fix or delete it; a test that is meant to fail is \`test.fails\`.`,
44
+ { fix },
45
+ )
46
+ }
47
+ }
48
+ }
49
+
50
+ function assertionRule(t, { asserting, report }, n, previouslyNoAssertion) {
51
+ if (n) {
52
+ if (!previouslyNoAssertion)
53
+ report('T001', n, `\`${norm(n)}\` has no matcher, so it asserts nothing.`, {
54
+ help: 'Finish it: `expect(x).toBe(…)`, `.toHaveTextContent(…)`, …',
55
+ })
56
+ return
57
+ }
58
+ const body = t.fn.body
59
+ const noAssertion = !asserts(body, asserting)
60
+ if (noAssertion) {
61
+ const title =
62
+ t.call.arguments[0] && ts.isStringLiteralLike(t.call.arguments[0])
63
+ ? ` "${t.call.arguments[0].text}"`
64
+ : ''
65
+ report(
66
+ 'T001',
67
+ t.call.expression,
68
+ `Test${title} makes no assertion: it passes as long as nothing throws.`,
69
+ )
70
+ }
71
+
72
+ return noAssertion
73
+ }
74
+
75
+ function conditionalRule(t, ctx, noAssertion) {
76
+ const { report } = ctx
77
+ const body = t.fn.body
78
+ // A looped `expect` is fine next to one that always runs; a conditional one never is.
79
+ const looped = []
80
+ let always = false
81
+ walk(body, (n) => {
82
+ if (!ts.isCallExpression(n) || !isSubject(n)) return
83
+ const m = matcherOf(n)
84
+ if (!m) {
85
+ assertionRule(t, ctx, n, noAssertion)
86
+ return
87
+ }
88
+ let why
89
+ for (let a = n.parent; a && a !== t.fn && !why; a = a.parent) why = conditional(a, n)
90
+ if (!why) always = true
91
+ else if (why.loop) looped.push([m.call, why.text])
92
+ else
93
+ report(
94
+ 'T008',
95
+ m.call,
96
+ `This \`expect\` only runs ${why.text}, so the test can pass without checking anything.`,
97
+ )
98
+ })
99
+ if (!always)
100
+ for (const [call, how] of looped)
101
+ report(
102
+ 'T008',
103
+ call,
104
+ `Every \`expect\` in this test runs ${how}, so the test can pass without checking anything.`,
105
+ )
106
+ }
107
+
108
+ export function setRule(t, { report }) {
109
+ const body = t.fn.body
110
+ if (ts.isBlock(body)) assertsWhatItSet(body.statements, report)
111
+ }
112
+
113
+ export const testRules = [focusRule, assertionRule, conditionalRule, setRule]
114
+
115
+ export function runTestRules(t, ctx) {
116
+ testRules[0](t, ctx)
117
+ if (
118
+ t.suite ||
119
+ !t.fn ||
120
+ t.mods.some((m) => ['todo', 'skip'].includes(m.name)) ||
121
+ skipRoots[t.root]
122
+ )
123
+ return
124
+ const noAssertion = testRules[1](t, ctx)
125
+ testRules[2](t, ctx, noAssertion)
126
+ testRules[3](t, ctx)
127
+ }
@@ -0,0 +1,219 @@
1
+ // Test cases in a test file, and what changed between two versions of one: which tests are new or edited (the ones
2
+ // the gate must prove), and T020, an existing test deleted, skipped or loosened without a written reason.
3
+ //
4
+ // // kerf-allow T020: the old assertion pinned the bug this change fixes
5
+
6
+ import ts from 'typescript'
7
+ import { diagnostic, positions } from './diag.mjs'
8
+ import { allowances, isSubject, matcherOf, norm, parse, testCall } from './tests.mjs'
9
+
10
+ const skipMods = new Set(['skip', 'todo'])
11
+ const skipRoots = new Set(['xit', 'xtest', 'xdescribe'])
12
+
13
+ /** A case's name as vitest reports it: suite titles and the test title joined by ' > '. */
14
+ const join = (names) => names.join(' > ')
15
+
16
+ function nameOf(arg) {
17
+ if (!arg) return { name: '<anonymous>', dynamic: true }
18
+ if (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg))
19
+ return { name: arg.text, dynamic: false }
20
+ return { name: arg.getText(), dynamic: true }
21
+ }
22
+
23
+ /**
24
+ * Every test case in one file, in order.
25
+ * @returns {{ name: string, line: number, end: number, body: string, skipped: boolean, fails: boolean, dynamic: boolean, asserts: { key: string, subject: string, matcher: string, not: boolean, args: string, line: number }[], expected: number | null }[]}
26
+ */
27
+ export function testCases(text, rel) {
28
+ const sf = parse(text, rel)
29
+ const pos = positions(text)
30
+ const out = []
31
+ const visit = (node, suites, skipped, dynamic) => {
32
+ if (ts.isCallExpression(node)) {
33
+ const t = testCall(node)
34
+ if (t) {
35
+ const each = t.mods.some((m) => m.name === 'each' || m.name === 'for')
36
+ const { name, dynamic: dyn } = nameOf(node.arguments[0])
37
+ const skip = skipped || skipRoots.has(t.root) || t.mods.some((m) => skipMods.has(m.name))
38
+ const isDynamic = dynamic || dyn || each
39
+ if (t.suite) {
40
+ if (t.fn?.body)
41
+ ts.forEachChild(t.fn.body, (c) => visit(c, [...suites, name], skip, isDynamic))
42
+ return
43
+ }
44
+ const asserts = []
45
+ let expected = null
46
+ if (t.fn?.body)
47
+ walk(t.fn.body, (n) => {
48
+ if (!ts.isCallExpression(n)) return
49
+ if (isSubject(n)) {
50
+ const m = matcherOf(n)
51
+ if (!m) return
52
+ const subject = n.arguments[0] ? norm(n.arguments[0]) : ''
53
+ const args = m.call.arguments.map(norm).join(', ')
54
+ asserts.push({
55
+ key: `${subject}|${m.not ? 'not.' : ''}${m.name}|${args}`,
56
+ subject,
57
+ matcher: m.name,
58
+ not: m.not,
59
+ args,
60
+ line: pos.lineCol(n.getStart(sf))[0],
61
+ })
62
+ } else if (
63
+ ts.isPropertyAccessExpression(n.expression) &&
64
+ ts.isIdentifier(n.expression.expression) &&
65
+ n.expression.expression.text === 'expect' &&
66
+ n.expression.name.text === 'assertions'
67
+ ) {
68
+ expected = Number(n.arguments[0]?.getText()) || null
69
+ }
70
+ })
71
+ out.push({
72
+ name: join([...suites, name]),
73
+ line: pos.lineCol(node.getStart(sf))[0],
74
+ end: pos.lineCol(node.getEnd())[0],
75
+ body: t.fn?.body ? norm(t.fn.body) : '',
76
+ skipped: skip,
77
+ fails: t.mods.some((m) => m.name === 'fails'),
78
+ dynamic: isDynamic,
79
+ asserts,
80
+ expected,
81
+ })
82
+ return
83
+ }
84
+ }
85
+ ts.forEachChild(node, (c) => visit(c, suites, skipped, dynamic))
86
+ }
87
+ visit(sf, [], false, false)
88
+ return out
89
+ }
90
+
91
+ function walk(node, fn) {
92
+ const go = (n) => {
93
+ fn(n)
94
+ ts.forEachChild(n, go)
95
+ }
96
+ go(node)
97
+ }
98
+
99
+ /** The test names in `after` that are new or whose body changed since `before` (null: the file is new). */
100
+ export function changedCases(before, after, rel) {
101
+ const old = new Map((before == null ? [] : testCases(before, rel)).map((c) => [c.name, c]))
102
+ return testCases(after, rel).filter((c) => !c.skipped && old.get(c.name)?.body !== c.body)
103
+ }
104
+
105
+ /**
106
+ * Loosening a matcher: the new one accepts everything the old one did, and more. Keyed by the old matcher.
107
+ * Changing an expected value (`toBe(3)` → `toBe(4)`) is not loosening: a fix often has to.
108
+ */
109
+ const looser = {
110
+ toBe: ['toBeTruthy', 'toBeFalsy', 'toBeDefined', 'toEqual', 'toBeTypeOf', 'toBeInstanceOf'],
111
+ toEqual: ['toBeTruthy', 'toBeDefined', 'toMatchObject', 'toBeTypeOf', 'toBeInstanceOf'],
112
+ toStrictEqual: ['toEqual', 'toBeTruthy', 'toBeDefined', 'toMatchObject'],
113
+ toHaveLength: ['toBeTruthy', 'toBeDefined'],
114
+ toHaveBeenCalledWith: ['toHaveBeenCalled'],
115
+ toHaveBeenCalledTimes: ['toHaveBeenCalled'],
116
+ toHaveBeenLastCalledWith: ['toHaveBeenCalled'],
117
+ toContain: ['toBeTruthy', 'toBeDefined'],
118
+ toMatch: ['toBeTruthy', 'toBeDefined'],
119
+ toThrow: ['toThrow'], // with an argument → without one (checked below)
120
+ toBeNull: ['toBeFalsy'],
121
+ toBeUndefined: ['toBeFalsy'],
122
+ toBeGreaterThan: ['toBeGreaterThanOrEqual'],
123
+ toBeLessThan: ['toBeLessThanOrEqual'],
124
+ }
125
+
126
+ function loosened(a, b) {
127
+ if (a.subject !== b.subject || a.not !== b.not) return false
128
+ if (a.matcher === 'toThrow' || a.matcher === 'toThrowError')
129
+ return b.matcher.startsWith('toThrow') && a.args && !b.args
130
+ return looser[a.matcher]?.includes(b.matcher) ?? false
131
+ }
132
+
133
+ /**
134
+ * T020 for one test file: an existing test deleted, skipped, marked `.fails`, or with an assertion removed or loosened.
135
+ * `after` null: the whole file was deleted (reported on `before`'s path, line 1).
136
+ */
137
+ export function weakened(before, after, rel) {
138
+ if (before == null) return []
139
+ const old = testCases(before, rel)
140
+ if (after == null) {
141
+ const live = old.filter((c) => !c.skipped)
142
+ return live.length
143
+ ? [
144
+ t020(
145
+ rel,
146
+ null,
147
+ 1,
148
+ `${rel} was deleted with ${live.length} test${live.length > 1 ? 's' : ''} in it (${live
149
+ .slice(0, 3)
150
+ .map((c) => `"${c.name}"`)
151
+ .join(', ')}${live.length > 3 ? ', …' : ''})`,
152
+ ),
153
+ ]
154
+ : []
155
+ }
156
+ const sf = parse(after, rel)
157
+ const allowed = allowances(after, sf)
158
+ const now = testCases(after, rel)
159
+ const byName = new Map(now.map((c) => [c.name, c]))
160
+ const byBody = new Set(now.map((c) => c.body))
161
+ const out = []
162
+ const report = (line, why) => {
163
+ if (!allowed('T020', line)) out.push(t020(rel, after, line, why))
164
+ }
165
+ for (const o of old) {
166
+ if (o.skipped || o.dynamic) continue
167
+ const n = byName.get(o.name)
168
+ if (!n) {
169
+ if (!byBody.has(o.body)) report(1, `test "${o.name}" was deleted`)
170
+ continue
171
+ }
172
+ if (n.skipped) {
173
+ report(n.line, `test "${o.name}" is now skipped`)
174
+ continue
175
+ }
176
+ if (n.fails && !o.fails) {
177
+ report(n.line, `test "${o.name}" is now marked \`.fails\``)
178
+ continue
179
+ }
180
+ if (o.expected && (n.expected ?? 0) < o.expected)
181
+ report(
182
+ n.line,
183
+ `test "${o.name}" now expects ${n.expected ?? 'no'} assertions instead of ${o.expected}`,
184
+ )
185
+ const nowKeys = new Set(n.asserts.map((a) => a.key))
186
+ const oldKeys = new Set(o.asserts.map((a) => a.key))
187
+ const gone = o.asserts.filter((a) => !nowKeys.has(a.key))
188
+ const added = n.asserts.filter((a) => !oldKeys.has(a.key))
189
+ for (const a of gone) {
190
+ const loose = added.find((b) => loosened(a, b))
191
+ if (loose)
192
+ report(
193
+ loose.line,
194
+ `in "${o.name}", \`expect(${a.subject}).${a.not ? 'not.' : ''}${a.matcher}(${a.args})\` became \`${loose.not ? 'not.' : ''}${loose.matcher}(${loose.args})\`, which accepts more`,
195
+ )
196
+ }
197
+ const replaced = gone.filter((a) => !added.some((b) => loosened(a, b)))
198
+ if (n.asserts.length < o.asserts.length && replaced.length)
199
+ report(
200
+ n.line,
201
+ `"${o.name}" lost ${o.asserts.length - n.asserts.length} assertion${o.asserts.length - n.asserts.length > 1 ? 's' : ''}: ${replaced
202
+ .slice(0, 2)
203
+ .map((a) => `\`expect(${a.subject}).${a.matcher}(…)\``)
204
+ .join(', ')}`,
205
+ )
206
+ }
207
+ return out
208
+ }
209
+
210
+ function t020(rel, _text, line, why) {
211
+ const span = [line, 1, line, 1]
212
+ return diagnostic({
213
+ code: 'T020',
214
+ file: rel,
215
+ span,
216
+ why: `${why}. An existing test got weaker, so it may no longer catch what it used to.`,
217
+ help: 'Restore it; or, when the change really is intended (the old test pinned a bug), keep it with `// kerf-allow T020: <reason>` on that test, where the reviewer sees it',
218
+ })
219
+ }
package/src/tests.mjs ADDED
@@ -0,0 +1,120 @@
1
+ // Static T-codes for test files (PLAN §7b, research 05 §5.1): tests that can't be junk.
2
+ //
3
+ // T001 no assertion T004 sleeps / real timers T007 unapproved snapshot
4
+ // T002 tautology T005 implementation queries T008 conditional or looped `expect`
5
+ // T003 asserts what it set T006 mocks kerf or the unit T009 `.only` / `.skip`
6
+ // T013 a real socket
7
+ //
8
+ // Syntax only (TypeScript's parser, no type checker), like the project view. `@kerf-js/core/test` adds a runtime T001 for
9
+ // assertions this pass can't see. A finding a test needs on purpose is kept with a written reason:
10
+ //
11
+ // // kerf-allow T004, T005: hydration tests read the server DOM and wait for real timers
12
+ //
13
+ // in the file's leading comments covers the whole file; anywhere else it covers its own line and the next one.
14
+ // Without a reason it is ignored.
15
+
16
+ import { readFileSync } from 'node:fs'
17
+ import { join } from 'node:path'
18
+ import ts from 'typescript'
19
+ import { diagnostic, positions } from './diag.mjs'
20
+ import { parse, testCall, walk } from './test-rules/syntax.mjs'
21
+ import { contextOf } from './test-rules/context.mjs'
22
+ import { runTestRules } from './test-rules/test-rules.mjs'
23
+ import { fileRules, renderResultsOf } from './test-rules/file-rules.mjs'
24
+
25
+ export { isSubject, matcherOf, norm, parse, resolveImport, testCall } from './test-rules/syntax.mjs'
26
+
27
+ export const testGlobs = ['**/*.{test,spec}.{ts,tsx,mts,cts,js,jsx,mjs,cjs}']
28
+
29
+ /** Comment directives: `// kerf-allow T004, T005: reason`. */
30
+ export function allowances(text, sf) {
31
+ const firstCode = sf.statements[0]?.getStart(sf) ?? text.length
32
+ const file = new Set()
33
+ const lines = new Map()
34
+ const pos = positions(text)
35
+ for (const m of text.matchAll(
36
+ /\/\/[ \t]*kerf-allow[ \t]+((?:T\d{3}[ \t,]*)+)(?::[ \t]*(\S.*))?$/gm,
37
+ )) {
38
+ if (!m[2]?.trim()) continue
39
+ const codes = m[1].match(/T\d{3}/g)
40
+ if (m.index < firstCode) for (const c of codes) file.add(c)
41
+ else {
42
+ const [line] = pos.lineCol(m.index)
43
+ for (const l of [line, line + 1]) for (const c of codes) lines.set(`${c}:${l}`, true)
44
+ }
45
+ }
46
+ return (code, line) => file.has(code) || lines.has(`${code}:${line}`)
47
+ }
48
+
49
+ /**
50
+ * T-codes for one test file.
51
+ * @param {string} text
52
+ * @param {string} rel path relative to the project root (for diagnostics)
53
+ * @param {{ abs?: string, root?: string }} [options] `abs` lets T001/T006 read the helpers and units the file imports
54
+ */
55
+ export function checkTestFile(text, rel, options = {}) {
56
+ const abs = options.abs ?? rel
57
+ const sf = parse(text, rel)
58
+ const pos = positions(text)
59
+ const allowed = allowances(text, sf)
60
+ const out = []
61
+ const seen = new Set()
62
+ const report = (code, node, why, extra = {}) => {
63
+ const start = node.getStart(sf)
64
+ const end = node.getEnd()
65
+ const span = pos.span(start, end)
66
+ const key = `${code}:${span[0]}:${span[1]}`
67
+ if (allowed(code, span[0]) || seen.has(key)) return
68
+ seen.add(key)
69
+ out.push(diagnostic({ code, file: rel, span, offset: [start, end], why, ...extra }))
70
+ }
71
+ const edit = (start, end, newText) => ({
72
+ file: rel,
73
+ span: pos.span(start, end),
74
+ offset: [start, end],
75
+ text: newText,
76
+ })
77
+ const context = { ...contextOf(sf, abs), sf, edit, report }
78
+ const tests = []
79
+ walk(sf, (n) => {
80
+ if (!ts.isCallExpression(n)) return
81
+ const t = testCall(n)
82
+ if (t) tests.push(t)
83
+ })
84
+ for (const t of tests) runTestRules(t, context)
85
+ context.renderResults = renderResultsOf(sf, report)
86
+ walk(sf, (n) => {
87
+ for (const rule of fileRules) rule(n, context)
88
+ })
89
+ return out
90
+ }
91
+
92
+ /**
93
+ * T-codes for the project's test files.
94
+ * @param {string} root absolute project root
95
+ * @param {string[]} rels test files, relative to `root`
96
+ */
97
+ export function checkTests(root, rels) {
98
+ return rels.flatMap((rel) => {
99
+ const abs = join(root, rel)
100
+ return checkTestFile(readFileSync(abs, 'utf8'), rel, { abs })
101
+ })
102
+ }
103
+
104
+ export const isTestFile = (rel) => /\.(test|spec)\.[cm]?[jt]sx?$/.test(rel)
105
+
106
+ /** Which T-codes this pass reports: each catalog example must produce its own code (the T side of `probe()`). */
107
+ export function probeTests(catalog) {
108
+ const out = {}
109
+ for (const e of catalog) {
110
+ if (!/^T\d{3}$/.test(e.code) || e.by !== 'cli') continue // T012 is @kerf-js/core/test's runtime check
111
+ const hit =
112
+ e.example && checkTestFile(e.example, 'probe.test.tsx').find((d) => d.code === e.code)
113
+ out[e.code] = {
114
+ implemented: Boolean(hit),
115
+ autofix: hit?.fix?.safe === true,
116
+ suggestion: Boolean(hit?.fix?.edits) && hit.fix.safe !== true,
117
+ }
118
+ }
119
+ return out
120
+ }