@cmodjs/rulebook 0.6.0 → 0.8.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 (3) hide show
  1. package/package.json +3 -2
  2. package/src/api.ts +21 -11
  3. package/src/rules.ts +98 -40
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cmodjs/rulebook",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Checks every file, reply, tool call, and commit against your rules and linters before it lands.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -42,11 +42,12 @@
42
42
  "@ast-grep/lang-markdown": "0.0.6",
43
43
  "@ast-grep/lang-php": "0.0.7",
44
44
  "@ast-grep/lang-python": "0.0.6",
45
+ "@ast-grep/lang-rust": "0.0.7",
45
46
  "@ast-grep/lang-toml": "0.0.9",
46
47
  "@ast-grep/lang-yaml": "0.0.6",
47
48
  "@ast-grep/napi": "0.51.1",
48
49
  "@biomejs/biome": "2.6.4",
49
- "@cmodjs/core": "6.0.2",
50
+ "@cmodjs/core": "6.2.0",
50
51
  "diff": "9.0.0",
51
52
  "marked": "15.0.0",
52
53
  "oxlint": "1.86.0",
package/src/api.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { SgNode } from '@ast-grep/napi'
2
+
1
3
  export type Severity = 'error' | 'warn'
2
4
 
3
5
  export type Runs = 'always' | 'manual'
@@ -12,9 +14,9 @@ export type Call = {
12
14
  readonly transcriptPath?: string
13
15
  }
14
16
 
15
- export type Document = { readonly lineNumber: 1; readonly text: string }
17
+ export type { SgNode }
16
18
 
17
- export type Line = { readonly lineNumber: number; readonly text: string; readonly isInCodeBlock: boolean }
19
+ export type Document = { readonly text: string }
18
20
 
19
21
  export type Command = {
20
22
  readonly lineNumber: number
@@ -23,32 +25,40 @@ export type Command = {
23
25
  readonly argv: readonly [string, ...string[]]
24
26
  readonly folder: string
25
27
  readonly input?: number
28
+ readonly runner?: number
26
29
  }
27
30
 
28
31
  export type Shell = {
32
+ readonly commands: readonly Command[]
29
33
  readonly reads: readonly string[]
30
34
  readonly writes: readonly string[]
31
35
  readonly fetches: readonly string[]
32
36
  readonly isFullyParsed: boolean
33
37
  }
34
38
 
35
- export type Node = Document | Line | Command
39
+ export type Node = SgNode | Command | Shell | Document
40
+
41
+ export type SourceCode = {
42
+ readonly text: string
43
+ readonly lines: readonly string[]
44
+ readonly ast: SgNode | Shell | Document
45
+ }
46
+
47
+ export type Position = { readonly line: number; readonly column: number }
48
+
49
+ export type Problem = { readonly node: Node } | { readonly loc: { readonly start: Position; readonly end?: Position } }
36
50
 
37
51
  export type Context = {
38
52
  readonly root: string
39
- readonly path: string
40
- readonly text: string
41
- readonly lines: readonly Line[]
42
- readonly commands: readonly Command[]
43
- readonly shell?: Shell
53
+ readonly filename: string
54
+ readonly sourceCode: SourceCode
44
55
  readonly call?: Call
45
- report(finding: { readonly node: Node }): void
56
+ report(problem: Problem): void
46
57
  }
47
58
 
48
59
  export type Visitors = {
49
- readonly Document?: (document: Document) => void | Promise<void>
50
- readonly Line?: (line: Line) => void | Promise<void>
51
60
  readonly Command?: (command: Command) => void | Promise<void>
61
+ readonly [kind: string]: ((node: SgNode) => void | Promise<void>) | ((command: Command) => void | Promise<void>) | undefined
52
62
  }
53
63
 
54
64
  export type Rule = {
package/src/rules.ts CHANGED
@@ -1,9 +1,9 @@
1
1
  import { existsSync, mkdirSync, renameSync } from 'node:fs'
2
- import { basename, join } from 'node:path'
3
- import type { NapiConfig } from '@ast-grep/napi'
2
+ import { basename, extname, join, resolve } from 'node:path'
3
+ import type { NapiConfig, SgNode } from '@ast-grep/napi'
4
4
  import type { ParsedShell } from '@cmodjs/core/shell.js'
5
- import type { Call, Command, Context, Document, Line, Rule, RuleSettings, Runs, Severity, Visitors } from './api.ts'
6
- import { importsRule, noSuppressionsRule } from './check.ts'
5
+ import type { Call, Command, Context, Node, Rule, RuleSettings, Runs, Severity, Shell, SourceCode, Visitors } from './api.ts'
6
+ import { COMMAND, importsRule, noSuppressionsRule } from './check.ts'
7
7
  import type { Import } from './claude-md.ts'
8
8
  import { isRecord, isRuns, isSeverity, isStrings, isThreshold, isTimeout, rootRelative, type Settings } from './config.ts'
9
9
  import { isJev } from './jev.ts'
@@ -62,9 +62,12 @@ const SCRIPT_KEYS = new Set([...COMMON_KEYS, 'create'])
62
62
  const FRONTMATTER_KEYS = new Set([...COMMON_KEYS, 'timeout', 'threshold', 'agent', 'model', 'effort', 'allowed-tools', 'disallowed-tools'])
63
63
  const CLAUDE_KEYS = ['agent', 'effort', 'allowed-tools', 'disallowed-tools'] as const
64
64
  const PATTERN_KEYS = new Set([...COMMON_KEYS, 'language', 'rule'])
65
- const VISITORS = new Set(['Document', 'Line', 'Command'])
66
- const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown']
67
- const CODE_FENCE = /^\s*(`{3,}|~{3,})(.*)$/
65
+ const LANGUAGES = ['typescript', 'tsx', 'javascript', 'html', 'css', 'php', 'python', 'bash', 'lua', 'json', 'yaml', 'toml', 'markdown', 'rust']
66
+ const EXTENSIONS: Readonly<Record<string, string>> = {
67
+ ts: 'typescript', mts: 'typescript', cts: 'typescript', tsx: 'tsx', js: 'javascript', mjs: 'javascript', cjs: 'javascript', jsx: 'javascript',
68
+ html: 'html', htm: 'html', css: 'css', php: 'php', phpt: 'php', py: 'python', pyi: 'python', sh: 'bash', bash: 'bash', zsh: 'bash', ksh: 'bash', bats: 'bash',
69
+ lua: 'lua', json: 'json', yaml: 'yaml', yml: 'yaml', toml: 'toml', md: 'markdown', mdx: 'markdown', markdown: 'markdown', rs: 'rust',
70
+ }
68
71
 
69
72
  let astGrep: Promise<typeof import('@ast-grep/napi')> | undefined
70
73
 
@@ -122,52 +125,106 @@ async function scriptRule(id: string, source: string): Promise<StaticRule> {
122
125
 
123
126
  async function visited(source: string, create: Rule['create'], file: CheckedFile): Promise<readonly Finding[]> {
124
127
  const found: Finding[] = []
125
- const lines = linesOf(file)
126
- const commands = commandsOf(file)
127
- const document: Document = { lineNumber: 1, text: file.text }
128
+ const language = languageOf(file.path)
129
+ const sourceCode = await sourceCodeOf(file, language)
128
130
  const context: Context = {
129
131
  root: file.root,
130
- path: file.path,
131
- text: file.text,
132
- lines,
133
- commands,
134
- ...(file.shell === undefined ? {} : { shell: { reads: file.shell.reads, writes: file.shell.writes, fetches: file.shell.fetches, isFullyParsed: file.shell.isFullyParsed } }),
132
+ filename: file.path.startsWith('@') ? file.path : resolve(file.root, file.path),
133
+ sourceCode,
135
134
  ...(file.call === undefined ? {} : { call: file.call }),
136
- report: ({ node }) => {
137
- found.push(node === document ? { line: 1, isWhole: true } : { line: node.lineNumber })
135
+ report: (problem) => {
136
+ found.push('loc' in problem ? { line: problem.loc.start.line } : findingOf(problem.node))
138
137
  },
139
138
  }
140
139
  const visitors: Visitors = await create(context)
141
- if (!isRecord(visitors)) throw new Error(`${source}: create returns an object of visitors, such as { Line(line) { … } }.`)
142
- for (const key of Object.keys(visitors)) if (!VISITORS.has(key)) throw new Error(`${source}: create returns the visitor "${key}". rulebook visits ${[...VISITORS].join(', ')}.`)
143
- await visitors.Document?.(document)
144
- if (visitors.Line !== undefined) for (const line of lines) await visitors.Line(line)
145
- if (visitors.Command !== undefined) for (const command of commands) await visitors.Command(command)
140
+ if (!isRecord(visitors)) throw new Error(`${source}: create returns an object of visitors, such as { call_expression(call) { … } }.`)
141
+ const kinds = Object.keys(visitors).filter((key) => key !== 'Command')
142
+ const unknown = await unknownKinds(kinds)
143
+ if (unknown.length > 0) throw new Error(`${source}: create returns the visitor "${unknown[0]}", which names no node. A visitor names Command or a node kind of ${LANGUAGES.join(', ')}.`)
144
+ const { ast } = sourceCode
145
+ if (isShell(ast)) {
146
+ if (visitors.Command !== undefined) for (const command of ast.commands) await visitors.Command(command)
147
+ } else if (language !== undefined) {
148
+ const own = await ownKinds(language, kinds)
149
+ if (own.length > 0) for (const node of (ast as SgNode).findAll({ rule: { any: own.map((kind) => ({ kind })) } })) await (visitors[node.kind()] as (node: SgNode) => void | Promise<void>)(node)
150
+ }
146
151
  return found
147
152
  }
148
153
 
149
- function linesOf({ path, lines }: CheckedFile): readonly Line[] {
150
- const isMarkdown = (path.startsWith('@') && path !== '@command') || /\.(md|mdx|markdown)$/i.test(path)
151
- let fence: { readonly marker: string; readonly length: number } | undefined
152
- return lines.map((text, index) => {
153
- const match = isMarkdown ? CODE_FENCE.exec(text) : null
154
- const isInCodeBlock = fence !== undefined || match !== null
155
- if (match !== null) {
156
- const marker = match[1] ?? ''
157
- if (fence === undefined) fence = { marker: marker[0] ?? '`', length: marker.length }
158
- else if (marker[0] === fence.marker && marker.length >= fence.length && (match[2] ?? '').trim() === '') fence = undefined
159
- }
160
- return { lineNumber: index + 1, text, isInCodeBlock }
161
- })
154
+ function findingOf(node: Node): Finding {
155
+ if ('lineNumber' in node) return { line: node.lineNumber }
156
+ if (!('kind' in node) || node.parent() === null) return { line: 1, isWhole: true }
157
+ return { line: node.range().start.line + 1 }
158
+ }
159
+
160
+ function isShell(node: Node): node is Shell {
161
+ return 'commands' in node
162
162
  }
163
163
 
164
- function commandsOf({ shell, lines }: CheckedFile): readonly Command[] {
165
- return (shell?.commands ?? []).map(({ argv, folder, input }) => {
164
+ const sourceCodes = new WeakMap<CheckedFile, Promise<SourceCode>>()
165
+
166
+ function sourceCodeOf(file: CheckedFile, language: string | undefined): Promise<SourceCode> {
167
+ const known = sourceCodes.get(file)
168
+ if (known !== undefined) return known
169
+ const sourceCode = parsed(file, language)
170
+ sourceCodes.set(file, sourceCode)
171
+ return sourceCode
172
+ }
173
+
174
+ async function parsed({ text, lines, shell }: CheckedFile, language: string | undefined): Promise<SourceCode> {
175
+ if (shell !== undefined) return { text, lines, ast: { commands: commandsOf(shell, lines), reads: shell.reads, writes: shell.writes, fetches: shell.fetches, isFullyParsed: shell.isFullyParsed } }
176
+ if (language === undefined) return { text, lines, ast: { text } }
177
+ const { parse } = await (astGrep ??= loadAstGrep())
178
+ let root: SgNode | undefined
179
+ return {
180
+ text,
181
+ lines,
182
+ get ast() {
183
+ root ??= parse(language, text).root()
184
+ return root
185
+ },
186
+ }
187
+ }
188
+
189
+ function languageOf(path: string): string | undefined {
190
+ if (path === COMMAND) return undefined
191
+ if (path.startsWith('@')) return 'markdown'
192
+ return EXTENSIONS[extname(path).slice(1).toLowerCase()]
193
+ }
194
+
195
+ function commandsOf(shell: ParsedShell, lines: readonly string[]): readonly Command[] {
196
+ return shell.commands.map(({ argv, folder, input, runner }) => {
166
197
  const index = lines.findIndex((line) => line.includes(argv[0]))
167
- return { lineNumber: index === -1 ? 1 : index + 1, program: basename(argv[0]), args: argv.slice(1), argv, folder, ...(input === undefined ? {} : { input }) }
198
+ return { lineNumber: index === -1 ? 1 : index + 1, program: basename(argv[0]), args: argv.slice(1), argv, folder, ...(input === undefined ? {} : { input }), ...(runner === undefined ? {} : { runner }) }
199
+ })
200
+ }
201
+
202
+ const kindsOfLanguages = new Map<string, boolean>()
203
+
204
+ async function ownKinds(language: string, kinds: readonly string[]): Promise<readonly string[]> {
205
+ const { parse } = await (astGrep ??= loadAstGrep())
206
+ return kinds.filter((kind) => {
207
+ const key = `${language}\0${kind}`
208
+ let isOwn = kindsOfLanguages.get(key)
209
+ if (isOwn === undefined) {
210
+ try {
211
+ parse(language, '').root().findAll({ rule: { kind } })
212
+ isOwn = true
213
+ } catch {
214
+ isOwn = false
215
+ }
216
+ kindsOfLanguages.set(key, isOwn)
217
+ }
218
+ return isOwn
168
219
  })
169
220
  }
170
221
 
222
+ async function unknownKinds(kinds: readonly string[]): Promise<readonly string[]> {
223
+ if (kinds.length === 0) return []
224
+ const known = new Set((await Promise.all(LANGUAGES.map((language) => ownKinds(language, kinds)))).flat())
225
+ return kinds.filter((kind) => !known.has(kind))
226
+ }
227
+
171
228
  async function agenticRule(id: string, source: string, timeout: number): Promise<AgenticRule> {
172
229
  const fail = (problem: string): never => {
173
230
  throw new Error(`${source}: ${problem}`)
@@ -221,7 +278,7 @@ async function patternRule(id: string, source: string): Promise<StaticRule> {
221
278
  }
222
279
 
223
280
  async function loadAstGrep(): Promise<typeof import('@ast-grep/napi')> {
224
- const [napi, php, python, bash, lua, json, yaml, toml, markdown] = await Promise.all([
281
+ const [napi, php, python, bash, lua, json, yaml, toml, markdown, rust] = await Promise.all([
225
282
  import('@ast-grep/napi'),
226
283
  import('@ast-grep/lang-php'),
227
284
  import('@ast-grep/lang-python'),
@@ -231,8 +288,9 @@ async function loadAstGrep(): Promise<typeof import('@ast-grep/napi')> {
231
288
  import('@ast-grep/lang-yaml'),
232
289
  import('@ast-grep/lang-toml'),
233
290
  import('@ast-grep/lang-markdown'),
291
+ import('@ast-grep/lang-rust'),
234
292
  ])
235
- const packages = { php, python, bash, lua, json, yaml, toml, markdown }
293
+ const packages = { php, python, bash, lua, json, yaml, toml, markdown, rust }
236
294
  napi.registerDynamicLanguage(Object.fromEntries(await Promise.all(Object.entries(packages).map(async ([language, { default: registration }]) => {
237
295
  const { extensions, languageSymbol = `tree_sitter_${language}`, expandoChar = '$' } = registration
238
296
  return [language, { libraryPath: Bun.isStandaloneExecutable ? await embeddedParser(language) : registration.libraryPath, extensions, languageSymbol, expandoChar }] as const