@open-wa/api 5.0.0-alpha.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.
package/dist/index.cjs ADDED
@@ -0,0 +1,1545 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let hono = require("hono");
3
+ let hono_cors = require("hono/cors");
4
+ let hono_logger = require("hono/logger");
5
+ let _hono_node_server = require("@hono/node-server");
6
+ let http = require("http");
7
+ let _hono_node_ws = require("@hono/node-ws");
8
+ let _open_wa_schema = require("@open-wa/schema");
9
+ let _open_wa_screencaster_server = require("@open-wa/screencaster/server");
10
+ require("@open-wa/schema/methods");
11
+ let _open_wa_mcp = require("@open-wa/mcp");
12
+ let _elastic_elasticsearch = require("@elastic/elasticsearch");
13
+ let path = require("path");
14
+ let fs = require("fs");
15
+ let _hono_node_server_serve_static = require("@hono/node-server/serve-static");
16
+ //#region src/compat/deprecation.ts
17
+ function applyDeprecationHeaders(c, notice) {
18
+ const parts = [notice.message];
19
+ if (notice.replacement) parts.push(`Use ${notice.replacement} instead.`);
20
+ c.header("X-OpenWA-Deprecated", notice.route);
21
+ c.header("Warning", `299 open-wa "${parts.join(" ")}"`);
22
+ }
23
+ function deprecatedJson(c, notice, status = 200, extra = {}) {
24
+ applyDeprecationHeaders(c, notice);
25
+ return c.json({
26
+ deprecated: true,
27
+ route: notice.route,
28
+ message: notice.message,
29
+ replacement: notice.replacement,
30
+ ...extra
31
+ }, status);
32
+ }
33
+ //#endregion
34
+ //#region src/auth/api-key.ts
35
+ function apiKeyMiddleware(apiKey) {
36
+ return async (c, next) => {
37
+ const queryKey = c.req.query("api_key") || c.req.query("key");
38
+ const headerKey = c.req.header("X-API-Key") || c.req.header("api_key") || c.req.header("key");
39
+ const resolvedKey = queryKey || headerKey;
40
+ if (c.req.query("api_key") || c.req.query("key") || c.req.header("api_key") || c.req.header("key")) applyDeprecationHeaders(c, {
41
+ route: "legacy-api-key-alias",
42
+ message: "Legacy API key aliases are deprecated.",
43
+ replacement: "X-API-Key header"
44
+ });
45
+ if (!resolvedKey || resolvedKey !== apiKey) return c.json({
46
+ error: "Unauthorized",
47
+ details: "Invalid or missing API key"
48
+ }, 401);
49
+ return await next();
50
+ };
51
+ }
52
+ //#endregion
53
+ //#region src/middleware/rate-limit.ts
54
+ const requests = /* @__PURE__ */ new Map();
55
+ function getRequestKey(c) {
56
+ const forwarded = c.req.header("x-forwarded-for");
57
+ if (forwarded) return forwarded.split(",")[0].trim();
58
+ return c.req.header("x-real-ip") || "unknown";
59
+ }
60
+ function rateLimitMiddleware(maxRequests = 100, windowMs = 6e4) {
61
+ return async (c, next) => {
62
+ const requestKey = getRequestKey(c);
63
+ const now = Date.now();
64
+ const recentRequests = (requests.get(requestKey) || []).filter((time) => now - time < windowMs);
65
+ if (recentRequests.length >= maxRequests) return c.json({
66
+ error: "Too Many Requests",
67
+ details: "Rate limit exceeded"
68
+ }, 429);
69
+ recentRequests.push(now);
70
+ requests.set(requestKey, recentRequests);
71
+ return await next();
72
+ };
73
+ }
74
+ //#endregion
75
+ //#region src/compat/session-path.ts
76
+ function assertSessionPath(expectedSessionId, requestedSessionId, useSessionIdInPath) {
77
+ if (!useSessionIdInPath) return { ok: true };
78
+ if (!requestedSessionId) return {
79
+ ok: false,
80
+ status: 404,
81
+ error: "Session id missing from request path"
82
+ };
83
+ if (requestedSessionId !== expectedSessionId) return {
84
+ ok: false,
85
+ status: 404,
86
+ error: `Unknown session path: ${requestedSessionId}`
87
+ };
88
+ return { ok: true };
89
+ }
90
+ //#endregion
91
+ //#region src/createApiMiddleware.ts
92
+ function resolveClient(clientSource) {
93
+ return typeof clientSource === "function" ? clientSource() : clientSource;
94
+ }
95
+ async function readRequestBody(c) {
96
+ try {
97
+ return await c.req.json();
98
+ } catch {
99
+ return {};
100
+ }
101
+ }
102
+ function readQueryParams(c) {
103
+ const url = new URL(c.req.url);
104
+ return Object.fromEntries(url.searchParams.entries());
105
+ }
106
+ function toLocalPath(path, basePath) {
107
+ const normalizedBase = basePath === "/" ? "" : basePath.replace(/\/+$/, "");
108
+ if (!normalizedBase) return path || "/";
109
+ if (!path.startsWith(normalizedBase)) return path || "/";
110
+ const stripped = path.slice(normalizedBase.length);
111
+ return stripped.startsWith("/") ? stripped : `/${stripped}`;
112
+ }
113
+ function createMethodMap(methodDefinitions) {
114
+ const entries = [];
115
+ for (const definition of methodDefinitions) for (const name of definition.invocationNames) entries.push([name, definition]);
116
+ return new Map(entries);
117
+ }
118
+ function shouldBlockForLifecycle(options) {
119
+ if (!options.isSessionConnected) return false;
120
+ if (options.config.apiLifecycle === "immediate") return false;
121
+ return !options.isSessionConnected();
122
+ }
123
+ function createApiMiddleware(clientSource, options) {
124
+ const app = new hono.Hono();
125
+ const basePath = options.basePath || "/api";
126
+ const methodDefinitions = options.methodDefinitions || (0, _open_wa_schema.getHttpMethodDefinitions)(basePath);
127
+ const methods = createMethodMap(methodDefinitions);
128
+ const useSessionIdInPath = options.useSessionIdInPath || false;
129
+ app.use("/*", rateLimitMiddleware(100, 6e4));
130
+ if (options.config.apiKey) app.use("/*", apiKeyMiddleware(options.config.apiKey));
131
+ const handleInvocation = async (c, routeMethod, routeSessionId, routeDefinition) => {
132
+ if (shouldBlockForLifecycle(options)) return c.json({
133
+ error: "API not available until the session is truly ready",
134
+ status: 503
135
+ }, 503);
136
+ const sessionCheck = assertSessionPath(options.config.sessionId, routeSessionId, useSessionIdInPath);
137
+ if (!sessionCheck.ok) return c.json({ error: sessionCheck.error }, sessionCheck.status);
138
+ const query = readQueryParams(c);
139
+ const payload = {
140
+ ...c.req.method === "GET" || c.req.method === "DELETE" ? {} : await readRequestBody(c),
141
+ ...query
142
+ };
143
+ const methodName = routeMethod || routeDefinition?.functionName || (typeof payload.method === "string" ? payload.method : void 0);
144
+ if (!methodName) return c.json({ error: "Missing method name" }, 400);
145
+ const definition = routeDefinition || methods.get(methodName);
146
+ if (!definition) return c.json({ error: `Unknown method: ${methodName}` }, 404);
147
+ const result = await (0, _open_wa_mcp.executeCapability)({
148
+ client: resolveClient(clientSource),
149
+ definition,
150
+ payload,
151
+ elasticEmitter: options.elasticEmitter,
152
+ sessionId: options.config.sessionId
153
+ });
154
+ if (result.success) return c.json({
155
+ success: true,
156
+ data: result.data
157
+ });
158
+ return c.json({
159
+ error: result.error,
160
+ details: result.details
161
+ }, result.status);
162
+ };
163
+ const redirectToCanonical = (definition, c) => {
164
+ c.header("X-OpenWA-Aliases", definition.routeSignatures.join(", "));
165
+ const query = new URL(c.req.url).search;
166
+ return c.redirect(`${definition.path}${query}`, 308);
167
+ };
168
+ for (const definition of methodDefinitions) {
169
+ const localCanonicalPath = toLocalPath(definition.path, basePath);
170
+ app.on(definition.httpMethod, localCanonicalPath, (c) => handleInvocation(c, definition.functionName, void 0, definition));
171
+ for (const aliasRoute of definition.aliasRoutes) {
172
+ const localAliasPath = toLocalPath(aliasRoute.path, basePath);
173
+ app.on(definition.httpMethod, localAliasPath, (c) => redirectToCanonical(definition, c));
174
+ }
175
+ }
176
+ app.post("/", (c) => handleInvocation(c, void 0));
177
+ app.post("/:method", (c) => handleInvocation(c, c.req.param("method")));
178
+ app.post("/:namespace/:method", (c) => handleInvocation(c, `${c.req.param("namespace")}.${c.req.param("method")}`));
179
+ if (useSessionIdInPath) {
180
+ app.post("/:sessionId", (c) => handleInvocation(c, void 0, c.req.param("sessionId")));
181
+ app.post("/:sessionId/:method", (c) => handleInvocation(c, c.req.param("method"), c.req.param("sessionId")));
182
+ app.post("/:sessionId/:namespace/:method", (c) => handleInvocation(c, `${c.req.param("namespace")}.${c.req.param("method")}`, c.req.param("sessionId")));
183
+ }
184
+ app.get("/", (c) => c.json({ endpoints: methodDefinitions.map((def) => ({
185
+ method: def.httpMethod,
186
+ path: def.path,
187
+ name: def.functionName,
188
+ namespacedName: def.namespacedName,
189
+ description: def.description,
190
+ category: def.namespace,
191
+ aliases: def.aliases,
192
+ routeSignatures: def.routeSignatures
193
+ })) }));
194
+ return app;
195
+ }
196
+ //#endregion
197
+ //#region src/docs/openapi.ts
198
+ function schemaToOpenApi(schema) {
199
+ if (typeof schema?.toJSONSchema === "function") return schema.toJSONSchema({ target: "openapi-3.0" });
200
+ return {
201
+ type: "object",
202
+ additionalProperties: true
203
+ };
204
+ }
205
+ function buildQueryParameters(def) {
206
+ const inputSchema = schemaToOpenApi(def.inputSchema);
207
+ const properties = inputSchema.properties ?? {};
208
+ const required = new Set(inputSchema.required ?? []);
209
+ return def.parameterOrder.map((name) => ({
210
+ name,
211
+ in: "query",
212
+ required: required.has(name),
213
+ description: properties[name]?.description || `Argument: ${name}`,
214
+ schema: properties[name] || { type: "string" }
215
+ }));
216
+ }
217
+ function createOpenApiDocument(methodDefinitions, options) {
218
+ const paths = Object.fromEntries(methodDefinitions.map((def) => [def.path, { [def.httpMethod.toLowerCase()]: {
219
+ summary: def.description,
220
+ operationId: def.functionName,
221
+ tags: [def.namespace],
222
+ ...def.httpMethod === "GET" || def.httpMethod === "DELETE" ? { parameters: buildQueryParameters(def) } : { requestBody: {
223
+ required: def.parameterOrder.length > 0,
224
+ content: { "application/json": { schema: schemaToOpenApi(def.inputSchema) } }
225
+ } },
226
+ "x-openwa-aliases": def.routeSignatures.filter((signature) => signature !== `${def.httpMethod} ${def.path}`),
227
+ responses: { "200": {
228
+ description: "Successful response",
229
+ content: { "application/json": { schema: schemaToOpenApi(def.outputSchema) } }
230
+ } }
231
+ } }]));
232
+ return {
233
+ openapi: "3.0.3",
234
+ info: {
235
+ title: options.title || "open-wa Easy API",
236
+ version: options.version || "5.0.0"
237
+ },
238
+ servers: [{ url: options.origin }],
239
+ paths
240
+ };
241
+ }
242
+ //#endregion
243
+ //#region src/docs/postman.ts
244
+ function createPostmanCollection(methodDefinitions, options) {
245
+ const basePath = options.basePath || "/api";
246
+ return {
247
+ info: {
248
+ name: options.name || "open-wa Easy API",
249
+ schema: "https://schema.getpostman.com/json/collection/v2.1.0/collection.json"
250
+ },
251
+ variable: [{
252
+ key: "baseUrl",
253
+ value: `${options.origin}${basePath}`.replace(/\/api\/api$/, "/api")
254
+ }],
255
+ item: methodDefinitions.map((def) => ({
256
+ name: def.functionName,
257
+ request: {
258
+ method: "POST",
259
+ header: [{
260
+ key: "Content-Type",
261
+ value: "application/json"
262
+ }],
263
+ url: {
264
+ raw: `{{baseUrl}}/${def.functionName}`,
265
+ host: ["{{baseUrl}}"],
266
+ path: [def.functionName]
267
+ },
268
+ body: {
269
+ mode: "raw",
270
+ raw: JSON.stringify(Object.fromEntries(def.parameterOrder.map((name) => [name, `<${name}>`])), null, 2)
271
+ },
272
+ description: def.description
273
+ }
274
+ }))
275
+ };
276
+ }
277
+ //#endregion
278
+ //#region src/routes/meta.ts
279
+ function joinPath$1(...parts) {
280
+ const normalized = parts.filter(Boolean).map((part, index) => {
281
+ if (index === 0) return part.replace(/\/+$/, "");
282
+ return part.replace(/^\/+/, "").replace(/\/+$/, "");
283
+ }).filter(Boolean).join("/");
284
+ return normalized.startsWith("/") ? normalized : `/${normalized}`;
285
+ }
286
+ function getExternalBase(c) {
287
+ return c.req.header("x-openwa-external-base") || "";
288
+ }
289
+ function renderExplorerHtml(config, methodDefinitions, origin, externalBase) {
290
+ const commandRows = methodDefinitions.map((def) => `
291
+ <tr>
292
+ <td><code>${def.functionName}</code></td>
293
+ <td><span class="ns-badge">${def.namespace}</span></td>
294
+ <td>${def.description}</td>
295
+ </tr>`).join("");
296
+ const listenerRows = _open_wa_schema.eventRegistry.getAll().map((def) => `
297
+ <tr>
298
+ <td><code>${def.meta.eventName}</code></td>
299
+ <td><code class="legacy">${def.meta.legacyName}</code></td>
300
+ <td><span class="ns-badge">${def.meta.namespace || "core"}</span></td>
301
+ <td>${def.meta.description || def.meta.eventName}</td>
302
+ </tr>`).join("");
303
+ const swaggerPath = joinPath$1(externalBase, "meta/swagger.json");
304
+ const postmanPath = joinPath$1(externalBase, "meta/postman.json");
305
+ const commandsPath = joinPath$1(externalBase, "meta/basic/commands");
306
+ const listenersPath = joinPath$1(externalBase, "meta/basic/listeners");
307
+ const apiBasePath = joinPath$1(externalBase, "api");
308
+ return `<!doctype html>
309
+ <html lang="en">
310
+ <head>
311
+ <meta charset="utf-8" />
312
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
313
+ <title>open-wa API Explorer — ${config.sessionId}</title>
314
+ <link rel="preconnect" href="https://fonts.googleapis.com" />
315
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
316
+ <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;700&family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet" />
317
+ <style>
318
+ :root {
319
+ --bg: #faf6f0;
320
+ --fg: #3e2723;
321
+ --card: #ffffff;
322
+ --muted: #efebe9;
323
+ --muted-fg: #5d4037;
324
+ --primary: #8d6e63;
325
+ --border: #d7ccc8;
326
+ --code-bg: #2d221e;
327
+ --code-fg: #f5ebe6;
328
+ }
329
+ @media (prefers-color-scheme: dark) {
330
+ :root {
331
+ --bg: #2d221e;
332
+ --fg: #f5ebe6;
333
+ --card: #3e2f2a;
334
+ --muted: #4e3b33;
335
+ --muted-fg: #bcaaa4;
336
+ --primary: #bcaaa4;
337
+ --border: #4e3b33;
338
+ --code-bg: #1e1614;
339
+ --code-fg: #f5ebe6;
340
+ }
341
+ }
342
+
343
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
344
+
345
+ body {
346
+ font-family: 'Inter', -apple-system, sans-serif;
347
+ background: var(--bg);
348
+ color: var(--fg);
349
+ line-height: 1.6;
350
+ min-height: 100vh;
351
+ position: relative;
352
+ }
353
+
354
+ /* Dither texture overlay on body */
355
+ body::before {
356
+ content: '';
357
+ position: fixed;
358
+ inset: 0;
359
+ background-image: radial-gradient(var(--border) 20%, transparent 20%),
360
+ radial-gradient(var(--border) 20%, transparent 20%);
361
+ background-size: 6px 6px;
362
+ background-position: 0 0, 3px 3px;
363
+ opacity: 0.08;
364
+ pointer-events: none;
365
+ z-index: 0;
366
+ }
367
+
368
+ .container {
369
+ max-width: 1100px;
370
+ margin: 0 auto;
371
+ padding: 2rem 1.5rem 4rem;
372
+ position: relative;
373
+ z-index: 1;
374
+ }
375
+
376
+ /* Header card */
377
+ .header-card {
378
+ border: 2px solid var(--fg);
379
+ border-radius: 1rem;
380
+ background: var(--card);
381
+ padding: 1.5rem 2rem;
382
+ box-shadow: 4px 4px 0px 0px var(--fg);
383
+ margin-bottom: 2rem;
384
+ position: relative;
385
+ overflow: hidden;
386
+ }
387
+ .header-card::before {
388
+ content: '';
389
+ position: absolute;
390
+ inset: 0;
391
+ background-image: radial-gradient(var(--border) 20%, transparent 20%),
392
+ radial-gradient(var(--border) 20%, transparent 20%);
393
+ background-size: 6px 6px;
394
+ background-position: 0 0, 3px 3px;
395
+ opacity: 0.06;
396
+ pointer-events: none;
397
+ }
398
+
399
+ h1 {
400
+ font-family: 'Space Grotesk', sans-serif;
401
+ font-weight: 700;
402
+ font-size: 1.75rem;
403
+ letter-spacing: -0.02em;
404
+ position: relative;
405
+ }
406
+ h1 .emoji { font-size: 1.5rem; margin-right: 0.5rem; }
407
+
408
+ .session-info {
409
+ margin-top: 0.75rem;
410
+ font-size: 0.875rem;
411
+ color: var(--muted-fg);
412
+ position: relative;
413
+ }
414
+ .session-info strong { color: var(--fg); font-weight: 600; }
415
+ .session-info code {
416
+ font-family: 'JetBrains Mono', monospace;
417
+ font-size: 0.8rem;
418
+ background: var(--code-bg);
419
+ color: var(--code-fg);
420
+ padding: 0.15rem 0.5rem;
421
+ border-radius: 0.5rem;
422
+ border: 1px solid var(--border);
423
+ }
424
+
425
+ /* Quick links */
426
+ .quick-links {
427
+ display: flex;
428
+ flex-wrap: wrap;
429
+ gap: 0.5rem;
430
+ margin-top: 1rem;
431
+ position: relative;
432
+ }
433
+ .quick-links a {
434
+ display: inline-flex;
435
+ align-items: center;
436
+ gap: 0.35rem;
437
+ font-family: 'Space Grotesk', sans-serif;
438
+ font-weight: 500;
439
+ font-size: 0.8rem;
440
+ text-decoration: none;
441
+ color: var(--fg);
442
+ background: var(--muted);
443
+ border: 2px solid var(--fg);
444
+ border-radius: 0.5rem;
445
+ padding: 0.35rem 0.75rem;
446
+ box-shadow: 2px 2px 0px 0px var(--fg);
447
+ transition: all 0.15s ease;
448
+ }
449
+ .quick-links a:hover {
450
+ transform: translate(-1px, -1px);
451
+ box-shadow: 3px 3px 0px 0px var(--fg);
452
+ background: var(--primary);
453
+ color: var(--bg);
454
+ }
455
+ .quick-links a:active {
456
+ transform: translate(1px, 1px);
457
+ box-shadow: 1px 1px 0px 0px var(--fg);
458
+ }
459
+
460
+ /* Section headers */
461
+ h2 {
462
+ font-family: 'Space Grotesk', sans-serif;
463
+ font-weight: 700;
464
+ font-size: 1.25rem;
465
+ margin: 2rem 0 0.75rem;
466
+ display: flex;
467
+ align-items: center;
468
+ gap: 0.5rem;
469
+ }
470
+ h2 .count {
471
+ font-family: 'JetBrains Mono', monospace;
472
+ font-size: 0.7rem;
473
+ font-weight: 500;
474
+ background: var(--muted);
475
+ color: var(--muted-fg);
476
+ border: 1.5px solid var(--fg);
477
+ border-radius: 2rem;
478
+ padding: 0.1rem 0.5rem;
479
+ }
480
+
481
+ /* Table card */
482
+ .table-card {
483
+ border: 2px solid var(--fg);
484
+ border-radius: 1rem;
485
+ background: var(--card);
486
+ box-shadow: 4px 4px 0px 0px var(--fg);
487
+ overflow: hidden;
488
+ margin-bottom: 1.5rem;
489
+ }
490
+
491
+ table { border-collapse: collapse; width: 100%; }
492
+
493
+ thead {
494
+ background: var(--muted);
495
+ border-bottom: 2px solid var(--fg);
496
+ }
497
+ th {
498
+ font-family: 'Space Grotesk', sans-serif;
499
+ font-weight: 700;
500
+ font-size: 0.7rem;
501
+ text-transform: uppercase;
502
+ letter-spacing: 0.1em;
503
+ padding: 0.75rem 1rem;
504
+ text-align: left;
505
+ color: var(--fg);
506
+ }
507
+
508
+ td {
509
+ padding: 0.625rem 1rem;
510
+ font-size: 0.85rem;
511
+ color: var(--muted-fg);
512
+ border-bottom: 1px solid var(--border);
513
+ vertical-align: top;
514
+ }
515
+ tr:last-child td { border-bottom: none; }
516
+ tr:hover { background: color-mix(in srgb, var(--muted) 40%, transparent); }
517
+
518
+ code {
519
+ font-family: 'JetBrains Mono', monospace;
520
+ font-size: 0.8rem;
521
+ background: var(--code-bg);
522
+ color: var(--code-fg);
523
+ padding: 0.1rem 0.4rem;
524
+ border-radius: 0.35rem;
525
+ border: 1px solid var(--border);
526
+ }
527
+ code.legacy {
528
+ opacity: 0.6;
529
+ font-size: 0.75rem;
530
+ }
531
+
532
+ .ns-badge {
533
+ display: inline-block;
534
+ font-family: 'Space Grotesk', sans-serif;
535
+ font-size: 0.7rem;
536
+ font-weight: 600;
537
+ background: var(--primary);
538
+ color: var(--bg);
539
+ border-radius: 0.35rem;
540
+ padding: 0.1rem 0.5rem;
541
+ text-transform: lowercase;
542
+ }
543
+
544
+ /* Search/filter input */
545
+ .filter-bar {
546
+ margin-bottom: 1rem;
547
+ }
548
+ .filter-bar input {
549
+ width: 100%;
550
+ max-width: 400px;
551
+ font-family: 'JetBrains Mono', monospace;
552
+ font-size: 0.85rem;
553
+ padding: 0.5rem 0.75rem;
554
+ border: 2px solid var(--fg);
555
+ border-radius: 0.75rem;
556
+ background: var(--card);
557
+ color: var(--fg);
558
+ box-shadow: 2px 2px 0px 0px var(--fg);
559
+ outline: none;
560
+ transition: box-shadow 0.15s ease, transform 0.15s ease;
561
+ }
562
+ .filter-bar input:focus {
563
+ transform: translate(-1px, -1px);
564
+ box-shadow: 3px 3px 0px 0px var(--fg);
565
+ }
566
+ .filter-bar input::placeholder { color: var(--muted-fg); opacity: 0.5; }
567
+
568
+ @media (max-width: 640px) {
569
+ .container { padding: 1rem; }
570
+ .header-card { padding: 1rem 1.25rem; }
571
+ h1 { font-size: 1.25rem; }
572
+ .quick-links { flex-direction: column; }
573
+ .quick-links a { justify-content: center; }
574
+ }
575
+ </style>
576
+ </head>
577
+ <body>
578
+ <div class="container">
579
+ <div class="header-card">
580
+ <h1><span class="emoji">🧰</span> open-wa API Explorer</h1>
581
+ <div class="session-info">
582
+ Session: <strong>${config.sessionId}</strong> &middot;
583
+ Base URL: <code>${origin}${apiBasePath}</code>
584
+ </div>
585
+ <div class="quick-links">
586
+ <a href="${swaggerPath}">📋 Swagger JSON</a>
587
+ <a href="${postmanPath}">📮 Postman Collection</a>
588
+ <a href="${commandsPath}">⚡ Commands JSON</a>
589
+ <a href="${listenersPath}">📡 Listeners JSON</a>
590
+ </div>
591
+ </div>
592
+
593
+ <h2>⚡ Commands <span class="count">${methodDefinitions.length}</span></h2>
594
+ <div class="filter-bar">
595
+ <input type="text" id="cmd-filter" placeholder="Filter commands..." oninput="filterTable('cmd-table', this.value)" />
596
+ </div>
597
+ <div class="table-card">
598
+ <table id="cmd-table">
599
+ <thead><tr><th>Method</th><th>Namespace</th><th>Description</th></tr></thead>
600
+ <tbody>${commandRows}</tbody>
601
+ </table>
602
+ </div>
603
+
604
+ <h2>📡 Listeners <span class="count">${_open_wa_schema.eventRegistry.getAll().length}</span></h2>
605
+ <div class="filter-bar">
606
+ <input type="text" id="evt-filter" placeholder="Filter listeners..." oninput="filterTable('evt-table', this.value)" />
607
+ </div>
608
+ <div class="table-card">
609
+ <table id="evt-table">
610
+ <thead><tr><th>Event</th><th>Legacy Alias</th><th>Namespace</th><th>Description</th></tr></thead>
611
+ <tbody>${listenerRows}</tbody>
612
+ </table>
613
+ </div>
614
+ </div>
615
+ <script>
616
+ function filterTable(tableId, query) {
617
+ var table = document.getElementById(tableId);
618
+ var rows = table.querySelectorAll('tbody tr');
619
+ var q = query.toLowerCase();
620
+ rows.forEach(function(row) {
621
+ row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
622
+ });
623
+ }
624
+ <\/script>
625
+ </body>
626
+ </html>`;
627
+ }
628
+ function registerMetaRoutes(app, options) {
629
+ app.get("/", (c) => c.redirect("/api-docs/"));
630
+ app.get("/api-docs", (c) => c.redirect("/api-docs/"));
631
+ app.get("/api-docs/", (c) => {
632
+ const origin = new URL(c.req.url).origin;
633
+ const externalBase = getExternalBase(c);
634
+ return c.html(renderExplorerHtml(options.config, options.methodDefinitions, origin, externalBase));
635
+ });
636
+ app.get("/meta/swagger.json", (c) => {
637
+ const origin = new URL(c.req.url).origin;
638
+ const basePath = joinPath$1(getExternalBase(c), "api");
639
+ return c.json(createOpenApiDocument(options.methodDefinitions, {
640
+ origin,
641
+ basePath
642
+ }));
643
+ });
644
+ app.get("/meta/postman.json", (c) => {
645
+ const origin = new URL(c.req.url).origin;
646
+ const basePath = joinPath$1(getExternalBase(c), "api");
647
+ return c.json(createPostmanCollection(options.methodDefinitions, {
648
+ origin,
649
+ basePath
650
+ }));
651
+ });
652
+ app.get("/meta/basic/commands", (c) => {
653
+ return c.json(options.methodDefinitions.map((def) => ({
654
+ method: def.functionName,
655
+ namespacedName: def.namespacedName,
656
+ namespace: def.namespace,
657
+ description: def.description,
658
+ path: def.path,
659
+ parameterOrder: def.parameterOrder,
660
+ aliases: def.aliases,
661
+ aliasRoutes: def.aliasRoutes,
662
+ routeSignatures: def.routeSignatures
663
+ })));
664
+ });
665
+ app.get("/meta/basic/listeners", (c) => {
666
+ return c.json(_open_wa_schema.eventRegistry.getAll().map((def) => ({
667
+ eventName: def.meta.eventName,
668
+ legacyName: def.meta.legacyName,
669
+ namespace: def.meta.namespace,
670
+ description: def.meta.description,
671
+ status: def.meta.status
672
+ })));
673
+ });
674
+ if (options.config.mcp?.exposeToolsMeta) app.get("/meta/mcp-tools.json", (c) => {
675
+ return c.json({
676
+ endpoint: options.config.mcp?.path || "/mcp",
677
+ requiresApiKey: true,
678
+ tools: (0, _open_wa_mcp.getMcpToolDefinitions)()
679
+ });
680
+ });
681
+ app.get("/swagger-stats", (c) => {
682
+ applyDeprecationHeaders(c, {
683
+ route: "/swagger-stats",
684
+ message: "swagger-stats is not carried forward in v5.",
685
+ replacement: "/api-docs/"
686
+ });
687
+ return c.redirect("/api-docs/");
688
+ });
689
+ app.get("/swagger-stats/", (c) => {
690
+ applyDeprecationHeaders(c, {
691
+ route: "/swagger-stats/",
692
+ message: "swagger-stats is not carried forward in v5.",
693
+ replacement: "/api-docs/"
694
+ });
695
+ return c.redirect("/api-docs/");
696
+ });
697
+ app.post("/meta/codegen/:language", (c) => {
698
+ return deprecatedJson(c, {
699
+ route: "/meta/codegen/:language",
700
+ message: "Runtime codegen is no longer generated inline by the Easy API server.",
701
+ replacement: "/meta/swagger.json or /meta/postman.json"
702
+ }, 410, {
703
+ language: c.req.param("language"),
704
+ availableArtifacts: ["/meta/swagger.json", "/meta/postman.json"]
705
+ });
706
+ });
707
+ app.post("/meta/process/exit", (c) => deprecatedJson(c, {
708
+ route: "/meta/process/exit",
709
+ message: "Process-control endpoints are not exposed by the shared v5 API runtime.",
710
+ replacement: "external process manager controls"
711
+ }, 410));
712
+ app.post("/meta/process/restart", (c) => deprecatedJson(c, {
713
+ route: "/meta/process/restart",
714
+ message: "Process-control endpoints are not exposed by the shared v5 API runtime.",
715
+ replacement: "external process manager controls"
716
+ }, 410));
717
+ app.post("/disengage", (c) => deprecatedJson(c, {
718
+ route: "/disengage",
719
+ message: "The disengage route is deprecated in the shared v5 API runtime.",
720
+ replacement: "/meta/process/restart or external orchestration controls"
721
+ }, 410));
722
+ }
723
+ //#endregion
724
+ //#region src/routes/debug.ts
725
+ function registerDebugRoutes(app, options) {
726
+ app.get("/meta/debug/memory", (c) => {
727
+ const mem = process.memoryUsage();
728
+ return c.json({
729
+ heapUsed: mem.heapUsed,
730
+ heapTotal: mem.heapTotal,
731
+ rss: mem.rss,
732
+ external: mem.external,
733
+ arrayBuffers: mem.arrayBuffers,
734
+ timestamp: Date.now()
735
+ });
736
+ });
737
+ app.get("/meta/debug/config", (c) => {
738
+ const redacted = { ...options.getConfig() };
739
+ for (const key of [
740
+ "apiKey",
741
+ "licenseKey",
742
+ "elasticPassword",
743
+ "elasticUsername"
744
+ ]) if (redacted[key]) redacted[key] = "***REDACTED***";
745
+ if (redacted.proxyServerCredentials) redacted.proxyServerCredentials = {
746
+ ...redacted.proxyServerCredentials,
747
+ password: "***REDACTED***"
748
+ };
749
+ if (redacted.s3Sync) redacted.s3Sync = {
750
+ ...redacted.s3Sync,
751
+ secretAccessKey: "***REDACTED***"
752
+ };
753
+ return c.json(redacted);
754
+ });
755
+ app.get("/meta/debug/info", (c) => {
756
+ return c.json({
757
+ nodeVersion: process.version,
758
+ platform: process.platform,
759
+ arch: process.arch,
760
+ pid: process.pid,
761
+ uptime: process.uptime(),
762
+ cwd: process.cwd()
763
+ });
764
+ });
765
+ app.get("/meta/integrations", (c) => {
766
+ const config = options.getConfig();
767
+ return c.json(config.integrations || {});
768
+ });
769
+ app.put("/meta/integrations/:id", async (c) => {
770
+ const id = c.req.param("id");
771
+ const { enabled, config: integConfig } = await c.req.json();
772
+ if (options.setIntegration) {
773
+ options.setIntegration(id, {
774
+ enabled,
775
+ config: integConfig
776
+ });
777
+ return c.json({
778
+ success: true,
779
+ message: `Integration '${id}' updated. Restart session to apply changes.`
780
+ });
781
+ }
782
+ return c.json({
783
+ success: false,
784
+ message: "Integration management not available"
785
+ }, 501);
786
+ });
787
+ app.patch("/meta/integrations/:id", async (c) => {
788
+ const id = c.req.param("id");
789
+ const { enabled } = await c.req.json();
790
+ if (options.setIntegration) {
791
+ const existing = options.getConfig().integrations?.[id] || {
792
+ enabled: false,
793
+ config: {}
794
+ };
795
+ options.setIntegration(id, {
796
+ ...existing,
797
+ enabled
798
+ });
799
+ return c.json({
800
+ success: true,
801
+ message: `Integration '${id}' ${enabled ? "enabled" : "disabled"}. Restart session to apply.`
802
+ });
803
+ }
804
+ return c.json({
805
+ success: false,
806
+ message: "Integration management not available"
807
+ }, 501);
808
+ });
809
+ }
810
+ //#endregion
811
+ //#region src/routes/agent-discovery.ts
812
+ function joinPath(...parts) {
813
+ const normalized = parts.filter(Boolean).map((part, index) => {
814
+ if (index === 0) return part.replace(/\/+$/, "");
815
+ return part.replace(/^\/+/, "").replace(/\/+$/, "");
816
+ }).filter(Boolean).join("/");
817
+ return normalized.startsWith("/") ? normalized : `/${normalized}`;
818
+ }
819
+ function registerAgentDiscoveryRoutes(app, options) {
820
+ app.get("/robots.txt", (c) => {
821
+ const origin = new URL(c.req.url).origin;
822
+ const content = `User-agent: GPTBot
823
+ Allow: /
824
+
825
+ User-agent: Claude-Web
826
+ Allow: /
827
+
828
+ User-agent: *
829
+ Allow: /
830
+
831
+ Sitemap: ${joinPath(origin, "sitemap.xml")}
832
+ `;
833
+ c.header("Content-Signal", "ai-train=no, search=yes, ai-input=no");
834
+ return c.text(content);
835
+ });
836
+ app.get("/sitemap.xml", (c) => {
837
+ const origin = new URL(c.req.url).origin;
838
+ const now = (/* @__PURE__ */ new Date()).toISOString();
839
+ const content = `<?xml version="1.0" encoding="UTF-8"?>
840
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
841
+ <url>
842
+ <loc>${origin}/</loc>
843
+ <lastmod>${now}</lastmod>
844
+ <changefreq>daily</changefreq>
845
+ <priority>1.0</priority>
846
+ </url>
847
+ <url>
848
+ <loc>${origin}/api-docs</loc>
849
+ <lastmod>${now}</lastmod>
850
+ <changefreq>weekly</changefreq>
851
+ <priority>0.8</priority>
852
+ </url>
853
+ </urlset>`;
854
+ c.header("Content-Type", "application/xml");
855
+ return c.text(content);
856
+ });
857
+ app.get("/.well-known/http-message-signatures-directory", (c) => {
858
+ return c.json({ keys: [] });
859
+ });
860
+ app.get("/.well-known/api-catalog", (c) => {
861
+ const origin = new URL(c.req.url).origin;
862
+ c.header("Content-Type", "application/linkset+json");
863
+ return c.json({ linkset: [{
864
+ anchor: joinPath(origin, "api"),
865
+ "service-desc": [{ href: joinPath(origin, "api-docs") }],
866
+ status: [{ href: joinPath(origin, "health") }]
867
+ }] });
868
+ });
869
+ app.get("/.well-known/oauth-authorization-server", (c) => {
870
+ const origin = new URL(c.req.url).origin;
871
+ return c.json({
872
+ issuer: origin,
873
+ authorization_endpoint: joinPath(origin, "api"),
874
+ token_endpoint: joinPath(origin, "api"),
875
+ grant_types_supported: ["client_credentials"],
876
+ note: "Easy API uses X-API-Key headers strictly for authentication."
877
+ });
878
+ });
879
+ app.get("/.well-known/openid-configuration", (c) => {
880
+ const origin = new URL(c.req.url).origin;
881
+ return c.json({
882
+ issuer: origin,
883
+ authorization_endpoint: joinPath(origin, "api"),
884
+ token_endpoint: joinPath(origin, "api"),
885
+ grant_types_supported: ["client_credentials"],
886
+ note: "Easy API uses X-API-Key headers strictly for authentication."
887
+ });
888
+ });
889
+ app.get("/.well-known/oauth-protected-resource", (c) => {
890
+ const origin = new URL(c.req.url).origin;
891
+ return c.json({
892
+ resource: joinPath(origin, "api"),
893
+ authorization_servers: [origin],
894
+ scopes_supported: ["all"]
895
+ });
896
+ });
897
+ app.get("/.well-known/mcp/server-card.json", (c) => {
898
+ const endpoint = options.config.mcp?.path || "/mcp";
899
+ return c.json({
900
+ serverInfo: {
901
+ name: "open-wa",
902
+ version: "5.0.0"
903
+ },
904
+ transport: {
905
+ type: "sse",
906
+ endpoint
907
+ },
908
+ capabilities: {}
909
+ });
910
+ });
911
+ app.get("/.well-known/agent-card.json", (c) => {
912
+ return c.json({
913
+ name: "open-wa-bot",
914
+ version: "5.0.0",
915
+ supportedInterfaces: ["mcp"]
916
+ });
917
+ });
918
+ app.get("/.well-known/agent-skills/index.json", (c) => {
919
+ const origin = new URL(c.req.url).origin;
920
+ return c.json({
921
+ $schema: "https://agentskills.io/schema.json",
922
+ skills: [{
923
+ name: "check-health",
924
+ type: "rest",
925
+ description: "Check session health",
926
+ url: joinPath(origin, "health"),
927
+ digest: "sha256-dummy"
928
+ }]
929
+ });
930
+ });
931
+ }
932
+ //#endregion
933
+ //#region src/health/HealthStore.ts
934
+ /**
935
+ * HealthStore
936
+ *
937
+ * Lightweight in-memory accumulator for system health data.
938
+ * Captures launch timeline, patches, license info, and reconnection events
939
+ * from the core event emitter. Exposed via the `/health` REST endpoint
940
+ * so the dashboard can poll it without maintaining a persistent socket subscription.
941
+ *
942
+ * Memory-efficient: uses bounded arrays (max 100 reconnections) and
943
+ * only stores small summaries — no message payloads.
944
+ */
945
+ const MAX_RECONNECTIONS = 100;
946
+ const MAX_TIMELINE_STEPS = 50;
947
+ var HealthStore = class {
948
+ constructor() {
949
+ this.timeline = [];
950
+ this.patches = [];
951
+ this.license = null;
952
+ this.reconnections = [];
953
+ this.startedAt = null;
954
+ this.lastEventAt = null;
955
+ this.stepStarts = /* @__PURE__ */ new Map();
956
+ }
957
+ /**
958
+ * Process an event from the core emitter.
959
+ * Call this from the onAny bridge with the event name and payload.
960
+ */
961
+ processEvent(event, payload) {
962
+ const data = payload;
963
+ const ts = Date.now();
964
+ this.lastEventAt = ts;
965
+ if (event.startsWith("launch.") && event.endsWith(".before")) {
966
+ const step = event.replace(".before", "");
967
+ this.stepStarts.set(step, ts);
968
+ return;
969
+ }
970
+ if (event.startsWith("launch.") && event.endsWith(".after")) {
971
+ const step = event.replace(".after", "");
972
+ const startTime = this.stepStarts.get(step);
973
+ const durationMs = startTime ? ts - startTime : 0;
974
+ this.stepStarts.delete(step);
975
+ const details = data;
976
+ const hasFailed = details?.success === false || details?.blockingFailure === true;
977
+ this.addTimelineStep({
978
+ step,
979
+ status: hasFailed ? "failed" : "done",
980
+ durationMs: details?.durationMs || durationMs,
981
+ details: details ? this.sanitizeDetails(details) : void 0,
982
+ timestamp: ts
983
+ });
984
+ if (step === "launch.patch.init") this.capturePatchInfo(details);
985
+ if (step === "launch.license.preload" || step === "launch.license.check") this.captureLicenseInfo(details);
986
+ return;
987
+ }
988
+ if (event === "launch.create.start") {
989
+ this.startedAt = ts;
990
+ this.addTimelineStep({
991
+ step: event,
992
+ status: "done",
993
+ durationMs: 0,
994
+ details: data ? this.sanitizeDetails(data) : void 0,
995
+ timestamp: ts
996
+ });
997
+ return;
998
+ }
999
+ if (event === "launch.create.ready") {
1000
+ this.addTimelineStep({
1001
+ step: event,
1002
+ status: "done",
1003
+ durationMs: 0,
1004
+ details: data ? this.sanitizeDetails(data) : void 0,
1005
+ timestamp: ts
1006
+ });
1007
+ return;
1008
+ }
1009
+ if (event === "session.connection.disconnected") {
1010
+ this.reconnections.push({
1011
+ timestamp: Math.floor(ts / 1e3),
1012
+ reason: data?.reason || "unknown",
1013
+ downtimeMs: 0,
1014
+ success: false
1015
+ });
1016
+ if (this.reconnections.length > MAX_RECONNECTIONS) this.reconnections.shift();
1017
+ return;
1018
+ }
1019
+ if (event === "session.connection.reconnected") {
1020
+ const last = this.reconnections[this.reconnections.length - 1];
1021
+ if (last && !last.success) {
1022
+ last.success = true;
1023
+ last.downtimeMs = data?.downtimeMs || 0;
1024
+ } else {
1025
+ this.reconnections.push({
1026
+ timestamp: Math.floor(ts / 1e3),
1027
+ reason: "reconnected",
1028
+ downtimeMs: data?.downtimeMs || 0,
1029
+ success: true
1030
+ });
1031
+ if (this.reconnections.length > MAX_RECONNECTIONS) this.reconnections.shift();
1032
+ }
1033
+ return;
1034
+ }
1035
+ if (event === "session.state.changed") this.addTimelineStep({
1036
+ step: event,
1037
+ status: "done",
1038
+ durationMs: 0,
1039
+ details: data ? this.sanitizeDetails(data) : void 0,
1040
+ timestamp: ts
1041
+ });
1042
+ }
1043
+ /**
1044
+ * Get a snapshot of all accumulated health data.
1045
+ * This is what gets returned by the /health endpoint.
1046
+ */
1047
+ getSnapshot() {
1048
+ return {
1049
+ launchTimeline: [...this.timeline],
1050
+ patches: [...this.patches],
1051
+ license: this.license ? { ...this.license } : null,
1052
+ reconnections: [...this.reconnections],
1053
+ startedAt: this.startedAt,
1054
+ lastEventAt: this.lastEventAt
1055
+ };
1056
+ }
1057
+ addTimelineStep(step) {
1058
+ this.timeline.push(step);
1059
+ if (this.timeline.length > MAX_TIMELINE_STEPS) this.timeline.shift();
1060
+ }
1061
+ capturePatchInfo(details) {
1062
+ if (!details) return;
1063
+ const applied = details.applied || [];
1064
+ const available = details.available || applied;
1065
+ const outcome = details.outcome;
1066
+ this.patches = available.map((id) => ({
1067
+ patchId: id,
1068
+ description: `Patch ${id}`,
1069
+ required: true,
1070
+ outcome: applied.includes(id) ? "applied" : outcome === "none" ? "not_applicable" : "failed"
1071
+ }));
1072
+ }
1073
+ captureLicenseInfo(details) {
1074
+ if (!details) return;
1075
+ this.license = {
1076
+ status: details.status || "missing",
1077
+ source: details.source || "unknown",
1078
+ keyType: details.payloadSource || "unknown",
1079
+ detail: details.detail || `License ${details.status || "check complete"}`
1080
+ };
1081
+ }
1082
+ /** Remove large/noisy fields from details to keep memory lean */
1083
+ sanitizeDetails(data) {
1084
+ const clean = {};
1085
+ for (const [key, val] of Object.entries(data)) {
1086
+ if (key === "correlationId" || key === "ts" || key === "step") continue;
1087
+ if (Array.isArray(val) && val.length > 10) {
1088
+ clean[key] = `[${val.length} items]`;
1089
+ continue;
1090
+ }
1091
+ clean[key] = val;
1092
+ }
1093
+ return clean;
1094
+ }
1095
+ };
1096
+ //#endregion
1097
+ //#region src/events/EventBroadcaster.ts
1098
+ const DEFAULT_KEEPALIVE_MS = 2e4;
1099
+ function normalizeTopics(topics) {
1100
+ if (!topics || topics.length === 0 || topics.includes("*")) return null;
1101
+ return new Set(topics);
1102
+ }
1103
+ function formatEventFrame(envelope) {
1104
+ return `id: ${envelope.id}\nevent: ${envelope.event}\ndata: ${JSON.stringify(envelope)}\n\n`;
1105
+ }
1106
+ var EventBroadcaster = class {
1107
+ constructor(sessionId) {
1108
+ this.encoder = new TextEncoder();
1109
+ this.nextEventId = 0;
1110
+ this.nextSubscriberId = 0;
1111
+ this.subscribers = /* @__PURE__ */ new Map();
1112
+ this.sessionId = sessionId ?? "";
1113
+ }
1114
+ broadcast(event, payload) {
1115
+ const envelope = {
1116
+ id: String(++this.nextEventId),
1117
+ event,
1118
+ payload,
1119
+ ts: Date.now(),
1120
+ sessionId: this.sessionId
1121
+ };
1122
+ const frame = formatEventFrame(envelope);
1123
+ for (const subscriber of this.subscribers.values()) {
1124
+ if (subscriber.topics && !subscriber.topics.has(event)) continue;
1125
+ subscriber.push(frame);
1126
+ }
1127
+ return envelope;
1128
+ }
1129
+ createStream(options = {}) {
1130
+ const topics = normalizeTopics(options.topics);
1131
+ const keepaliveMs = options.keepaliveMs ?? DEFAULT_KEEPALIVE_MS;
1132
+ let cleanup = () => {};
1133
+ return new ReadableStream({
1134
+ start: (controller) => {
1135
+ const subscriberId = ++this.nextSubscriberId;
1136
+ let closed = false;
1137
+ const keepaliveTimer = setInterval(() => {
1138
+ push(":keepalive\n\n");
1139
+ }, keepaliveMs);
1140
+ cleanup = () => {
1141
+ if (closed) return;
1142
+ closed = true;
1143
+ this.subscribers.delete(subscriberId);
1144
+ clearInterval(keepaliveTimer);
1145
+ options.signal?.removeEventListener("abort", cleanup);
1146
+ };
1147
+ const push = (chunk) => {
1148
+ if (closed) return;
1149
+ try {
1150
+ controller.enqueue(this.encoder.encode(chunk));
1151
+ } catch {
1152
+ cleanup();
1153
+ }
1154
+ };
1155
+ if (typeof keepaliveTimer.unref === "function") keepaliveTimer.unref();
1156
+ this.subscribers.set(subscriberId, {
1157
+ topics,
1158
+ push
1159
+ });
1160
+ options.signal?.addEventListener("abort", cleanup, { once: true });
1161
+ push("retry: 3000\n\n");
1162
+ },
1163
+ cancel: () => {
1164
+ cleanup();
1165
+ }
1166
+ });
1167
+ }
1168
+ getSubscriberCount() {
1169
+ return this.subscribers.size;
1170
+ }
1171
+ };
1172
+ //#endregion
1173
+ //#region src/monitoring/elastic.ts
1174
+ var ElasticEmitter = class {
1175
+ constructor(config) {
1176
+ this.buffer = [];
1177
+ this.config = {
1178
+ bufferSize: 50,
1179
+ indexPrefix: "open-wa-",
1180
+ ...config
1181
+ };
1182
+ this.client = new _elastic_elasticsearch.Client({
1183
+ node: this.config.url,
1184
+ auth: this.config.username && this.config.password ? {
1185
+ username: this.config.username,
1186
+ password: this.config.password
1187
+ } : void 0,
1188
+ maxRetries: 3,
1189
+ requestTimeout: 5e3,
1190
+ sniffOnStart: true
1191
+ });
1192
+ }
1193
+ async start() {
1194
+ await this.client.ping();
1195
+ this.flushInterval = setInterval(() => {
1196
+ this.flush();
1197
+ }, 1e4);
1198
+ }
1199
+ log(logEntry) {
1200
+ this.buffer.push({
1201
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1202
+ level: logEntry.level || "info",
1203
+ ...logEntry
1204
+ });
1205
+ if (this.buffer.length >= (this.config.bufferSize || 50)) this.flush();
1206
+ }
1207
+ async flush() {
1208
+ if (this.buffer.length === 0) return;
1209
+ const docs = [...this.buffer];
1210
+ this.buffer = [];
1211
+ const indexName = `${this.config.indexPrefix}${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`;
1212
+ try {
1213
+ await this.client.bulk({ body: docs.flatMap((document) => [{ index: { _index: indexName } }, document]) });
1214
+ } catch (error) {
1215
+ console.error("Failed to flush to ElasticSearch:", error);
1216
+ this.buffer.unshift(...docs);
1217
+ }
1218
+ }
1219
+ async stop() {
1220
+ if (this.flushInterval) clearInterval(this.flushInterval);
1221
+ await this.flush();
1222
+ await this.client.close();
1223
+ }
1224
+ };
1225
+ //#endregion
1226
+ //#region src/dashboard/middleware.ts
1227
+ function findDashboardDir() {
1228
+ const monorepoPath = [(0, path.resolve)(__dirname, "../../../apps/dashboard-neo"), (0, path.resolve)(__dirname, "../../../../apps/dashboard-neo")].find((candidate) => (0, fs.existsSync)((0, path.resolve)(candidate, "package.json")));
1229
+ if (monorepoPath) return monorepoPath;
1230
+ try {
1231
+ return (0, path.dirname)(require.resolve("@open-wa/dashboard-neo/package.json"));
1232
+ } catch {}
1233
+ return null;
1234
+ }
1235
+ async function setupViteDevServer() {
1236
+ const dashboardDir = findDashboardDir();
1237
+ if (!dashboardDir) return null;
1238
+ if (process.env.NODE_ENV === "production" || !(0, fs.existsSync)((0, path.resolve)(dashboardDir, "vite.config.ts"))) return null;
1239
+ try {
1240
+ const viteServer = await (await import("vite")).createServer({
1241
+ root: dashboardDir,
1242
+ server: { middlewareMode: true },
1243
+ appType: "spa",
1244
+ base: "/dashboard/"
1245
+ });
1246
+ console.log(`\n🚀 Dashboard mounted at /dashboard/ (Vite dev middleware)\n`);
1247
+ return viteServer;
1248
+ } catch (e) {
1249
+ console.warn(`[dashboard] Failed to mount Vite middleware: ${e.message}`);
1250
+ return null;
1251
+ }
1252
+ }
1253
+ async function mountDashboardProduction(app) {
1254
+ const dashboardDir = findDashboardDir();
1255
+ if (!dashboardDir) return false;
1256
+ const distPath = (0, path.resolve)(dashboardDir, "dist");
1257
+ if ((0, fs.existsSync)(distPath)) {
1258
+ app.use("/dashboard/*", (0, _hono_node_server_serve_static.serveStatic)({
1259
+ root: distPath,
1260
+ rewriteRequestPath: (path$1) => path$1.replace(/^\/dashboard/, "")
1261
+ }));
1262
+ app.get("/dashboard/*", (c) => {
1263
+ if ((c.req.header("Accept") || "").includes("text/markdown")) {
1264
+ const origin = new URL(c.req.url).origin;
1265
+ c.header("Content-Type", "text/markdown");
1266
+ 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.`);
1267
+ }
1268
+ const indexPath = (0, path.resolve)(distPath, "index.html");
1269
+ if ((0, fs.existsSync)(indexPath)) return c.html((0, fs.readFileSync)(indexPath, "utf-8"));
1270
+ return c.notFound();
1271
+ });
1272
+ console.log(`\n🚀 Dashboard mounted at /dashboard/ (Production static)\n`);
1273
+ return true;
1274
+ }
1275
+ return false;
1276
+ }
1277
+ //#endregion
1278
+ //#region src/createApiServer.ts
1279
+ function parseCorsOrigin(corsConfig) {
1280
+ if (corsConfig === "*") return "*";
1281
+ if (Array.isArray(corsConfig)) return corsConfig;
1282
+ if (typeof corsConfig === "string" && corsConfig.includes(",")) return corsConfig.split(",").map((origin) => origin.trim());
1283
+ return corsConfig;
1284
+ }
1285
+ var ApiServer = class {
1286
+ constructor(options) {
1287
+ this.latestQR = null;
1288
+ this.injectWebSocket = null;
1289
+ this.isDashboardActive = false;
1290
+ this.healthStore = new HealthStore();
1291
+ this.config = options.config;
1292
+ if (this.config.mcp?.enabled && !this.config.apiKey) throw new Error("MCP requires Easy API apiKey. Refusing to start with MCP enabled and no apiKey configured.");
1293
+ this.app = new hono.Hono();
1294
+ this.screencastManager = new _open_wa_screencaster_server.ScreencastManager();
1295
+ this.eventBroadcaster = new EventBroadcaster(this.config.sessionId);
1296
+ const { injectWebSocket, upgradeWebSocket } = (0, _hono_node_ws.createNodeWebSocket)({ app: this.app });
1297
+ this.injectWebSocket = injectWebSocket;
1298
+ if (this.config.elasticUrl) this.elasticEmitter = new ElasticEmitter({
1299
+ url: this.config.elasticUrl,
1300
+ username: this.config.elasticUsername,
1301
+ password: this.config.elasticPassword,
1302
+ bufferSize: this.config.elasticBufferSize,
1303
+ pipeline: this.config.elasticPipeline,
1304
+ indexPrefix: this.config.elasticIndexPrefix
1305
+ });
1306
+ this.setupMiddleware();
1307
+ this.registerRoutes();
1308
+ this.app.get("/screencast", (0, _open_wa_screencaster_server.createScreencastRoute)(upgradeWebSocket, this.screencastManager));
1309
+ }
1310
+ setClient(client) {
1311
+ this.client = client;
1312
+ }
1313
+ setEventBridge(bridge) {
1314
+ if (this.eventBridge && this.eventBridgeListener) this.eventBridge.offAny(this.eventBridgeListener);
1315
+ this.eventBridge = bridge;
1316
+ this.eventBridgeListener = (event, payload) => {
1317
+ this.healthStore.processEvent(event, payload);
1318
+ this.eventBroadcaster.broadcast(event, payload);
1319
+ };
1320
+ bridge.onAny(this.eventBridgeListener);
1321
+ }
1322
+ setReadinessProvider(provider) {
1323
+ this.readinessProvider = provider;
1324
+ }
1325
+ /**
1326
+ * Bind a CDP-capable page for screencasting.
1327
+ * Call this once the browser page is ready.
1328
+ */
1329
+ async setPage(page) {
1330
+ await this.screencastManager.setPage(page);
1331
+ }
1332
+ /**
1333
+ * Unbind the screencaster page (session ended).
1334
+ */
1335
+ async clearPage() {
1336
+ await this.screencastManager.clearPage();
1337
+ }
1338
+ setQR(qr) {
1339
+ this.latestQR = qr;
1340
+ }
1341
+ getApp() {
1342
+ return this.app;
1343
+ }
1344
+ getEventBroadcaster() {
1345
+ return this.eventBroadcaster;
1346
+ }
1347
+ /**
1348
+ * Mount plugin routes and manifest endpoint.
1349
+ * Call this after the PluginHost has all plugins registered.
1350
+ */
1351
+ mountPlugins(pluginHost) {
1352
+ this.pluginHost = pluginHost;
1353
+ for (const { name, router } of pluginHost.getRoutes()) this.app.route(`/plugins/${name}`, router);
1354
+ this.app.get("/plugins/manifest", (c) => c.json(pluginHost.getManifest()));
1355
+ }
1356
+ async start() {
1357
+ let viteDevServer = null;
1358
+ if (this.config.dashboard) {
1359
+ viteDevServer = await setupViteDevServer();
1360
+ if (!viteDevServer) this.isDashboardActive = await mountDashboardProduction(this.app);
1361
+ else this.isDashboardActive = true;
1362
+ }
1363
+ const honoListener = (0, _hono_node_server.getRequestListener)(this.app.fetch);
1364
+ const requestListener = (req, res) => {
1365
+ if (viteDevServer && req.url?.startsWith("/dashboard")) {
1366
+ viteDevServer.middlewares(req, res, () => {
1367
+ honoListener(req, res);
1368
+ });
1369
+ return;
1370
+ }
1371
+ honoListener(req, res);
1372
+ };
1373
+ const server = (0, http.createServer)(requestListener);
1374
+ server.listen(this.config.port, this.config.host, () => {
1375
+ console.log(`Server running on http://${this.config.host}:${this.config.port}`);
1376
+ });
1377
+ if (this.injectWebSocket) {
1378
+ let honoUpgradeListener = null;
1379
+ this.injectWebSocket({ on: (event, listener) => {
1380
+ if (event === "upgrade") honoUpgradeListener = listener;
1381
+ } });
1382
+ if (honoUpgradeListener) server.on("upgrade", (req, socket, head) => {
1383
+ honoUpgradeListener(req, socket, head);
1384
+ });
1385
+ }
1386
+ if (this.elasticEmitter) await this.elasticEmitter.start();
1387
+ }
1388
+ async stop() {
1389
+ await this.screencastManager.destroy();
1390
+ if (this.elasticEmitter) await this.elasticEmitter.stop();
1391
+ }
1392
+ isDashboardRunning() {
1393
+ return this.isDashboardActive;
1394
+ }
1395
+ isSessionConnected() {
1396
+ const readiness = this.readinessProvider?.();
1397
+ if (readiness) return readiness.ready;
1398
+ if (!this.client) return false;
1399
+ return typeof this.client.isConnected === "function" ? this.client.isConnected() : false;
1400
+ }
1401
+ setupMiddleware() {
1402
+ this.app.use("/*", (0, hono_cors.cors)({
1403
+ origin: parseCorsOrigin(this.config.cors),
1404
+ credentials: true
1405
+ }));
1406
+ this.app.use("/*", async (c, next) => {
1407
+ const path = new URL(c.req.url).pathname;
1408
+ if (path === "/" || path.startsWith("/dashboard")) c.header("Link", [
1409
+ `</.well-known/api-catalog>; rel="api-catalog"`,
1410
+ `</.well-known/mcp/server-card.json>; rel="mcp"`,
1411
+ `</.well-known/agent-card.json>; rel="describedby"`
1412
+ ].join(", "));
1413
+ if (path === "/" && (c.req.header("Accept") || "").includes("text/markdown")) {
1414
+ const origin = new URL(c.req.url).origin;
1415
+ c.header("Content-Type", "text/markdown");
1416
+ return c.text(`# 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`);
1417
+ }
1418
+ await next();
1419
+ });
1420
+ if (this.config.logLevel !== "silent") this.app.use("*", (0, hono_logger.logger)());
1421
+ }
1422
+ registerRoutes() {
1423
+ const methodDefinitions = (0, _open_wa_schema.getHttpMethodDefinitions)();
1424
+ registerAgentDiscoveryRoutes(this.app, {
1425
+ config: this.config,
1426
+ methodDefinitions
1427
+ });
1428
+ this.app.get("/health", (c) => {
1429
+ const healthSnapshot = this.healthStore.getSnapshot();
1430
+ return c.json({
1431
+ status: "ok",
1432
+ version: "5.0.0",
1433
+ host: {
1434
+ available: true,
1435
+ api: true,
1436
+ dashboard: {
1437
+ enabled: this.config.dashboard,
1438
+ running: this.isDashboardRunning(),
1439
+ port: this.config.dashboardPort
1440
+ },
1441
+ mcp: {
1442
+ enabled: Boolean(this.config.mcp?.enabled),
1443
+ available: Boolean(this.config.apiKey && this.config.mcp?.enabled),
1444
+ path: this.config.mcp?.path || "/mcp"
1445
+ }
1446
+ },
1447
+ capabilities: {
1448
+ apiKeyConfigured: Boolean(this.config.apiKey),
1449
+ mcpEnabled: Boolean(this.config.mcp?.enabled),
1450
+ mcpAvailable: Boolean(this.config.apiKey && this.config.mcp?.enabled),
1451
+ mcpPath: this.config.mcp?.path || "/mcp"
1452
+ },
1453
+ connected: this.isSessionConnected(),
1454
+ session: this.readinessProvider?.() ?? {
1455
+ ready: false,
1456
+ status: this.client ? "legacy" : "unavailable",
1457
+ state: this.client ? "UNKNOWN" : "DISCONNECTED",
1458
+ pending: this.client ? ["session_readiness_unavailable"] : ["client_not_bound"],
1459
+ blockers: [],
1460
+ exposureSafe: false
1461
+ },
1462
+ qr: this.latestQR ?? null,
1463
+ launchTimeline: healthSnapshot.launchTimeline,
1464
+ patches: healthSnapshot.patches,
1465
+ license: healthSnapshot.license,
1466
+ reconnections: healthSnapshot.reconnections,
1467
+ startedAt: healthSnapshot.startedAt,
1468
+ lastEventAt: healthSnapshot.lastEventAt
1469
+ });
1470
+ });
1471
+ this.app.get("/qr", (c) => {
1472
+ if (!this.config.ezqr) return c.json({ error: "QR endpoint disabled" }, 404);
1473
+ if (!this.latestQR) return c.json({
1474
+ error: "QR code not available",
1475
+ note: "Session might be connected or generating QR"
1476
+ }, 404);
1477
+ return c.json({
1478
+ qr: this.latestQR,
1479
+ note: "Scan this QR code in WhatsApp"
1480
+ });
1481
+ });
1482
+ this.app.get("/api/events", (c) => {
1483
+ if (this.config.apiKey) {
1484
+ const apiKey = c.req.header("X-API-Key") || c.req.query("api_key") || c.req.query("key");
1485
+ if (!apiKey || apiKey !== this.config.apiKey) return c.json({
1486
+ error: "Unauthorized",
1487
+ details: "Invalid or missing API key"
1488
+ }, 401);
1489
+ }
1490
+ const topicsParam = c.req.query("topics");
1491
+ const topics = topicsParam ? topicsParam.split(",").map((topic) => topic.trim()).filter(Boolean) : ["*"];
1492
+ return new Response(this.eventBroadcaster.createStream({
1493
+ signal: c.req.raw.signal,
1494
+ topics
1495
+ }), { headers: {
1496
+ "Cache-Control": "no-cache, no-transform",
1497
+ Connection: "keep-alive",
1498
+ "Content-Type": "text/event-stream",
1499
+ "X-Accel-Buffering": "no"
1500
+ } });
1501
+ });
1502
+ registerMetaRoutes(this.app, {
1503
+ config: this.config,
1504
+ methodDefinitions
1505
+ });
1506
+ registerDebugRoutes(this.app, {
1507
+ config: this.config,
1508
+ getConfig: () => this.config,
1509
+ setIntegration: (id, data) => {
1510
+ if (!this.config.integrations) this.config.integrations = {};
1511
+ this.config.integrations[id] = data;
1512
+ }
1513
+ });
1514
+ this.app.route("/api", createApiMiddleware(() => this.client, {
1515
+ config: this.config,
1516
+ basePath: "/api",
1517
+ elasticEmitter: this.elasticEmitter,
1518
+ isSessionConnected: () => this.isSessionConnected()
1519
+ }));
1520
+ if (this.config.mcp?.enabled) (0, _open_wa_mcp.createHonoMcpAdapter)({
1521
+ config: this.config,
1522
+ clientSource: () => this.client,
1523
+ elasticEmitter: this.elasticEmitter,
1524
+ basePath: "/api",
1525
+ isSessionConnected: () => this.isSessionConnected()
1526
+ }).mount(this.app, this.config.mcp.path || "/mcp");
1527
+ }
1528
+ };
1529
+ function createApiServer(config) {
1530
+ return new ApiServer({ config });
1531
+ }
1532
+ //#endregion
1533
+ exports.ApiServer = ApiServer;
1534
+ exports.ElasticEmitter = ElasticEmitter;
1535
+ exports.EventBroadcaster = EventBroadcaster;
1536
+ exports.apiKeyMiddleware = apiKeyMiddleware;
1537
+ exports.createApiMiddleware = createApiMiddleware;
1538
+ exports.createApiServer = createApiServer;
1539
+ Object.defineProperty(exports, "invokeClientMethod", {
1540
+ enumerable: true,
1541
+ get: function() {
1542
+ return _open_wa_mcp.invokeClientMethod;
1543
+ }
1544
+ });
1545
+ exports.rateLimitMiddleware = rateLimitMiddleware;