hookloom 1.0.1 → 1.2.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,123 @@
1
+ import { posix } from "node:path";
2
+ import { a as stringField, o as toolInput, t as splitCommand } from "./shell-4WSaabze.mjs";
3
+ // src/dispatch/permission-rule.ts
4
+ /**
5
+ * 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.
6
+ */
7
+ const COMMAND_TOOLS = /* @__PURE__ */ new Set([
8
+ "Bash",
9
+ "Monitor",
10
+ "PowerShell"
11
+ ]);
12
+ const FILE_TOOLS = /* @__PURE__ */ new Map([["Edit", /* @__PURE__ */ new Set([
13
+ "Edit",
14
+ "Write",
15
+ "NotebookEdit",
16
+ "MultiEdit"
17
+ ])], ["Read", /* @__PURE__ */ new Set(["Read"])]]);
18
+ const PATH_RULES_NEVER_MATCHED = /* @__PURE__ */ new Set([
19
+ "Write",
20
+ "NotebookEdit",
21
+ "MultiEdit",
22
+ "Glob",
23
+ "Grep"
24
+ ]);
25
+ const PARAMETER = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$/u;
26
+ function parsePermissionRule(rule) {
27
+ const match = /^([^()\s]+)(?:\((.*)\))?$/su.exec(rule);
28
+ const tool = match?.[1];
29
+ if (tool === void 0) return void 0;
30
+ const specifier = match?.[2];
31
+ return specifier === void 0 || specifier === "*" ? { tool } : {
32
+ tool,
33
+ specifier
34
+ };
35
+ }
36
+ /** Why a rule cannot be evaluated, or `undefined` when it can. */
37
+ function permissionRuleProblem(rule) {
38
+ const parsed = parsePermissionRule(rule);
39
+ if (parsed === void 0) return `${JSON.stringify(rule)} is not a permission rule`;
40
+ const { tool, specifier } = parsed;
41
+ if (specifier === void 0 || COMMAND_TOOLS.has(tool) || FILE_TOOLS.has(tool)) return void 0;
42
+ if (PATH_RULES_NEVER_MATCHED.has(tool)) return `Claude Code never matches a ${tool}(...) path rule; write an Edit or Read rule`;
43
+ if (tool.startsWith("mcp__")) return "Claude Code skips an MCP rule that has parentheses";
44
+ if (!PARAMETER.test(specifier)) return `cannot evaluate the specifier of a ${tool} rule`;
45
+ }
46
+ function escaped(text) {
47
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
48
+ }
49
+ /** Whether `text` matches a pattern in which `*` stands for any text. */
50
+ function wildcard(pattern, text) {
51
+ return new RegExp(`^${pattern.split("*").map(escaped).join(".*")}$`, "su").test(text);
52
+ }
53
+ function commandMatches(specifier, command) {
54
+ const pattern = specifier.endsWith(":*") ? `${specifier.slice(0, -2)} *` : specifier;
55
+ return command === (pattern.endsWith(" *") && pattern.indexOf("*") === pattern.length - 1 ? pattern.slice(0, -2) : void 0) || wildcard(pattern, command);
56
+ }
57
+ function commandRuleMatches(specifier, command) {
58
+ const split = splitCommand(command);
59
+ if (split === void 0) return true;
60
+ const namesMoreThanTheProgram = specifier.replace(/(?: \*|:\*)$/u, "").includes(" ");
61
+ if (split.expands && namesMoreThanTheProgram) return true;
62
+ return split.commands.some((simple) => commandMatches(specifier, simple));
63
+ }
64
+ function globSource(pattern) {
65
+ return pattern.split(/(\*\*\/|\*\*|\*|\?)/u).map((part) => {
66
+ if (part === "**/") return "(?:[^/]*/)*";
67
+ if (part === "**") return ".*";
68
+ if (part === "*") return "[^/]*";
69
+ return part === "?" ? "[^/]" : escaped(part);
70
+ }).join("");
71
+ }
72
+ function posixPath(path) {
73
+ return path.replaceAll("\\", "/").replace(/^([A-Za-z]):/u, (_drive, letter) => `/${letter.toLowerCase()}`);
74
+ }
75
+ function pathMatches(specifier, path, directories) {
76
+ const target = posix.resolve(posixPath(directories.cwd), posixPath(path));
77
+ let anchor = posixPath(directories.cwd);
78
+ let pattern = specifier;
79
+ if (specifier.startsWith("//")) {
80
+ anchor = "";
81
+ pattern = specifier.slice(2);
82
+ } else if (specifier.startsWith("~/")) {
83
+ anchor = posixPath(directories.home);
84
+ pattern = specifier.slice(2);
85
+ } else if (specifier.startsWith("/")) {
86
+ anchor = posixPath(directories.settings);
87
+ pattern = specifier.slice(1);
88
+ } else if (specifier.startsWith("./")) pattern = specifier.slice(2);
89
+ const anyDepth = !specifier.startsWith("./") && !specifier.startsWith("/") && !specifier.startsWith("~/") && !pattern.includes("/") ? "(?:[^/]*/)*" : "";
90
+ const prefix = escaped(anchor.replace(/\/$/u, ""));
91
+ return new RegExp(`^${prefix}/${anyDepth}${globSource(pattern.replace(/\/$/u, ""))}(?:/.*)?$`, "su").test(target);
92
+ }
93
+ function parameterMatches(specifier, payload, tool) {
94
+ const match = PARAMETER.exec(specifier);
95
+ const [name, expected] = [match?.[1], match?.[2]?.trim()];
96
+ if (name === void 0 || expected === void 0) return false;
97
+ const input = toolInput(payload);
98
+ if (tool === "WebFetch" && name === "domain") {
99
+ const url = input["url"];
100
+ return typeof url === "string" && URL.canParse(url) && wildcard(expected, new URL(url).hostname);
101
+ }
102
+ const value = input[name];
103
+ return (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && wildcard(expected, String(value));
104
+ }
105
+ /** Whether a tool call satisfies a rule. A payload that describes no tool call satisfies none. */
106
+ function permissionRuleMatches(rule, payload, directories) {
107
+ const tool = stringField(payload, "tool_name");
108
+ if (tool === void 0) return false;
109
+ const covered = FILE_TOOLS.get(rule.tool);
110
+ const named = rule.tool.includes("*") ? wildcard(rule.tool, tool) : tool === rule.tool;
111
+ if (rule.specifier === void 0) return named;
112
+ const input = toolInput(payload);
113
+ if (COMMAND_TOOLS.has(rule.tool)) {
114
+ const command = input["command"];
115
+ return named && typeof command === "string" && commandRuleMatches(rule.specifier, command);
116
+ }
117
+ if (covered !== void 0) {
118
+ const path = input["file_path"] ?? input["notebook_path"];
119
+ return covered.has(tool) && typeof path === "string" && pathMatches(rule.specifier, path, directories);
120
+ }
121
+ return named && parameterMatches(rule.specifier, payload, tool);
122
+ }
123
+ export { permissionRuleMatches as n, permissionRuleProblem as r, parsePermissionRule as t };
@@ -0,0 +1,254 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { n as isRecord, t as splitCommand } from "./shell-4WSaabze.mjs";
5
+ import { t as atomicWrite } from "./files-CBn-xAo2.mjs";
6
+ // src/examples/private-references.ts
7
+ /**
8
+ * Finds text going into a public GitHub repository that names a private one.
9
+ *
10
+ * A reference is a GitHub URL or SSH address, `owner/repo#N`, or a bare `owner/repo` whose owner is one of the signed-in user's own accounts (a bare pair with any other owner is too easily a path or a phrase). A repository is private only when the GitHub API says so; one it cannot see is unknown and never blocks, and text counts as going to a public repository only on the same evidence.
11
+ */
12
+ /** The variable that lets a deliberate reference through when written before the command. */
13
+ const ESCAPE = "PRIVATE_REF_OK";
14
+ const LOOKUP_TIMEOUT_MILLISECONDS = 2e4;
15
+ const URL_REFERENCE = /github\.com[/:]([\w.-]+)\/([\w.-]+)/gu;
16
+ const NUMBERED_REFERENCE = /(?<![\w/.:@-])([\w.-]+)\/([\w.-]+)(?=#\d+)/gu;
17
+ const WRITING = /* @__PURE__ */ new Set([
18
+ "issue create",
19
+ "issue edit",
20
+ "issue comment",
21
+ "issue close",
22
+ "pr create",
23
+ "pr edit",
24
+ "pr comment",
25
+ "pr review",
26
+ "pr close",
27
+ "pr merge",
28
+ "release create",
29
+ "release edit"
30
+ ]);
31
+ const API_VALUE_FLAGS = /* @__PURE__ */ new Set([
32
+ "-X",
33
+ "--method",
34
+ "-H",
35
+ "--header",
36
+ "-f",
37
+ "--raw-field",
38
+ "-F",
39
+ "--field",
40
+ "--input",
41
+ "-q",
42
+ "--jq",
43
+ "-t",
44
+ "--template",
45
+ "--hostname",
46
+ "--cache",
47
+ "-p",
48
+ "--preview"
49
+ ]);
50
+ const API_BODY_FLAGS = /* @__PURE__ */ new Set([
51
+ "-f",
52
+ "--raw-field",
53
+ "-F",
54
+ "--field",
55
+ "--input"
56
+ ]);
57
+ const BODY_FILE_FLAGS = /* @__PURE__ */ new Set([
58
+ "-F",
59
+ "--body-file",
60
+ "--file"
61
+ ]);
62
+ const ENDPOINT = /^\/?repos\/([^/{}]+)\/([^/{}]+)(?:\/|$)/u;
63
+ const gh = (args) => {
64
+ try {
65
+ return execFileSync("gh", [...args], {
66
+ encoding: "utf8",
67
+ timeout: LOOKUP_TIMEOUT_MILLISECONDS,
68
+ stdio: [
69
+ "ignore",
70
+ "pipe",
71
+ "ignore"
72
+ ]
73
+ });
74
+ } catch {
75
+ return;
76
+ }
77
+ };
78
+ /** The user's account names and each repository's visibility, read through `gh` and cached on disk. */
79
+ var Lookups = class {
80
+ run;
81
+ file;
82
+ now;
83
+ constructor(run, file, now = Date.now) {
84
+ this.run = run;
85
+ this.file = file;
86
+ this.now = now;
87
+ }
88
+ /** The signed-in user's login and organisations in lower case; none when `gh` cannot say. */
89
+ owners() {
90
+ const known = this.recall("owners");
91
+ if (Array.isArray(known)) return known.map(String);
92
+ const login = this.run([
93
+ "api",
94
+ "user",
95
+ "--jq",
96
+ ".login"
97
+ ]);
98
+ if (login === void 0) return [];
99
+ const organisations = this.run([
100
+ "api",
101
+ "user/orgs",
102
+ "--paginate",
103
+ "--jq",
104
+ ".[].login"
105
+ ]) ?? "";
106
+ const owners = [...new Set([login, ...organisations.split("\n")].map((name) => name.trim().toLowerCase()).filter((name) => name !== ""))].toSorted();
107
+ this.remember("owners", owners);
108
+ return owners;
109
+ }
110
+ visibility(repository) {
111
+ const key = `repository:${repository}`;
112
+ const known = this.recall(key);
113
+ if (known === "private" || known === "public") return known;
114
+ const answer = this.run([
115
+ "api",
116
+ `repos/${repository}`,
117
+ "--jq",
118
+ ".private"
119
+ ])?.trim();
120
+ if (answer !== "true" && answer !== "false") return "unknown";
121
+ const visibility = answer === "true" ? "private" : "public";
122
+ this.remember(key, visibility);
123
+ return visibility;
124
+ }
125
+ load() {
126
+ try {
127
+ const value = JSON.parse(readFileSync(this.file, "utf8"));
128
+ return isRecord(value) ? value : {};
129
+ } catch {
130
+ return {};
131
+ }
132
+ }
133
+ recall(key) {
134
+ const entry = this.load()[key];
135
+ return isRecord(entry) && typeof entry["at"] === "number" && this.now() - entry["at"] < 36e5 ? entry["value"] : void 0;
136
+ }
137
+ remember(key, value) {
138
+ try {
139
+ atomicWrite(this.file, JSON.stringify({
140
+ ...this.load(),
141
+ [key]: {
142
+ at: this.now(),
143
+ value
144
+ }
145
+ }));
146
+ } catch {}
147
+ }
148
+ };
149
+ function slug(owner, name) {
150
+ return `${owner}/${name.replace(/\.+$/u, "").replace(/\.git$/u, "").replace(/\.+$/u, "")}`.toLowerCase();
151
+ }
152
+ function escaped(text) {
153
+ return text.replaceAll(/[.*+?^${}()|[\]\\]/gu, "\\$&");
154
+ }
155
+ /** The repositories a text names, as lower-case `owner/name`, in order and once each. */
156
+ function references(text, owners) {
157
+ const own = owners.length === 0 ? [] : [new RegExp(`(?<![\\w/.:@-])(${owners.map(escaped).join("|")})/([\\w.-]*\\w)`, "giu")];
158
+ const found = [
159
+ URL_REFERENCE,
160
+ NUMBERED_REFERENCE,
161
+ ...own
162
+ ].flatMap((pattern) => [...text.matchAll(pattern)].map((match) => slug(match[1] ?? "", match[2] ?? "")));
163
+ return [...new Set(found.filter((repository) => !repository.endsWith("/")))];
164
+ }
165
+ /** The private repositories `added` names that `previous` did not, when `target` is public. */
166
+ function addedPrivateReferences(change, lookups) {
167
+ const owners = lookups.owners();
168
+ const already = new Set(references(change.previous, owners));
169
+ const added = references(change.added, owners).filter((repository) => !already.has(repository));
170
+ if (added.length === 0 || lookups.visibility(change.target.toLowerCase()) !== "public") return [];
171
+ return added.filter((repository) => lookups.visibility(repository) === "private");
172
+ }
173
+ const SSH_ADDRESS = /^git@(?:ssh\.)?github\.com[\w.-]*:(.+)$/u;
174
+ /** `owner/name` from the address of a GitHub repository. */
175
+ function repositoryOfAddress(address) {
176
+ const short = SSH_ADDRESS.exec(address)?.[1];
177
+ const url = short === void 0 && URL.canParse(address) ? new URL(address) : void 0;
178
+ const [owner, name] = (short ?? (url?.hostname.endsWith("github.com") === true ? url.pathname : "")).split("/").filter((part) => part !== "");
179
+ return owner === void 0 || name === void 0 ? void 0 : slug(owner, name);
180
+ }
181
+ /** `owner/name` of the GitHub repository whose working tree holds a directory, from its `origin` remote. */
182
+ function originRepository(directory) {
183
+ try {
184
+ return repositoryOfAddress(execFileSync("git", [
185
+ "-C",
186
+ directory,
187
+ "remote",
188
+ "get-url",
189
+ "origin"
190
+ ], {
191
+ encoding: "utf8",
192
+ timeout: LOOKUP_TIMEOUT_MILLISECONDS,
193
+ stdio: [
194
+ "ignore",
195
+ "pipe",
196
+ "ignore"
197
+ ]
198
+ }).trim());
199
+ } catch {
200
+ return;
201
+ }
202
+ }
203
+ function flagValue(words, flags) {
204
+ const index = words.findIndex((word) => flags.has(word) || word.startsWith("--") && flags.has(word.split("=", 1)[0] ?? "") && word.includes("="));
205
+ const word = words[index];
206
+ if (word === void 0) return void 0;
207
+ return word.includes("=") ? word.slice(word.indexOf("=") + 1) : words[index + 1];
208
+ }
209
+ function apiTarget(words) {
210
+ let endpoint;
211
+ for (let index = 0; index < words.length; index += 1) {
212
+ const word = words[index] ?? "";
213
+ if (API_VALUE_FLAGS.has(word)) index += 1;
214
+ else if (!word.startsWith("-")) endpoint ??= word;
215
+ }
216
+ const match = (flagValue(words, /* @__PURE__ */ new Set(["-X", "--method"]))?.toUpperCase() ?? (words.some((word) => API_BODY_FLAGS.has(word)) ? "POST" : "GET")) === "GET" ? null : ENDPOINT.exec(endpoint ?? "");
217
+ return match === null ? void 0 : slug(match[1] ?? "", match[2] ?? "");
218
+ }
219
+ function fileText(path) {
220
+ try {
221
+ return readFileSync(path, "utf8");
222
+ } catch {
223
+ return "";
224
+ }
225
+ }
226
+ function writeOf(words, cwd) {
227
+ const [program, ...rest] = words;
228
+ const here = (directory) => originRepository(resolve(cwd, directory));
229
+ if (program === "git") return rest.slice(0, rest.indexOf("commit") + 1).includes("commit") ? here(flagValue(rest.slice(0, rest.indexOf("commit")), /* @__PURE__ */ new Set(["-C"])) ?? ".") : void 0;
230
+ if (program !== "gh") return void 0;
231
+ if (rest[0] === "api") return apiTarget(rest.slice(1));
232
+ if (!WRITING.has(rest.slice(0, 2).join(" "))) return void 0;
233
+ const named = flagValue(rest, /* @__PURE__ */ new Set(["-R", "--repo"]));
234
+ return named?.includes("/") === true ? named.toLowerCase() : here(".");
235
+ }
236
+ /** The commands of a command line that write text to GitHub or a commit, leaving out any that opt out. */
237
+ function repositoryWrites(command, cwd) {
238
+ const split = splitCommand(command);
239
+ if (split === void 0) return [];
240
+ return split.words.flatMap((words, position) => {
241
+ const target = (split.prefixes[position] ?? []).some((word) => word.startsWith(`PRIVATE_REF_OK=`) && !["", "0"].includes(word.slice(15))) ? void 0 : writeOf(words, cwd);
242
+ if (target === void 0) return [];
243
+ return [{
244
+ target,
245
+ files: words.flatMap((word, index) => BODY_FILE_FLAGS.has(word) ? [fileText(resolve(cwd, words[index + 1] ?? ""))] : []).join("\n")
246
+ }];
247
+ });
248
+ }
249
+ /** The nearest directory of a path that exists, which decides the repository of a file not yet written. */
250
+ function existingDirectory(path, exists) {
251
+ const parent = dirname(path);
252
+ return exists(parent) || parent === dirname(parent) ? parent : existingDirectory(parent, exists);
253
+ }
254
+ export { gh as a, existingDirectory as i, Lookups as n, originRepository as o, addedPrivateReferences as r, repositoryWrites as s, ESCAPE as t };
@@ -0,0 +1,29 @@
1
+ // src/dispatch/prompt-text.ts
2
+ /**
3
+ * Separates what a person wrote in a prompt from what the harness put there: other sessions' messages, background-task notices and the harness's own wrappers arrive through the same field as typing.
4
+ */
5
+ const MESSAGE_BLOCK = /<(?<tag>agent-message|teammate-message|cross-session-message|task-notification)(?=[\s/>])[^>\n]*>(?:[^\n]*?<\/\k<tag>>|[\s\S]*?^[ \t]*<\/\k<tag>>)/gmu;
6
+ const NOTICE_BLOCK = /<(?<tag>system-reminder|codex_internal_context)(?=[\s/>])[^>]*>[\s\S]*?<\/\k<tag>>|<artifact-content-authored-by-others\s*\/>/gu;
7
+ const CROSS_SESSION_NOTICE = /^\[Cross-session idle notice\](?:[\s\S]*?This is an automated notice from that session's harness[^\n]*|[^\n]*)|^\[Cross-session delivery notice\][^\n]*$/gmu;
8
+ const HARNESS_LINES = new RegExp([
9
+ "^Another Claude session sent a message(?: while you were working)?:[ \\t]*$",
10
+ "^This came from another Claude session\\b[^\\n]*\\bnot typed by your user\\b[^\\n]*$",
11
+ "^That \"[^\\n]*?\" is an agent working inside this same session\\b[^\\n]*$",
12
+ "^\\[SYSTEM NOTIFICATION - NOT USER INPUT\\][ \\t]*(?:\\n(?:This is an automated background-task event|Do NOT interpret this as|No human input has been received)[^\\n]*)*",
13
+ "^Goal check-in: «(?:[\\s\\S]*?^Check on their progress[^\\n]*|[^\\n]*)",
14
+ "^\\[Earlier usage-limit notes no longer apply\\.[^\\n]*$",
15
+ "^\\[Request interrupted by user[^\\n]*$",
16
+ "^This session is being continued from another machine\\. Application state may have changed\\.[^\\n]*$"
17
+ ].join("|"), "gmu");
18
+ const HARNESS_PROMPT = /^\s*(?:Stop hook feedback:|Base directory for this skill:|This session is being continued from a previous conversation|The summarized conversation included Artifact content)/u;
19
+ /** The prompt without other sessions' messages and the harness's notices, keeping the user's commands and attachments; empty when nothing of the user's is left. */
20
+ function withoutHarnessMessages(prompt) {
21
+ const stripped = [
22
+ MESSAGE_BLOCK,
23
+ NOTICE_BLOCK,
24
+ CROSS_SESSION_NOTICE,
25
+ HARNESS_LINES
26
+ ].reduce((text, pattern) => text.replaceAll(pattern, " "), prompt);
27
+ return HARNESS_PROMPT.test(stripped) ? "" : stripped.trim();
28
+ }
29
+ export { withoutHarnessMessages as t };
@@ -0,0 +1,112 @@
1
+ import { n as eventNames, r as harnesses } from "./events-CHsq0Cl4.mjs";
2
+ import { a as int, c as number, d as strictObject, f as string, h as url, i as discriminatedUnion, n as array, o as literal, p as union, r as boolean, t as _enum, u as record } from "./schemas-B4KRDIno.mjs";
3
+ // src/registry/schema.ts
4
+ /**
5
+ * The shape of a registry document, defined once: the types, the runtime validator and the published JSON Schema all come from these definitions. Rules that depend on the harness or the event are in `check.ts`.
6
+ */
7
+ const environment = record(string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/u), string().regex(/^[^\0]*$/u));
8
+ const positive = number().positive();
9
+ const regularExpression = string().refine((pattern) => {
10
+ try {
11
+ new RegExp(pattern);
12
+ return true;
13
+ } catch {
14
+ return false;
15
+ }
16
+ }, "is not a valid regular expression");
17
+ const common = {
18
+ timeout: positive.optional(),
19
+ statusMessage: string().optional(),
20
+ if: string().optional(),
21
+ onFailure: _enum(["block", "continue"]).optional(),
22
+ env: environment.optional(),
23
+ /** Run the handler only when the named payload field matches, so an event it would ignore starts no process. */
24
+ when: strictObject({
25
+ field: string(),
26
+ pattern: regularExpression
27
+ }).optional(),
28
+ /** Reuse a successful result for `ttl` seconds per distinct value of the `key` payload fields, while the files `inputs` matches are unchanged. A hit is silent unless `replay` is set. */
29
+ cache: strictObject({
30
+ ttl: positive,
31
+ key: array(string()).optional(),
32
+ inputs: array(string()).optional(),
33
+ replay: boolean().optional()
34
+ }).optional(),
35
+ /** Drop output identical to what the handler last emitted to the session within the window; `ignore_digits` treats texts differing only in numbers as identical. */
36
+ repeat: strictObject({
37
+ window_seconds: positive,
38
+ ignore_digits: boolean().optional()
39
+ }).optional()
40
+ };
41
+ const commandHandler = strictObject({
42
+ type: literal("command"),
43
+ command: string().min(1),
44
+ args: array(string()).optional(),
45
+ commandWindows: string().min(1).optional(),
46
+ shell: _enum(["bash", "powershell"]).optional(),
47
+ async: boolean().optional(),
48
+ asyncRewake: boolean().optional(),
49
+ additionalContextLimit: int().min(0).optional(),
50
+ ...common
51
+ });
52
+ const httpHandler = strictObject({
53
+ type: literal("http"),
54
+ url: url({ protocol: /^https?$/u }),
55
+ headers: record(string(), string()).optional(),
56
+ allowedEnvVars: array(string()).refine((names) => new Set(names).size === names.length, "repeats a name").optional(),
57
+ ...common
58
+ });
59
+ const handler = discriminatedUnion("type", [commandHandler, httpHandler]);
60
+ const selection = {
61
+ harnesses: array(_enum(harnesses)).min(1).refine((names) => new Set(names).size === names.length, "repeats a harness"),
62
+ matcher: string().optional(),
63
+ env: environment.optional()
64
+ };
65
+ const group = union([strictObject({
66
+ ...selection,
67
+ hooks: array(handler).min(1)
68
+ }), strictObject({
69
+ ...selection,
70
+ command: string().min(1),
71
+ timeout: positive.optional()
72
+ })]);
73
+ const groups = array(group).optional();
74
+ const events = Object.fromEntries([...new Set(harnesses.flatMap((harness) => eventNames(harness)))].map((event) => [event, groups]));
75
+ const schemaPointer = { $schema: string().optional() };
76
+ /** A registry written with its events at the top level or under `hooks`. */
77
+ const registryDocument = union([strictObject({
78
+ ...schemaPointer,
79
+ config: strictObject({ env: environment.optional() }).optional(),
80
+ hooks: strictObject(events)
81
+ }), strictObject({
82
+ ...schemaPointer,
83
+ env: environment.optional(),
84
+ ...events
85
+ })]);
86
+ const eventGroups = record(string(), array(group));
87
+ /**
88
+ * Validates a parsed registry document and returns its events and shared environment.
89
+ * @throws z.ZodError when the document does not match the schema.
90
+ */
91
+ function parseRegistry(value) {
92
+ const document = registryDocument.parse(value);
93
+ if ("hooks" in document) return {
94
+ events: eventGroups.parse(document.hooks),
95
+ env: document.config?.env ?? {}
96
+ };
97
+ const entries = Object.entries(document).filter(([key]) => key !== "$schema" && key !== "env");
98
+ return {
99
+ events: eventGroups.parse(Object.fromEntries(entries)),
100
+ env: environment.parse(document.env ?? {})
101
+ };
102
+ }
103
+ /** The handlers of a group, with the single-command shorthand written out. */
104
+ function handlersOf(entry) {
105
+ if ("hooks" in entry) return entry.hooks;
106
+ return [{
107
+ type: "command",
108
+ command: entry.command,
109
+ ...entry.timeout === void 0 ? {} : { timeout: entry.timeout }
110
+ }];
111
+ }
112
+ export { parseRegistry as n, registryDocument as r, handlersOf as t };
@@ -1 +1 @@
1
- export { t as handlersOf, n as parseRegistry, r as registryDocument } from "./schema-78xAlSN_.mjs";
1
+ export { t as handlersOf, n as parseRegistry, r as registryDocument } from "./schema-Dl9EJYyt.mjs";