hookloom 0.0.0 → 1.0.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.
@@ -0,0 +1,355 @@
1
+ import { posix } from "node:path";
2
+ // src/dispatch/payload.ts
3
+ function isRecord(value) {
4
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5
+ }
6
+ /**
7
+ * Reads a hook input document.
8
+ * @throws SyntaxError when the text is not JSON.
9
+ * @throws TypeError when it is not a JSON object.
10
+ */
11
+ function parsePayload(text) {
12
+ const value = JSON.parse(text);
13
+ if (!isRecord(value)) throw new TypeError("hook input must be a JSON object");
14
+ return value;
15
+ }
16
+ /** The string at a top-level field, or `undefined` when the field is absent or not a string. */
17
+ function stringField(payload, name) {
18
+ const value = payload[name];
19
+ return typeof value === "string" ? value : void 0;
20
+ }
21
+ /** The tool call's arguments, empty when the payload describes no tool call. */
22
+ function toolInput(payload) {
23
+ const input = payload["tool_input"];
24
+ return isRecord(input) ? input : {};
25
+ }
26
+ /** A field named by a registry, read from the top level of the payload or failing that from the tool arguments, as text. Absent fields read as empty. */
27
+ function namedField(payload, name) {
28
+ const value = payload[name] ?? toolInput(payload)[name];
29
+ if (value === void 0 || value === null) return "";
30
+ return typeof value === "string" ? value : JSON.stringify(value);
31
+ }
32
+ // src/dispatch/shell.ts
33
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*\+?=/u;
34
+ const KEYWORDS = /* @__PURE__ */ new Set([
35
+ "!",
36
+ "{",
37
+ "}",
38
+ "if",
39
+ "then",
40
+ "elif",
41
+ "else",
42
+ "fi",
43
+ "while",
44
+ "until",
45
+ "do",
46
+ "done"
47
+ ]);
48
+ const WRAPPERS = /* @__PURE__ */ new Map([
49
+ ["time", skipOptions],
50
+ ["nohup", skipOptions],
51
+ ["noglob", skipOptions],
52
+ ["builtin", skipOptions],
53
+ ["stdbuf", skipOptions],
54
+ ["command", (rest) => rest[0] === "-v" || rest[0] === "-V" ? void 0 : skipOptions(rest)],
55
+ ["nice", (rest) => rest[0] === "-n" ? 2 : skipOptions(rest)],
56
+ ["timeout", skipTimeout],
57
+ ["xargs", (rest) => rest[0]?.startsWith("-") === true ? void 0 : 0]
58
+ ]);
59
+ function skipOptions(rest) {
60
+ const index = rest.findIndex((word) => !word.startsWith("-"));
61
+ return index === -1 ? rest.length : index;
62
+ }
63
+ function skipTimeout(rest) {
64
+ let index = 0;
65
+ while (rest[index]?.startsWith("-") === true) index += rest[index] === "-s" || rest[index] === "-k" ? 2 : 1;
66
+ return index + 1;
67
+ }
68
+ var Unsplittable = class extends Error {};
69
+ var Scanner = class {
70
+ commands = [];
71
+ expands = false;
72
+ position = 0;
73
+ source;
74
+ constructor(source) {
75
+ this.source = source;
76
+ }
77
+ /** Reads commands until the end of the source, or until the closing character of a substitution or subshell. */
78
+ scan(closing) {
79
+ let words = [];
80
+ let wordStart;
81
+ let pendingOperator = false;
82
+ const heredocs = [];
83
+ const endWord = () => {
84
+ if (wordStart !== void 0) words.push({
85
+ start: wordStart,
86
+ end: this.position
87
+ });
88
+ wordStart = void 0;
89
+ };
90
+ const endCommand = () => {
91
+ endWord();
92
+ this.emit(words);
93
+ if (words.length > 0) pendingOperator = false;
94
+ words = [];
95
+ };
96
+ while (this.position < this.source.length) {
97
+ const character = this.source[this.position];
98
+ const next = this.source[this.position + 1];
99
+ if (character === closing) {
100
+ endCommand();
101
+ if (pendingOperator) throw new Unsplittable();
102
+ this.position += 1;
103
+ return;
104
+ }
105
+ if (character === " " || character === " " || character === "\r") {
106
+ endWord();
107
+ this.position += 1;
108
+ } else if (character === "#" && wordStart === void 0) {
109
+ const newline = this.source.indexOf("\n", this.position);
110
+ this.position = newline === -1 ? this.source.length : newline;
111
+ } else if (character === "\n") {
112
+ endCommand();
113
+ this.position += 1;
114
+ for (const delimiter of heredocs.splice(0)) this.skipHeredoc(delimiter);
115
+ } else if (character === "<" && next === "<" && this.source[this.position + 2] !== "<") {
116
+ endWord();
117
+ heredocs.push(this.heredocDelimiter());
118
+ } else if (character === "&" && next === ">" || (character === ">" || character === "<") && next === "&") {
119
+ wordStart ??= this.position;
120
+ this.position += 2;
121
+ } else if (character === ";" || character === "&" || character === "|") {
122
+ endCommand();
123
+ const double = character === "&" && next === "&" || character === "|" && next === "|";
124
+ pendingOperator = double;
125
+ this.position += double || character === "|" && next === "&" ? 2 : 1;
126
+ } else if (character === "(") {
127
+ endCommand();
128
+ this.position += 1;
129
+ this.scan(")");
130
+ } else if (character === ")") {
131
+ endCommand();
132
+ this.position += 1;
133
+ } else {
134
+ wordStart ??= this.position;
135
+ this.word(character ?? "");
136
+ }
137
+ }
138
+ if (closing !== void 0) throw new Unsplittable();
139
+ endCommand();
140
+ if (pendingOperator) throw new Unsplittable();
141
+ }
142
+ word(character) {
143
+ if (character === "\\") this.position += 2;
144
+ else if (character === "'") this.skipTo("'");
145
+ else if (character === "\"") this.doubleQuoted();
146
+ else if (!this.expansion()) this.position += 1;
147
+ }
148
+ /** Consumes a substitution or variable at the current position, reporting whether there was one. */
149
+ expansion() {
150
+ const character = this.source[this.position];
151
+ const next = this.source[this.position + 1];
152
+ if (character === "`") {
153
+ this.expands = true;
154
+ this.position += 1;
155
+ this.scan("`");
156
+ return true;
157
+ }
158
+ if (character !== "$" || next === void 0) return false;
159
+ if (next === "(") {
160
+ this.expands = true;
161
+ this.position += 2;
162
+ this.scan(")");
163
+ return true;
164
+ }
165
+ if (/[A-Za-z_{0-9@*?#!]/u.test(next)) this.expands = true;
166
+ return false;
167
+ }
168
+ skipTo(quote) {
169
+ const end = this.source.indexOf(quote, this.position + 1);
170
+ if (end === -1) throw new Unsplittable();
171
+ this.position = end + 1;
172
+ }
173
+ doubleQuoted() {
174
+ this.position += 1;
175
+ while (this.position < this.source.length) {
176
+ const character = this.source[this.position];
177
+ if (character === "\"") {
178
+ this.position += 1;
179
+ return;
180
+ }
181
+ if (character === "\\") this.position += 2;
182
+ else if (!this.expansion()) this.position += 1;
183
+ }
184
+ throw new Unsplittable();
185
+ }
186
+ heredocDelimiter() {
187
+ const match = /^<<-?[ \t]*(["']?)([^\s"';&|<>()]+)\1/u.exec(this.source.slice(this.position));
188
+ const delimiter = match?.[2];
189
+ if (match === null || delimiter === void 0) throw new Unsplittable();
190
+ this.position += match[0].length;
191
+ return delimiter.replace(/^\\/u, "");
192
+ }
193
+ skipHeredoc(delimiter) {
194
+ while (this.position < this.source.length) {
195
+ const newline = this.source.indexOf("\n", this.position);
196
+ const end = newline === -1 ? this.source.length : newline;
197
+ const line = this.source.slice(this.position, end).replace(/^\t+/u, "");
198
+ this.position = end + 1;
199
+ if (line === delimiter) return;
200
+ }
201
+ }
202
+ emit(words) {
203
+ const texts = words.map((word) => this.source.slice(word.start, word.end));
204
+ let index = 0;
205
+ for (;;) {
206
+ const text = texts[index];
207
+ if (text === void 0) return;
208
+ if (KEYWORDS.has(text) || ASSIGNMENT.test(text)) {
209
+ index += 1;
210
+ continue;
211
+ }
212
+ const skip = WRAPPERS.get(text)?.(texts.slice(index + 1));
213
+ if (skip === void 0 || index + 1 + skip >= texts.length) break;
214
+ index += 1 + skip;
215
+ }
216
+ const first = words[index];
217
+ const last = words.at(-1);
218
+ if (first !== void 0 && last !== void 0) this.commands.push(this.source.slice(first.start, last.end));
219
+ }
220
+ };
221
+ /** The simple commands of a command line, or `undefined` when it cannot be split. */
222
+ function splitCommand(command) {
223
+ const scanner = new Scanner(command);
224
+ try {
225
+ scanner.scan();
226
+ } catch (error) {
227
+ if (error instanceof Unsplittable) return void 0;
228
+ throw error;
229
+ }
230
+ return {
231
+ commands: scanner.commands,
232
+ expands: scanner.expands
233
+ };
234
+ }
235
+ // src/dispatch/permission-rule.ts
236
+ /**
237
+ * Evaluates the permission rule a handler's `if` field holds against a tool call, following https://code.claude.com/docs/en/permissions and the hook-specific behaviour at https://code.claude.com/docs/en/hooks.
238
+ */
239
+ const COMMAND_TOOLS = /* @__PURE__ */ new Set([
240
+ "Bash",
241
+ "Monitor",
242
+ "PowerShell"
243
+ ]);
244
+ const FILE_TOOLS = /* @__PURE__ */ new Map([["Edit", /* @__PURE__ */ new Set([
245
+ "Edit",
246
+ "Write",
247
+ "NotebookEdit",
248
+ "MultiEdit"
249
+ ])], ["Read", /* @__PURE__ */ new Set(["Read"])]]);
250
+ const PATH_RULES_NEVER_MATCHED = /* @__PURE__ */ new Set([
251
+ "Write",
252
+ "NotebookEdit",
253
+ "MultiEdit",
254
+ "Glob",
255
+ "Grep"
256
+ ]);
257
+ const PARAMETER = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/u;
258
+ function parsePermissionRule(rule) {
259
+ const match = /^([^()\s]+)(?:\((.*)\))?$/su.exec(rule);
260
+ const tool = match?.[1];
261
+ if (tool === void 0) return void 0;
262
+ const specifier = match?.[2];
263
+ return specifier === void 0 || specifier === "*" ? { tool } : {
264
+ tool,
265
+ specifier
266
+ };
267
+ }
268
+ /** Why a rule cannot be evaluated, or `undefined` when it can. */
269
+ function permissionRuleProblem(rule) {
270
+ const parsed = parsePermissionRule(rule);
271
+ if (parsed === void 0) return `${JSON.stringify(rule)} is not a permission rule`;
272
+ const { tool, specifier } = parsed;
273
+ if (specifier === void 0 || COMMAND_TOOLS.has(tool) || FILE_TOOLS.has(tool)) return void 0;
274
+ if (PATH_RULES_NEVER_MATCHED.has(tool)) return `Claude Code never matches a ${tool}(...) path rule; write an Edit or Read rule`;
275
+ if (tool.startsWith("mcp__")) return "Claude Code skips an MCP rule that has parentheses";
276
+ if (!PARAMETER.test(specifier)) return `cannot evaluate the specifier of a ${tool} rule`;
277
+ }
278
+ function escaped(text) {
279
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
280
+ }
281
+ /** Whether `text` matches a pattern in which `*` stands for any text. */
282
+ function wildcard(pattern, text) {
283
+ return new RegExp(`^${pattern.split("*").map(escaped).join(".*")}$`, "su").test(text);
284
+ }
285
+ function commandMatches(specifier, command) {
286
+ const pattern = specifier.endsWith(":*") ? `${specifier.slice(0, -2)} *` : specifier;
287
+ return command === (pattern.endsWith(" *") && pattern.indexOf("*") === pattern.length - 1 ? pattern.slice(0, -2) : void 0) || wildcard(pattern, command);
288
+ }
289
+ function commandRuleMatches(specifier, command) {
290
+ const split = splitCommand(command);
291
+ if (split === void 0) return true;
292
+ const namesMoreThanTheProgram = specifier.replace(/(?: \*|:\*)$/u, "").includes(" ");
293
+ if (split.expands && namesMoreThanTheProgram) return true;
294
+ return split.commands.some((simple) => commandMatches(specifier, simple));
295
+ }
296
+ function globSource(pattern) {
297
+ return pattern.split(/(\*\*\/|\*\*|\*|\?)/u).map((part) => {
298
+ if (part === "**/") return "(?:[^/]*/)*";
299
+ if (part === "**") return ".*";
300
+ if (part === "*") return "[^/]*";
301
+ return part === "?" ? "[^/]" : escaped(part);
302
+ }).join("");
303
+ }
304
+ function posixPath(path) {
305
+ return path.replaceAll("\\", "/").replace(/^([A-Za-z]):/u, (_drive, letter) => `/${letter.toLowerCase()}`);
306
+ }
307
+ function pathMatches(specifier, path, directories) {
308
+ const target = posix.resolve(posixPath(directories.cwd), posixPath(path));
309
+ let anchor = posixPath(directories.cwd);
310
+ let pattern = specifier;
311
+ if (specifier.startsWith("//")) {
312
+ anchor = "";
313
+ pattern = specifier.slice(2);
314
+ } else if (specifier.startsWith("~/")) {
315
+ anchor = posixPath(directories.home);
316
+ pattern = specifier.slice(2);
317
+ } else if (specifier.startsWith("/")) {
318
+ anchor = posixPath(directories.settings);
319
+ pattern = specifier.slice(1);
320
+ } else if (specifier.startsWith("./")) pattern = specifier.slice(2);
321
+ const anyDepth = !specifier.startsWith("./") && !specifier.startsWith("/") && !specifier.startsWith("~/") && !pattern.includes("/") ? "(?:[^/]*/)*" : "";
322
+ const prefix = escaped(anchor.replace(/\/$/u, ""));
323
+ return new RegExp(`^${prefix}/${anyDepth}${globSource(pattern.replace(/\/$/u, ""))}(?:/.*)?$`, "su").test(target);
324
+ }
325
+ function parameterMatches(specifier, payload, tool) {
326
+ const match = PARAMETER.exec(specifier);
327
+ const [name, expected] = [match?.[1], match?.[2]?.trim()];
328
+ if (name === void 0 || expected === void 0) return false;
329
+ const input = toolInput(payload);
330
+ if (tool === "WebFetch" && name === "domain") {
331
+ const url = input["url"];
332
+ return typeof url === "string" && URL.canParse(url) && wildcard(expected, new URL(url).hostname);
333
+ }
334
+ const value = input[name];
335
+ return (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && wildcard(expected, String(value));
336
+ }
337
+ /** Whether a tool call satisfies a rule. A payload that describes no tool call satisfies none. */
338
+ function permissionRuleMatches(rule, payload, directories) {
339
+ const tool = stringField(payload, "tool_name");
340
+ if (tool === void 0) return false;
341
+ const covered = FILE_TOOLS.get(rule.tool);
342
+ const named = rule.tool.includes("*") ? wildcard(rule.tool, tool) : tool === rule.tool;
343
+ if (rule.specifier === void 0) return named;
344
+ const input = toolInput(payload);
345
+ if (COMMAND_TOOLS.has(rule.tool)) {
346
+ const command = input["command"];
347
+ return named && typeof command === "string" && commandRuleMatches(rule.specifier, command);
348
+ }
349
+ if (covered !== void 0) {
350
+ const path = input["file_path"] ?? input["notebook_path"];
351
+ return covered.has(tool) && typeof path === "string" && pathMatches(rule.specifier, path, directories);
352
+ }
353
+ return named && parameterMatches(rule.specifier, payload, tool);
354
+ }
355
+ export { namedField as a, toolInput as c, isRecord as i, permissionRuleMatches as n, parsePayload as o, permissionRuleProblem as r, stringField as s, parsePermissionRule as t };