@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
package/src/start.mjs ADDED
@@ -0,0 +1,394 @@
1
+ // `kerf dev`, `kerf build` and `kerf routes` for an app with src/routes: they run @kerf-js/start (research 25 §6–7).
2
+ // @kerf-js/start resolves from the app first (its own version), then from this workspace.
3
+
4
+ import { spawn, spawnSync } from 'node:child_process'
5
+ import { createHash } from 'node:crypto'
6
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
7
+ import { createRequire } from 'node:module'
8
+ import { dirname, join } from 'node:path'
9
+ import { pathToFileURL } from 'node:url'
10
+ import { parseEnv } from 'node:util'
11
+ import { dbLayer } from './db-layer.mjs'
12
+ import { diagnostic } from './diag.mjs'
13
+ import { routeDiagnostics } from './start/routes.mjs'
14
+ import { finishBuild, startBuildSidecars, buildPreset } from './start/build.mjs'
15
+ import { writeMap } from './map.mjs'
16
+
17
+ import { loadConfig } from './load-config.mjs'
18
+ import { sync } from './plugins.mjs'
19
+ import { requireTrust } from './trust.mjs'
20
+ import { attachProps } from './props-listener.mjs'
21
+
22
+ export { routeDiagnostics } from './start/routes.mjs'
23
+
24
+ export async function start(root, sub) {
25
+ let file
26
+ try {
27
+ file = createRequire(join(root, 'package.json')).resolve(`@kerf-js/start/${sub}`)
28
+ } catch {
29
+ const sibling = new URL(`../../start/src/${sub}.mjs`, import.meta.url)
30
+ if (!existsSync(sibling))
31
+ throw Object.assign(new Error('@kerf-js/start is not installed in this project'), {
32
+ code: 'E_USAGE',
33
+ })
34
+ file = sibling
35
+ }
36
+ return import(typeof file === 'string' ? pathToFileURL(file).href : file.href)
37
+ }
38
+
39
+ /** The config's `site` (metadata defaults), and the config diagnostics. Slot files are synced first, so @kerf-js/core/vite
40
+ * finds the build-side providers (`.kerf/slots/<id>.build.json`, research 26 §3.1). */
41
+ async function site(root) {
42
+ const loaded = await loadConfig(root)
43
+ if (!loaded.diagnostics.some((d) => d.code === 'P007') && loaded.config?.plugins?.length)
44
+ sync(root, loaded)
45
+ // A build on a config that doesn't load would quietly drop every plugin: fonts, tokens and slots.
46
+ const bad = loaded.diagnostics.find((d) => d.code === 'P007')
47
+ if (bad) throw Object.assign(new Error(`P007: ${bad.message ?? bad.why}`), { code: 'E_REFUSED' }) // the config's fault, not the command's
48
+ return {
49
+ site: siteOf(loaded),
50
+ hydration: loaded.config?.hydration,
51
+ diagnostics: loaded.diagnostics,
52
+ }
53
+ }
54
+
55
+ /** `site` with what plugins know about the app's look (`card` in a manifest): veneer's colours, the text plugin's faces. */
56
+ export function siteOf(loaded) {
57
+ const base = loaded.config?.site ?? {}
58
+ const given = (loaded.contributions ?? []).map((c) => c.manifest.card).filter(Boolean)
59
+ if (!given.length) return base
60
+ const card = Object.assign({}, ...given)
61
+ return { ...base, card: { ...card, ...base.card, fonts: { ...card.fonts, ...base.card?.fonts } } }
62
+ }
63
+
64
+ /** `runtime` in kerf.config.ts or `--runtime`, as a Nitro preset (research 28 §5). */
65
+ export const PRESETS = { node: 'node', bun: 'bun', deno: 'deno_server' }
66
+ /** With no `runtime` in the config, the one running this: a machine may have only that one. */
67
+ export const hostRuntime = () =>
68
+ process.versions.deno ? 'deno' : process.versions.bun ? 'bun' : 'node'
69
+
70
+ /** `.env` under what's already set. Not `process.loadEnvFile`: on Deno the file wins. */
71
+ export function loadEnv(root) {
72
+ const file = join(root, '.env')
73
+ if (existsSync(file))
74
+ for (const [key, value] of Object.entries(parseEnv(readFileSync(file, 'utf8'))))
75
+ process.env[key] ??= value
76
+ }
77
+
78
+ export async function devCommand(root, { port } = {}) {
79
+ // Production takes the host's environment; dev takes `.env`. What's already set wins.
80
+ loadEnv(root)
81
+ requireTrust(root, await loadConfig(root))
82
+ const { dev } = await start(root, 'app')
83
+ await writeMap(root)
84
+ const config = await site(root)
85
+ const rust = (await loadConfig(root)).config?.rust
86
+ const { devSidecars, usesRemote } = await start(root, 'sidecar')
87
+ // Before the dev server: its worker inherits the addresses, and a request can't reach a sidecar that's still building.
88
+ const sidecars = usesRemote(root)
89
+ ? await devSidecars({ root, site: config.site, rust })
90
+ : undefined
91
+ const server = await dev({ root, ...config, port })
92
+ if (server.watcher) server.kerfProps = attachProps(server, root, (await loadConfig(root)).config)
93
+ if (sidecars) {
94
+ sidecars.attach(server)
95
+ const close = server.close.bind(server)
96
+ server.close = async () => (await sidecars.close(), close())
97
+ }
98
+ return server
99
+ }
100
+
101
+ /**
102
+ * `--unsafe-allow` and `build.unsafeAllow`: codes (or a family, `L`, or `all`) a build reports and goes on past instead
103
+ * of failing on. For forcing a deploy you have looked at; each one it lets through is listed, as a warning, every build.
104
+ */
105
+ export function unsafeAllowed(flag, config) {
106
+ const reasons = config?.build?.unsafeAllow ?? {}
107
+ const codes = [...String(flag ?? '').split(','), ...Object.keys(reasons)]
108
+ .map((c) => c.trim())
109
+ .filter(Boolean)
110
+ const allows = (d) =>
111
+ codes.some((c) => c === 'all' || c === d.code || (/^[A-Z]$/.test(c) && d.code.startsWith(c)))
112
+ const reason = (d) =>
113
+ reasons[d.code] ?? reasons[d.code[0]] ?? reasons.all ?? (flag ? '--unsafe-allow' : '')
114
+ return {
115
+ allows,
116
+ let: (d) => ({
117
+ ...d,
118
+ severity: 'warning',
119
+ why: `UNSAFE, let through (${reason(d)}): ${d.why}`,
120
+ }),
121
+ }
122
+ }
123
+
124
+ export async function buildCommand(root, { preset, runtime, unsafeAllow } = {}) {
125
+ const loaded = await loadConfig(root)
126
+ requireTrust(root, loaded)
127
+ // A plugin that refused its options contributed nothing: its look or data would go missing from a build that succeeds.
128
+ const declined = loaded.diagnostics.find((d) => d.severity === 'error' && d.owner !== 'core')
129
+ if (declined)
130
+ throw Object.assign(new Error(`${declined.code}: ${declined.why}`), { code: 'E_USAGE' })
131
+ const unsafe = unsafeAllowed(unsafeAllow, loaded.config)
132
+ const forced = []
133
+ const { build } = await start(root, 'app')
134
+ const { writeContract } = await start(root, 'contract')
135
+ const t = performance.now()
136
+ const config = await site(root)
137
+ preset = await buildPreset(root, { preset, runtime, hostRuntime, PRESETS })
138
+ // A build holds no secrets: an app's env check stands down, and server modules load without a database.
139
+ const held = process.env.KERF_BUILD
140
+ process.env.KERF_BUILD = '1'
141
+ try {
142
+ const rust = (await loadConfig(root)).config?.rust
143
+ const refuse = (d) => {
144
+ if (unsafe.allows(d)) return void forced.push(unsafe.let(d))
145
+ // a finding, not a misuse: exit 1 with the fix and the way past it, never the usage text
146
+ throw Object.assign(
147
+ new Error(
148
+ `${d.code}: ${d.why}${d.rendered ? `\n${d.rendered}` : ''}\nTo build anyway: --unsafe-allow ${d.code}, or build.unsafeAllow in kerf.config.ts with why.`,
149
+ ),
150
+ { code: 'E_REFUSED' },
151
+ )
152
+ }
153
+ // What the preset can't do fails now, not after a build: a verify runs at the end, against a target that's up.
154
+ const { readLivePlan } = await start(root, 'contract')
155
+ const plan = await readLivePlan({
156
+ root,
157
+ site: config.site,
158
+ preset,
159
+ live: (await loadConfig(root)).config?.live,
160
+ verify: false,
161
+ })
162
+ const unlive = plan.diagnostics.find((d) => d.severity === 'error')
163
+ if (unlive) refuse(unlive)
164
+ const { running, warned, shipSidecars } = await startBuildSidecars({
165
+ start,
166
+ root,
167
+ config,
168
+ preset,
169
+ rust,
170
+ refuse,
171
+ writeContract,
172
+ })
173
+ const before = { ...process.env }
174
+ Object.assign(process.env, running?.env)
175
+ let output
176
+ try {
177
+ ;({ output } = await build({ root, ...config, preset, logLevel: 'warn' }))
178
+ } finally {
179
+ running?.close()
180
+ for (const k of Object.keys(running?.env ?? {}))
181
+ before[k] === undefined ? delete process.env[k] : (process.env[k] = before[k])
182
+ }
183
+ return await finishBuild({
184
+ root,
185
+ config,
186
+ preset,
187
+ rust,
188
+ refuse,
189
+ running,
190
+ shipSidecars,
191
+ output,
192
+ warned,
193
+ unsafe,
194
+ forced,
195
+ loaded,
196
+ t,
197
+ writeContract,
198
+ })
199
+ } finally {
200
+ if (held === undefined) delete process.env.KERF_BUILD
201
+ else process.env.KERF_BUILD = held
202
+ }
203
+ }
204
+
205
+ /** The built server's command for each runtime: `.env` for a local run, the host's environment otherwise. */
206
+ const SERVERS = {
207
+ node: ['node', ['--disable-warning=ExperimentalWarning']],
208
+ bun: ['bun', ['run']],
209
+ deno: ['deno', ['run', '-A']],
210
+ }
211
+
212
+ /** `kerf start`: run `.output/` on the runtime it was built for. Resolves with the exit code. */
213
+ export async function startCommand(root, { runtime } = {}) {
214
+ const chosen = runtime ?? (await loadConfig(root)).config?.runtime ?? hostRuntime()
215
+ if (!SERVERS[chosen])
216
+ throw Object.assign(
217
+ new Error(`unknown runtime "${chosen}": use ${Object.keys(SERVERS).join(', ')}`),
218
+ { code: 'E_USAGE' },
219
+ )
220
+ loadEnv(root)
221
+ const [cmd, flags] = SERVERS[chosen]
222
+ // Sidecars first: the server's environment has their addresses, and they outlive a crash of either side.
223
+ const { startSidecars } = await start(root, 'sidecar')
224
+ const sidecars = await startSidecars({ root })
225
+ // The running binary when it can be: Deno on Windows doesn't find itself on PATH.
226
+ const child = spawn(
227
+ chosen === hostRuntime() ? process.execPath : cmd,
228
+ [...flags, join('.output', 'server', 'index.mjs')],
229
+ { cwd: root, stdio: 'inherit', env: { ...process.env, ...sidecars.env } },
230
+ )
231
+ process.once('SIGINT', () => child.kill('SIGINT'))
232
+ process.once('SIGTERM', () => child.kill('SIGTERM'))
233
+ return new Promise((ok) => {
234
+ child.on('close', (code) => {
235
+ sidecars.close()
236
+ ok(code ?? 0)
237
+ })
238
+ })
239
+ }
240
+
241
+ /** The hash `kerf db generate` records and Q015 compares. */
242
+ export const schemaHash = (text) => createHash('sha256').update(text).digest('hex').slice(0, 16)
243
+
244
+ /** What `kerf db` takes. There's no `migrate`: new migrations apply on the next request. */
245
+ export const DB_COMMANDS = ['generate', 'live', 'listen']
246
+
247
+ /** `kerf db generate [name]`: the data layer's migration, on Node like all of dev (research 28 §2, 34 §4). */
248
+ export async function dbCommand(root, sub, name) {
249
+ if (!DB_COMMANDS.includes(sub))
250
+ throw Object.assign(
251
+ new Error(
252
+ `kerf db ${sub ?? ''}: use generate (new migrations apply on the next request), live or listen`,
253
+ ),
254
+ { code: 'E_USAGE' },
255
+ )
256
+ if (sub === 'live') return dbLive(root)
257
+ if (sub === 'listen') return dbListen(root)
258
+ const layer = await dbLayer(root)
259
+ if (!layer)
260
+ throw Object.assign(new Error('this app has no database: `kerf add db` adds one'), {
261
+ code: 'E_USAGE',
262
+ })
263
+ const output = layer.generate(root, name)
264
+ const schema = layer.schema && join(root, layer.schema)
265
+ if (schema && existsSync(schema))
266
+ writeFileSync(
267
+ join(root, layer.migrations, '.schema-hash'),
268
+ schemaHash(readFileSync(schema)) + '\n',
269
+ )
270
+ return { ok: true, output }
271
+ }
272
+
273
+ /** `kerf db live`: a migration that adds change triggers to the tables in `changes` (Postgres, SQLite, MySQL). */
274
+ async function dbLive(root) {
275
+ const held = process.env.KERF_BUILD
276
+ process.env.KERF_BUILD = '1'
277
+ const config = await site(root)
278
+ const { withRealtime } = await start(root, 'contract')
279
+ const { changeSql } = await start(root, 'changes-sql')
280
+ let sql, tables
281
+ try {
282
+ ;({ sql, tables } = await withRealtime({ root, site: config.site }, async ({ changes }) => {
283
+ if (!changes?.defs)
284
+ throw Object.assign(
285
+ new Error('`src/realtime.server.ts` has no `changes: dbChanges(db, [tables])`'),
286
+ { code: 'E_USAGE' },
287
+ )
288
+ const defs = await changes.defs()
289
+ return { sql: changeSql(changes.dialect, defs), tables: defs.map((t) => t.name) }
290
+ }))
291
+ } finally {
292
+ if (held === undefined) delete process.env.KERF_BUILD
293
+ else process.env.KERF_BUILD = held
294
+ }
295
+ const layer = await dbLayer(root)
296
+ if (layer?.layer !== 'drizzle')
297
+ return { ok: true, output: `${sql}\n-- add this to a migration of your data layer` }
298
+ const req = createRequire(join(root, 'package.json'))
299
+ const bin = join(dirname(req.resolve('drizzle-kit')), 'bin.cjs')
300
+ const r = spawnSync(process.execPath, [bin, 'generate', '--custom', '--name=kerf_live'], {
301
+ cwd: root,
302
+ encoding: 'utf8',
303
+ })
304
+ if (r.status !== 0)
305
+ throw Object.assign(new Error(`drizzle-kit generate failed:\n${r.stdout}${r.stderr}`), {
306
+ code: 'E_INTERNAL',
307
+ })
308
+ const { entries } = JSON.parse(
309
+ readFileSync(join(root, layer.migrations, 'meta', '_journal.json'), 'utf8'),
310
+ )
311
+ const file = join(layer.migrations, `${entries.at(-1).tag}.sql`)
312
+ writeFileSync(join(root, file), sql)
313
+ return {
314
+ ok: true,
315
+ output: `${file}: change triggers for ${tables.join(', ')}. They apply on the next request.`,
316
+ }
317
+ }
318
+
319
+ /** `kerf db listen`: the change feed as its own process, for an app on functions. Runs until SIGINT or SIGTERM. */
320
+ async function dbListen(root) {
321
+ if (existsSync(join(root, '.env'))) process.loadEnvFile(join(root, '.env'))
322
+ const config = await site(root)
323
+ const { withRealtime } = await start(root, 'contract')
324
+ await withRealtime({ root, site: config.site }, async ({ changes, bus }, server) => {
325
+ if (!changes)
326
+ throw Object.assign(new Error('`src/realtime.server.ts` has no `changes`'), {
327
+ code: 'E_USAGE',
328
+ })
329
+ const { listen } = await server.ssrLoadModule('@kerf-js/start/listen')
330
+ const stop = await listen({ changes, bus: bus ?? { name: 'memory' } })
331
+ await new Promise((ok) => {
332
+ process.once('SIGINT', ok)
333
+ process.once('SIGTERM', ok)
334
+ })
335
+ await stop()
336
+ })
337
+ return { ok: true, output: 'kerf db listen: stopped' }
338
+ }
339
+
340
+ /** `kerf doctor`: what live data does on this deploy target, and what to do about what it can't. */
341
+ export async function doctorCommand(root, { preset, runtime } = {}) {
342
+ const config = await site(root)
343
+ const chosen = runtime ?? (await loadConfig(root)).config?.runtime ?? 'node'
344
+ const held = process.env.KERF_BUILD
345
+ process.env.KERF_BUILD = '1'
346
+ try {
347
+ const { readLivePlan } = await start(root, 'contract')
348
+ const plan = await readLivePlan({
349
+ root,
350
+ site: config.site,
351
+ preset: preset ?? PRESETS[chosen],
352
+ live: (await loadConfig(root)).config?.live,
353
+ verify: false,
354
+ })
355
+ return {
356
+ ...plan,
357
+ diagnostics: plan.diagnostics.map((d) =>
358
+ diagnostic({ file: 'src/realtime.server.ts', ...d }),
359
+ ),
360
+ }
361
+ } finally {
362
+ if (held === undefined) delete process.env.KERF_BUILD
363
+ else process.env.KERF_BUILD = held
364
+ }
365
+ }
366
+
367
+ /** Every route's merged metadata, tags and card mode (`--meta`), or just the route table. */
368
+ export async function routesCommand(root, { meta, preset } = {}) {
369
+ const config = await site(root)
370
+ if (meta) {
371
+ const { routesMeta } = await start(root, 'inspect')
372
+ const result = await routesMeta({ root, site: config.site, preset })
373
+ return {
374
+ ...result,
375
+ diagnostics: [...config.diagnostics, ...routeDiagnostics(root, result.diagnostics)],
376
+ }
377
+ }
378
+ const { scanRoutes, filePath } = await start(root, 'routes')
379
+ const manifest = scanRoutes(root)
380
+ return {
381
+ version: 1,
382
+ ok: true,
383
+ problems: manifest.problems,
384
+ routes: manifest.routes.map((r) => ({
385
+ path: r.kind === 'page' ? filePath(manifest, r) : r.kind,
386
+ kind: r.kind,
387
+ file: r.file,
388
+ layouts: r.layouts,
389
+ params: r.params,
390
+ card: r.card ?? null,
391
+ })),
392
+ diagnostics: config.diagnostics,
393
+ }
394
+ }
@@ -0,0 +1,223 @@
1
+ // Bind identities without loading dependencies or checking project types. Only explicit core
2
+ // value imports and stable const aliases establish state provenance; spelling alone does not.
3
+ import ts from 'typescript'
4
+
5
+ function peel(expression) {
6
+ while (
7
+ ts.isParenthesizedExpression(expression) ||
8
+ ts.isAsExpression(expression) ||
9
+ ts.isNonNullExpression(expression) ||
10
+ ts.isSatisfiesExpression(expression)
11
+ )
12
+ expression = expression.expression
13
+ return expression
14
+ }
15
+
16
+ const member = (base, name) =>
17
+ base === 'namespace' && name === 'state'
18
+ ? 'state'
19
+ : base === 'state' && ['linked', 'global'].includes(name)
20
+ ? name
21
+ : undefined
22
+
23
+ function binder(root, graph) {
24
+ const files = new Map([...graph.values()].map(({ sf }) => [sf.fileName, sf]))
25
+ const options = {
26
+ noLib: true,
27
+ noResolve: true,
28
+ types: [],
29
+ allowJs: true,
30
+ jsx: ts.JsxEmit.Preserve,
31
+ }
32
+ const host = ts.createCompilerHost(options)
33
+ host.getSourceFile = (file) => files.get(file)
34
+ host.fileExists = (file) => files.has(file)
35
+ host.readFile = (file) => files.get(file)?.text
36
+ host.getCurrentDirectory = () => root
37
+ return ts.createProgram([...files.keys()], options, host).getTypeChecker()
38
+ }
39
+
40
+ function written(node, symbol, out) {
41
+ node = peel(node)
42
+ if (ts.isIdentifier(node)) {
43
+ const sym = symbol(node)
44
+ if (sym) out.add(sym)
45
+ } else if (ts.isArrayLiteralExpression(node))
46
+ for (const element of node.elements)
47
+ written(ts.isSpreadElement(element) ? element.expression : element, symbol, out)
48
+ else if (ts.isObjectLiteralExpression(node)) {
49
+ for (const property of node.properties) {
50
+ if (ts.isShorthandPropertyAssignment(property)) written(property.name, symbol, out)
51
+ if (ts.isPropertyAssignment(property)) written(property.initializer, symbol, out)
52
+ if (ts.isSpreadAssignment(property)) written(property.expression, symbol, out)
53
+ }
54
+ } else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.EqualsToken)
55
+ written(node.left, symbol, out)
56
+ }
57
+
58
+ function scanWrites(sf, symbol, writes, aliases) {
59
+ const scan = (node) => {
60
+ if (ts.isBinaryExpression(node)) {
61
+ const operator = node.operatorToken.kind
62
+ if (
63
+ operator === ts.SyntaxKind.EqualsToken ||
64
+ (operator >= ts.SyntaxKind.FirstCompoundAssignment &&
65
+ operator <= ts.SyntaxKind.LastCompoundAssignment)
66
+ )
67
+ written(node.left, symbol, writes)
68
+ }
69
+ if (ts.isPrefixUnaryExpression(node) || ts.isPostfixUnaryExpression(node)) {
70
+ if ([ts.SyntaxKind.PlusPlusToken, ts.SyntaxKind.MinusMinusToken].includes(node.operator))
71
+ written(node.operand, symbol, writes)
72
+ }
73
+ if (
74
+ ts.isVariableDeclaration(node) &&
75
+ node.initializer &&
76
+ node.parent.flags & ts.NodeFlags.Const
77
+ )
78
+ aliases.push(node)
79
+ ts.forEachChild(node, scan)
80
+ }
81
+ scan(sf)
82
+ }
83
+
84
+ /** Resolve state, linked and explicit global calls through local binding identities. */
85
+ export function coreState(root, graph) {
86
+ const checker = binder(root, graph)
87
+ const symbol = (node) => {
88
+ const parent = node.parent
89
+ return parent && ts.isShorthandPropertyAssignment(parent) && parent.name === node
90
+ ? checker.getShorthandAssignmentValueSymbol(parent)
91
+ : checker.getSymbolAtLocation(node)
92
+ }
93
+ const values = new Map(),
94
+ writes = new Set(),
95
+ aliases = []
96
+ const remember = (node, tag) => {
97
+ const sym = symbol(node)
98
+ if (sym && tag && !writes.has(sym)) values.set(sym, tag)
99
+ }
100
+ for (const { sf } of graph.values()) {
101
+ scanWrites(sf, symbol, writes, aliases)
102
+ for (const node of sf.statements) {
103
+ if (
104
+ !ts.isImportDeclaration(node) ||
105
+ node.moduleSpecifier.text !== '@kerf-js/core' ||
106
+ !node.importClause ||
107
+ node.importClause.isTypeOnly
108
+ )
109
+ continue
110
+ const named = node.importClause.namedBindings
111
+ if (named && ts.isNamespaceImport(named)) remember(named.name, 'namespace')
112
+ if (named && ts.isNamedImports(named))
113
+ for (const spec of named.elements)
114
+ if (!spec.isTypeOnly && (spec.propertyName ?? spec.name).text === 'state')
115
+ remember(spec.name, 'state')
116
+ }
117
+ }
118
+ for (const sym of writes) values.delete(sym)
119
+ const resolve = (expression) => {
120
+ expression = peel(expression)
121
+ if (ts.isIdentifier(expression)) return values.get(symbol(expression))
122
+ if (ts.isPropertyAccessExpression(expression))
123
+ return member(resolve(expression.expression), expression.name.text)
124
+ if (
125
+ ts.isElementAccessExpression(expression) &&
126
+ expression.argumentExpression &&
127
+ ts.isStringLiteralLike(expression.argumentExpression)
128
+ )
129
+ return member(resolve(expression.expression), expression.argumentExpression.text)
130
+ return undefined
131
+ }
132
+ for (let round = 0; round <= aliases.length; round++) {
133
+ const before = values.size
134
+ for (const alias of aliases) {
135
+ const base = resolve(alias.initializer)
136
+ if (!base) continue
137
+ if (ts.isIdentifier(alias.name) && !writes.has(symbol(alias.name))) remember(alias.name, base)
138
+ if (ts.isObjectBindingPattern(alias.name))
139
+ for (const element of alias.name.elements) {
140
+ if (
141
+ !ts.isIdentifier(element.name) ||
142
+ element.initializer ||
143
+ element.dotDotDotToken ||
144
+ writes.has(symbol(element.name))
145
+ )
146
+ continue
147
+ const name = element.propertyName ?? element.name
148
+ if (!ts.isIdentifier(name) && !ts.isStringLiteralLike(name)) continue
149
+ const tag = member(base, name.text)
150
+ remember(element.name, tag)
151
+ }
152
+ }
153
+ if (values.size === before) break
154
+ }
155
+ return (expression) => resolve(expression)
156
+ }
157
+
158
+ // This syntax cannot produce undefined on normal completion. Identifiers, member reads,
159
+ // calls and compound expressions remain unknown; type assertions add no runtime evidence.
160
+ function nonUndefined(expression) {
161
+ expression = peel(expression)
162
+ return [
163
+ ts.SyntaxKind.NumericLiteral,
164
+ ts.SyntaxKind.BigIntLiteral,
165
+ ts.SyntaxKind.StringLiteral,
166
+ ts.SyntaxKind.NoSubstitutionTemplateLiteral,
167
+ ts.SyntaxKind.RegularExpressionLiteral,
168
+ ts.SyntaxKind.TrueKeyword,
169
+ ts.SyntaxKind.FalseKeyword,
170
+ ts.SyntaxKind.NullKeyword,
171
+ ts.SyntaxKind.ObjectLiteralExpression,
172
+ ts.SyntaxKind.ArrayLiteralExpression,
173
+ ts.SyntaxKind.FunctionExpression,
174
+ ts.SyntaxKind.ArrowFunction,
175
+ ts.SyntaxKind.ClassExpression,
176
+ ts.SyntaxKind.NewExpression,
177
+ ts.SyntaxKind.PrefixUnaryExpression,
178
+ ts.SyntaxKind.PostfixUnaryExpression,
179
+ ts.SyntaxKind.TypeOfExpression,
180
+ ts.SyntaxKind.DeleteExpression,
181
+ ].includes(expression.kind)
182
+ }
183
+
184
+ function iifeDefaults(call, callee, visit) {
185
+ const spread = call.arguments.findIndex(ts.isSpreadElement)
186
+ const fixed = spread < 0 ? call.arguments.length : spread
187
+ // A TypeScript this parameter consumes no positional argument.
188
+ const params = callee.parameters.filter(
189
+ (param) => !ts.isIdentifier(param.name) || param.name.text !== 'this',
190
+ )
191
+ for (const [index, param] of params.entries()) {
192
+ if (param.initializer && (index >= fixed || !nonUndefined(call.arguments[index])))
193
+ visit(param.initializer)
194
+ }
195
+ }
196
+
197
+ /** Walk module evaluation, not deferred factories or instance-field initializers. */
198
+ export function moduleCalls(sf, report) {
199
+ const visit = (node) => {
200
+ if (ts.isCallExpression(node)) {
201
+ report(node)
202
+ const callee = peel(node.expression)
203
+ if (ts.isFunctionExpression(callee) || ts.isArrowFunction(callee)) {
204
+ iifeDefaults(node, callee, visit)
205
+ // Generator calls create iterators; their bodies wait for iteration.
206
+ if (!ts.isFunctionExpression(callee) || !callee.asteriskToken) visit(callee.body)
207
+ }
208
+ }
209
+ if (ts.isFunctionLike(node)) {
210
+ if (node.name && ts.isComputedPropertyName(node.name)) visit(node.name.expression)
211
+ return
212
+ }
213
+ if (
214
+ ts.isPropertyDeclaration(node) &&
215
+ !node.modifiers?.some((modifier) => modifier.kind === ts.SyntaxKind.StaticKeyword)
216
+ ) {
217
+ if (ts.isComputedPropertyName(node.name)) visit(node.name.expression)
218
+ return
219
+ }
220
+ ts.forEachChild(node, visit)
221
+ }
222
+ visit(sf)
223
+ }
@@ -0,0 +1,17 @@
1
+ // Shared server-module conventions and local resolution for project state checks.
2
+ import { existsSync } from 'node:fs'
3
+ import { join, relative } from 'node:path'
4
+ import { local } from '../alias.mjs'
5
+
6
+ /** Whether a file uses the server module convention. */
7
+ export const isServerModule = (rel) =>
8
+ rel.startsWith('src/server/') || /\.server\.[cm]?[jt]sx?$/.test(rel)
9
+ /** Resolve a local project module with the existing state-check extensions. */
10
+ export function moduleFile(root, from, spec) {
11
+ const abs = local(join(root, from), spec)
12
+ if (!abs) return undefined
13
+ const base = relative(root, abs).split('\\').join('/').replace(/\.js$/, '')
14
+ return ['', '.ts', '.tsx', '.mts', '.js', '/index.ts']
15
+ .map((x) => base + x)
16
+ .find((f) => /\.[cm]?[jt]sx?$/.test(f) && existsSync(join(root, f)))
17
+ }