@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,280 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
2
+ import { createRequire } from 'node:module'
3
+ import { join, relative } from 'node:path'
4
+ import { pathToFileURL } from 'node:url'
5
+ import { diagnostic, locate } from '../diag.mjs'
6
+ import { start } from '../start.mjs'
7
+
8
+ const posix = (p) => p.split('\\').join('/')
9
+
10
+ /**
11
+ * R101, R102 from the contract, and R103, R109 from `cargo check`, for an app with a sidecar: an agent gets the same
12
+ * answer here as from `kerf build`, with the function's id on it.
13
+ */
14
+ export async function rustChecks(root, loaded) {
15
+ let sidecar
16
+ try {
17
+ sidecar = await start(root, 'sidecar')
18
+ } catch {
19
+ return []
20
+ }
21
+ if (!sidecar.usesRemote(root)) return []
22
+ const rust = loaded.config?.rust
23
+ const held = process.env.KERF_BUILD
24
+ process.env.KERF_BUILD = '1'
25
+ try {
26
+ const { writeContract } = await start(root, 'contract')
27
+ const preset = { node: 'node', bun: 'bun', deno: 'deno_server' }[
28
+ loaded.config?.runtime ?? 'node'
29
+ ]
30
+ const { contract, diagnostics } = await writeContract({
31
+ root,
32
+ site: loaded.config?.site,
33
+ rust,
34
+ preset,
35
+ })
36
+ const out = diagnostics
37
+ .filter((d) => d.code.startsWith('R1'))
38
+ .map((d) => diagnostic({ ...d, file: '.kerf/contract.json' }))
39
+ if (out.some((d) => d.severity === 'error')) return out
40
+ for (const service of Object.keys(contract.services ?? {})) {
41
+ if (rust?.services?.[service]?.external) continue
42
+ const dir = sidecar.crateDir(root, rust, service)
43
+ if (!existsSync(dir)) {
44
+ out.push(
45
+ diagnostic({
46
+ code: 'R109',
47
+ file: '.kerf/contract.json',
48
+ why: `\`rust://${service}\` has no crate at \`${posix(relative(root, dir))}\`.`,
49
+ }),
50
+ )
51
+ continue
52
+ }
53
+ const checked = await sidecar.cargo('check', { root, dir, service, contract })
54
+ out.push(
55
+ ...checked.diagnostics.map(({ rendered, ...d }) => diagnostic({ ...d, help: rendered })),
56
+ )
57
+ out.push(...untouchedQueries(root, dir, contract, service))
58
+ if (contract.services[service].kind !== 'native' || !checked.ok) continue
59
+ const wasm = await sidecar.checkWasm({ root, dir, service, contract, preset, rust })
60
+ out.push(...wasm.diagnostics.map((d) => diagnostic(d)))
61
+ }
62
+ return out
63
+ } catch (e) {
64
+ return [
65
+ diagnostic({
66
+ code: 'R109',
67
+ severity: 'warning',
68
+ file: '.kerf/contract.json',
69
+ why: `the contract couldn't be written, so the sidecars weren't checked: ${e.message.split('\n')[0]}`,
70
+ }),
71
+ ]
72
+ } finally {
73
+ if (held === undefined) delete process.env.KERF_BUILD
74
+ else process.env.KERF_BUILD = held
75
+ }
76
+ }
77
+
78
+ /** R105 before anything runs: a cached query with tags whose Rust never mentions `touch`, or hands `ctx` to anything. */
79
+ function untouchedQueries(root, dir, contract, service) {
80
+ const sources = readdirSync(join(dir, 'src'), { recursive: true, withFileTypes: true })
81
+ .filter((f) => f.isFile() && f.name.endsWith('.rs'))
82
+ .map((f) => join(f.parentPath, f.name))
83
+ const out = []
84
+ for (const f of contract.functions) {
85
+ if (f.impl?.service !== service || !f.cache || !(f.tags === 'dynamic' || f.tags?.length))
86
+ continue
87
+ const method = f.name.replace(/[A-Z]/g, (c, i) => `${i ? '_' : ''}${c.toLowerCase()}`)
88
+ for (const file of sources) {
89
+ const text = readFileSync(file, 'utf8')
90
+ const at = text.search(new RegExp(`\\bfn\\s+${method}\\s*\\(`))
91
+ if (at < 0) continue
92
+ const open = text.indexOf('{', at)
93
+ let depth = 0,
94
+ end = open
95
+ for (; end < text.length; end++) {
96
+ if (text[end] === '{') depth++
97
+ if (text[end] === '}' && --depth === 0) break
98
+ }
99
+ const body = text.slice(open, end)
100
+ const line = text.slice(0, at).split('\n').length
101
+ if (!/\.touch\(|\(\s*&?ctx\b|,\s*&?ctx\b/.test(body))
102
+ out.push(
103
+ diagnostic({
104
+ code: 'R105',
105
+ severity: 'warning',
106
+ file: posix(relative(root, file)),
107
+ span: [line, 1, line, 1],
108
+ why: `\`${f.id}\` is cached under tags and reports no table: nothing can tell whether they cover what it reads. Call \`ctx.touch("table")\`, or drop \`tags\` if it reads none.`,
109
+ }),
110
+ )
111
+ break
112
+ }
113
+ }
114
+ return out
115
+ }
116
+
117
+ /** R013, R014 and R018: what the deploy target does to live data. Only an app with `changes` or `required` loads anything. */
118
+ export async function liveChecks(root, loaded, preset) {
119
+ const file = join(root, 'src/realtime.server.ts')
120
+ let target
121
+ try {
122
+ target = await start(root, 'live-target')
123
+ } catch {
124
+ return []
125
+ }
126
+ const required = target.scanRequired(root)
127
+ if (
128
+ !required.length &&
129
+ !target.literalSecrets(root).length &&
130
+ !(existsSync(file) && /\bchanges\s*[:,}]/.test(readFileSync(file, 'utf8')))
131
+ )
132
+ return []
133
+ const held = process.env.KERF_BUILD
134
+ process.env.KERF_BUILD = '1'
135
+ try {
136
+ const { readLivePlan } = await start(root, 'contract')
137
+ const plan = await readLivePlan({
138
+ root,
139
+ site: loaded.config?.site,
140
+ live: loaded.config?.live,
141
+ preset:
142
+ preset ??
143
+ { node: 'node', bun: 'bun', deno: 'deno_server' }[loaded.config?.runtime ?? 'node'],
144
+ })
145
+ return plan.diagnostics.map((d) =>
146
+ diagnostic({ ...d, file: d.file ?? required[0]?.file ?? 'src/realtime.server.ts' }),
147
+ )
148
+ } catch (e) {
149
+ return [
150
+ diagnostic({
151
+ code: 'R014',
152
+ severity: 'warning',
153
+ file: 'src/realtime.server.ts',
154
+ why: `the deploy target couldn't be checked: ${e.message.split('\n')[0]}`,
155
+ }),
156
+ ]
157
+ } finally {
158
+ if (held === undefined) delete process.env.KERF_BUILD
159
+ else process.env.KERF_BUILD = held
160
+ }
161
+ }
162
+
163
+ /** R001 for a server module's `channel`, and R004 for a socket handler of the app's own (research 32 §1). */
164
+ export async function socketChecks(root) {
165
+ const src = join(root, 'src')
166
+ if (!existsSync(src)) return []
167
+ const out = []
168
+ let withIds
169
+ for (const f of readdirSync(src, { recursive: true, withFileTypes: true })) {
170
+ if (!f.isFile() || !/\.[cm]?[jt]sx?$/.test(f.name) || f.name.endsWith('.d.ts')) continue
171
+ const abs = join(f.parentPath, f.name),
172
+ rel = relative(root, abs).replaceAll('\\', '/'),
173
+ text = readFileSync(abs, 'utf8')
174
+ const hand = /from\s+['"]crossws|\bdefineWebSocketHandler\b/.exec(text)
175
+ if (hand)
176
+ out.push(
177
+ diagnostic({
178
+ code: 'R004',
179
+ file: rel,
180
+ ...locate(text, hand[0]),
181
+ why: 'A WebSocket handler of its own skips the Origin check, `authorize`, the limits and resume. Use `channel`.',
182
+ }),
183
+ )
184
+ if (
185
+ !/\b(channel|sharedState)\s*[(<]/.test(text) ||
186
+ !/^src\/server\/|\.server\.[cm]?[jt]sx?$/.test(rel)
187
+ )
188
+ continue
189
+ if (withIds === undefined) {
190
+ try {
191
+ withIds = (
192
+ await import(
193
+ pathToFileURL(createRequire(join(root, 'package.json')).resolve('@kerf-js/start/vite'))
194
+ .href
195
+ )
196
+ ).withIds
197
+ } catch {
198
+ withIds = null
199
+ }
200
+ }
201
+ try {
202
+ withIds?.(text, abs, rel)
203
+ } catch (e) {
204
+ if (e.code !== 'R001') continue
205
+ const line = +/:(\d+) /.exec(e.message)?.[1]
206
+ out.push(
207
+ diagnostic({
208
+ code: 'R001',
209
+ file: rel,
210
+ span: [line, 1, line, 1],
211
+ why: e.message.split('\n')[0].replace(/^R001: \S+ /, ''),
212
+ }),
213
+ )
214
+ }
215
+ }
216
+ return out
217
+ }
218
+
219
+ /** kerf owns the connection: these bypass reconnects, resume and the fake transport (research 30 §8). */
220
+ const SOCKET_PACKAGES = [
221
+ 'ws',
222
+ 'socket.io-client',
223
+ 'reconnecting-websocket',
224
+ '@microsoft/fetch-event-source',
225
+ ]
226
+
227
+ /** P002 (`package.json` scripts that aren't `kerf …`), P120 (kerf plugins wired straight into Vite), R007 (socket libraries). */
228
+ export function hygiene(root) {
229
+ const out = []
230
+ const pkgFile = join(root, 'package.json')
231
+ if (existsSync(pkgFile)) {
232
+ const text = readFileSync(pkgFile, 'utf8')
233
+ let scripts = {},
234
+ deps = {}
235
+ try {
236
+ const pkg = JSON.parse(text)
237
+ scripts = pkg.scripts ?? {}
238
+ deps = pkg.dependencies ?? {}
239
+ } catch {}
240
+ for (const name of SOCKET_PACKAGES) {
241
+ if (deps[name])
242
+ out.push(
243
+ diagnostic({
244
+ code: 'R007',
245
+ file: 'package.json',
246
+ ...locate(text, `"${name}"`),
247
+ why: `\`${name}\` is a dependency: its connection has no resume, no cleanup and no fake in @kerf-js/core/test. Use \`stream\`, \`.live()\` or \`channel\`.`,
248
+ }),
249
+ )
250
+ }
251
+ for (const [name, cmd] of Object.entries(scripts)) {
252
+ if (!/^kerf(\s|$)/.test(cmd.trim())) {
253
+ out.push(
254
+ diagnostic({
255
+ code: 'P002',
256
+ file: 'package.json',
257
+ ...locate(text, `"${name}"`),
258
+ why: `Script \`${name}\` runs \`${cmd}\`, not \`kerf …\`: agents can't see what it does or what it touches.`,
259
+ }),
260
+ )
261
+ }
262
+ }
263
+ }
264
+ for (const name of ['vite.config.ts', 'vite.config.mts', 'vite.config.js', 'vite.config.mjs']) {
265
+ const file = join(root, name)
266
+ if (!existsSync(file)) continue
267
+ const text = readFileSync(file, 'utf8')
268
+ for (const m of text.matchAll(/from\s+['"](@kerf-js\/(?:plugin-[\w-]+|text))/g)) {
269
+ out.push(
270
+ diagnostic({
271
+ code: 'P120',
272
+ file: name,
273
+ ...locate(text, m[1]),
274
+ why: `\`${m[1]}\` is registered in ${name}, which bypasses kerf.config.ts.`,
275
+ }),
276
+ )
277
+ }
278
+ }
279
+ return out
280
+ }
package/src/check.mjs ADDED
@@ -0,0 +1,321 @@
1
+ // `kerf check`: compile every project file in check mode, add the project view, the X-codes (text-checks.mjs), plugin
2
+ // `check` hooks, the test T-codes, the config P-codes, the style D-codes (style.mjs) and the design D-codes (design-checks.mjs), and keep `.kerf/styles.json`
3
+ // current when the project has style groups.
4
+
5
+ import { existsSync, readFileSync } from 'node:fs'
6
+ import { createRequire } from 'node:module'
7
+ import { isAbsolute, join, relative, resolve } from 'node:path'
8
+ import { pathToFileURL } from 'node:url'
9
+ import { diagnostic, positions, sortDiagnostics, summarize } from './diag.mjs'
10
+ import { discover } from './files.mjs'
11
+ import { isDataConfig, loadConfig, writeConfigSchema } from './load-config.mjs'
12
+ import { sync } from './plugins.mjs'
13
+ import { writeMap } from './map.mjs'
14
+ import { projectView } from './project.mjs'
15
+ import { designChecks, hasTokens } from './design-checks.mjs'
16
+ import {
17
+ classSoup,
18
+ matrixDiagnostics,
19
+ styleFiles,
20
+ styleModule,
21
+ usesTailwind,
22
+ writeMatrixFile,
23
+ } from './style.mjs'
24
+ import { checkTests, isTestFile, testGlobs } from './tests.mjs'
25
+ import { pluginChecks } from './plugin-checks.mjs'
26
+ import { propChecks } from './props-checks.mjs'
27
+ import { reactChecks } from './react-checks.mjs'
28
+ import { trustDiagnostics } from './trust.mjs'
29
+ import { shareChecks } from './share-checks.mjs'
30
+ import { stateChecks } from './state-checks.mjs'
31
+ import { serverStateChecks } from './server-state-checks.mjs'
32
+ import { surfaceChecks } from './surface-checks.mjs'
33
+ import { textChecks } from './text-checks.mjs'
34
+ import { loadCompiler, resolveKerf } from './kerf.mjs'
35
+ import { dbLayer } from './db-layer.mjs'
36
+ import { loadEnv, routeDiagnostics, schemaHash, siteOf, start } from './start.mjs'
37
+ import { deployChecks } from './deploy/index.mjs'
38
+ import { rustChecks, liveChecks, socketChecks, hygiene } from './check/runtime.mjs'
39
+
40
+ const posix = (p) => p.split('\\').join('/')
41
+
42
+ /** Q015: the schema's hash against the one `kerf db generate` recorded (research 28 §2). */
43
+ function schemaDrift(root, layer) {
44
+ const schema = layer?.schema && join(root, layer.schema)
45
+ if (!schema || !existsSync(schema)) return []
46
+ const file = join(root, layer.migrations, '.schema-hash')
47
+ if (existsSync(file) && readFileSync(file, 'utf8').trim() === schemaHash(readFileSync(schema)))
48
+ return []
49
+ return [
50
+ diagnostic({
51
+ code: 'Q015',
52
+ file: layer.schema,
53
+ why: existsSync(file)
54
+ ? 'The schema changed since the last `kerf db generate`: the database will not match it.'
55
+ : 'No migrations yet: the first request that reads a table fails with Q014.',
56
+ }),
57
+ ]
58
+ }
59
+
60
+ /** I001–I003: the walk a build does (@kerf-js/veneer-icons/compile), when the project has the package. */
61
+ async function iconChecks(root) {
62
+ const require = createRequire(join(root, 'package.json'))
63
+ let compile
64
+ for (const from of [
65
+ () => require.resolve('@kerf-js/veneer-icons/compile'),
66
+ () =>
67
+ createRequire(require.resolve('@kerf-js/veneer')).resolve('@kerf-js/veneer-icons/compile'),
68
+ ]) {
69
+ try {
70
+ compile = from()
71
+ break
72
+ } catch {
73
+ /* not this way */
74
+ }
75
+ }
76
+ if (!compile) return []
77
+ const { findings } = await import(pathToFileURL(compile).href)
78
+ return findings(root).map((f) =>
79
+ diagnostic({
80
+ code: f.code,
81
+ file: f.file,
82
+ span: [f.line, f.column, f.line, f.column],
83
+ why: f.why,
84
+ }),
85
+ )
86
+ }
87
+
88
+ /** H010: what the last build or `kerf dev` found keeps an island from waiting (`.kerf/hydration.json`, @kerf-js/core/hydration). */
89
+ function hydrationChecks(root) {
90
+ const file = join(root, '.kerf', 'hydration.json')
91
+ if (!existsSync(file)) return []
92
+ try {
93
+ return JSON.parse(readFileSync(file, 'utf8'))
94
+ .diagnostics.filter((d) => existsSync(join(root, d.file)))
95
+ .map((d) =>
96
+ diagnostic({
97
+ code: d.code,
98
+ file: d.file,
99
+ span: [d.line, 1, d.line, 1],
100
+ why: d.why,
101
+ help: d.fix,
102
+ }),
103
+ )
104
+ } catch {
105
+ return []
106
+ }
107
+ }
108
+
109
+ /**
110
+ * H001–H007, H011–H016: page metadata, per route, on what the routes really produce (`inspect.mjs`). With `files`, only
111
+ * when a route is among them. An app that can't run here is still read: a check never fails for what it couldn't start.
112
+ */
113
+ async function routeChecks(root, loaded, given, reported) {
114
+ if (
115
+ !existsSync(join(root, 'src', 'routes')) ||
116
+ loaded.config?.check?.routes === false ||
117
+ loaded.diagnostics.some((d) => d.code === 'P007')
118
+ )
119
+ return []
120
+ if (given?.length && !given.some((f) => f.startsWith('src/routes/'))) return []
121
+ let inspect
122
+ // The routes run as they do under `kerf dev`, so they get the same `.env` (an env schema throws without it).
123
+ loadEnv(root)
124
+ try {
125
+ inspect = await start(root, 'inspect')
126
+ } catch {
127
+ return []
128
+ }
129
+ const keep = (list) =>
130
+ routeDiagnostics(root, list).filter((d) => !(d.code === 'H001' && reported.has('H001')))
131
+ try {
132
+ return keep((await inspect.routesMeta({ root, site: siteOf(loaded) })).diagnostics)
133
+ } catch (error) {
134
+ return keep([
135
+ ...inspect.staticRouteChecks(root),
136
+ {
137
+ code: 'H016',
138
+ severity: 'info',
139
+ file: 'src/routes',
140
+ route: '*',
141
+ why: `The routes didn't load here, so only their source was checked: ${String(error?.message ?? error).split('\n')[0]}`,
142
+ },
143
+ ])
144
+ }
145
+ }
146
+
147
+ function compileFiles(root, rels, compiler, scan, style) {
148
+ const files = []
149
+ const posByAbs = new Map()
150
+ for (const rel of rels) {
151
+ const abs = join(root, rel)
152
+ const text = readFileSync(abs, 'utf8')
153
+ const pos = positions(text)
154
+ posByAbs.set(abs, pos)
155
+ const groups = scan
156
+ ? style.importedGroups(abs, text, (f) => scan.groups.filter((g) => join(root, g.file) === f))
157
+ : {}
158
+ const out = compiler.transform(
159
+ text,
160
+ Object.keys(groups).length
161
+ ? { filename: abs, checkOnly: true, groups }
162
+ : { filename: rel, checkOnly: true },
163
+ )
164
+ const diagnostics = out.diagnostics.map((d) => {
165
+ const from = pos.fromByte(d.start)
166
+ const end = pos.fromByte(d.end)
167
+ const fix = d.fix && {
168
+ description: d.fix.description,
169
+ safe: d.fix.safe,
170
+ edits: d.fix.edits.map((e) => {
171
+ const a = pos.fromByte(e.start)
172
+ const b = pos.fromByte(e.end)
173
+ return { file: rel, span: pos.span(a, b), offset: [a, b], text: e.text }
174
+ }),
175
+ }
176
+ return diagnostic({
177
+ code: d.code,
178
+ severity: d.severity,
179
+ file: rel,
180
+ span: pos.span(from, end),
181
+ offset: [from, end],
182
+ why: d.message,
183
+ help: d.help,
184
+ fix,
185
+ })
186
+ })
187
+ files.push({ abs, rel, text, diagnostics })
188
+ }
189
+
190
+ return { files, posByAbs }
191
+ }
192
+
193
+ async function collectDiagnostics({
194
+ root,
195
+ loaded,
196
+ config,
197
+ files,
198
+ exclude,
199
+ styles,
200
+ testRels,
201
+ options,
202
+ given,
203
+ }) {
204
+ const fontBuild =
205
+ typeof loaded.slots['font.build'] === 'string' &&
206
+ !loaded.slots['font.build'].startsWith('kerf:default')
207
+ const diagnostics = [
208
+ ...loaded.diagnostics,
209
+ ...(loaded.diagnostics.some((d) => d.code === 'P007') ? [] : trustDiagnostics(root, loaded)),
210
+ ...files.flatMap((f) => f.diagnostics),
211
+ ...styles,
212
+ ...(config.check?.design === false
213
+ ? []
214
+ : designChecks(root, { files, exclude, tokens: hasTokens(root) })),
215
+ ...textChecks(root, { files, exclude, fontBuild }),
216
+ ...stateChecks(root, { files, exclude }),
217
+ ...serverStateChecks(root, { files, exclude }),
218
+ ...shareChecks(root, { files }),
219
+ ...reactChecks({ files }),
220
+ ...surfaceChecks(root, { files, exclude, slots: loaded.slots }),
221
+ ...(await pluginChecks(root, loaded, { files, exclude })),
222
+ ...(await propChecks(root, config)),
223
+ ...checkTests(root, testRels),
224
+ ...(await iconChecks(root)),
225
+ ...hydrationChecks(root),
226
+ ...hygiene(root),
227
+ ...(await socketChecks(root)),
228
+ ...schemaDrift(root, await dbLayer(root, loaded)),
229
+ ...(await rustChecks(root, loaded)),
230
+ ...(await liveChecks(root, loaded, options.preset)),
231
+ ...(loaded.diagnostics.some((d) => d.code === 'P007')
232
+ ? []
233
+ : deployChecks(root, config, { preset: options.preset })),
234
+ ]
235
+ diagnostics.push(
236
+ ...(await routeChecks(root, loaded, given, new Set(loaded.diagnostics.map((d) => d.code)))),
237
+ )
238
+ sortDiagnostics(diagnostics)
239
+ return diagnostics
240
+ }
241
+
242
+ /**
243
+ * @param {string} root
244
+ * @param {{ files?: string[] }} [options] files relative to `root` (or absolute); default: discovered
245
+ */
246
+ export async function check(root, options = {}) {
247
+ const started = performance.now()
248
+ root = resolve(root)
249
+ const kerf = resolveKerf(root)
250
+ const compiler = loadCompiler(kerf)
251
+ const loaded = await loadConfig(root)
252
+ const { config } = loaded
253
+ // Slot modules and plugin token files stay current with the config (research 13 §2.6).
254
+ if (
255
+ !loaded.diagnostics.some((d) => d.code === 'P007') &&
256
+ (config.plugins?.length || existsSync(join(root, '.kerf', 'slots')))
257
+ )
258
+ sync(root, loaded)
259
+
260
+ if (loaded.file && isDataConfig(loaded.file)) writeConfigSchema(root)
261
+ if (existsSync(join(root, '.kerf'))) await writeMap(root)
262
+
263
+ const exclude = [...(config.check?.exclude ?? []), ...(config.scope?.forbid ?? [])]
264
+ const given = options.files?.map((f) => posix(relative(root, isAbsolute(f) ? f : join(root, f))))
265
+ const include = config.check?.include ?? ['**/*.{tsx,jsx}']
266
+ const rels = given?.length
267
+ ? given.filter((f) => /\.[jt]sx$/.test(f) || !isTestFile(f))
268
+ : discover(root, { include, exclude })
269
+ const testRels = given?.length
270
+ ? given.filter(isTestFile)
271
+ : discover(root, { include: config.test?.include ?? testGlobs, exclude })
272
+
273
+ // Style groups (research 23): the project's definitions first, so each file compiles with the groups it imports.
274
+ const style = await styleModule(kerf)
275
+ const sfiles = style ? styleFiles(root, config) : []
276
+ const scan = sfiles.some((f) =>
277
+ readFileSync(join(root, f), 'utf8').includes('@kerf-js/core/style'),
278
+ )
279
+ ? style.scanProject(root, sfiles, (...a) => compiler.transform(...a))
280
+ : null
281
+
282
+ const { files, posByAbs } = compileFiles(root, rels, compiler, scan, style)
283
+
284
+ projectView(files, (file) => posByAbs.get(file.abs))
285
+
286
+ const matrix = scan && style.buildMatrix(scan.groups, scan.uses)
287
+ if (matrix && scan.groups.length) writeMatrixFile(root, matrix)
288
+ const styles = [
289
+ ...(usesTailwind(root) ? [] : classSoup(files.filter((f) => /\.[jt]sx$/.test(f.rel)))),
290
+ ...(matrix ? matrixDiagnostics(root, matrix) : []),
291
+ ]
292
+
293
+ const diagnostics = await collectDiagnostics({
294
+ root,
295
+ loaded,
296
+ config,
297
+ files,
298
+ exclude,
299
+ styles,
300
+ testRels,
301
+ options,
302
+ given,
303
+ })
304
+ const summary = { files: files.length, tests: testRels.length, ...summarize(diagnostics) }
305
+ return {
306
+ version: 1,
307
+ ok: summary.errors === 0,
308
+ root,
309
+ kerf: { version: kerf.version, from: kerf.from, compiler: kerf.compilerPath },
310
+ config: loaded.file ? posix(relative(root, loaded.file)) : null,
311
+ summary,
312
+ diagnostics,
313
+ slots: loaded.slots,
314
+ styles: matrix
315
+ ? { groups: Object.keys(matrix.groups).length, matrix: '.kerf/styles.json' }
316
+ : null,
317
+ files: rels,
318
+ tests: testRels,
319
+ ms: Math.round(performance.now() - started),
320
+ }
321
+ }