@hop-top/kit 0.4.0-alpha.1

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 (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,190 @@
1
+ import { describe, it, expect, vi } from "vitest";
2
+ import {
3
+ APIClient,
4
+ APIRequestError,
5
+ type Entity,
6
+ type APIError,
7
+ } from "./api";
8
+
9
+ interface Item extends Entity {
10
+ id: string;
11
+ name: string;
12
+ }
13
+
14
+ function mockFetch(status: number, body?: unknown): typeof fetch {
15
+ return vi.fn().mockResolvedValue({
16
+ ok: status >= 200 && status < 300,
17
+ status,
18
+ statusText: "mock",
19
+ json: () => Promise.resolve(body),
20
+ }) as unknown as typeof fetch;
21
+ }
22
+
23
+ describe("APIClient", () => {
24
+ const base = "http://localhost:8080/items";
25
+
26
+ it("create sends POST and returns entity", async () => {
27
+ const created: Item = { id: "1", name: "foo" };
28
+ const f = mockFetch(201, created);
29
+ const client = new APIClient<Item>(base, { fetch: f });
30
+
31
+ const result = await client.create({ name: "foo" });
32
+
33
+ expect(result).toEqual(created);
34
+ expect(f).toHaveBeenCalledWith(
35
+ `${base}/`,
36
+ expect.objectContaining({ method: "POST" }),
37
+ );
38
+ });
39
+
40
+ it("get sends GET /{id}", async () => {
41
+ const item: Item = { id: "42", name: "bar" };
42
+ const f = mockFetch(200, item);
43
+ const client = new APIClient<Item>(base, { fetch: f });
44
+
45
+ const result = await client.get("42");
46
+
47
+ expect(result).toEqual(item);
48
+ expect(f).toHaveBeenCalledWith(
49
+ `${base}/42`,
50
+ expect.objectContaining({ method: "GET" }),
51
+ );
52
+ });
53
+
54
+ it("list sends GET with query params", async () => {
55
+ const items: Item[] = [{ id: "1", name: "a" }];
56
+ const f = mockFetch(200, items);
57
+ const client = new APIClient<Item>(base, { fetch: f });
58
+
59
+ const result = await client.list({
60
+ limit: 10,
61
+ offset: 5,
62
+ sort: "name",
63
+ search: "test",
64
+ });
65
+
66
+ expect(result).toEqual(items);
67
+ const url = (f as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
68
+ expect(url).toContain("limit=10");
69
+ expect(url).toContain("offset=5");
70
+ expect(url).toContain("sort=name");
71
+ expect(url).toContain("search=test");
72
+ });
73
+
74
+ it("list sends GET without params when query omitted", async () => {
75
+ const f = mockFetch(200, []);
76
+ const client = new APIClient<Item>(base, { fetch: f });
77
+
78
+ await client.list();
79
+
80
+ expect(f).toHaveBeenCalledWith(
81
+ `${base}/`,
82
+ expect.objectContaining({ method: "GET" }),
83
+ );
84
+ });
85
+
86
+ it("update sends PUT /{id}", async () => {
87
+ const item: Item = { id: "7", name: "updated" };
88
+ const f = mockFetch(200, item);
89
+ const client = new APIClient<Item>(base, { fetch: f });
90
+
91
+ const result = await client.update(item);
92
+
93
+ expect(result).toEqual(item);
94
+ expect(f).toHaveBeenCalledWith(
95
+ `${base}/7`,
96
+ expect.objectContaining({ method: "PUT" }),
97
+ );
98
+ });
99
+
100
+ it("delete sends DELETE /{id}", async () => {
101
+ const f = mockFetch(204);
102
+ const client = new APIClient<Item>(base, { fetch: f });
103
+
104
+ await client.delete("99");
105
+
106
+ expect(f).toHaveBeenCalledWith(
107
+ `${base}/99`,
108
+ expect.objectContaining({ method: "DELETE" }),
109
+ );
110
+ });
111
+
112
+ it("throws APIRequestError on non-2xx", async () => {
113
+ const errBody: APIError = {
114
+ status: 404,
115
+ code: "not_found",
116
+ message: "not found",
117
+ };
118
+ const f = mockFetch(404, errBody);
119
+ const client = new APIClient<Item>(base, { fetch: f });
120
+
121
+ try {
122
+ await client.get("missing");
123
+ expect.fail("should have thrown");
124
+ } catch (e) {
125
+ expect(e).toBeInstanceOf(APIRequestError);
126
+ const err = e as APIRequestError;
127
+ expect(err.status).toBe(404);
128
+ expect(err.code).toBe("not_found");
129
+ expect(err.message).toBe("not found");
130
+ }
131
+ });
132
+
133
+ it("sets Authorization header when auth provided", async () => {
134
+ const f = mockFetch(200, []);
135
+ const client = new APIClient<Item>(base, {
136
+ fetch: f,
137
+ auth: "tok_123",
138
+ });
139
+
140
+ await client.list();
141
+
142
+ const headers = (f as ReturnType<typeof vi.fn>).mock.calls[0][1]
143
+ .headers as Record<string, string>;
144
+ expect(headers["Authorization"]).toBe("Bearer tok_123");
145
+ });
146
+
147
+ it("omits Authorization header when no auth", async () => {
148
+ const f = mockFetch(200, []);
149
+ const client = new APIClient<Item>(base, { fetch: f });
150
+
151
+ await client.list();
152
+
153
+ const headers = (f as ReturnType<typeof vi.fn>).mock.calls[0][1]
154
+ .headers as Record<string, string>;
155
+ expect(headers["Authorization"]).toBeUndefined();
156
+ });
157
+
158
+ it("sets Content-Type header", async () => {
159
+ const f = mockFetch(200, []);
160
+ const client = new APIClient<Item>(base, { fetch: f });
161
+
162
+ await client.list();
163
+
164
+ const headers = (f as ReturnType<typeof vi.fn>).mock.calls[0][1]
165
+ .headers as Record<string, string>;
166
+ expect(headers["Content-Type"]).toBe("application/json");
167
+ });
168
+
169
+ it("strips trailing slash from baseURL", async () => {
170
+ const f = mockFetch(200, { id: "1", name: "x" });
171
+ const client = new APIClient<Item>(base + "///", { fetch: f });
172
+
173
+ await client.get("1");
174
+
175
+ expect(f).toHaveBeenCalledWith(
176
+ `${base}/1`,
177
+ expect.anything(),
178
+ );
179
+ });
180
+
181
+ it("encodes special characters in id", async () => {
182
+ const f = mockFetch(200, { id: "a/b", name: "x" });
183
+ const client = new APIClient<Item>(base, { fetch: f });
184
+
185
+ await client.get("a/b");
186
+
187
+ const url = (f as ReturnType<typeof vi.fn>).mock.calls[0][0] as string;
188
+ expect(url).toContain(encodeURIComponent("a/b"));
189
+ });
190
+ });
package/src/api.ts ADDED
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Typed REST API client + WebSocket client for kit services.
3
+ *
4
+ * Mirrors Go-side api.Service[T] (CRUD) and api.WSMessage (pub/sub).
5
+ */
6
+
7
+ // --- Types ---
8
+
9
+ export interface Entity {
10
+ id: string;
11
+ }
12
+
13
+ export interface Query {
14
+ limit?: number;
15
+ offset?: number;
16
+ sort?: string;
17
+ search?: string;
18
+ }
19
+
20
+ export interface APIError {
21
+ status: number;
22
+ code: string;
23
+ message: string;
24
+ }
25
+
26
+ export interface WSMessage {
27
+ type: string;
28
+ topic: string;
29
+ payload: unknown;
30
+ }
31
+
32
+ // --- APIError as throwable ---
33
+
34
+ export class APIRequestError extends Error implements APIError {
35
+ status: number;
36
+ code: string;
37
+
38
+ constructor(err: APIError) {
39
+ super(err.message);
40
+ this.name = "APIRequestError";
41
+ this.status = err.status;
42
+ this.code = err.code;
43
+ }
44
+ }
45
+
46
+ // --- APIClient ---
47
+
48
+ export interface APIClientOptions {
49
+ auth?: string;
50
+ fetch?: typeof globalThis.fetch;
51
+ }
52
+
53
+ export class APIClient<T extends Entity> {
54
+ private baseURL: string;
55
+ private auth?: string;
56
+ private fetchFn: typeof globalThis.fetch;
57
+
58
+ constructor(baseURL: string, opts?: APIClientOptions) {
59
+ // strip trailing slash
60
+ this.baseURL = baseURL.replace(/\/+$/, "");
61
+ this.auth = opts?.auth;
62
+ this.fetchFn = opts?.fetch ?? globalThis.fetch.bind(globalThis);
63
+ }
64
+
65
+ private headers(): Record<string, string> {
66
+ const h: Record<string, string> = {
67
+ "Content-Type": "application/json",
68
+ };
69
+ if (this.auth) {
70
+ h["Authorization"] = `Bearer ${this.auth}`;
71
+ }
72
+ return h;
73
+ }
74
+
75
+ private async request<R>(
76
+ method: string,
77
+ path: string,
78
+ body?: unknown,
79
+ ): Promise<R> {
80
+ const res = await this.fetchFn(`${this.baseURL}${path}`, {
81
+ method,
82
+ headers: this.headers(),
83
+ body: body !== undefined ? JSON.stringify(body) : undefined,
84
+ });
85
+
86
+ if (!res.ok) {
87
+ let err: APIError;
88
+ try {
89
+ err = (await res.json()) as APIError;
90
+ } catch {
91
+ err = {
92
+ status: res.status,
93
+ code: "unknown",
94
+ message: res.statusText,
95
+ };
96
+ }
97
+ throw new APIRequestError(err);
98
+ }
99
+
100
+ if (res.status === 204) return undefined as R;
101
+ return (await res.json()) as R;
102
+ }
103
+
104
+ async create(entity: Omit<T, "id"> | T): Promise<T> {
105
+ return this.request<T>("POST", "/", entity);
106
+ }
107
+
108
+ async get(id: string): Promise<T> {
109
+ return this.request<T>("GET", `/${encodeURIComponent(id)}`);
110
+ }
111
+
112
+ async list(q?: Query): Promise<T[]> {
113
+ const params = new URLSearchParams();
114
+ if (q?.limit !== undefined) params.set("limit", String(q.limit));
115
+ if (q?.offset !== undefined) params.set("offset", String(q.offset));
116
+ if (q?.sort) params.set("sort", q.sort);
117
+ if (q?.search) params.set("search", q.search);
118
+ const qs = params.toString();
119
+ return this.request<T[]>("GET", `/${qs ? `?${qs}` : ""}`);
120
+ }
121
+
122
+ async update(entity: T): Promise<T> {
123
+ return this.request<T>(
124
+ "PUT",
125
+ `/${encodeURIComponent(entity.id)}`,
126
+ entity,
127
+ );
128
+ }
129
+
130
+ async delete(id: string): Promise<void> {
131
+ return this.request<void>(
132
+ "DELETE",
133
+ `/${encodeURIComponent(id)}`,
134
+ );
135
+ }
136
+ }
137
+
138
+ // --- WSClient ---
139
+
140
+ type MessageHandler = (msg: WSMessage) => void;
141
+
142
+ export class WSClient {
143
+ private url: string;
144
+ private ws?: WebSocket;
145
+ private handlers: MessageHandler[] = [];
146
+
147
+ constructor(url: string) {
148
+ this.url = url;
149
+ }
150
+
151
+ private static async resolveWS(): Promise<typeof WebSocket> {
152
+ if (typeof globalThis.WebSocket !== "undefined") {
153
+ return globalThis.WebSocket;
154
+ }
155
+ // Node <21 fallback; ws is an optional peer dep.
156
+ // CJS-only — safe because package.json declares "type": "commonjs".
157
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
158
+ try { return require("ws") as typeof WebSocket; } catch { /* noop */ }
159
+ throw new Error("ws: no WebSocket implementation available");
160
+ }
161
+
162
+ async connect(): Promise<void> {
163
+ const WS = await WSClient.resolveWS();
164
+
165
+ return new Promise<void>((resolve, reject) => {
166
+ const ws = new WS(this.url);
167
+
168
+ ws.onopen = () => {
169
+ this.ws = ws;
170
+ resolve();
171
+ };
172
+
173
+ ws.onerror = (e: Event) => {
174
+ reject(e);
175
+ };
176
+
177
+ ws.onmessage = (ev: MessageEvent) => {
178
+ try {
179
+ const msg = JSON.parse(
180
+ typeof ev.data === "string" ? ev.data : String(ev.data),
181
+ ) as WSMessage;
182
+ for (const fn of this.handlers) {
183
+ fn(msg);
184
+ }
185
+ } catch {
186
+ // ignore malformed messages
187
+ }
188
+ };
189
+ });
190
+ }
191
+
192
+ subscribe(topic: string): void {
193
+ this.send({ type: "subscribe", topic, payload: null });
194
+ }
195
+
196
+ unsubscribe(topic: string): void {
197
+ this.send({ type: "unsubscribe", topic, payload: null });
198
+ }
199
+
200
+ onMessage(fn: MessageHandler): void {
201
+ this.handlers.push(fn);
202
+ }
203
+
204
+ close(): void {
205
+ this.ws?.close();
206
+ this.ws = undefined;
207
+ this.handlers = [];
208
+ }
209
+
210
+ private send(msg: WSMessage): void {
211
+ if (!this.ws) throw new Error("ws: not connected");
212
+ this.ws.send(JSON.stringify(msg));
213
+ }
214
+ }
@@ -0,0 +1,24 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { NoAuth } from './auth';
3
+
4
+ describe('NoAuth', () => {
5
+ it('inspect returns anonymous credential', async () => {
6
+ const auth = new NoAuth();
7
+ const cred = await auth.inspect();
8
+ expect(cred.source).toBe('none');
9
+ expect(cred.identity).toBe('anonymous');
10
+ expect(cred.scopes).toEqual([]);
11
+ expect(cred.renewable).toBe(false);
12
+ });
13
+
14
+ it('inspect returns no expiration', async () => {
15
+ const auth = new NoAuth();
16
+ const cred = await auth.inspect();
17
+ expect(cred.expiresAt).toBeUndefined();
18
+ });
19
+
20
+ it('refresh resolves without error', async () => {
21
+ const auth = new NoAuth();
22
+ await expect(auth.refresh()).resolves.toBeUndefined();
23
+ });
24
+ });
package/src/auth.ts ADDED
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @module auth
3
+ * @package @hop-top/kit
4
+ *
5
+ * Factor 12 — Auth and Credential Lifecycle.
6
+ *
7
+ * Provides introspection and refresh for credentials.
8
+ * NoAuth is the zero-value implementation.
9
+ */
10
+
11
+ export interface Credential {
12
+ source: string;
13
+ identity: string;
14
+ scopes: string[];
15
+ expiresAt?: string;
16
+ renewable: boolean;
17
+ }
18
+
19
+ export interface AuthIntrospector {
20
+ inspect(): Promise<Credential>;
21
+ refresh(): Promise<void>;
22
+ }
23
+
24
+ export class NoAuth implements AuthIntrospector {
25
+ async inspect(): Promise<Credential> {
26
+ return {
27
+ source: 'none',
28
+ identity: 'anonymous',
29
+ scopes: [],
30
+ renewable: false,
31
+ };
32
+ }
33
+
34
+ async refresh(): Promise<void> {
35
+ // no-op
36
+ }
37
+ }
@@ -0,0 +1,178 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ createBus,
4
+ createEvent,
5
+ MemoryAdapter,
6
+ type Adapter,
7
+ type Event,
8
+ type Bus,
9
+ } from "./bus";
10
+
11
+ describe("createEvent", () => {
12
+ it("sets topic, source, payload and timestamp", () => {
13
+ const before = new Date();
14
+ const e = createEvent("llm.request", "src", { model: "claude" });
15
+ const after = new Date();
16
+
17
+ expect(e.topic).toBe("llm.request");
18
+ expect(e.source).toBe("src");
19
+ expect(e.payload).toEqual({ model: "claude" });
20
+ expect(e.timestamp.getTime()).toBeGreaterThanOrEqual(before.getTime());
21
+ expect(e.timestamp.getTime()).toBeLessThanOrEqual(after.getTime());
22
+ });
23
+ });
24
+
25
+ describe("Bus", () => {
26
+ let bus: Bus;
27
+
28
+ it("delivers event to exact-match subscriber", () => {
29
+ bus = createBus();
30
+ const got: Event[] = [];
31
+ bus.subscribe("test.event", (e) => { got.push(e); });
32
+
33
+ const e = createEvent("test.event", "src", "hello");
34
+ bus.publish(e);
35
+
36
+ expect(got).toHaveLength(1);
37
+ expect(got[0].source).toBe("src");
38
+ });
39
+
40
+ it("does not deliver to non-matching subscriber", () => {
41
+ bus = createBus();
42
+ let called = false;
43
+ bus.subscribe("llm.request", () => { called = true; });
44
+
45
+ bus.publish(createEvent("llm.response", "src", null));
46
+ expect(called).toBe(false);
47
+ });
48
+
49
+ it("supports * wildcard matching one segment", () => {
50
+ bus = createBus();
51
+ const got: string[] = [];
52
+ bus.subscribe("llm.*", (e) => { got.push(e.topic); });
53
+
54
+ bus.publish(createEvent("llm.request", "src", null));
55
+ bus.publish(createEvent("llm.response", "src", null));
56
+ bus.publish(createEvent("llm.request.start", "src", null)); // too deep
57
+ bus.publish(createEvent("tool.exec", "src", null)); // wrong prefix
58
+
59
+ expect(got).toEqual(["llm.request", "llm.response"]);
60
+ });
61
+
62
+ it("supports * in any position", () => {
63
+ bus = createBus();
64
+ const got: string[] = [];
65
+ bus.subscribe("*.request", (e) => { got.push(e.topic); });
66
+
67
+ bus.publish(createEvent("llm.request", "src", null));
68
+ bus.publish(createEvent("tool.request", "src", null));
69
+ bus.publish(createEvent("llm.response", "src", null));
70
+
71
+ expect(got).toEqual(["llm.request", "tool.request"]);
72
+ });
73
+
74
+ it("supports # wildcard matching zero or more trailing segments", () => {
75
+ bus = createBus();
76
+ const got: string[] = [];
77
+ bus.subscribe("llm.#", (e) => { got.push(e.topic); });
78
+
79
+ bus.publish(createEvent("llm.request", "src", null));
80
+ bus.publish(createEvent("llm.request.start", "src", null));
81
+ bus.publish(createEvent("llm", "src", null));
82
+ bus.publish(createEvent("tool.exec", "src", null));
83
+
84
+ expect(got).toEqual(["llm.request", "llm.request.start", "llm"]);
85
+ });
86
+
87
+ it("# alone matches everything", () => {
88
+ bus = createBus();
89
+ const got: string[] = [];
90
+ bus.subscribe("#", (e) => { got.push(e.topic); });
91
+
92
+ bus.publish(createEvent("llm.request", "src", null));
93
+ bus.publish(createEvent("anything", "src", null));
94
+
95
+ expect(got).toEqual(["llm.request", "anything"]);
96
+ });
97
+
98
+ it("unsubscribe stops delivery", () => {
99
+ bus = createBus();
100
+ let count = 0;
101
+ const unsub = bus.subscribe("test.event", () => { count++; });
102
+
103
+ bus.publish(createEvent("test.event", "src", null));
104
+ expect(count).toBe(1);
105
+
106
+ unsub();
107
+ bus.publish(createEvent("test.event", "src", null));
108
+ expect(count).toBe(1);
109
+ });
110
+
111
+ it("multiple subscribers all receive events", () => {
112
+ bus = createBus();
113
+ let a = 0, b = 0;
114
+ bus.subscribe("test.event", () => { a++; });
115
+ bus.subscribe("test.event", () => { b++; });
116
+
117
+ bus.publish(createEvent("test.event", "src", null));
118
+ expect(a).toBe(1);
119
+ expect(b).toBe(1);
120
+ });
121
+
122
+ it("async handlers run via microtask", async () => {
123
+ bus = createBus();
124
+ let called = false;
125
+ bus.subscribe("test.event", async () => {
126
+ called = true;
127
+ });
128
+
129
+ bus.publish(createEvent("test.event", "src", null));
130
+ // async handler scheduled but not yet run
131
+ await Promise.resolve();
132
+ // after microtask flush
133
+ expect(called).toBe(true);
134
+ });
135
+
136
+ it("close prevents further publish", () => {
137
+ bus = createBus();
138
+ bus.close();
139
+ expect(() => {
140
+ bus.publish(createEvent("test", "src", null));
141
+ }).toThrow(/closed/);
142
+ });
143
+ });
144
+
145
+ describe("MemoryAdapter", () => {
146
+ it("implements Adapter interface directly", () => {
147
+ const adapter: Adapter = new MemoryAdapter();
148
+ const got: Event[] = [];
149
+ adapter.subscribe("test.event", (e) => { got.push(e); });
150
+
151
+ adapter.publish(createEvent("test.event", "src", "hello"));
152
+ expect(got).toHaveLength(1);
153
+ expect(got[0].source).toBe("src");
154
+ adapter.close();
155
+ });
156
+ });
157
+
158
+ describe("createBus with adapter", () => {
159
+ it("accepts a custom adapter", () => {
160
+ const adapter = new MemoryAdapter();
161
+ const bus = createBus(adapter);
162
+ const got: Event[] = [];
163
+ bus.subscribe("test.event", (e) => { got.push(e); });
164
+
165
+ bus.publish(createEvent("test.event", "src", "hello"));
166
+ expect(got).toHaveLength(1);
167
+ bus.close();
168
+ });
169
+
170
+ it("defaults to MemoryAdapter when no adapter given", () => {
171
+ const bus = createBus();
172
+ const got: Event[] = [];
173
+ bus.subscribe("x", (e) => { got.push(e); });
174
+ bus.publish(createEvent("x", "src", null));
175
+ expect(got).toHaveLength(1);
176
+ bus.close();
177
+ });
178
+ });