@open-wa/api 5.0.0 → 5.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.
Files changed (34) hide show
  1. package/dashboard-neo/dist/assets/{AgentScalarDrawer.vue-BGBDvSQB.js → AgentScalarDrawer.vue-Cly13x9l.js} +3 -3
  2. package/dashboard-neo/dist/assets/index-CP58_PDI.css +1 -0
  3. package/dashboard-neo/dist/assets/index-Dl0sJuu6.js +2162 -0
  4. package/dashboard-neo/dist/assets/{modal-CKSoZwLD.js → modal-BTlJ4pQT.js} +1 -1
  5. package/dashboard-neo/dist/index.html +2 -2
  6. package/dist/index.cjs +167 -8
  7. package/dist/index.d.cts +1 -0
  8. package/dist/index.d.cts.map +1 -1
  9. package/package.json +5 -4
  10. package/src/auth/api-key.ts +28 -0
  11. package/src/compat/args.ts +1 -0
  12. package/src/compat/deprecation.ts +35 -0
  13. package/src/compat/session-path.ts +19 -0
  14. package/src/createApiMiddleware.ts +184 -0
  15. package/src/createApiServer.ts +472 -0
  16. package/src/dashboard/middleware.ts +94 -0
  17. package/src/diagnostics/DiagnosticStore.ts +99 -0
  18. package/src/docs/openapi.ts +132 -0
  19. package/src/docs/postman.ts +42 -0
  20. package/src/events/EventBridge.ts +4 -0
  21. package/src/events/EventBroadcaster.ts +126 -0
  22. package/src/execution/kernel.ts +1 -0
  23. package/src/health/HealthStore.ts +252 -0
  24. package/src/index.ts +9 -0
  25. package/src/invoke-client-method.ts +1 -0
  26. package/src/middleware/rate-limit.ts +30 -0
  27. package/src/monitoring/elastic.ts +104 -0
  28. package/src/routes/agent-discovery.ts +150 -0
  29. package/src/routes/debug.ts +114 -0
  30. package/src/routes/meta.ts +512 -0
  31. package/src/types.ts +31 -0
  32. package/src/version.ts +4 -0
  33. package/dashboard-neo/dist/assets/index-DM5k7cbF.css +0 -1
  34. package/dashboard-neo/dist/assets/index-rjufqWkX.js +0 -2149
@@ -0,0 +1,472 @@
1
+ import { Hono } from 'hono';
2
+ import { cors } from 'hono/cors';
3
+ import { logger } from 'hono/logger';
4
+ import { createAdaptorServer, upgradeWebSocket } from '@hono/node-server';
5
+ import { createServer, type Server } from 'node:http';
6
+ import { WebSocketServer } from 'ws';
7
+ import { getHttpMethodDefinitions, type Config } from '@open-wa/schema';
8
+ import '@open-wa/schema';
9
+ import {
10
+ createScreencastRoute,
11
+ ScreencastManager,
12
+ } from '@open-wa/screencaster/server';
13
+ import { createApiMiddleware } from './createApiMiddleware';
14
+ import { createHonoMcpAdapter } from '@open-wa/mcp';
15
+ import { registerMetaRoutes } from './routes/meta';
16
+ import { registerDebugRoutes } from './routes/debug';
17
+ import { registerAgentDiscoveryRoutes } from './routes/agent-discovery';
18
+ import { type EventBridge } from './events/EventBridge';
19
+ import { HealthStore } from './health/HealthStore';
20
+ import { DiagnosticStore } from './diagnostics/DiagnosticStore';
21
+ import { API_VERSION } from './version';
22
+ import { EventBroadcaster } from './events/EventBroadcaster';
23
+ import { ElasticEmitter } from './monitoring/elastic';
24
+ import {
25
+ setupViteDevServer,
26
+ mountDashboardProduction,
27
+ } from './dashboard/middleware';
28
+ import type { ApiServerOptions, ClientMethodMap } from './types';
29
+ import type { IScreencastPage } from '@open-wa/screencaster/server';
30
+ import type { PluginHost } from '@open-wa/core';
31
+
32
+ function parseCorsOrigin(corsConfig: string | string[]): string | string[] {
33
+ if (corsConfig === '*') {
34
+ return '*';
35
+ }
36
+
37
+ if (Array.isArray(corsConfig)) {
38
+ return corsConfig;
39
+ }
40
+
41
+ if (typeof corsConfig === 'string' && corsConfig.includes(',')) {
42
+ return corsConfig.split(',').map((origin) => origin.trim());
43
+ }
44
+
45
+ return corsConfig;
46
+ }
47
+
48
+ export class ApiServer {
49
+ private app: Hono;
50
+ private config: Config;
51
+ private client: ClientMethodMap | undefined;
52
+ private elasticEmitter?: ElasticEmitter;
53
+ private latestQR: string | null = null;
54
+ private screencastManager: ScreencastManager;
55
+ private server?: Server;
56
+ private isDashboardActive: boolean = false;
57
+ private pluginHost?: PluginHost;
58
+ private healthStore: HealthStore = new HealthStore();
59
+ private diagnosticStore: DiagnosticStore = new DiagnosticStore();
60
+ private eventBroadcaster: EventBroadcaster;
61
+ private eventBridge?: EventBridge;
62
+ private eventBridgeListener?: (event: string, payload: any) => void;
63
+ private readinessProvider?: () =>
64
+ | {
65
+ state?: string;
66
+ status?: string;
67
+ ready: boolean;
68
+ exposureSafe?: boolean;
69
+ pending?: string[];
70
+ blockers?: string[];
71
+ }
72
+ | undefined;
73
+
74
+ constructor(options: ApiServerOptions) {
75
+ this.config = options.config;
76
+
77
+ // Validate MCP configuration
78
+ if (this.config.mcp?.enabled && !this.config.apiKey) {
79
+ throw new Error(
80
+ 'MCP requires Easy API apiKey. Refusing to start with MCP enabled and no apiKey configured.',
81
+ );
82
+ }
83
+
84
+ this.app = new Hono();
85
+ this.screencastManager = new ScreencastManager();
86
+ this.eventBroadcaster = new EventBroadcaster(this.config.sessionId);
87
+
88
+ if (this.config.elasticUrl) {
89
+ this.elasticEmitter = new ElasticEmitter({
90
+ url: this.config.elasticUrl,
91
+ username: this.config.elasticUsername,
92
+ password: this.config.elasticPassword,
93
+ bufferSize: this.config.elasticBufferSize,
94
+ pipeline: this.config.elasticPipeline,
95
+ indexPrefix: this.config.elasticIndexPrefix,
96
+ });
97
+ }
98
+
99
+ this.setupMiddleware();
100
+ this.registerRoutes();
101
+
102
+ // Register screencast WebSocket route
103
+ this.app.get(
104
+ '/screencast',
105
+ createScreencastRoute(upgradeWebSocket, this.screencastManager),
106
+ );
107
+ }
108
+
109
+ public setClient(client: ClientMethodMap | undefined) {
110
+ this.client = client;
111
+ }
112
+
113
+ public setEventBridge(bridge: EventBridge) {
114
+ if (this.eventBridge && this.eventBridgeListener) {
115
+ this.eventBridge.offAny(this.eventBridgeListener);
116
+ }
117
+
118
+ this.eventBridge = bridge;
119
+ this.eventBridgeListener = (event: string, payload: any) => {
120
+ this.healthStore.processEvent(event, payload);
121
+ this.diagnosticStore.capture(event, payload);
122
+ this.eventBroadcaster.broadcast(event, payload);
123
+ };
124
+
125
+ // Also wire events into the HealthStore so /health returns accumulated data
126
+ bridge.onAny(this.eventBridgeListener);
127
+ this.diagnosticStore.attach();
128
+ }
129
+
130
+ public setReadinessProvider(
131
+ provider:
132
+ | (() =>
133
+ | {
134
+ state?: string;
135
+ status?: string;
136
+ ready: boolean;
137
+ exposureSafe?: boolean;
138
+ pending?: string[];
139
+ blockers?: string[];
140
+ }
141
+ | undefined)
142
+ | undefined,
143
+ ) {
144
+ this.readinessProvider = provider;
145
+ }
146
+
147
+ /**
148
+ * Bind a CDP-capable page for screencasting.
149
+ * Call this once the browser page is ready.
150
+ */
151
+ public async setPage(page: IScreencastPage): Promise<void> {
152
+ await this.screencastManager.setPage(page);
153
+ }
154
+
155
+ /**
156
+ * Unbind the screencaster page (session ended).
157
+ */
158
+ public async clearPage(): Promise<void> {
159
+ await this.screencastManager.clearPage();
160
+ }
161
+
162
+ public setQR(qr: string) {
163
+ this.latestQR = qr;
164
+ }
165
+
166
+ public getApp() {
167
+ return this.app;
168
+ }
169
+
170
+ public getEventBroadcaster() {
171
+ return this.eventBroadcaster;
172
+ }
173
+
174
+ /**
175
+ * Mount plugin routes and manifest endpoint.
176
+ * Call this after the PluginHost has all plugins registered.
177
+ */
178
+ public mountPlugins(pluginHost: PluginHost): void {
179
+ this.pluginHost = pluginHost;
180
+
181
+ // Mount each plugin's routes at /plugins/<name>/
182
+ for (const { name, router } of pluginHost.getRoutes()) {
183
+ this.app.route(`/plugins/${name}`, router);
184
+ }
185
+ }
186
+
187
+ public async start() {
188
+ let viteDevServer: any = null;
189
+ if (this.config.dashboard) {
190
+ viteDevServer = await setupViteDevServer();
191
+ if (!viteDevServer) {
192
+ this.isDashboardActive = await mountDashboardProduction(this.app);
193
+ } else {
194
+ this.isDashboardActive = true;
195
+ }
196
+ }
197
+
198
+ const server = createAdaptorServer({
199
+ fetch: this.app.fetch,
200
+ websocket: {
201
+ server: new WebSocketServer({ noServer: true }),
202
+ },
203
+ createServer: (options, honoListener) =>
204
+ createServer(options, (request, response) => {
205
+ if (viteDevServer && request.url?.startsWith('/dashboard')) {
206
+ viteDevServer.middlewares(request, response, () => {
207
+ void honoListener(request, response);
208
+ });
209
+ return;
210
+ }
211
+ void honoListener(request, response);
212
+ }),
213
+ });
214
+ this.server = server as Server;
215
+
216
+ await new Promise<void>((resolve, reject) => {
217
+ const onError = (error: Error) => {
218
+ server.off('error', onError);
219
+ reject(error);
220
+ };
221
+ server.once('error', onError);
222
+ server.listen(this.config.port, this.config.host, () => {
223
+ server.off('error', onError);
224
+ console.log(
225
+ `Server running on http://${this.config.host}:${this.config.port}`,
226
+ );
227
+ resolve();
228
+ });
229
+ });
230
+
231
+ if (this.elasticEmitter) {
232
+ await this.elasticEmitter.start();
233
+ }
234
+ }
235
+
236
+ public async stop() {
237
+ const server = this.server;
238
+ this.server = undefined;
239
+ if (server?.listening) {
240
+ await new Promise<void>((resolve, reject) => {
241
+ server.close((error) => (error ? reject(error) : resolve()));
242
+ });
243
+ }
244
+ await this.screencastManager.destroy();
245
+ if (this.elasticEmitter) {
246
+ await this.elasticEmitter.stop();
247
+ }
248
+ }
249
+
250
+ public isDashboardRunning() {
251
+ return this.isDashboardActive;
252
+ }
253
+
254
+ private isSessionConnected() {
255
+ const readiness = this.readinessProvider?.();
256
+ if (readiness) {
257
+ return readiness.ready;
258
+ }
259
+
260
+ if (!this.client) {
261
+ return false;
262
+ }
263
+
264
+ return typeof this.client.isConnected === 'function'
265
+ ? this.client.isConnected()
266
+ : false;
267
+ }
268
+
269
+ private setupMiddleware() {
270
+ this.app.use(
271
+ '/*',
272
+ cors({
273
+ origin: parseCorsOrigin(this.config.cors),
274
+ credentials: true,
275
+ }),
276
+ );
277
+
278
+ this.app.use('/*', async (c, next) => {
279
+ const path = new URL(c.req.url).pathname;
280
+ if (path === '/' || path.startsWith('/dashboard')) {
281
+ c.header(
282
+ 'Link',
283
+ [
284
+ `</.well-known/api-catalog>; rel="api-catalog"`,
285
+ `</.well-known/mcp/server-card.json>; rel="mcp"`,
286
+ `</.well-known/agent-card.json>; rel="describedby"`,
287
+ ].join(', '),
288
+ );
289
+ }
290
+
291
+ if (
292
+ path === '/' &&
293
+ (c.req.header('Accept') || '').includes('text/markdown')
294
+ ) {
295
+ const origin = new URL(c.req.url).origin;
296
+ c.header('Content-Type', 'text/markdown');
297
+ return c.text(
298
+ `# Open-WA Easy API\n\nThis is an Agent-Native API endpoint.\n\n## API Catalog\nExplore endpoints at \`${origin}/.well-known/api-catalog\` and docs at \`${origin}/api-docs\`.\n\n## MCP Endpoint\nAn MCP server is running for agents at \`${origin}/mcp\`.\n`,
299
+ );
300
+ }
301
+ await next();
302
+ });
303
+
304
+ if (this.config.logLevel !== 'silent') {
305
+ this.app.use('*', logger());
306
+ }
307
+ }
308
+
309
+ private registerRoutes() {
310
+ const methodDefinitions = getHttpMethodDefinitions();
311
+ registerAgentDiscoveryRoutes(this.app, {
312
+ config: this.config,
313
+ methodDefinitions,
314
+ });
315
+
316
+ this.app.get('/plugins/manifest', (c) =>
317
+ c.json(this.pluginHost?.getManifest() ?? { plugins: [] }),
318
+ );
319
+
320
+ this.app.get('/health', (c) => {
321
+ const healthSnapshot = this.healthStore.getSnapshot();
322
+ return c.json({
323
+ status: 'ok',
324
+ version: API_VERSION,
325
+ host: {
326
+ available: true,
327
+ api: true,
328
+ dashboard: {
329
+ enabled: this.config.dashboard,
330
+ running: this.isDashboardRunning(),
331
+ port: this.config.dashboardPort,
332
+ },
333
+ mcp: {
334
+ enabled: Boolean(this.config.mcp?.enabled),
335
+ available: Boolean(this.config.apiKey && this.config.mcp?.enabled),
336
+ path: this.config.mcp?.path || '/mcp',
337
+ },
338
+ },
339
+ capabilities: {
340
+ apiKeyConfigured: Boolean(this.config.apiKey),
341
+ mcpEnabled: Boolean(this.config.mcp?.enabled),
342
+ mcpAvailable: Boolean(this.config.apiKey && this.config.mcp?.enabled),
343
+ mcpPath: this.config.mcp?.path || '/mcp',
344
+ },
345
+ connected: this.isSessionConnected(),
346
+ session: this.readinessProvider?.() ?? {
347
+ ready: false,
348
+ status: this.client ? 'legacy' : 'unavailable',
349
+ state: this.client ? 'UNKNOWN' : 'DISCONNECTED',
350
+ pending: this.client
351
+ ? ['session_readiness_unavailable']
352
+ : ['client_not_bound'],
353
+ blockers: [],
354
+ exposureSafe: false,
355
+ },
356
+ // QR code for pre-launch scanning
357
+ qr: this.latestQR ?? null,
358
+ // Accumulated health data for the dashboard
359
+ launchTimeline: healthSnapshot.launchTimeline,
360
+ patches: healthSnapshot.patches,
361
+ license: healthSnapshot.license,
362
+ reconnections: healthSnapshot.reconnections,
363
+ startedAt: healthSnapshot.startedAt,
364
+ lastEventAt: healthSnapshot.lastEventAt,
365
+ });
366
+ });
367
+
368
+ this.app.get('/qr', (c) => {
369
+ if (!this.config.ezqr) {
370
+ return c.json({ error: 'QR endpoint disabled' }, 404);
371
+ }
372
+
373
+ if (!this.latestQR) {
374
+ return c.json(
375
+ {
376
+ error: 'QR code not available',
377
+ note: 'Session might be connected or generating QR',
378
+ },
379
+ 404,
380
+ );
381
+ }
382
+
383
+ return c.json({
384
+ qr: this.latestQR,
385
+ note: 'Scan this QR code in WhatsApp',
386
+ });
387
+ });
388
+
389
+ this.app.get('/api/events', (c) => {
390
+ // TODO: Unify this inline auth check with the shared apiKeyMiddleware used across Easy API.
391
+ // Note: This intentionally supports query params to preserve legacy Easy API behavior,
392
+ // unlike the MCP adapter which strictly enforces header-only auth (X-API-Key) for security.
393
+ if (this.config.apiKey) {
394
+ const apiKey =
395
+ c.req.header('X-API-Key') ||
396
+ c.req.query('api_key') ||
397
+ c.req.query('key');
398
+
399
+ if (!apiKey || apiKey !== this.config.apiKey) {
400
+ return c.json(
401
+ { error: 'Unauthorized', details: 'Invalid or missing API key' },
402
+ 401,
403
+ );
404
+ }
405
+ }
406
+
407
+ const topicsParam = c.req.query('topics');
408
+ const topics = topicsParam
409
+ ? topicsParam
410
+ .split(',')
411
+ .map((topic) => topic.trim())
412
+ .filter(Boolean)
413
+ : ['*'];
414
+
415
+ return new Response(
416
+ this.eventBroadcaster.createStream({
417
+ signal: c.req.raw.signal,
418
+ topics,
419
+ }),
420
+ {
421
+ headers: {
422
+ 'Cache-Control': 'no-cache, no-transform',
423
+ Connection: 'keep-alive',
424
+ 'Content-Type': 'text/event-stream',
425
+ 'X-Accel-Buffering': 'no',
426
+ },
427
+ },
428
+ );
429
+ });
430
+
431
+ registerMetaRoutes(this.app, {
432
+ config: this.config,
433
+ methodDefinitions,
434
+ });
435
+
436
+ registerDebugRoutes(this.app, {
437
+ config: this.config,
438
+ getConfig: () => this.config,
439
+ getDiagnostics: () => this.diagnosticStore.getSnapshot(),
440
+ setIntegration: (id, data) => {
441
+ if (!this.config.integrations) {
442
+ this.config.integrations = {};
443
+ }
444
+ this.config.integrations[id] = data;
445
+ },
446
+ });
447
+ this.app.route(
448
+ '/api',
449
+ createApiMiddleware(() => this.client, {
450
+ config: this.config,
451
+ basePath: '/api',
452
+ elasticEmitter: this.elasticEmitter,
453
+ isSessionConnected: () => this.isSessionConnected(),
454
+ }),
455
+ );
456
+
457
+ if (this.config.mcp?.enabled) {
458
+ const mcpAdapter = createHonoMcpAdapter({
459
+ config: this.config,
460
+ clientSource: () => this.client,
461
+ elasticEmitter: this.elasticEmitter,
462
+ basePath: '/api',
463
+ isSessionConnected: () => this.isSessionConnected(),
464
+ });
465
+ mcpAdapter.mount(this.app, this.config.mcp.path || '/mcp');
466
+ }
467
+ }
468
+ }
469
+
470
+ export function createApiServer(config: Config) {
471
+ return new ApiServer({ config });
472
+ }
@@ -0,0 +1,94 @@
1
+ import { resolve, dirname } from 'path';
2
+ import { existsSync, readFileSync } from 'fs';
3
+ import type { Hono } from 'hono';
4
+ import { serveStatic } from '@hono/node-server/serve-static';
5
+ export function findDashboardDir(): string | null {
6
+ const monorepoCandidates = [
7
+ resolve(__dirname, '../../../apps/dashboard-neo'),
8
+ resolve(__dirname, '../../../../apps/dashboard-neo'),
9
+ ];
10
+
11
+ const monorepoPath = monorepoCandidates.find((candidate) => existsSync(resolve(candidate, 'package.json')));
12
+ if (monorepoPath) {
13
+ return monorepoPath;
14
+ }
15
+
16
+ const embeddedCandidates = [
17
+ resolve(__dirname, '../dashboard-neo'),
18
+ resolve(__dirname, 'dashboard-neo'),
19
+ ];
20
+ const embeddedPath = embeddedCandidates.find((candidate) => existsSync(resolve(candidate, 'dist/index.html')));
21
+ if (embeddedPath) {
22
+ return embeddedPath;
23
+ }
24
+
25
+ try {
26
+ const pkgPath = require.resolve('@open-wa/dashboard-neo/package.json');
27
+ return dirname(pkgPath);
28
+ } catch {
29
+ // Not installed
30
+ }
31
+
32
+ return null;
33
+ }
34
+
35
+
36
+ export async function setupViteDevServer(): Promise<any | null> {
37
+ const dashboardDir = findDashboardDir();
38
+ if (!dashboardDir) return null;
39
+
40
+ const isProd = process.env.NODE_ENV === 'production' || !existsSync(resolve(dashboardDir, 'vite.config.ts'));
41
+ if (isProd) return null;
42
+
43
+ try {
44
+ const vite = await import('vite');
45
+ const viteServer = await vite.createServer({
46
+ root: dashboardDir,
47
+ server: { middlewareMode: true },
48
+ appType: 'spa',
49
+ base: '/dashboard/',
50
+ });
51
+ console.log(`\n🚀 Dashboard mounted at /dashboard/ (Vite dev middleware)\n`);
52
+ return viteServer;
53
+ } catch (e: any) {
54
+ console.warn(`[dashboard] Failed to mount Vite middleware: ${e.message}`);
55
+ return null;
56
+ }
57
+ }
58
+
59
+ export async function mountDashboardProduction(app: Hono): Promise<boolean> {
60
+ const dashboardDir = findDashboardDir();
61
+ if (!dashboardDir) return false;
62
+ const distPath = resolve(dashboardDir, 'dist');
63
+ if (existsSync(distPath)) {
64
+ // Determine the root for serveStatic relative to process.cwd, or just use absolute?
65
+ // serveStatic usually looks at relative paths from process.cwd() unless configured.
66
+ // wait, @hono/node-server/serve-static `root` defaults to "./".
67
+ // It's safer to use a custom middleware to read the files, or pass absolute path directly if supported.
68
+ app.use('/dashboard/*', serveStatic({
69
+ root: distPath,
70
+ rewriteRequestPath: (path) => path.replace(/^\/dashboard/, '')
71
+ }));
72
+
73
+ // Fallback for SPA
74
+ app.get('/dashboard/*', (c) => {
75
+ const accept = c.req.header('Accept') || '';
76
+ if (accept.includes('text/markdown')) {
77
+ const origin = new URL(c.req.url).origin;
78
+ c.header('Content-Type', 'text/markdown');
79
+ return c.text(`# Open-WA Dashboard\n\nThe dashboard UI is a Single Page Application.\n\n## Developer API\nThe Easy API is available at \`${origin}/api\`.\nRefer to \`${origin}/api-docs\` for more details.\n\n## MCP Server\nThe local MCP server is running and discoverable. Check \`${origin}/.well-known/mcp/server-card.json\` for constraints.`);
80
+ }
81
+
82
+ const indexPath = resolve(distPath, 'index.html');
83
+ if (existsSync(indexPath)) {
84
+ return c.html(readFileSync(indexPath, 'utf-8'));
85
+ }
86
+ return c.notFound();
87
+ });
88
+
89
+ console.log(`\n🚀 Dashboard mounted at /dashboard/ (Production static)\n`);
90
+ return true;
91
+ }
92
+
93
+ return false;
94
+ }
@@ -0,0 +1,99 @@
1
+ export type ServerDiagnosticRecord = {
2
+ id: number;
3
+ event: string;
4
+ timestamp: number;
5
+ message: string;
6
+ stack: string | null;
7
+ scope: string | null;
8
+ method: string | null;
9
+ route: string | null;
10
+ component: string | null;
11
+ };
12
+
13
+ const MAX_RECORDS = 100;
14
+ const MAX_TEXT = 8_000;
15
+
16
+ function text(value: unknown, limit = 500): string | null {
17
+ if (typeof value !== 'string' || !value.trim()) return null;
18
+ const clean = value.trim();
19
+ if (clean.length <= limit) return clean;
20
+ const notice = `\n[truncated at ${limit} characters]`;
21
+ return `${clean.slice(0, limit - notice.length)}${notice}`;
22
+ }
23
+
24
+ function unwrap(payload: unknown): Record<string, unknown> {
25
+ if (!payload || typeof payload !== 'object') return {};
26
+ const record = payload as Record<string, unknown>;
27
+ const nested = record.details ?? record.ctx ?? record.payload;
28
+ return nested && typeof nested === 'object' ? nested as Record<string, unknown> : record;
29
+ }
30
+
31
+ function isErrorEvent(event: string, payload: unknown) {
32
+ const outer = payload && typeof payload === 'object' ? payload as Record<string, unknown> : {};
33
+ const nested = unwrap(payload);
34
+ const records = outer === nested ? [outer] : [outer, nested];
35
+ const levels = records.map((record) => String(record.level ?? record.severity ?? record.type ?? record.kind ?? '').toLowerCase());
36
+ if (records.some((record) => record.warning === true) || levels.some((level) => ['warn', 'warning', 'info', 'debug', 'trace', 'verbose'].includes(level))) return false;
37
+ if (event === 'error') return true;
38
+ const nestedError = nested.error && typeof nested.error === 'object'
39
+ ? nested.error as Record<string, unknown>
40
+ : null;
41
+ return event === 'debug:log' && (
42
+ levels.some((level) => level === 'error' || level === 'fatal')
43
+ || payload instanceof Error
44
+ || records.some((record) => record.error instanceof Error)
45
+ || Boolean(nestedError && (typeof nestedError.message === 'string' || typeof nestedError.stack === 'string'))
46
+ || records.some((record) => Boolean(record.stack) && record.fatal !== false)
47
+ );
48
+ }
49
+
50
+ /** Holds structured runtime errors observed on this API server's event bridge. */
51
+ export class DiagnosticStore {
52
+ private nextId = 0;
53
+ private records: ServerDiagnosticRecord[] = [];
54
+ private attached = false;
55
+
56
+ attach() {
57
+ this.attached = true;
58
+ }
59
+
60
+ capture(event: string, payload: unknown) {
61
+ if (!isErrorEvent(event, payload)) return;
62
+ const outer = payload && typeof payload === 'object' ? payload as Record<string, unknown> : {};
63
+ const record = unwrap(payload);
64
+ const error = record.error instanceof Error
65
+ ? record.error
66
+ : outer.error instanceof Error
67
+ ? outer.error
68
+ : null;
69
+ const errorRecord = record.error && typeof record.error === 'object'
70
+ ? record.error as Record<string, unknown>
71
+ : {};
72
+ const stackValue = error?.stack ?? errorRecord.stack ?? record.stack ?? record.trace;
73
+ const message = text(error?.message ?? errorRecord.message ?? record.message ?? record.msg ?? (typeof record.error === 'string' ? record.error : undefined) ?? (event === 'error' && typeof payload === 'string' ? payload : undefined), 1_500)
74
+ ?? text(typeof stackValue === 'string' ? stackValue.split(/\r?\n/, 1)[0] : null, 1_500);
75
+ if (!message) return;
76
+ const stack = text(stackValue, MAX_TEXT);
77
+ this.records.push({
78
+ id: ++this.nextId,
79
+ event,
80
+ timestamp: Date.now(),
81
+ message,
82
+ stack,
83
+ scope: text(record.scope ?? record.name, 240),
84
+ method: text(record.method ?? record.operation, 240),
85
+ route: text(record.route ?? record.path ?? record.endpoint, 240),
86
+ component: text(record.component ?? record.source ?? record.module, 240),
87
+ });
88
+ if (this.records.length > MAX_RECORDS) this.records.splice(0, this.records.length - MAX_RECORDS);
89
+ }
90
+
91
+ getSnapshot() {
92
+ return {
93
+ available: this.attached,
94
+ captureSource: 'session event bridge' as const,
95
+ captureLimit: MAX_RECORDS,
96
+ records: this.records.slice(),
97
+ };
98
+ }
99
+ }