@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,240 @@
1
+ // `kerf lsp`: TypeScript 7 loads no plugins and its content mappers refuse `.tsx`, so the one place left to stand is
2
+ // between the editor and `tsc --lsp`. Buffers go in as their shadows; positions are mapped both ways (research 44 §6).
3
+
4
+ import { spawn } from 'node:child_process'
5
+ import { realpathSync } from 'node:fs'
6
+ import { dirname, join } from 'node:path'
7
+ import { createRequire } from 'node:module'
8
+ import { fileURLToPath } from 'node:url'
9
+ import ts from 'typescript'
10
+
11
+ const require = createRequire(import.meta.url)
12
+ const { Session, projectTypescript } = require('./session.cjs')
13
+ const { inGenerated, toShadow, toSource } = require('./shadow.cjs')
14
+
15
+ const RANGES = new Set([
16
+ 'range',
17
+ 'selectionRange',
18
+ 'targetRange',
19
+ 'targetSelectionRange',
20
+ 'originSelectionRange',
21
+ 'insert',
22
+ 'replace',
23
+ ])
24
+
25
+ function framed(stream, on) {
26
+ let buffer = Buffer.alloc(0)
27
+ stream.on('data', (d) => {
28
+ buffer = Buffer.concat([buffer, d])
29
+ for (;;) {
30
+ const head = buffer.indexOf('\r\n\r\n')
31
+ if (head < 0) return
32
+ const len = Number(/Content-Length: (\d+)/i.exec(buffer.subarray(0, head).toString())[1])
33
+ if (buffer.length < head + 4 + len) return
34
+ const msg = JSON.parse(buffer.subarray(head + 4, head + 4 + len).toString())
35
+ buffer = buffer.subarray(head + 4 + len)
36
+ on(msg)
37
+ }
38
+ })
39
+ }
40
+ const frame = (msg) => {
41
+ const body = Buffer.from(JSON.stringify(msg))
42
+ return Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`), body])
43
+ }
44
+
45
+ const offsetAt = (text, { line, character }) => {
46
+ let at = 0
47
+ for (let i = 0; i < line; i++) {
48
+ const n = text.indexOf('\n', at)
49
+ if (n < 0) return text.length
50
+ at = n + 1
51
+ }
52
+ return at + character
53
+ }
54
+ const positionAt = (text, offset) => {
55
+ const head = text.slice(0, offset)
56
+ const line = head.split('\n').length - 1
57
+ return { line, character: offset - (head.lastIndexOf('\n') + 1) }
58
+ }
59
+
60
+ export function lsp(root, { input = process.stdin, output = process.stdout } = {}) {
61
+ const dir = projectTypescript(root)
62
+ if (!dir)
63
+ throw Object.assign(
64
+ new Error(
65
+ '`kerf lsp` needs TypeScript 7 in the project; older versions use the tsserver plugin',
66
+ ),
67
+ { code: 'E_USAGE' },
68
+ )
69
+ const exe = join(
70
+ dirname(
71
+ createRequire(join(realpathSync(dir), 'package.json')).resolve(
72
+ `@typescript/typescript-${process.platform}-${process.arch}/package.json`,
73
+ ),
74
+ ),
75
+ 'lib',
76
+ process.platform === 'win32' ? 'tsc.exe' : 'tsc',
77
+ )
78
+ const server = spawn(exe, ['--lsp', '--stdio'], { cwd: root, stdio: ['pipe', 'pipe', 'inherit'] })
79
+ const session = new Session(ts, root)
80
+ const docs = new Map() // uri → { file, text, sent, version }
81
+ const pending = new Map() // request id → uri
82
+ const toServer = (m) => server.stdin.write(frame(m))
83
+ const toClient = (m) => output.write(frame(m))
84
+ const fileOf = (uri) => fileURLToPath(uri)
85
+ const { pos, back, items } = makeMapping(session, docs)
86
+
87
+ const client = makeClient({ docs, session, toServer, pos, fileOf, pending })
88
+
89
+ // One at a time: a request has to see the shadow its position is mapped for.
90
+ let line = Promise.resolve()
91
+ framed(input, (msg) => {
92
+ line = line.then(() => client(msg)).catch((e) => process.stderr.write(`kerf lsp: ${e.stack}\n`))
93
+ })
94
+
95
+ framed(server.stdout, (msg) => {
96
+ if (msg.method === 'textDocument/publishDiagnostics') {
97
+ const doc = docs.get(msg.params.uri)
98
+ return toClient(
99
+ doc
100
+ ? { ...msg, params: { ...msg.params, diagnostics: items(doc, msg.params.diagnostics) } }
101
+ : msg,
102
+ )
103
+ }
104
+ const hold = msg.id !== undefined && !msg.method ? pending.get(msg.id) : null
105
+ if (!hold) return toClient(msg)
106
+ pending.delete(msg.id)
107
+ if (hold.method === 'textDocument/diagnostic' && msg.result?.items)
108
+ return toClient({
109
+ ...msg,
110
+ result: { ...msg.result, items: items(hold.doc, msg.result.items) },
111
+ })
112
+ toClient({ ...msg, result: back(msg.result, hold.doc) })
113
+ })
114
+ server.on('exit', (code) => {
115
+ session.close()
116
+ process.exitCode = code ?? 0
117
+ })
118
+ return {
119
+ server,
120
+ close: () => {
121
+ server.kill()
122
+ session.close()
123
+ },
124
+ }
125
+ }
126
+
127
+ function makeMapping(session, docs) {
128
+ const mapOf = (doc) => doc && session.engine.maps.get(doc.file)
129
+
130
+ const pos = (doc, p, to) => {
131
+ const map = mapOf(doc)
132
+ if (!map) return p
133
+ return to
134
+ ? positionAt(map.text, toShadow(map, offsetAt(doc.text, p)))
135
+ : positionAt(doc.text, toSource(map, offsetAt(map.text, p)))
136
+ }
137
+ const back = (value, doc) => {
138
+ if (Array.isArray(value)) return value.map((v) => back(v, doc))
139
+ if (!value || typeof value !== 'object') return value
140
+ const uri = value.uri ?? value.targetUri
141
+ const here = uri ? (docs.get(uri) ?? doc) : doc
142
+ const out = {}
143
+ for (const [k, v] of Object.entries(value)) {
144
+ if (RANGES.has(k) && v?.start && mapOf(here))
145
+ out[k] = { start: pos(here, v.start), end: pos(here, v.end) }
146
+ else out[k] = back(v, here)
147
+ }
148
+ return out
149
+ }
150
+ const generated = (doc, d) => {
151
+ const map = mapOf(doc)
152
+ if (!map) return false
153
+ const a = offsetAt(map.text, d.range.start)
154
+ return inGenerated(map, a, offsetAt(map.text, d.range.end) - a)
155
+ }
156
+ const ours = (doc) =>
157
+ (session.engine.findings.get(doc.file) ?? []).map((f) => ({
158
+ range: { start: positionAt(doc.text, f.start), end: positionAt(doc.text, f.end) },
159
+ severity: f.severity === 'warning' ? 2 : 1,
160
+ code: f.code,
161
+ source: 'kerf',
162
+ message: `${f.why} Fix: ${f.help}`,
163
+ }))
164
+ const items = (doc, list) => [
165
+ ...back(
166
+ list.filter((d) => !generated(doc, d)),
167
+ doc,
168
+ ).filter(
169
+ (d) =>
170
+ !(session.engine.findings.get(doc.file) ?? []).some(
171
+ (f) =>
172
+ f.code === 'W084' &&
173
+ offsetAt(doc.text, d.range.start) < f.end &&
174
+ f.start <= offsetAt(doc.text, d.range.start),
175
+ ),
176
+ ),
177
+ ...ours(doc),
178
+ ]
179
+
180
+ return { pos, back, items }
181
+ }
182
+
183
+ function makeClient({ docs, session, toServer, pos, fileOf, pending }) {
184
+ /** Inference over the buffers, then every open file whose shadow moved. */
185
+ async function refresh(changed) {
186
+ if (session.host)
187
+ session.host.update(
188
+ new Map(
189
+ changed.flatMap((f) =>
190
+ session.engine.maps.has(f) ? [] : [[f, session.engine.texts.get(f)]],
191
+ ),
192
+ ),
193
+ )
194
+ await session.analyze(session.host ? changed : undefined)
195
+ for (const [uri, doc] of docs) {
196
+ const text = session.engine.maps.get(doc.file)?.text ?? doc.text
197
+ if (text === doc.sent) continue
198
+ doc.sent = text
199
+ toServer({
200
+ jsonrpc: '2.0',
201
+ method: 'textDocument/didChange',
202
+ params: { textDocument: { uri, version: ++doc.version }, contentChanges: [{ text }] },
203
+ })
204
+ }
205
+ }
206
+
207
+ async function client(msg) {
208
+ const p = msg.params
209
+ if (msg.method === 'textDocument/didOpen') {
210
+ const doc = {
211
+ file: fileOf(p.textDocument.uri),
212
+ text: p.textDocument.text,
213
+ version: p.textDocument.version,
214
+ }
215
+ docs.set(p.textDocument.uri, doc)
216
+ session.engine.set(doc.file, doc.text)
217
+ await refresh([doc.file])
218
+ doc.sent = session.engine.maps.get(doc.file)?.text ?? doc.text
219
+ return toServer({ ...msg, params: { textDocument: { ...p.textDocument, text: doc.sent } } })
220
+ }
221
+ if (msg.method === 'textDocument/didChange') {
222
+ const doc = docs.get(p.textDocument.uri)
223
+ for (const c of p.contentChanges)
224
+ doc.text = c.range
225
+ ? doc.text.slice(0, offsetAt(doc.text, c.range.start)) +
226
+ c.text +
227
+ doc.text.slice(offsetAt(doc.text, c.range.end))
228
+ : c.text
229
+ session.engine.set(doc.file, doc.text)
230
+ return refresh([doc.file])
231
+ }
232
+ const doc = p?.textDocument && docs.get(p.textDocument.uri)
233
+ if (msg.id !== undefined && doc) pending.set(msg.id, { doc, method: msg.method })
234
+ if (doc && p.position)
235
+ return toServer({ ...msg, params: { ...p, position: pos(doc, p.position, true) } })
236
+ toServer(msg)
237
+ }
238
+
239
+ return client
240
+ }
@@ -0,0 +1,161 @@
1
+ // One project's inference: a tsconfig's files, an engine, and a checker started only if something needs one. `kerf
2
+ // check`, `kerf tsc` and the dev worker all use this. The tsserver plugin has a language service of its own (plugin).
3
+
4
+ const { existsSync, readFileSync } = require('node:fs')
5
+ const { createRequire } = require('node:module')
6
+ const { dirname, join } = require('node:path')
7
+ const { Engine } = require('./engine.cjs')
8
+ const { languageHost, tsgoHost } = require('./hosts.cjs')
9
+ const { withBoxProps } = require('./box-props.cjs')
10
+
11
+ /** The project's TypeScript when it can be driven without a plugin (7's API), else ours. */
12
+ function projectTypescript(root) {
13
+ try {
14
+ const pkg = createRequire(join(root, 'package.json')).resolve('typescript/package.json')
15
+ const dir = dirname(pkg)
16
+ if (existsSync(join(dir, 'dist/api/sync/api.js'))) return dir
17
+ } catch {}
18
+ return null
19
+ }
20
+
21
+ /** A language service over the project and an overlay: TypeScript before 7. */
22
+ function memoryHost(ts, root, config, parsed, overlay) {
23
+ const versions = new Map()
24
+ const host = {
25
+ getCompilationSettings: () => parsed.options,
26
+ getScriptFileNames: () => parsed.fileNames,
27
+ getScriptVersion: (f) => String(versions.get(f) ?? 0),
28
+ getScriptSnapshot(f) {
29
+ const t = overlay.get(f) ?? (existsSync(f) ? readFileSync(f, 'utf8') : undefined)
30
+ return t === undefined ? undefined : ts.ScriptSnapshot.fromString(t)
31
+ },
32
+ getCurrentDirectory: () => root,
33
+ getDefaultLibFileName: (o) => ts.getDefaultLibFilePath(o),
34
+ fileExists: ts.sys.fileExists,
35
+ readFile: ts.sys.readFile,
36
+ readDirectory: ts.sys.readDirectory,
37
+ directoryExists: ts.sys.directoryExists,
38
+ getDirectories: ts.sys.getDirectories,
39
+ }
40
+ const service = ts.createLanguageService(host)
41
+ const bump = (f) => versions.set(f, (versions.get(f) ?? 0) + 1)
42
+ const out = languageHost(
43
+ ts,
44
+ () => service,
45
+ (files, touched) => {
46
+ for (const [f, t] of files) {
47
+ overlay.set(f, t)
48
+ bump(f)
49
+ }
50
+ touched.forEach(bump)
51
+ },
52
+ )
53
+ out.allDiagnostics = () =>
54
+ parsed.fileNames.flatMap((f) => out.diagnostics(f).map((d) => ({ ...d, file: f })))
55
+ return out
56
+ }
57
+
58
+ class Session {
59
+ constructor(ts, root, options = {}) {
60
+ this.ts = ts
61
+ this.root = root
62
+ this.config = options.config ?? join(root, 'tsconfig.json')
63
+ const raw = ts.readConfigFile(this.config, ts.sys.readFile)
64
+ this.parsed = ts.parseJsonConfigFileContent(raw.config ?? {}, ts.sys, root)
65
+ this.engine = new Engine({
66
+ ts,
67
+ read: (f) => (existsSync(f) ? readFileSync(f, 'utf8') : undefined),
68
+ routes: options.routes,
69
+ })
70
+ this.host = null
71
+ this.overlay = new Map()
72
+ this.errors = new Map()
73
+ for (const f of this.parsed.fileNames) if (/\.(?:[cm]?ts|tsx)$/.test(f)) this.engine.set(f)
74
+ }
75
+
76
+ async start() {
77
+ if (this.host) return this.host
78
+ const dir = projectTypescript(this.root)
79
+ this.host = dir
80
+ ? await tsgoHost({
81
+ root: this.root,
82
+ config: this.config,
83
+ typescriptDir: dir,
84
+ overlay: this.overlay,
85
+ })
86
+ : memoryHost(this.ts, this.root, this.config, this.parsed, this.overlay)
87
+ if (dir)
88
+ this.host = withBoxProps(this.host, () =>
89
+ memoryHost(this.ts, this.root, this.config, this.parsed, this.overlay),
90
+ )
91
+ return this.host
92
+ }
93
+
94
+ /** Saved files: the checker reads them again, except where a shadow still stands in for them. */
95
+ touch(files) {
96
+ const plain = files.filter((f) => !this.engine.maps.has(f))
97
+ for (const f of plain) this.overlay.delete(f)
98
+ this.host.update(new Map(), plain)
99
+ }
100
+
101
+ /** Findings and the checker's errors in the files inference touches, in source positions. */
102
+ async analyze(changed) {
103
+ if (!this.engine.needed()) return { findings: new Map(), errors: new Map(), started: false }
104
+ const fresh = !this.host
105
+ const host = await this.start()
106
+ const findings = this.engine.run(host, fresh ? undefined : changed)
107
+ const redo =
108
+ fresh || !changed || this.engine.typedChecksNeeded()
109
+ ? this.engine.affected()
110
+ : this.engine.touched
111
+ for (const file of redo) {
112
+ if (!this.engine.facts.has(file)) {
113
+ this.errors.delete(file)
114
+ continue
115
+ }
116
+ const list = this.engine.errors(host, file)
117
+ if (list.length) this.errors.set(file, list)
118
+ else this.errors.delete(file)
119
+ }
120
+ return { findings, errors: this.errors, started: true }
121
+ }
122
+
123
+ /** Every file's errors, the way `tsc --noEmit` would report them with inference applied. */
124
+ async all() {
125
+ const host = await this.start()
126
+ const findings = this.engine.needed() ? this.engine.run(host) : new Map()
127
+ const diags = host.allDiagnostics()
128
+ const errors = new Map()
129
+ const files = new Set(diags.map((d) => d.file))
130
+ for (const file of files) {
131
+ const real =
132
+ [...this.engine.facts.keys()].find((f) => f.toLowerCase() === file.toLowerCase()) ?? file
133
+ if (!this.engine.facts.has(real)) {
134
+ errors.set(
135
+ real,
136
+ diags
137
+ .filter((d) => d.file === file)
138
+ .map((d) => ({
139
+ code: `TS${d.code}`,
140
+ start: d.start,
141
+ end: d.start + d.length,
142
+ why: d.text,
143
+ help: 'Fix the type error',
144
+ ...d.kerf,
145
+ })),
146
+ )
147
+ continue
148
+ }
149
+ const list = this.engine.errors(host, real)
150
+ if (list.length) errors.set(real, list)
151
+ }
152
+ return { findings, errors }
153
+ }
154
+
155
+ close() {
156
+ this.host?.close()
157
+ this.host = null
158
+ }
159
+ }
160
+
161
+ module.exports = { Session, projectTypescript }
@@ -0,0 +1,54 @@
1
+ // A shadow is the source with a few spans replaced (annotations in, `bind:` out). Nothing else moves, so mapping a
2
+ // position is a binary search over the edits, in both directions, and it never needs a source map. Research 44 §5.
3
+
4
+ /** @param {string} text @param {{ start: number, end: number, text: string }[]} edits sorted, not overlapping */
5
+ function shadow(text, edits) {
6
+ const sorted = [...edits].sort((a, b) => a.start - b.start)
7
+ const parts = []
8
+ const segments = [] // { src, out, len }: runs that are unchanged
9
+ let at = 0,
10
+ out = 0
11
+ for (const e of sorted) {
12
+ const len = e.start - at
13
+ segments.push({ src: at, out, len })
14
+ parts.push(text.slice(at, e.start), e.text)
15
+ out += len + e.text.length
16
+ at = e.end
17
+ }
18
+ segments.push({ src: at, out, len: text.length - at })
19
+ parts.push(text.slice(at))
20
+ return { text: parts.join(''), segments, edits: sorted }
21
+ }
22
+
23
+ function find(segments, pos, key) {
24
+ let lo = 0,
25
+ hi = segments.length - 1
26
+ while (lo < hi) {
27
+ const mid = (lo + hi + 1) >> 1
28
+ if (segments[mid][key] <= pos) lo = mid
29
+ else hi = mid - 1
30
+ }
31
+ return segments[lo]
32
+ }
33
+
34
+ /** Source position to shadow position. */
35
+ const toShadow = (map, pos) => {
36
+ const s = find(map.segments, pos, 'src')
37
+ return s.out + Math.min(pos - s.src, s.len)
38
+ }
39
+
40
+ /** Shadow position to source position. A position inside generated text lands where that text was inserted. */
41
+ const toSource = (map, pos) => {
42
+ const s = find(map.segments, pos, 'out')
43
+ return s.src + Math.min(pos - s.out, s.len)
44
+ }
45
+
46
+ /** Whether a shadow span is inside text the source doesn't have. */
47
+ const inGenerated = (map, start, length) => {
48
+ const s = find(map.segments, start, 'out')
49
+ return start >= s.out + s.len && length >= 0
50
+ }
51
+
52
+ const identity = (text) => ({ text, segments: [{ src: 0, out: 0, len: text.length }], edits: [] })
53
+
54
+ module.exports = { shadow, toShadow, toSource, inGenerated, identity }
@@ -0,0 +1,145 @@
1
+ // The dev listener's thread (research 44 §7). It takes file names, waits out a burst of saves, and works out what they
2
+ // changed. HMR never waits on it: the main thread only posts a name here, and TypeScript runs in its own process.
3
+
4
+ const { createHash } = require('node:crypto')
5
+ const { mkdirSync, readFileSync, renameSync, writeFileSync } = require('node:fs')
6
+ const { join, relative } = require('node:path')
7
+ const { parentPort, workerData } = require('node:worker_threads')
8
+ const ts = require('typescript')
9
+ const { Session } = require('./session.cjs')
10
+
11
+ const { root, write, debounce = 25, settle = 400, rest = 120_000 } = workerData
12
+ const session = new Session(ts, root)
13
+ const pending = new Set()
14
+ let timer = null,
15
+ running = false,
16
+ last = '',
17
+ writes = null,
18
+ resting = null
19
+
20
+ function publish(list) {
21
+ const text = JSON.stringify(list)
22
+ if (text === last) return false
23
+ last = text
24
+ mkdirSync(join(root, '.kerf'), { recursive: true })
25
+ const file = join(root, '.kerf', 'props.json')
26
+ writeFileSync(`${file}.tmp`, `${JSON.stringify({ diagnostics: list }, null, 2)}\n`)
27
+ renameSync(`${file}.tmp`, file)
28
+ return true
29
+ }
30
+
31
+ const applyEdits = (text, edits) =>
32
+ [...edits]
33
+ .sort((a, b) => b.start - a.start)
34
+ .reduce((t, e) => t.slice(0, e.start) + e.text + t.slice(e.end), text)
35
+
36
+ /** Exported types go into the source once the file has been quiet, and only if it's still the text they were made from. */
37
+ function scheduleWrites(findings) {
38
+ clearTimeout(writes)
39
+ if (!write) return
40
+ const jobs = [...findings].flatMap(([file, list]) => {
41
+ const edits = list.filter((f) => f.safe && f.edits).flatMap((f) => f.edits)
42
+ return edits.length
43
+ ? [
44
+ {
45
+ file,
46
+ edits,
47
+ hash: session.engine.facts.get(file)?.hash,
48
+ codes: list.map((f) => f.code),
49
+ },
50
+ ]
51
+ : []
52
+ })
53
+ if (!jobs.length) return
54
+ writes = setTimeout(() => {
55
+ for (const job of jobs) {
56
+ const text = readFileSync(job.file, 'utf8')
57
+ if (createHash('sha1').update(text).digest('base64url').slice(0, 16) !== job.hash) continue
58
+ writeFileSync(job.file, applyEdits(text, job.edits))
59
+ parentPort.postMessage({ type: 'wrote', file: relative(root, job.file) })
60
+ }
61
+ }, settle)
62
+ }
63
+
64
+ /** The checker holds a few hundred MB, so it goes after two quiet minutes. The next save starts it again. */
65
+ function rested() {
66
+ clearTimeout(resting)
67
+ resting = setTimeout(() => session.close(), rest)
68
+ resting.unref()
69
+ }
70
+
71
+ async function first() {
72
+ running = true
73
+ try {
74
+ await report(performance.now())
75
+ } catch (e) {
76
+ parentPort.postMessage({ type: 'failed', message: e.stack })
77
+ } finally {
78
+ running = false
79
+ }
80
+ await drain()
81
+ }
82
+
83
+ async function report(t, files) {
84
+ const { findings, errors } = await session.analyze(files)
85
+ const flat = []
86
+ for (const [file, list] of [...findings, ...errors])
87
+ for (const f of list)
88
+ flat.push({
89
+ file: relative(root, file),
90
+ line: session.engine.texts.get(file).slice(0, f.start).split('\n').length,
91
+ code: f.code,
92
+ severity: f.severity ?? 'error',
93
+ why: f.why,
94
+ help: f.help,
95
+ })
96
+ scheduleWrites(findings)
97
+ const changed = publish(flat)
98
+ rested()
99
+ parentPort.postMessage({
100
+ type: 'done',
101
+ ms: performance.now() - t,
102
+ at: Date.now(),
103
+ changed,
104
+ diagnostics: flat,
105
+ })
106
+ }
107
+
108
+ async function drain() {
109
+ if (running) return
110
+ running = true
111
+ try {
112
+ while (pending.size) {
113
+ const files = [...pending]
114
+ pending.clear()
115
+ const t = performance.now()
116
+ let changed = false
117
+ for (const f of files) if (session.engine.set(f)) changed = true
118
+ if (session.host) session.touch(files)
119
+ if (!changed || !files.some((f) => session.engine.relevant(f))) {
120
+ parentPort.postMessage({ type: 'idle', ms: performance.now() - t })
121
+ continue
122
+ }
123
+ await report(t, files)
124
+ }
125
+ } catch (e) {
126
+ parentPort.postMessage({ type: 'failed', message: e.stack })
127
+ } finally {
128
+ running = false
129
+ }
130
+ }
131
+
132
+ parentPort.on('message', (msg) => {
133
+ if (msg === 'close') {
134
+ clearTimeout(timer)
135
+ clearTimeout(writes)
136
+ session.close()
137
+ process.exit(0)
138
+ }
139
+ pending.add(msg)
140
+ clearTimeout(timer)
141
+ timer = setTimeout(() => void drain(), debounce)
142
+ })
143
+
144
+ parentPort.postMessage({ type: 'ready', needed: session.engine.needed() })
145
+ if (session.engine.needed()) void first()