@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.
@@ -0,0 +1,414 @@
1
+ import { Hono } from 'hono';
2
+ import { cors } from 'hono/cors';
3
+ import { logger } from 'hono/logger';
4
+ import { getRequestListener } from '@hono/node-server';
5
+ import { createServer } from 'http';
6
+ import { createNodeWebSocket } from '@hono/node-ws';
7
+ import { getHttpMethodDefinitions, type Config } from '@open-wa/schema';
8
+ import '@open-wa/schema';
9
+ import { createScreencastRoute, ScreencastManager } from '@open-wa/screencaster/server';
10
+ import { createApiMiddleware } from './createApiMiddleware';
11
+ import { createHonoMcpAdapter } from '@open-wa/mcp';
12
+ import { registerMetaRoutes } from './routes/meta';
13
+ import { registerDebugRoutes } from './routes/debug';
14
+ import { registerAgentDiscoveryRoutes } from './routes/agent-discovery';
15
+ import { type EventBridge } from './events/EventBridge';
16
+ import { HealthStore } from './health/HealthStore';
17
+ import { EventBroadcaster } from './events/EventBroadcaster';
18
+ import { ElasticEmitter } from './monitoring/elastic';
19
+ import { setupViteDevServer, mountDashboardProduction } from './dashboard/middleware';
20
+ import type { ApiServerOptions, ClientMethodMap } from './types';
21
+ import type { IScreencastPage } from '@open-wa/screencaster/server';
22
+ import type { PluginHost } from '@open-wa/core';
23
+
24
+ function parseCorsOrigin(corsConfig: string | string[]): string | string[] {
25
+ if (corsConfig === '*') {
26
+ return '*';
27
+ }
28
+
29
+ if (Array.isArray(corsConfig)) {
30
+ return corsConfig;
31
+ }
32
+
33
+ if (typeof corsConfig === 'string' && corsConfig.includes(',')) {
34
+ return corsConfig.split(',').map((origin) => origin.trim());
35
+ }
36
+
37
+ return corsConfig;
38
+ }
39
+
40
+ export class ApiServer {
41
+ private app: Hono;
42
+ private config: Config;
43
+ private client: ClientMethodMap | undefined;
44
+ private elasticEmitter?: ElasticEmitter;
45
+ private latestQR: string | null = null;
46
+ private screencastManager: ScreencastManager;
47
+ private injectWebSocket: ((server: unknown) => void) | null = null;
48
+ private isDashboardActive: boolean = false;
49
+ private pluginHost?: PluginHost;
50
+ private healthStore: HealthStore = new HealthStore();
51
+ private eventBroadcaster: EventBroadcaster;
52
+ private eventBridge?: EventBridge;
53
+ private eventBridgeListener?: (event: string, payload: any) => void;
54
+ private readinessProvider?: () => {
55
+ state?: string;
56
+ status?: string;
57
+ ready: boolean;
58
+ exposureSafe?: boolean;
59
+ pending?: string[];
60
+ blockers?: string[];
61
+ } | undefined;
62
+
63
+ constructor(options: ApiServerOptions) {
64
+ this.config = options.config;
65
+
66
+ // Validate MCP configuration
67
+ if (this.config.mcp?.enabled && !this.config.apiKey) {
68
+ throw new Error(
69
+ 'MCP requires Easy API apiKey. Refusing to start with MCP enabled and no apiKey configured.'
70
+ );
71
+ }
72
+
73
+ this.app = new Hono();
74
+ this.screencastManager = new ScreencastManager();
75
+ this.eventBroadcaster = new EventBroadcaster(this.config.sessionId);
76
+
77
+ // Set up WebSocket adapter for Node.js
78
+ const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: this.app });
79
+ this.injectWebSocket = injectWebSocket as (server: unknown) => void;
80
+
81
+ if (this.config.elasticUrl) {
82
+ this.elasticEmitter = new ElasticEmitter({
83
+ url: this.config.elasticUrl,
84
+ username: this.config.elasticUsername,
85
+ password: this.config.elasticPassword,
86
+ bufferSize: this.config.elasticBufferSize,
87
+ pipeline: this.config.elasticPipeline,
88
+ indexPrefix: this.config.elasticIndexPrefix,
89
+ });
90
+ }
91
+
92
+ this.setupMiddleware();
93
+ this.registerRoutes();
94
+
95
+ // Register screencast WebSocket route
96
+ this.app.get('/screencast', createScreencastRoute(upgradeWebSocket, this.screencastManager));
97
+ }
98
+
99
+ public setClient(client: ClientMethodMap | undefined) {
100
+ this.client = client;
101
+ }
102
+
103
+ public setEventBridge(bridge: EventBridge) {
104
+ if (this.eventBridge && this.eventBridgeListener) {
105
+ this.eventBridge.offAny(this.eventBridgeListener);
106
+ }
107
+
108
+ this.eventBridge = bridge;
109
+ this.eventBridgeListener = (event: string, payload: any) => {
110
+ this.healthStore.processEvent(event, payload);
111
+ this.eventBroadcaster.broadcast(event, payload);
112
+ };
113
+
114
+ // Also wire events into the HealthStore so /health returns accumulated data
115
+ bridge.onAny(this.eventBridgeListener);
116
+ }
117
+
118
+ public setReadinessProvider(
119
+ provider: (() => {
120
+ state?: string;
121
+ status?: string;
122
+ ready: boolean;
123
+ exposureSafe?: boolean;
124
+ pending?: string[];
125
+ blockers?: string[];
126
+ } | undefined) | undefined
127
+ ) {
128
+ this.readinessProvider = provider;
129
+ }
130
+
131
+ /**
132
+ * Bind a CDP-capable page for screencasting.
133
+ * Call this once the browser page is ready.
134
+ */
135
+ public async setPage(page: IScreencastPage): Promise<void> {
136
+ await this.screencastManager.setPage(page);
137
+ }
138
+
139
+ /**
140
+ * Unbind the screencaster page (session ended).
141
+ */
142
+ public async clearPage(): Promise<void> {
143
+ await this.screencastManager.clearPage();
144
+ }
145
+
146
+ public setQR(qr: string) {
147
+ this.latestQR = qr;
148
+ }
149
+
150
+ public getApp() {
151
+ return this.app;
152
+ }
153
+
154
+ public getEventBroadcaster() {
155
+ return this.eventBroadcaster;
156
+ }
157
+
158
+ /**
159
+ * Mount plugin routes and manifest endpoint.
160
+ * Call this after the PluginHost has all plugins registered.
161
+ */
162
+ public mountPlugins(pluginHost: PluginHost): void {
163
+ this.pluginHost = pluginHost;
164
+
165
+ // Mount each plugin's routes at /plugins/<name>/
166
+ for (const { name, router } of pluginHost.getRoutes()) {
167
+ this.app.route(`/plugins/${name}`, router);
168
+ }
169
+
170
+ // Serve the manifest for the dashboard to discover plugin pages
171
+ this.app.get('/plugins/manifest', (c) => c.json(pluginHost.getManifest()));
172
+ }
173
+
174
+ public async start() {
175
+ let viteDevServer: any = null;
176
+ if (this.config.dashboard) {
177
+ viteDevServer = await setupViteDevServer();
178
+ if (!viteDevServer) {
179
+ this.isDashboardActive = await mountDashboardProduction(this.app);
180
+ } else {
181
+ this.isDashboardActive = true;
182
+ }
183
+ }
184
+
185
+ const honoListener = getRequestListener(this.app.fetch);
186
+
187
+ const requestListener = (req: any, res: any) => {
188
+ if (viteDevServer && req.url?.startsWith('/dashboard')) {
189
+ viteDevServer.middlewares(req, res, () => {
190
+ honoListener(req, res);
191
+ });
192
+ return;
193
+ }
194
+ honoListener(req, res);
195
+ };
196
+
197
+ const server = createServer(requestListener);
198
+ server.listen(this.config.port, this.config.host, () => {
199
+ console.log(`Server running on http://${this.config.host}:${this.config.port}`);
200
+ });
201
+
202
+ if (this.injectWebSocket) {
203
+ let honoUpgradeListener: Function | null = null;
204
+ this.injectWebSocket({
205
+ on: (event: string, listener: Function) => {
206
+ if (event === 'upgrade') honoUpgradeListener = listener;
207
+ }
208
+ });
209
+ if (honoUpgradeListener) {
210
+ server.on('upgrade', (req, socket, head) => {
211
+ honoUpgradeListener!(req, socket, head);
212
+ });
213
+ }
214
+ }
215
+
216
+ if (this.elasticEmitter) {
217
+ await this.elasticEmitter.start();
218
+ }
219
+ }
220
+
221
+ public async stop() {
222
+ await this.screencastManager.destroy();
223
+ if (this.elasticEmitter) {
224
+ await this.elasticEmitter.stop();
225
+ }
226
+ }
227
+
228
+ public isDashboardRunning() {
229
+ return this.isDashboardActive;
230
+ }
231
+
232
+ private isSessionConnected() {
233
+ const readiness = this.readinessProvider?.();
234
+ if (readiness) {
235
+ return readiness.ready;
236
+ }
237
+
238
+ if (!this.client) {
239
+ return false;
240
+ }
241
+
242
+ return typeof this.client.isConnected === 'function' ? this.client.isConnected() : false;
243
+ }
244
+
245
+ private setupMiddleware() {
246
+ this.app.use('/*',
247
+ cors({
248
+ origin: parseCorsOrigin(this.config.cors),
249
+ credentials: true,
250
+ })
251
+ );
252
+
253
+ this.app.use('/*', async (c, next) => {
254
+ const path = new URL(c.req.url).pathname;
255
+ if (path === '/' || path.startsWith('/dashboard')) {
256
+ c.header('Link', [
257
+ `</.well-known/api-catalog>; rel="api-catalog"`,
258
+ `</.well-known/mcp/server-card.json>; rel="mcp"`,
259
+ `</.well-known/agent-card.json>; rel="describedby"`
260
+ ].join(', '));
261
+ }
262
+
263
+ if (path === '/' && (c.req.header('Accept') || '').includes('text/markdown')) {
264
+ const origin = new URL(c.req.url).origin;
265
+ c.header('Content-Type', 'text/markdown');
266
+ 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`);
267
+ }
268
+ await next();
269
+ });
270
+
271
+ if (this.config.logLevel !== 'silent') {
272
+ this.app.use('*', logger());
273
+ }
274
+ }
275
+
276
+ private registerRoutes() {
277
+ const methodDefinitions = getHttpMethodDefinitions();
278
+ registerAgentDiscoveryRoutes(this.app, { config: this.config, methodDefinitions });
279
+
280
+ this.app.get('/health', (c) => {
281
+ const healthSnapshot = this.healthStore.getSnapshot();
282
+ return c.json({
283
+ status: 'ok',
284
+ version: '5.0.0',
285
+ host: {
286
+ available: true,
287
+ api: true,
288
+ dashboard: {
289
+ enabled: this.config.dashboard,
290
+ running: this.isDashboardRunning(),
291
+ port: this.config.dashboardPort,
292
+ },
293
+ mcp: {
294
+ enabled: Boolean(this.config.mcp?.enabled),
295
+ available: Boolean(this.config.apiKey && this.config.mcp?.enabled),
296
+ path: this.config.mcp?.path || '/mcp',
297
+ },
298
+ },
299
+ capabilities: {
300
+ apiKeyConfigured: Boolean(this.config.apiKey),
301
+ mcpEnabled: Boolean(this.config.mcp?.enabled),
302
+ mcpAvailable: Boolean(this.config.apiKey && this.config.mcp?.enabled),
303
+ mcpPath: this.config.mcp?.path || '/mcp',
304
+ },
305
+ connected: this.isSessionConnected(),
306
+ session: this.readinessProvider?.() ?? {
307
+ ready: false,
308
+ status: this.client ? 'legacy' : 'unavailable',
309
+ state: this.client ? 'UNKNOWN' : 'DISCONNECTED',
310
+ pending: this.client ? ['session_readiness_unavailable'] : ['client_not_bound'],
311
+ blockers: [],
312
+ exposureSafe: false,
313
+ },
314
+ // QR code for pre-launch scanning
315
+ qr: this.latestQR ?? null,
316
+ // Accumulated health data for the dashboard
317
+ launchTimeline: healthSnapshot.launchTimeline,
318
+ patches: healthSnapshot.patches,
319
+ license: healthSnapshot.license,
320
+ reconnections: healthSnapshot.reconnections,
321
+ startedAt: healthSnapshot.startedAt,
322
+ lastEventAt: healthSnapshot.lastEventAt,
323
+ });
324
+ });
325
+
326
+ this.app.get('/qr', (c) => {
327
+ if (!this.config.ezqr) {
328
+ return c.json({ error: 'QR endpoint disabled' }, 404);
329
+ }
330
+
331
+ if (!this.latestQR) {
332
+ return c.json({ error: 'QR code not available', note: 'Session might be connected or generating QR' }, 404);
333
+ }
334
+
335
+ return c.json({ qr: this.latestQR, note: 'Scan this QR code in WhatsApp' });
336
+ });
337
+
338
+ this.app.get('/api/events', (c) => {
339
+ // TODO: Unify this inline auth check with the shared apiKeyMiddleware used across Easy API.
340
+ // Note: This intentionally supports query params to preserve legacy Easy API behavior,
341
+ // unlike the MCP adapter which strictly enforces header-only auth (X-API-Key) for security.
342
+ if (this.config.apiKey) {
343
+ const apiKey = c.req.header('X-API-Key') || c.req.query('api_key') || c.req.query('key');
344
+
345
+ if (!apiKey || apiKey !== this.config.apiKey) {
346
+ return c.json({ error: 'Unauthorized', details: 'Invalid or missing API key' }, 401);
347
+ }
348
+ }
349
+
350
+ const topicsParam = c.req.query('topics');
351
+ const topics = topicsParam
352
+ ? topicsParam
353
+ .split(',')
354
+ .map((topic) => topic.trim())
355
+ .filter(Boolean)
356
+ : ['*'];
357
+
358
+ return new Response(
359
+ this.eventBroadcaster.createStream({
360
+ signal: c.req.raw.signal,
361
+ topics,
362
+ }),
363
+ {
364
+ headers: {
365
+ 'Cache-Control': 'no-cache, no-transform',
366
+ Connection: 'keep-alive',
367
+ 'Content-Type': 'text/event-stream',
368
+ 'X-Accel-Buffering': 'no',
369
+ },
370
+ }
371
+ );
372
+ });
373
+
374
+ registerMetaRoutes(this.app, {
375
+ config: this.config,
376
+ methodDefinitions,
377
+ });
378
+
379
+ registerDebugRoutes(this.app, {
380
+ config: this.config,
381
+ getConfig: () => this.config,
382
+ setIntegration: (id, data) => {
383
+ if (!this.config.integrations) {
384
+ this.config.integrations = {};
385
+ }
386
+ this.config.integrations[id] = data;
387
+ },
388
+ });
389
+ this.app.route(
390
+ '/api',
391
+ createApiMiddleware(() => this.client, {
392
+ config: this.config,
393
+ basePath: '/api',
394
+ elasticEmitter: this.elasticEmitter,
395
+ isSessionConnected: () => this.isSessionConnected(),
396
+ })
397
+ );
398
+
399
+ if (this.config.mcp?.enabled) {
400
+ const mcpAdapter = createHonoMcpAdapter({
401
+ config: this.config,
402
+ clientSource: () => this.client,
403
+ elasticEmitter: this.elasticEmitter,
404
+ basePath: '/api',
405
+ isSessionConnected: () => this.isSessionConnected(),
406
+ });
407
+ mcpAdapter.mount(this.app, this.config.mcp.path || '/mcp');
408
+ }
409
+ }
410
+ }
411
+
412
+ export function createApiServer(config: Config) {
413
+ return new ApiServer({ config });
414
+ }
@@ -0,0 +1,85 @@
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
+ try {
17
+ const pkgPath = require.resolve('@open-wa/dashboard-neo/package.json');
18
+ return dirname(pkgPath);
19
+ } catch {
20
+ // Not installed
21
+ }
22
+
23
+ return null;
24
+ }
25
+
26
+
27
+ export async function setupViteDevServer(): Promise<any | null> {
28
+ const dashboardDir = findDashboardDir();
29
+ if (!dashboardDir) return null;
30
+
31
+ const isProd = process.env.NODE_ENV === 'production' || !existsSync(resolve(dashboardDir, 'vite.config.ts'));
32
+ if (isProd) return null;
33
+
34
+ try {
35
+ const vite = await import('vite');
36
+ const viteServer = await vite.createServer({
37
+ root: dashboardDir,
38
+ server: { middlewareMode: true },
39
+ appType: 'spa',
40
+ base: '/dashboard/',
41
+ });
42
+ console.log(`\n🚀 Dashboard mounted at /dashboard/ (Vite dev middleware)\n`);
43
+ return viteServer;
44
+ } catch (e: any) {
45
+ console.warn(`[dashboard] Failed to mount Vite middleware: ${e.message}`);
46
+ return null;
47
+ }
48
+ }
49
+
50
+ export async function mountDashboardProduction(app: Hono): Promise<boolean> {
51
+ const dashboardDir = findDashboardDir();
52
+ if (!dashboardDir) return false;
53
+ const distPath = resolve(dashboardDir, 'dist');
54
+ if (existsSync(distPath)) {
55
+ // Determine the root for serveStatic relative to process.cwd, or just use absolute?
56
+ // serveStatic usually looks at relative paths from process.cwd() unless configured.
57
+ // wait, @hono/node-server/serve-static `root` defaults to "./".
58
+ // It's safer to use a custom middleware to read the files, or pass absolute path directly if supported.
59
+ app.use('/dashboard/*', serveStatic({
60
+ root: distPath,
61
+ rewriteRequestPath: (path) => path.replace(/^\/dashboard/, '')
62
+ }));
63
+
64
+ // Fallback for SPA
65
+ app.get('/dashboard/*', (c) => {
66
+ const accept = c.req.header('Accept') || '';
67
+ if (accept.includes('text/markdown')) {
68
+ const origin = new URL(c.req.url).origin;
69
+ c.header('Content-Type', 'text/markdown');
70
+ 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.`);
71
+ }
72
+
73
+ const indexPath = resolve(distPath, 'index.html');
74
+ if (existsSync(indexPath)) {
75
+ return c.html(readFileSync(indexPath, 'utf-8'));
76
+ }
77
+ return c.notFound();
78
+ });
79
+
80
+ console.log(`\n🚀 Dashboard mounted at /dashboard/ (Production static)\n`);
81
+ return true;
82
+ }
83
+
84
+ return false;
85
+ }
@@ -0,0 +1,77 @@
1
+ import type { HttpMethodDefinition } from '@open-wa/schema';
2
+
3
+ function schemaToOpenApi(schema: { toJSONSchema?: (params?: unknown) => unknown }) {
4
+ if (typeof schema?.toJSONSchema === 'function') {
5
+ return schema.toJSONSchema({ target: 'openapi-3.0' });
6
+ }
7
+
8
+ return { type: 'object', additionalProperties: true };
9
+ }
10
+
11
+ function buildQueryParameters(def: HttpMethodDefinition) {
12
+ const inputSchema = schemaToOpenApi(def.inputSchema) as {
13
+ properties?: Record<string, Record<string, unknown>>;
14
+ required?: string[];
15
+ };
16
+ const properties = inputSchema.properties ?? {};
17
+ const required = new Set(inputSchema.required ?? []);
18
+
19
+ return def.parameterOrder.map((name) => ({
20
+ name,
21
+ in: 'query',
22
+ required: required.has(name),
23
+ description: properties[name]?.description || `Argument: ${name}`,
24
+ schema: properties[name] || { type: 'string' },
25
+ }));
26
+ }
27
+
28
+ export function createOpenApiDocument(
29
+ methodDefinitions: HttpMethodDefinition[],
30
+ options: { origin: string; basePath?: string; title?: string; version?: string }
31
+ ) {
32
+ const paths = Object.fromEntries(
33
+ methodDefinitions.map((def) => [
34
+ def.path,
35
+ {
36
+ [def.httpMethod.toLowerCase()]: {
37
+ summary: def.description,
38
+ operationId: def.functionName,
39
+ tags: [def.namespace],
40
+ ...(def.httpMethod === 'GET' || def.httpMethod === 'DELETE'
41
+ ? { parameters: buildQueryParameters(def) }
42
+ : {
43
+ requestBody: {
44
+ required: def.parameterOrder.length > 0,
45
+ content: {
46
+ 'application/json': {
47
+ schema: schemaToOpenApi(def.inputSchema),
48
+ },
49
+ },
50
+ },
51
+ }),
52
+ 'x-openwa-aliases': def.routeSignatures.filter((signature) => signature !== `${def.httpMethod} ${def.path}`),
53
+ responses: {
54
+ '200': {
55
+ description: 'Successful response',
56
+ content: {
57
+ 'application/json': {
58
+ schema: schemaToOpenApi(def.outputSchema),
59
+ },
60
+ },
61
+ },
62
+ },
63
+ },
64
+ },
65
+ ])
66
+ );
67
+
68
+ return {
69
+ openapi: '3.0.3',
70
+ info: {
71
+ title: options.title || 'open-wa Easy API',
72
+ version: options.version || '5.0.0',
73
+ },
74
+ servers: [{ url: options.origin }],
75
+ paths,
76
+ };
77
+ }
@@ -0,0 +1,42 @@
1
+ import type { HttpMethodDefinition } from '@open-wa/schema';
2
+
3
+ export function createPostmanCollection(
4
+ methodDefinitions: HttpMethodDefinition[],
5
+ options: { origin: string; basePath?: string; name?: string }
6
+ ) {
7
+ const basePath = options.basePath || '/api';
8
+
9
+ return {
10
+ info: {
11
+ name: options.name || 'open-wa Easy API',
12
+ schema: 'https://schema.getpostman.com/json/collection/v2.1.0/collection.json',
13
+ },
14
+ variable: [
15
+ {
16
+ key: 'baseUrl',
17
+ value: `${options.origin}${basePath}`.replace(/\/api\/api$/, '/api'),
18
+ },
19
+ ],
20
+ item: methodDefinitions.map((def) => ({
21
+ name: def.functionName,
22
+ request: {
23
+ method: 'POST',
24
+ header: [{ key: 'Content-Type', value: 'application/json' }],
25
+ url: {
26
+ raw: `{{baseUrl}}/${def.functionName}`,
27
+ host: ['{{baseUrl}}'],
28
+ path: [def.functionName],
29
+ },
30
+ body: {
31
+ mode: 'raw',
32
+ raw: JSON.stringify(
33
+ Object.fromEntries(def.parameterOrder.map((name) => [name, `<${name}>`])),
34
+ null,
35
+ 2
36
+ ),
37
+ },
38
+ description: def.description,
39
+ },
40
+ })),
41
+ };
42
+ }
@@ -0,0 +1,4 @@
1
+ export interface EventBridge {
2
+ onAny(listener: (event: string, value: any) => void): void;
3
+ offAny(listener: (event: string, value: any) => void): void;
4
+ }