返回 CodeWhale
config.ts
1 /**
2 * Parse Claude Code's event-to-matcher-group hook format into shared {@link MatcherGroup}s.
3 * Only command hooks run; other hook types are returned as skipped so the
4 * bridge can warn. Plugin-root and project-directory substitutions are applied
5 * to commands at parse time.
6 * @module @deepseek-ai/dsh-hooks-claude-code/config
7 */
8
9 import { matcherDiagnostic } from '../../hook-protocol/src/matcher.ts'
10 import type { MatcherGroup } from '../../hook-protocol/src/types.ts'
11
12 const CLAUDE_EVENTS = [
13 'SessionStart',
14 'UserPromptSubmit',
15 'PreToolUse',
16 'PostToolUse',
17 'Stop',
18 'SubagentStart',
19 'SubagentStop',
20 ] as const
21
22 /** A parsed CC config: event name → its matcher groups (command hooks only). */
23 export type ClaudeCodeHookConfig = Record<string, MatcherGroup[]>
24
25 /** A skipped non-command hook, surfaced so the bridge can warn about it. */
26 export interface SkippedHook {
27 event: string
28 type: string
29 }
30
31 /** The outcome of parsing one config file: the runnable groups + what was skipped. */
32 export interface ParsedClaudeConfig {
33 config: ClaudeCodeHookConfig
34 skipped: SkippedHook[]
35 }
36
37 /** Substitution variables applied to each `command` string at parse time. */
38 export interface SubstitutionVars {
39 /** Replaces `${CLAUDE_PLUGIN_ROOT}` — the plugin's root dir. */
40 pluginRoot?: string
41 /** Replaces `${CLAUDE_PROJECT_DIR}` — the project root. */
42 projectDir?: string
43 }
44
45 /** A plain (non-null, non-array) object, else undefined. */
46 function asObject(value: unknown): Record<string, unknown> | undefined {
47 return typeof value === 'object' && value !== null && !Array.isArray(value)
48 ? value as Record<string, unknown>
49 : undefined
50 }
51
52 /**
53 * Apply `${CLAUDE_PLUGIN_ROOT}` / `${CLAUDE_PROJECT_DIR}` substitution to a command string.
54 * @param command - the raw command from config.
55 * @param vars - the substitution values; a token whose variable is unset stays verbatim.
56 * @returns the command with every occurrence of each set token replaced.
57 */
58 export function substituteCommand(command: string, vars: SubstitutionVars): string {
59 let out = command
60 if (vars.pluginRoot !== undefined) out = out.split('${CLAUDE_PLUGIN_ROOT}').join(vars.pluginRoot)
61 if (vars.projectDir !== undefined) out = out.split('${CLAUDE_PROJECT_DIR}').join(vars.projectDir)
62 return out
63 }
64
65 /**
66 * Parse either a settings `hooks` value or a bare `hooks.json` event map. Malformed entries are
67 * ignored rather than failing boot; unsupported events are ignored before their groups are parsed,
68 * non-command hooks are returned in `skipped`, and substitutions are applied to every surviving
69 * command. Matcher fields on UserPromptSubmit and Stop are discarded because those events have no
70 * matcher subject. A matcher-bearing supported runnable group with an invalid regex throws a
71 * `SyntaxError`, allowing the bridge to reject the complete config before listener registration.
72 *
73 * @param raw - the parsed JSON config: a settings object with a `hooks` key, or the bare
74 * event map.
75 * @param vars - substitution values applied to every surviving `command` (defaults to
76 * none).
77 * @returns the runnable per-event groups plus the skipped non-command hooks.
78 */
79 export function parseClaudeCodeConfig(raw: unknown, vars: SubstitutionVars = {}): ParsedClaudeConfig {
80 const config: ClaudeCodeHookConfig = {}
81 const skipped: SkippedHook[] = []
82 // Accept either `{ hooks: { … } }` (a settings file) or the bare event map.
83 const root = asObject(raw)
84 const hooksMap = root ? asObject(root.hooks) ?? root : undefined
85 if (!hooksMap) return { config, skipped }
86
87 for (const event of CLAUDE_EVENTS) {
88 const rawGroups = hooksMap[event]
89 if (!Array.isArray(rawGroups)) continue
90 const groups: MatcherGroup[] = []
91 for (const rawGroup of rawGroups) {
92 const group = asObject(rawGroup)
93 if (!group || !Array.isArray(group.hooks)) continue
94 const commands: MatcherGroup['hooks'] = []
95 for (const rawHook of group.hooks) {
96 const hook = asObject(rawHook)
97 if (!hook) continue
98 const type = typeof hook.type === 'string' ? hook.type : 'command'
99 if (type !== 'command') {
100 skipped.push({ event, type })
101 continue
102 }
103 if (typeof hook.command !== 'string') continue
104 commands.push({
105 command: substituteCommand(hook.command, vars),
106 ...typeof hook.timeout === 'number' ? { timeoutSec: hook.timeout } : {},
107 })
108 }
109 if (commands.length === 0) continue
110 const matcher = event === 'UserPromptSubmit' || event === 'Stop'
111 ? undefined
112 : typeof group.matcher === 'string' ? group.matcher : undefined
113 const diagnostic = matcherDiagnostic(matcher, 'claude-code')
114 if (diagnostic !== undefined) throw new SyntaxError(`${diagnostic} on event ${JSON.stringify(event)}`)
115 groups.push({
116 ...matcher !== undefined ? { matcher } : {},
117 hooks: commands,
118 })
119 }
120 if (groups.length > 0) config[event] = groups
121 }
122
123 return { config, skipped }
124 }
125
125 lines TYPESCRIPT