@cmodjs/rulebook 0.0.0-stage → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/linters.ts ADDED
@@ -0,0 +1,338 @@
1
+ import { closeSync, existsSync, mkdtempSync, openSync, readFileSync, readSync, renameSync, rmSync, statSync } from 'node:fs'
2
+ import { homedir, tmpdir } from 'node:os'
3
+ import { basename, dirname, extname, join, relative, resolve } from 'node:path'
4
+ import packageJson from '../package.json' with { type: 'json' }
5
+ import type { Level, LinterName } from './api.ts'
6
+ import { existingFolder } from './config.ts'
7
+ import { oneLine, openedDiagnostics, seconds, type Diagnostic, type Server } from './lsp.ts'
8
+
9
+ type LinterFinding = { readonly file: string; readonly line: number; readonly level: Level; readonly rule: string; readonly message: string }
10
+
11
+ export type Covering = { readonly name: LinterName; readonly folder: string; readonly config: string | undefined }
12
+
13
+ export type ProjectLinter = Covering & { readonly files: readonly string[] }
14
+
15
+ type Program = { readonly path: string; readonly command: readonly string[]; readonly env: Readonly<Record<string, string>> }
16
+
17
+ type StylelintResult = { readonly source?: string; readonly warnings: readonly { readonly line: number; readonly rule: string; readonly severity: string; readonly text: string }[] }
18
+
19
+ type Linter = {
20
+ readonly extensions: readonly string[]
21
+ readonly shebang?: RegExp
22
+ readonly configs: readonly string[]
23
+ readonly copies: readonly string[]
24
+ readonly isBuiltIn?: boolean
25
+ readonly runsOnBun?: boolean
26
+ readonly program: string
27
+ lintText(program: Program, folder: string, file: string, text: string, timeout: number): Promise<readonly LinterFinding[]>
28
+ lintFolder(program: Program, folder: string, files: readonly string[], timeout: number): Promise<readonly LinterFinding[]>
29
+ }
30
+
31
+ const SCRIPTS = ['.js', '.jsx', '.mjs', '.cjs', '.ts', '.tsx', '.mts', '.cts']
32
+ const MAGO_REPORT = ['--reporting-format', 'json']
33
+ const SHELLCHECK_REPORT = ['--format', 'json1']
34
+ const SELENE_REPORT = ['--display-style', 'json2', '--no-summary']
35
+ const STYLELINT_CONFIGS = ['.stylelintrc', ...['json', 'yaml', 'yml', 'js', 'mjs', 'cjs', 'ts', 'mts', 'cts'].map((extension) => `.stylelintrc.${extension}`), ...['js', 'mjs', 'cjs', 'ts', 'mts', 'cts'].map((extension) => `stylelint.config.${extension}`)]
36
+ const BIOME = `node_modules/@biomejs/cli-${process.platform}-${process.arch}`
37
+
38
+ export const LINTERS: Readonly<Record<LinterName, Linter>> = {
39
+ mago: {
40
+ extensions: ['.php'],
41
+ configs: ['mago.toml'],
42
+ copies: ['vendor/bin/mago'],
43
+ program: 'mago',
44
+ lintText: async (program, folder, file, text, timeout) => magoFindings(folder, await Promise.all(['lint', 'analyze'].map((command) => run(program, [command, '--stdin-input', ...MAGO_REPORT, file], folder, text, timeout, [0, 1])))),
45
+ lintFolder: async (program, folder, _files, timeout) => magoFindings(folder, await Promise.all(['lint', 'analyze'].map((command) => run(program, [command, ...MAGO_REPORT], folder, undefined, timeout, [0, 1])))),
46
+ },
47
+ oxlint: {
48
+ extensions: SCRIPTS,
49
+ configs: ['.oxlintrc.json'],
50
+ copies: ['node_modules/oxlint/bin/oxlint'],
51
+ isBuiltIn: true,
52
+ runsOnBun: true,
53
+ program: 'oxlint',
54
+ lintText: async (program, folder, file, text, timeout) => diagnosticFindings(file, await openedDiagnostics([...program.command, '--lsp'], program.env, folder, file, text, timeout), oxlintRule),
55
+ lintFolder: async (program, folder, _files, timeout) => {
56
+ const { stdout } = await run(program, ['--format', 'json'], folder, undefined, timeout, [0, 1])
57
+ const { diagnostics } = JSON.parse(stdout) as { diagnostics: readonly { code?: string; severity: string; message: string; help?: string; filename: string; labels: readonly { span: { line: number } }[] }[] }
58
+ return diagnostics.map(({ code, severity, message, help, filename, labels }) => ({ file: resolve(folder, filename), line: labels[0]?.span.line ?? 1, level: levelOf(severity), rule: oxlintRule(code), message: oneLine(help === undefined ? message : `${message} help: ${help}`) }))
59
+ },
60
+ },
61
+ biome: {
62
+ extensions: [...SCRIPTS, '.css', '.json', '.jsonc'],
63
+ configs: ['biome.json', 'biome.jsonc'],
64
+ copies: [`${BIOME}/biome`, `${BIOME}-musl/biome`],
65
+ isBuiltIn: true,
66
+ program: 'biome',
67
+ lintText: async (program, folder, file, text, timeout) => diagnosticFindings(file, await openedDiagnostics([...program.command, 'lsp-proxy'], program.env, folder, file, text, timeout, (server) => isIgnoredByBiome(server, folder, file)), biomeRule),
68
+ lintFolder: async (program, folder, _files, timeout) => {
69
+ const { stdout } = await run(program, ['lint', '--reporter', 'github', '--max-diagnostics', 'none'], folder, undefined, timeout, [0, 1])
70
+ return stdout.split('\n').flatMap((line) => {
71
+ const match = /^::(error|warning|notice) title=([^,]*),file=([^,]*),line=(\d+),[^:]*::(.*)$/.exec(line)
72
+ const rule = biomeRule(unescaped(match?.[2] ?? ''))
73
+ return match === null || rule === undefined ? [] : [{ file: resolve(folder, unescaped(match[3] ?? '')), line: Number(match[4]), level: levelOf(match[1] ?? ''), rule, message: oneLine(unescaped(match[5] ?? '')) }]
74
+ })
75
+ },
76
+ },
77
+ stylelint: {
78
+ extensions: ['.css'],
79
+ configs: STYLELINT_CONFIGS,
80
+ copies: ['node_modules/stylelint/bin/stylelint.mjs'],
81
+ isBuiltIn: true,
82
+ runsOnBun: true,
83
+ program: 'stylelint',
84
+ lintText: async (program, folder, file, text, timeout) => {
85
+ const { default: stylelint } = (await import(Bun.resolveSync('stylelint', dirname(program.path)))) as typeof import('stylelint')
86
+ return stylelintWarnings((await within(stylelint.lint({ code: text, codeFilename: file, cwd: folder }), timeout)).results)
87
+ },
88
+ lintFolder: async (program, folder, _files, timeout) => stylelintFindings(await run(program, ['**/*.css', '--formatter', 'json', '--allow-empty-input'], folder, undefined, timeout, [0, 2])),
89
+ },
90
+ ruff: {
91
+ extensions: ['.py', '.pyi'],
92
+ configs: ['ruff.toml', '.ruff.toml', 'pyproject.toml'],
93
+ copies: ['.venv/bin/ruff'],
94
+ program: 'ruff',
95
+ lintText: async (program, folder, file, text, timeout) => ruffFindings(await run(program, ['check', '--output-format', 'json', '--force-exclude', '--stdin-filename', file, '-'], folder, text, timeout, [0, 1])),
96
+ lintFolder: async (program, folder, _files, timeout) => ruffFindings(await run(program, ['check', '--output-format', 'json'], folder, undefined, timeout, [0, 1])),
97
+ },
98
+ selene: {
99
+ extensions: ['.lua'],
100
+ configs: ['selene.toml'],
101
+ copies: [],
102
+ program: 'selene',
103
+ lintText: async (program, folder, file, text, timeout) => (isExcludedBySelene(folder, file) ? [] : seleneFindings(folder, file, await run(program, [...SELENE_REPORT, '-'], folder, text, timeout, [0, 1]))),
104
+ lintFolder: async (program, folder, _files, timeout) => seleneFindings(folder, undefined, await run(program, [...SELENE_REPORT, '.'], folder, undefined, timeout, [0, 1])),
105
+ },
106
+ shellcheck: {
107
+ extensions: ['.sh', '.bash', '.ksh', '.dash'],
108
+ shebang: /^#!.*\b(sh|bash|dash|ksh)\b/,
109
+ configs: [],
110
+ copies: [],
111
+ program: 'shellcheck',
112
+ lintText: async (program, folder, file, text, timeout) => shellcheckFindings(folder, file, await run(program, [...SHELLCHECK_REPORT, ...shellOf(file, text), '-'], folder, text, timeout, [0, 1])),
113
+ lintFolder: async (program, folder, files, timeout) => shellcheckFindings(folder, undefined, await run(program, [...SHELLCHECK_REPORT, ...files.map((file) => relative(folder, file))], folder, undefined, timeout, [0, 1])),
114
+ },
115
+ }
116
+
117
+ export function coveringLinters(names: readonly LinterName[], file: string, text: string, root: string): readonly Covering[] {
118
+ return names.flatMap((name): readonly Covering[] => {
119
+ const linter = LINTERS[name]
120
+ if (!covers(linter, file, () => text)) return []
121
+ const unconfigured = { name, folder: existingFolder(dirname(file)), config: undefined }
122
+ for (let folder = dirname(file); ; folder = dirname(folder)) {
123
+ const config = linter.configs.map((config) => join(folder, config)).find(isConfig)
124
+ if (config !== undefined) return [{ name, folder, config }]
125
+ if (folder === root || dirname(folder) === folder) return [unconfigured]
126
+ }
127
+ })
128
+ }
129
+
130
+ export function projectLinters(names: readonly LinterName[], files: readonly string[], root: string): readonly ProjectLinter[] {
131
+ return names.flatMap((name): readonly ProjectLinter[] => {
132
+ const linter = LINTERS[name]
133
+ const outermost = new Map<string, string | undefined>()
134
+ const configOf = (folder: string): string | undefined => {
135
+ if (outermost.has(folder)) return outermost.get(folder)
136
+ const above = folder === root || dirname(folder) === folder ? undefined : configOf(dirname(folder))
137
+ const config = above ?? linter.configs.map((config) => join(folder, config)).find(isConfig)
138
+ outermost.set(folder, config)
139
+ return config
140
+ }
141
+ const runs = new Map<string, { name: LinterName; folder: string; config: string | undefined; files: string[] }>()
142
+ for (const file of files.filter((file) => covers(linter, file, () => firstLine(file)))) {
143
+ const config = configOf(dirname(file))
144
+ const run = runs.get(config ?? '') ?? { name, folder: config === undefined ? root : dirname(config), config, files: [] }
145
+ run.files.push(file)
146
+ runs.set(config ?? '', run)
147
+ }
148
+ return [...runs.values()]
149
+ })
150
+ }
151
+
152
+ export async function lintText(linter: Covering, file: string, text: string, timeout: number): Promise<readonly LinterFinding[]> {
153
+ return LINTERS[linter.name].lintText(await programOf(linter), linter.folder, file, text, timeout)
154
+ }
155
+
156
+ export async function lintFolder(linter: ProjectLinter, timeout: number): Promise<readonly LinterFinding[]> {
157
+ return LINTERS[linter.name].lintFolder(await programOf(linter), linter.folder, linter.files, timeout)
158
+ }
159
+
160
+ function covers(linter: Linter, file: string, firstLineOf: () => string): boolean {
161
+ const extension = extname(file)
162
+ return linter.extensions.includes(extension) || (extension === '' && linter.shebang?.test(firstLineOf()) === true)
163
+ }
164
+
165
+ function isConfig(file: string): boolean {
166
+ if (!existsSync(file)) return false
167
+ if (basename(file) !== 'pyproject.toml') return true
168
+ return /^\s*\[tool\.ruff[.\]]/m.test(readFileSync(file, 'utf8'))
169
+ }
170
+
171
+ function firstLine(file: string): string {
172
+ if (statSync(file, { throwIfNoEntry: false })?.isFile() !== true) return ''
173
+ const handle = openSync(file, 'r')
174
+ try {
175
+ const start = Buffer.alloc(256)
176
+ return start.subarray(0, readSync(handle, start)).toString().split('\n', 1)[0] ?? ''
177
+ } finally {
178
+ closeSync(handle)
179
+ }
180
+ }
181
+
182
+ async function programOf({ name, folder }: Covering): Promise<Program> {
183
+ const linter = LINTERS[name]
184
+ const copy = copyAbove(linter, folder) ?? (linter.isBuiltIn === true ? copyAbove(linter, await builtInFolder()) : undefined)
185
+ if (copy !== undefined) return linter.runsOnBun === true ? { path: copy, command: [process.execPath, copy], env: { BUN_BE_BUN: '1' } } : { path: copy, command: [copy], env: {} }
186
+ if (linter.isBuiltIn === true) throw new Error(`this rulebook build holds no ${name}. Build it with the build script in cli/package.json, which builds oxlint, Biome, and Stylelint in.`)
187
+ const onPath = Bun.which(linter.program, { PATH: process.env.PATH ?? '' })
188
+ if (onPath !== null) return { path: onPath, command: [onPath], env: {} }
189
+ const places = [...linter.copies.map((copy) => `${copy} in ${folder} or a folder above it`), `${linter.program} on PATH`]
190
+ throw new Error(`linters names ${name}, but no ${name} program is installed: there is no ${places.join(' and no ')}. Install ${name}, or take ${name} out of linters in rulebook.config.ts.`)
191
+ }
192
+
193
+ function copyAbove(linter: Linter, folder: string): string | undefined {
194
+ for (let dir = folder; ; dir = dirname(dir)) {
195
+ const copy = linter.copies.map((path) => join(dir, path)).find((path) => existsSync(path))
196
+ if (copy !== undefined || dirname(dir) === dir) return copy
197
+ }
198
+ }
199
+
200
+ export function cacheFolder(): string {
201
+ return join(process.env.XDG_CACHE_HOME || join(homedir(), '.cache'), 'rulebook', packageJson.version)
202
+ }
203
+
204
+ let builtIn: Promise<string> | undefined
205
+
206
+ function builtInFolder(): Promise<string> {
207
+ builtIn ??= Bun.isStandaloneExecutable ? extractedLinters() : Promise.resolve(import.meta.dir)
208
+ return builtIn
209
+ }
210
+
211
+ async function extractedLinters(): Promise<string> {
212
+ const embedded = (Bun.embeddedFiles as readonly Bun.BunFile[]).find((file) => /(^|\/)linters-[^/]*\.tgz$/.test(file.name ?? ''))
213
+ if (embedded?.name === undefined) throw new Error('this rulebook build holds no oxlint, Biome, or Stylelint. Build it with the build script in cli/package.json, which builds them in.')
214
+ const folder = join(cacheFolder(), basename(embedded.name, '.tgz'))
215
+ if (existsSync(folder)) return folder
216
+ const partial = `${folder}.${crypto.randomUUID()}`
217
+ await new Bun.Archive(await embedded.bytes()).extract(partial)
218
+ try {
219
+ renameSync(partial, folder)
220
+ } catch (error) {
221
+ rmSync(partial, { recursive: true, force: true })
222
+ if (!existsSync(folder)) throw error
223
+ }
224
+ return folder
225
+ }
226
+
227
+ async function run(program: Program, args: readonly string[], cwd: string, stdin: string | undefined, timeout: number, passing: readonly number[]): Promise<{ readonly stdout: string; readonly stderr: string }> {
228
+ const output = mkdtempSync(join(tmpdir(), 'rulebook-linter-'))
229
+ try {
230
+ const [stdoutFile, stderrFile] = [join(output, 'stdout'), join(output, 'stderr')]
231
+ const started = performance.now()
232
+ const child = Bun.spawn([...program.command, ...args], { cwd, env: { ...process.env, ...program.env }, stdin: stdin === undefined ? 'ignore' : new Blob([stdin]), stdout: Bun.file(stdoutFile), stderr: Bun.file(stderrFile), timeout })
233
+ const code = await child.exited
234
+ const [stdout, stderr] = [stdoutFile, stderrFile].map((file) => (existsSync(file) ? readFileSync(file, 'utf8') : '')) as [string, string]
235
+ if (child.signalCode !== null) throw new Error(performance.now() - started >= timeout ? `it ran past ${seconds(timeout)}` : `it stopped on ${child.signalCode}`)
236
+ if (!passing.includes(code)) throw new Error(`it exited ${code}: ${oneLine(stderr) || oneLine(stdout)}`)
237
+ return { stdout, stderr }
238
+ } finally {
239
+ rmSync(output, { recursive: true, force: true })
240
+ }
241
+ }
242
+
243
+ function diagnosticFindings(file: string, diagnostics: readonly Diagnostic[], ruleOf: (code: string | undefined) => string | undefined): readonly LinterFinding[] {
244
+ return diagnostics.flatMap(({ range, severity = 1, code, message }) => {
245
+ const rule = ruleOf(code === undefined ? undefined : String(code))
246
+ return rule === undefined ? [] : [{ file, line: range.start.line + 1, level: severity === 1 ? 'error' : 'warning', rule, message: oneLine(message) }]
247
+ })
248
+ }
249
+
250
+ function oxlintRule(code: string | undefined): string {
251
+ const match = /^([^(]+)\((.+)\)$/.exec(code ?? '')
252
+ if (match === null) return `oxlint/${code ?? 'syntax'}`
253
+ return match[1] === 'eslint' ? `oxlint/${match[2]}` : `oxlint/${match[1]}/${match[2]}`
254
+ }
255
+
256
+ function biomeRule(code: string | undefined): string | undefined {
257
+ if (code?.startsWith('assist/') === true) return undefined
258
+ return `biome/${code?.replace(/^lint\//, '') ?? 'syntax'}`
259
+ }
260
+
261
+ async function isIgnoredByBiome(server: Server, folder: string, file: string): Promise<boolean> {
262
+ await server.asked('client/registerCapability')
263
+ const { projectKey } = (await server.request('biome/open_project', { path: folder, openUninitialized: true })) as { projectKey: number }
264
+ return (await server.request('biome/is_path_ignored', { projectKey, path: file, features: ['lint'], ignoreKind: 'ancestors' })) === true
265
+ }
266
+
267
+ function magoFindings(folder: string, runs: readonly { readonly stdout: string }[]): readonly LinterFinding[] {
268
+ return runs.flatMap(({ stdout }) => {
269
+ if (stdout.trim() === '') return []
270
+ const { issues } = JSON.parse(stdout) as { issues: readonly { level: string; code: string; message: string; annotations: readonly { kind: string; message?: string; span: { file_id: { path: string }; start: { line: number } } }[] }[] }
271
+ return issues.flatMap(({ level, code, message, annotations }) => {
272
+ const primary = annotations.find(({ kind }) => kind === 'Primary') ?? annotations[0]
273
+ return primary === undefined ? [] : [{ file: resolve(folder, primary.span.file_id.path), line: primary.span.start.line + 1, level: levelOf(level), rule: `mago/${code}`, message: oneLine(primary.message === undefined ? message : `${message} ${primary.message}`) }]
274
+ })
275
+ })
276
+ }
277
+
278
+ function stylelintFindings({ stdout, stderr }: { readonly stdout: string; readonly stderr: string }): readonly LinterFinding[] {
279
+ const output = [stdout, stderr].find((text) => text.trimStart().startsWith('['))
280
+ if (output === undefined) throw new Error(`it printed no results: ${oneLine(stderr) || oneLine(stdout)}`)
281
+ return stylelintWarnings(JSON.parse(output) as readonly StylelintResult[])
282
+ }
283
+
284
+ function stylelintWarnings(results: readonly StylelintResult[]): readonly LinterFinding[] {
285
+ return results.flatMap(({ source = '', warnings }) => warnings.map(({ line, rule, severity, text }) => ({ file: source, line, level: levelOf(severity), rule: `stylelint/${rule}`, message: oneLine(text.replace(` (${rule})`, '')) })))
286
+ }
287
+
288
+ async function within<T>(work: Promise<T>, timeout: number): Promise<T> {
289
+ let timer: Timer | undefined
290
+ const late = new Promise<never>((_, reject) => {
291
+ timer = setTimeout(() => reject(new Error(`it ran past ${seconds(timeout)}`)), timeout)
292
+ })
293
+ try {
294
+ return await Promise.race([work, late])
295
+ } finally {
296
+ clearTimeout(timer)
297
+ }
298
+ }
299
+
300
+ function ruffFindings({ stdout }: { readonly stdout: string }): readonly LinterFinding[] {
301
+ const diagnostics = JSON.parse(stdout) as readonly { code: string | null; message: string; filename: string; location: { row: number }; severity?: string }[]
302
+ return diagnostics.map(({ code, message, filename, location, severity = 'error' }) => ({ file: filename, line: location.row, level: levelOf(severity), rule: `ruff/${code ?? 'syntax-error'}`, message: oneLine(message) }))
303
+ }
304
+
305
+ function isExcludedBySelene(folder: string, file: string): boolean {
306
+ const config = join(folder, 'selene.toml')
307
+ if (!existsSync(config)) return false
308
+ const { exclude = [] } = Bun.TOML.parse(readFileSync(config, 'utf8')) as { exclude?: readonly string[] }
309
+ const path = relative(folder, file)
310
+ return exclude.some((glob) => new Bun.Glob(glob).match(path))
311
+ }
312
+
313
+ function seleneFindings(folder: string, file: string | undefined, { stdout, stderr }: { readonly stdout: string; readonly stderr: string }): readonly LinterFinding[] {
314
+ if (stderr.includes('ERROR')) throw new Error(oneLine(stderr))
315
+ return stdout.split('\n').filter((line) => line.startsWith('{')).flatMap((line) => {
316
+ const output = JSON.parse(line) as { type: string; severity?: string; code?: string | null; message?: string; primary_label?: { filename: string; span: { start_line: number } } }
317
+ if (output.type !== 'Diagnostic' || output.primary_label === undefined) return []
318
+ return [{ file: file ?? resolve(folder, output.primary_label.filename), line: output.primary_label.span.start_line + 1, level: levelOf(output.severity ?? ''), rule: `selene/${output.code ?? 'parse_error'}`, message: oneLine(output.message ?? '') }]
319
+ })
320
+ }
321
+
322
+ function shellOf(file: string, text: string): readonly string[] {
323
+ const extension = extname(file).slice(1)
324
+ return text.startsWith('#!') || !['bash', 'ksh', 'dash'].includes(extension) ? [] : ['--shell', extension]
325
+ }
326
+
327
+ function shellcheckFindings(folder: string, file: string | undefined, { stdout }: { readonly stdout: string }): readonly LinterFinding[] {
328
+ const { comments } = JSON.parse(stdout) as { comments: readonly { file: string; line: number; level: string; code: number; message: string }[] }
329
+ return comments.map((comment) => ({ file: file ?? resolve(folder, comment.file), line: comment.line, level: levelOf(comment.level), rule: `shellcheck/SC${comment.code}`, message: oneLine(comment.message) }))
330
+ }
331
+
332
+ function unescaped(text: string): string {
333
+ return text.replace(/%(25|0D|0A|3A|2C)/gi, (escape) => decodeURIComponent(escape))
334
+ }
335
+
336
+ function levelOf(severity: string): Level {
337
+ return severity.toLowerCase() === 'error' ? 'error' : 'warning'
338
+ }
package/src/lsp.ts ADDED
@@ -0,0 +1,105 @@
1
+ import { extname } from 'node:path'
2
+
3
+ export type Diagnostic = {
4
+ readonly range: { readonly start: { readonly line: number } }
5
+ readonly severity?: number
6
+ readonly code?: string | number
7
+ readonly message: string
8
+ }
9
+
10
+ export type Server = {
11
+ request(method: string, params: unknown): Promise<unknown>
12
+ asked(method: string): Promise<void>
13
+ }
14
+
15
+ type Message = { readonly id?: number | string; readonly method?: string; readonly params?: unknown; readonly result?: unknown; readonly error?: { readonly message: string } }
16
+
17
+ const LANGUAGES: Readonly<Record<string, string>> = {
18
+ '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'javascriptreact',
19
+ '.ts': 'typescript', '.mts': 'typescript', '.cts': 'typescript', '.tsx': 'typescriptreact',
20
+ '.css': 'css', '.json': 'json', '.jsonc': 'jsonc',
21
+ }
22
+
23
+ export async function openedDiagnostics(command: readonly string[], env: Readonly<Record<string, string>>, folder: string, file: string, text: string, timeout: number, isIgnored?: (server: Server) => Promise<boolean>): Promise<readonly Diagnostic[]> {
24
+ const started = performance.now()
25
+ const child = Bun.spawn([...command], { cwd: folder, env: { ...process.env, ...env }, stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', timeout })
26
+ let stderr = ''
27
+ void (async () => {
28
+ for await (const chunk of child.stderr) stderr += Buffer.from(chunk).toString()
29
+ })()
30
+ const uri = Bun.pathToFileURL(file).href
31
+ const answers = new Map<number, PromiseWithResolvers<unknown>>()
32
+ const asks = new Map<string, PromiseWithResolvers<void>>()
33
+ const ask = (method: string): PromiseWithResolvers<void> => asks.get(method) ?? asks.set(method, Promise.withResolvers<void>()).get(method) as PromiseWithResolvers<void>
34
+ const published = Promise.withResolvers<readonly Diagnostic[]>()
35
+ let lastId = 0
36
+
37
+ const send = (message: object): void => {
38
+ const body = JSON.stringify({ jsonrpc: '2.0', ...message })
39
+ void child.stdin.write(`Content-Length: ${Buffer.byteLength(body)}\r\n\r\n${body}`)
40
+ void child.stdin.flush()
41
+ }
42
+ const server: Server = {
43
+ request: (method, params) => {
44
+ lastId += 1
45
+ const answer = Promise.withResolvers<unknown>()
46
+ answers.set(lastId, answer)
47
+ send({ id: lastId, method, params })
48
+ return answer.promise
49
+ },
50
+ asked: (method) => ask(method).promise,
51
+ }
52
+ const receive = (message: Message): void => {
53
+ if (message.method !== undefined && message.id !== undefined) {
54
+ const items = (message.params as { items?: readonly unknown[] } | undefined)?.items ?? []
55
+ send({ id: message.id, result: message.method === 'workspace/configuration' ? items.map(() => null) : null })
56
+ ask(message.method).resolve()
57
+ } else if (message.method === 'textDocument/publishDiagnostics') {
58
+ const params = message.params as { uri: string; diagnostics: readonly Diagnostic[] }
59
+ if (params.uri === uri) published.resolve(params.diagnostics)
60
+ } else if (typeof message.id === 'number') {
61
+ const answer = answers.get(message.id)
62
+ if (message.error === undefined) answer?.resolve(message.result)
63
+ else answer?.reject(new Error(message.error.message))
64
+ }
65
+ }
66
+ const ended = Promise.withResolvers<never>()
67
+ ended.promise.catch(() => undefined)
68
+ read(child.stdout, receive).catch(ended.reject)
69
+ void child.exited.then((code) => ended.reject(new Error(child.signalCode === null ? `it exited ${code}: ${oneLine(stderr)}` : performance.now() - started >= timeout ? `it ran past ${seconds(timeout)}` : `it stopped on ${child.signalCode}`)))
70
+ const beforeEnd = <T>(work: Promise<T>): Promise<T> => Promise.race([work, ended.promise])
71
+
72
+ try {
73
+ const root = Bun.pathToFileURL(folder).href
74
+ await beforeEnd(server.request('initialize', { processId: process.pid, rootUri: root, workspaceFolders: [{ uri: root, name: 'rulebook' }], capabilities: {} }))
75
+ send({ method: 'initialized', params: {} })
76
+ if (isIgnored !== undefined && (await beforeEnd(isIgnored(server)))) return []
77
+ send({ method: 'textDocument/didOpen', params: { textDocument: { uri, languageId: LANGUAGES[extname(file)] ?? 'plaintext', version: 1, text } } })
78
+ return await beforeEnd(published.promise)
79
+ } finally {
80
+ child.kill()
81
+ }
82
+ }
83
+
84
+ async function read(stream: ReadableStream<Uint8Array>, receive: (message: Message) => void): Promise<void> {
85
+ let buffer = Buffer.alloc(0)
86
+ for await (const chunk of stream) {
87
+ buffer = Buffer.concat([buffer, chunk])
88
+ for (;;) {
89
+ const header = buffer.indexOf('\r\n\r\n')
90
+ if (header === -1) break
91
+ const length = Number(/Content-Length: *(\d+)/i.exec(buffer.subarray(0, header).toString())?.[1])
92
+ if (buffer.length < header + 4 + length) break
93
+ receive(JSON.parse(buffer.subarray(header + 4, header + 4 + length).toString()) as Message)
94
+ buffer = buffer.subarray(header + 4 + length)
95
+ }
96
+ }
97
+ }
98
+
99
+ export function seconds(ms: number): string {
100
+ return ms < 1000 ? `${ms} ms` : `${ms / 1000} s`
101
+ }
102
+
103
+ export function oneLine(text: string): string {
104
+ return text.split('\n').map((line) => line.trim()).filter((line) => line !== '').join(' ')
105
+ }
package/src/main.ts ADDED
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env bun
2
+ import { existsSync, realpathSync, statSync } from 'node:fs'
3
+ import { dirname, resolve } from 'node:path'
4
+ import { parseArgs } from 'node:util'
5
+ import packageJson from '../package.json' with { type: 'json' }
6
+ import { checkFile, displayPath, isCovered, isPrompt, lintProject } from './check.ts'
7
+ import { loadSettings, projectRoot, type Settings } from './config.ts'
8
+ import { filesBySettings, importedFiles, listedFiles, probeFiles, projectFiles } from './files.ts'
9
+ import { answer, projectOf, type Question } from './questions.ts'
10
+ import { textReport } from './report.ts'
11
+ import { loadRules, type LoadedRule } from './rules.ts'
12
+ import { serve } from './serve.ts'
13
+
14
+ const HELP = `rulebook ${packageJson.version}: lints Claude Code Prompts against static and agentic rules.
15
+
16
+ Usage:
17
+ rulebook [files...] Check every Prompt and probe of this project, or only the files named, with every rule.
18
+ rulebook --static [files...] Check with the static rules only.
19
+ rulebook --json [files...] Print the results as JSON.
20
+ rulebook edit Check the Edit, Write, or MultiEdit call Claude Code sends on stdin, before it runs.
21
+ rulebook text <@name> Check the message on stdin, such as @reply, with every rule whose paths cover its @-name.
22
+ rulebook rules Print, for each folder that holds a rulebook.config.ts, each rule that is on there, with its description and the paths it covers, and each message with the tools that send it, as JSON.
23
+ rulebook serve Answer edit, text, and rules as POST /edit, /text, and /rules on a Unix socket, keeping each project's configs and rules loaded, and print unix:<socket path> first.
24
+ rulebook --version Print the version.
25
+
26
+ A file's rules and settings come from ~/.config/rulebook/rulebook.config.ts and the nearest rulebook.config.ts in the file's folder or a folder above it, with every config they extend.`
27
+
28
+ async function main(argv: readonly string[]): Promise<number> {
29
+ const { values, positionals } = parseArgs({
30
+ args: [...argv],
31
+ allowPositionals: true,
32
+ options: { static: { type: 'boolean' }, json: { type: 'boolean' }, version: { type: 'boolean' }, help: { type: 'boolean', short: 'h' } },
33
+ })
34
+ if (values.version) return print(packageJson.version)
35
+ if (values.help) return print(HELP)
36
+ if (positionals[0] === 'serve') return serve()
37
+ if (positionals[0] === 'edit') return asked('edit', JSON.parse(await Bun.stdin.text()))
38
+ if (positionals[0] === 'text') return asked('text', { name: positionals[1] ?? '', text: await Bun.stdin.text(), cwd: process.cwd() })
39
+ if (positionals[0] === 'rules') return asked('rules', { cwd: process.cwd() })
40
+ return check(positionals, values.static === true, values.json === true)
41
+ }
42
+
43
+ async function asked(question: Question, input: unknown): Promise<number> {
44
+ return print(JSON.stringify(await answer(question, input, projectOf(question, input))))
45
+ }
46
+
47
+ async function check(named: readonly string[], isStatic: boolean, isJson: boolean): Promise<number> {
48
+ const listing = listedFiles(process.cwd())
49
+ const root = projectRoot(process.cwd(), process.cwd())
50
+ const settings = await loadSettings(process.cwd(), root)
51
+ const groups = new Map<Settings, readonly string[]>([[settings, []], ...(await filesBySettings(root, projectFiles(settings, await listing)))])
52
+ const imported = importedFiles(root, groups)
53
+ const unloaded = new Set<string>()
54
+ const rulesOf = async (own: Settings): Promise<readonly LoadedRule[]> => {
55
+ const { rules, failures } = await loadRules(own)
56
+ for (const failure of failures) unloaded.add(failure)
57
+ return rules
58
+ }
59
+ const files = named.length > 0 ? named.map((file) => realFile(file)) : await textFiles([...new Set([...(await coveredFiles(groups, rulesOf)), ...imported, ...messageFiles(settings)])])
60
+ const checked = await Promise.all(files.map(async (file) => {
61
+ const own = displayPath(settings, file).startsWith('@') ? settings : await loadSettings(dirname(file), root)
62
+ const report = await checkFile(own, await rulesOf(own), file, await Bun.file(file).text(), { scope: isStatic ? 'static' : 'all', imported: async () => imported })
63
+ if (report === undefined && named.length > 0) throw new Error(`${file} is not a Prompt, a probe, or a file a rule's paths cover.`)
64
+ return report
65
+ }))
66
+ const reports = await lintProject(groups, checked.filter((report) => report !== undefined), named.length > 0 ? files : undefined)
67
+ const failures = [...unloaded]
68
+ await print(isJson ? JSON.stringify({ reports, failures }) : textReport(reports, failures))
69
+ return failures.length > 0 || reports.some((report) => report.failures.length > 0 || report.findings.some(({ level }) => level === 'error')) ? 1 : 0
70
+ }
71
+
72
+ async function coveredFiles(groups: ReadonlyMap<Settings, readonly string[]>, rulesOf: (settings: Settings) => Promise<readonly LoadedRule[]>): Promise<readonly string[]> {
73
+ const covered = await Promise.all([...groups].map(async ([settings, files]) => {
74
+ const rules = await rulesOf(settings)
75
+ return [...files.filter((file) => isPrompt(settings, file) || isCovered(settings, rules, file)), ...probeFiles(settings)]
76
+ }))
77
+ return covered.flat()
78
+ }
79
+
80
+ function messageFiles(settings: Settings): readonly string[] {
81
+ return Object.values(settings.messages).flatMap(({ folder }) => (folder === undefined || !existsSync(folder) ? [] : [...new Bun.Glob('**').scanSync({ cwd: folder, absolute: true, dot: true })]))
82
+ }
83
+
84
+ async function textFiles(files: readonly string[]): Promise<readonly string[]> {
85
+ const texts = await Promise.all(files.map(async (file) => statSync(file, { throwIfNoEntry: false })?.isFile() === true && !(await Bun.file(file).slice(0, 8000).bytes()).includes(0)))
86
+ return files.filter((_, index) => texts[index])
87
+ }
88
+
89
+ function realFile(file: string): string {
90
+ const path = resolve(file)
91
+ if (!existsSync(path)) throw new Error(`${file} does not exist.`)
92
+ return realpathSync(path)
93
+ }
94
+
95
+ async function print(text: string): Promise<number> {
96
+ await Bun.write(Bun.stdout, `${text}\n`)
97
+ return 0
98
+ }
99
+
100
+ main(Bun.argv.slice(2)).then(
101
+ (code) => process.exit(code),
102
+ (error: unknown) => {
103
+ process.stderr.write(`rulebook: ${error instanceof Error ? error.message : String(error)}\n`)
104
+ process.exit(2)
105
+ },
106
+ )
package/src/modules.ts ADDED
@@ -0,0 +1,20 @@
1
+ import * as api from './api.ts'
2
+
3
+ let isRegistered = false
4
+
5
+ export async function importDefault(path: string): Promise<unknown> {
6
+ if (!isRegistered) {
7
+ Bun.plugin({
8
+ name: 'rulebook',
9
+ setup(build) {
10
+ build.module('@cmodjs/rulebook', () => ({ exports: { ...api }, loader: 'object' }))
11
+ },
12
+ })
13
+ isRegistered = true
14
+ }
15
+ const loaded: { default?: unknown } = await import(path).catch((error: unknown) => {
16
+ throw new Error(`${path}: ${error instanceof Error ? error.message : String(error)}`)
17
+ })
18
+ if (loaded.default === undefined) throw new Error(`${path} has no default export.`)
19
+ return loaded.default
20
+ }