@open-wa/api 5.0.0-alpha.3 ā 5.0.0-alpha.5
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/dashboard-neo/dist/assets/AgentScalarChatInterface.vue-BEM-e96p.js +18 -0
- package/dashboard-neo/dist/assets/Collection.vue-K8xkab2p.js +1 -0
- package/dashboard-neo/dist/assets/CollectionAuthentication.vue-DpUuH8Ca.js +1 -0
- package/dashboard-neo/dist/assets/CollectionCookies.vue-jgiUddei.js +1 -0
- package/dashboard-neo/dist/assets/CollectionEnvironment.vue-B0oC2CBH.js +1 -0
- package/dashboard-neo/dist/assets/CollectionOverview.vue-C5go3_xX.js +1 -0
- package/dashboard-neo/dist/assets/CollectionScripts.vue-DoZD9KS_.js +1 -0
- package/dashboard-neo/dist/assets/CollectionServers.vue-Dh15RVkK.js +1 -0
- package/dashboard-neo/dist/assets/CollectionSettings.vue-Bo9YqB0V.js +1 -0
- package/dashboard-neo/dist/assets/CollectionSync.vue-CfzmGYPL.js +1 -0
- package/dashboard-neo/dist/assets/Cookies.vue-y9E-rz2Y.js +1 -0
- package/dashboard-neo/dist/assets/DataTableInput.vue-D1oakGxr.js +1 -0
- package/dashboard-neo/dist/assets/DeleteSidebarListElement.vue-CsxnO1Bf.js +1 -0
- package/dashboard-neo/dist/assets/EditSidebarListElement.vue-BLjFSHLy.js +1 -0
- package/dashboard-neo/dist/assets/EmptyState.vue-Dt8wow3H.js +22 -0
- package/dashboard-neo/dist/assets/Environment.vue-Cb7A1mCr.js +1 -0
- package/dashboard-neo/dist/assets/EnvironmentModal.vue-DQS71tA1.js +1 -0
- package/dashboard-neo/dist/assets/Form.vue-CRMOM5yS.js +1 -0
- package/dashboard-neo/dist/assets/IconSelector.vue-m_NkHq-F.js +1 -0
- package/dashboard-neo/dist/assets/Request.vue-Do_GjDpa.js +1 -0
- package/dashboard-neo/dist/assets/RequestAuth.vue-DmCKBgQ0.js +1 -0
- package/dashboard-neo/dist/assets/RequestRoot.vue-BwCfLWGZ.js +19 -0
- package/dashboard-neo/dist/assets/Settings.vue-BXMJh3oE.js +1 -0
- package/dashboard-neo/dist/assets/SidebarButton.vue-Bw3z_ul7.js +1 -0
- package/dashboard-neo/dist/assets/SidebarListElement.vue-B_wb5A8B.js +1 -0
- package/dashboard-neo/dist/assets/basic-shape-diamond.svg-DSX6HE6C.js +1 -0
- package/dashboard-neo/dist/assets/basic-shape-hexagon.svg-D8TPOjRl.js +1 -0
- package/dashboard-neo/dist/assets/basic-shape-primary-circle-ellipse-round.svg-CpVktaCn.js +1 -0
- package/dashboard-neo/dist/assets/basic-shape-primary-square-rectangle.svg-CPu9zgKh.js +1 -0
- package/dashboard-neo/dist/assets/basic-shape-shield.svg-4IKVW7Xp.js +1 -0
- package/dashboard-neo/dist/assets/build-request-security-CGOYAw-J.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-desktop-monitor.svg-1HvbvOnd.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-desktop.svg-CtqcYXx1.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-laptop.svg-B2bM3iWZ.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-mobile-phone-android-samsung-back.svg-CtCumQJw.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-mobile-phone-android-samsung.svg-CTqTksmB.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-mobile-phone-iphone-x-back.svg-BKEERhEs.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-mobile-phone-iphone-x.svg-Eq6WEm3S.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-mobile-tablet-touch.svg-CUKTlTEy.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-mobile-tablet.svg-B835AKCv.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-network-ethernet-cat6.svg-CusgQ5zm.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-network-lan-www.svg-DZYss8vi.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-network-wifi-connection.svg-cILX5shc.js +1 -0
- package/dashboard-neo/dist/assets/computer-device-network-wifi-router.svg-ZbvUMvW1.js +1 -0
- package/dashboard-neo/dist/assets/dist-CBT2ukx1.js +1 -0
- package/dashboard-neo/dist/assets/ecology-science-erlenmeyer-flask.svg-DntGEszJ.js +1 -0
- package/dashboard-neo/dist/assets/geist-cyrillic-wght-normal-CHSlOQsW.woff2 +0 -0
- package/dashboard-neo/dist/assets/geist-latin-ext-wght-normal-DMtmJ5ZE.woff2 +0 -0
- package/dashboard-neo/dist/assets/geist-latin-wght-normal-Dm3htQBi.woff2 +0 -0
- package/dashboard-neo/dist/assets/image-flash-lightning.svg-Y3Y6Te6J.js +1 -0
- package/dashboard-neo/dist/assets/image-picture-flower.svg-CAUJHFen.js +1 -0
- package/dashboard-neo/dist/assets/index-CCPRtotd.js +2355 -0
- package/dashboard-neo/dist/assets/index-Oo2D96Pi.css +1 -0
- package/dashboard-neo/dist/assets/interface-alert-exclamation-diamond.svg-d8x2YZNn.js +1 -0
- package/dashboard-neo/dist/assets/interface-alert-exclamation-triangle-warning.svg-BPj89imQ.js +1 -0
- package/dashboard-neo/dist/assets/interface-alert-information-circle.svg-B3_ZhHCU.js +1 -0
- package/dashboard-neo/dist/assets/interface-award-crown.svg-9QzG81ME.js +1 -0
- package/dashboard-neo/dist/assets/interface-bookmark-tag.svg-zyBnDZXV.js +1 -0
- package/dashboard-neo/dist/assets/interface-bookmark.svg-BokfxgR_.js +1 -0
- package/dashboard-neo/dist/assets/interface-calendar-date-one.svg-BG-gZa9b.js +1 -0
- package/dashboard-neo/dist/assets/interface-content-book-open-pages.svg-2LtAxgBC.js +1 -0
- package/dashboard-neo/dist/assets/interface-content-book-page.svg-Ck6AkesE.js +1 -0
- package/dashboard-neo/dist/assets/interface-content-file.svg-DTYoClw_.js +1 -0
- package/dashboard-neo/dist/assets/interface-content-folder.svg-DmEiVPx0.js +1 -0
- package/dashboard-neo/dist/assets/interface-copy-clipboard.svg-CFus7XXk.js +1 -0
- package/dashboard-neo/dist/assets/interface-edit-attachment.svg-ip-RcK7K.js +1 -0
- package/dashboard-neo/dist/assets/interface-edit-binocular.svg-Ci4HHNIj.js +1 -0
- package/dashboard-neo/dist/assets/interface-edit-magic-wand.svg-DGQaaElT.js +1 -0
- package/dashboard-neo/dist/assets/interface-edit-tool-paint-roller.svg-CvdyF2GE.js +1 -0
- package/dashboard-neo/dist/assets/interface-edit-tool-pencil.svg-PzM9gUeP.js +1 -0
- package/dashboard-neo/dist/assets/interface-favorite-award.svg-D4J0srBs.js +1 -0
- package/dashboard-neo/dist/assets/interface-favorite-flag.svg-BMfv0feo.js +1 -0
- package/dashboard-neo/dist/assets/interface-favorite-heart.svg-BOAdq0BP.js +1 -0
- package/dashboard-neo/dist/assets/interface-favorite-star.svg-BGYVoec6.js +1 -0
- package/dashboard-neo/dist/assets/interface-favorite-stars-sparkles.svg-DqvQo_6g.js +1 -0
- package/dashboard-neo/dist/assets/interface-hierarchy-flowchart.svg-GtL4lLOG.js +1 -0
- package/dashboard-neo/dist/assets/interface-home-house.svg-ByuIxm9E.js +1 -0
- package/dashboard-neo/dist/assets/interface-hyperlink.svg-C89foWq5.js +1 -0
- package/dashboard-neo/dist/assets/interface-lighting-brightness.svg-ChIQbj49.js +1 -0
- package/dashboard-neo/dist/assets/interface-lock-closed.svg-BUVt-tMS.js +1 -0
- package/dashboard-neo/dist/assets/interface-lock-open-unlock.svg-DiCIpC_I.js +1 -0
- package/dashboard-neo/dist/assets/interface-login-key.svg-BySvd_q6.js +1 -0
- package/dashboard-neo/dist/assets/interface-search.svg-DHAFxwgB.js +1 -0
- package/dashboard-neo/dist/assets/interface-setting-cog.svg-CZJNW0Qp.js +1 -0
- package/dashboard-neo/dist/assets/interface-share-megaphone-bullhorn.svg-Cf4N4ThN.js +1 -0
- package/dashboard-neo/dist/assets/interface-share-rocket.svg-DSexRWyi.js +1 -0
- package/dashboard-neo/dist/assets/interface-share-satellite.svg-DEhioy9C.js +1 -0
- package/dashboard-neo/dist/assets/interface-share-space-ship.svg-DJ2GwTST.js +1 -0
- package/dashboard-neo/dist/assets/interface-share.svg-AKwkJy5n.js +1 -0
- package/dashboard-neo/dist/assets/interface-signal-square.svg-BvwEOUAz.js +1 -0
- package/dashboard-neo/dist/assets/interface-time-clock-circle.svg-DKSsyftW.js +1 -0
- package/dashboard-neo/dist/assets/interface-time-hour-glass.svg-Beix5CQK.js +1 -0
- package/dashboard-neo/dist/assets/interface-users-multiple.svg-CCK9Jspv.js +1 -0
- package/dashboard-neo/dist/assets/interface-weather-moon.svg-jTm4hfXN.js +1 -0
- package/dashboard-neo/dist/assets/mail-chat-bubble-square.svg-BgP35Rk8.js +1 -0
- package/dashboard-neo/dist/assets/mail-send-email-paper-airplane.svg-C21cjIbh.js +1 -0
- package/dashboard-neo/dist/assets/mail-send-envelope.svg-DIAAOaDX.js +1 -0
- package/dashboard-neo/dist/assets/money-cashier-receipt.svg-v-s0fxDU.js +1 -0
- package/dashboard-neo/dist/assets/money-currency-dollar-pay.svg-rgB3LEAf.js +1 -0
- package/dashboard-neo/dist/assets/money-graph-arrow-increase.svg-CNbgQBLG.js +1 -0
- package/dashboard-neo/dist/assets/money-graph-bar-chart-increase.svg-NQo1v4xC.js +1 -0
- package/dashboard-neo/dist/assets/nature-ecology-leaf.svg-vGhsbpt0.js +1 -0
- package/dashboard-neo/dist/assets/phone-telephone.svg-DRQCKRxO.js +1 -0
- package/dashboard-neo/dist/assets/programming-bug.svg-B9Gbws6t.js +1 -0
- package/dashboard-neo/dist/assets/programming-cloud.svg-jmIeTucH.js +1 -0
- package/dashboard-neo/dist/assets/programming-computer-database-server.svg-MOV-SlSh.js +1 -0
- package/dashboard-neo/dist/assets/programming-computer-database.svg-ChO7iZyg.js +1 -0
- package/dashboard-neo/dist/assets/programming-module-four-layout.svg-DTARmxUz.js +1 -0
- package/dashboard-neo/dist/assets/programming-module-three.svg-6GRL_949.js +1 -0
- package/dashboard-neo/dist/assets/programming-module.svg-DxyUt2RE.js +1 -0
- package/dashboard-neo/dist/assets/programming-script-code.svg-D38umHb6.js +1 -0
- package/dashboard-neo/dist/assets/shopping-cart.svg--6vpSNLL.js +1 -0
- package/dashboard-neo/dist/assets/shopping-gift-present.svg-ChCol47c.js +1 -0
- package/dashboard-neo/dist/assets/shopping-shipping-box-parcel-package.svg-kFdGUfEt.js +1 -0
- package/dashboard-neo/dist/assets/tag-new-circle.svg-D1ph809h.js +1 -0
- package/dashboard-neo/dist/assets/travel-map-earth-globe.svg-meBGbHvi.js +1 -0
- package/dashboard-neo/dist/favicon.ico +0 -0
- package/dashboard-neo/dist/index.html +14 -0
- package/dashboard-neo/dist/manifest.json +25 -0
- package/dashboard-neo/dist/robots.txt +3 -0
- package/dist/index.cjs +2 -0
- package/package.json +11 -6
- package/.turbo/turbo-build.log +0 -20
- package/.turbo/turbo-test.log +0 -56
- package/CHANGELOG.md +0 -43
- package/src/auth/api-key.ts +0 -28
- package/src/compat/args.ts +0 -1
- package/src/compat/deprecation.ts +0 -35
- package/src/compat/session-path.ts +0 -19
- package/src/createApiMiddleware.ts +0 -184
- package/src/createApiServer.ts +0 -414
- package/src/dashboard/middleware.ts +0 -85
- package/src/docs/openapi.ts +0 -77
- package/src/docs/postman.ts +0 -42
- package/src/events/EventBridge.ts +0 -4
- package/src/events/EventBroadcaster.ts +0 -126
- package/src/execution/kernel.ts +0 -1
- package/src/health/HealthStore.ts +0 -242
- package/src/index.ts +0 -9
- package/src/invoke-client-method.ts +0 -1
- package/src/middleware/rate-limit.ts +0 -30
- package/src/monitoring/elastic.ts +0 -104
- package/src/routes/agent-discovery.ts +0 -150
- package/src/routes/debug.ts +0 -99
- package/src/routes/meta.ts +0 -512
- package/src/types.ts +0 -31
- package/test/mcp-integration.test.ts +0 -142
- package/tsconfig.json +0 -18
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
export function assertSessionPath(
|
|
2
|
-
expectedSessionId: string,
|
|
3
|
-
requestedSessionId: string | undefined,
|
|
4
|
-
useSessionIdInPath: boolean
|
|
5
|
-
): { ok: true } | { ok: false; status: number; error: string } {
|
|
6
|
-
if (!useSessionIdInPath) {
|
|
7
|
-
return { ok: true };
|
|
8
|
-
}
|
|
9
|
-
|
|
10
|
-
if (!requestedSessionId) {
|
|
11
|
-
return { ok: false, status: 404, error: 'Session id missing from request path' };
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
if (requestedSessionId !== expectedSessionId) {
|
|
15
|
-
return { ok: false, status: 404, error: `Unknown session path: ${requestedSessionId}` };
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
return { ok: true };
|
|
19
|
-
}
|
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
2
|
-
import { getHttpMethodDefinitions, type HttpMethodDefinition } from '@open-wa/schema';
|
|
3
|
-
import '@open-wa/schema/methods';
|
|
4
|
-
import { apiKeyMiddleware } from './auth/api-key';
|
|
5
|
-
import { rateLimitMiddleware } from './middleware/rate-limit';
|
|
6
|
-
import { normalizeMethodPayload } from './compat/args';
|
|
7
|
-
import { assertSessionPath } from './compat/session-path';
|
|
8
|
-
import { invokeClientMethod } from './invoke-client-method';
|
|
9
|
-
import { executeCapability } from './execution/kernel';
|
|
10
|
-
import type { ApiMiddlewareOptions, ClientMethodMap, ClientSource } from './types';
|
|
11
|
-
|
|
12
|
-
function resolveClient(clientSource: ClientSource): ClientMethodMap | undefined {
|
|
13
|
-
return typeof clientSource === 'function' ? clientSource() : clientSource;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
async function readRequestBody(c: any): Promise<Record<string, unknown>> {
|
|
17
|
-
try {
|
|
18
|
-
return await c.req.json();
|
|
19
|
-
} catch {
|
|
20
|
-
return {};
|
|
21
|
-
}
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
function readQueryParams(c: any): Record<string, unknown> {
|
|
25
|
-
const url = new URL(c.req.url);
|
|
26
|
-
return Object.fromEntries(url.searchParams.entries());
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
function toLocalPath(path: string, basePath: string): string {
|
|
30
|
-
const normalizedBase = basePath === '/' ? '' : basePath.replace(/\/+$/, '');
|
|
31
|
-
if (!normalizedBase) {
|
|
32
|
-
return path || '/';
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
if (!path.startsWith(normalizedBase)) {
|
|
36
|
-
return path || '/';
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const stripped = path.slice(normalizedBase.length);
|
|
40
|
-
return stripped.startsWith('/') ? stripped : `/${stripped}`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function createMethodMap(methodDefinitions: HttpMethodDefinition[]) {
|
|
44
|
-
const entries: Array<[string, HttpMethodDefinition]> = [];
|
|
45
|
-
for (const definition of methodDefinitions) {
|
|
46
|
-
for (const name of definition.invocationNames) {
|
|
47
|
-
entries.push([name, definition]);
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
return new Map(entries);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
function shouldBlockForLifecycle(options: ApiMiddlewareOptions): boolean {
|
|
55
|
-
if (!options.isSessionConnected) {
|
|
56
|
-
return false;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
if (options.config.apiLifecycle === 'immediate') {
|
|
60
|
-
return false;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
return !options.isSessionConnected();
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export function createApiMiddleware(clientSource: ClientSource, options: ApiMiddlewareOptions) {
|
|
67
|
-
const app = new Hono();
|
|
68
|
-
const basePath = options.basePath || '/api';
|
|
69
|
-
const methodDefinitions = options.methodDefinitions || getHttpMethodDefinitions(basePath);
|
|
70
|
-
const methods = createMethodMap(methodDefinitions);
|
|
71
|
-
const useSessionIdInPath = options.useSessionIdInPath || false;
|
|
72
|
-
|
|
73
|
-
app.use('/*', rateLimitMiddleware(100, 60000));
|
|
74
|
-
|
|
75
|
-
if (options.config.apiKey) {
|
|
76
|
-
app.use('/*', apiKeyMiddleware(options.config.apiKey));
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
const handleInvocation = async (
|
|
80
|
-
c: any,
|
|
81
|
-
routeMethod: string | undefined,
|
|
82
|
-
routeSessionId?: string,
|
|
83
|
-
routeDefinition?: HttpMethodDefinition,
|
|
84
|
-
) => {
|
|
85
|
-
if (shouldBlockForLifecycle(options)) {
|
|
86
|
-
return c.json({ error: 'API not available until the session is truly ready', status: 503 }, 503);
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
const sessionCheck = assertSessionPath(options.config.sessionId, routeSessionId, useSessionIdInPath);
|
|
90
|
-
|
|
91
|
-
if (!sessionCheck.ok) {
|
|
92
|
-
return c.json({ error: sessionCheck.error }, sessionCheck.status as any);
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const startTime = Date.now();
|
|
96
|
-
const query = readQueryParams(c);
|
|
97
|
-
const body = c.req.method === 'GET' || c.req.method === 'DELETE' ? {} : await readRequestBody(c);
|
|
98
|
-
const payload = { ...body, ...query };
|
|
99
|
-
const methodName = routeMethod || routeDefinition?.functionName || (typeof payload.method === 'string' ? payload.method : undefined);
|
|
100
|
-
|
|
101
|
-
if (!methodName) {
|
|
102
|
-
return c.json({ error: 'Missing method name' }, 400);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const definition = routeDefinition || methods.get(methodName);
|
|
106
|
-
|
|
107
|
-
if (!definition) {
|
|
108
|
-
return c.json({ error: `Unknown method: ${methodName}` }, 404);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const result = await executeCapability({
|
|
112
|
-
client: resolveClient(clientSource),
|
|
113
|
-
definition,
|
|
114
|
-
payload,
|
|
115
|
-
elasticEmitter: options.elasticEmitter,
|
|
116
|
-
sessionId: options.config.sessionId,
|
|
117
|
-
});
|
|
118
|
-
|
|
119
|
-
if (result.success) {
|
|
120
|
-
return c.json({ success: true, data: result.data });
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
return c.json(
|
|
124
|
-
{
|
|
125
|
-
error: result.error,
|
|
126
|
-
details: result.details,
|
|
127
|
-
},
|
|
128
|
-
result.status as any,
|
|
129
|
-
);
|
|
130
|
-
};
|
|
131
|
-
|
|
132
|
-
const redirectToCanonical = (definition: HttpMethodDefinition, c: any) => {
|
|
133
|
-
c.header('X-OpenWA-Aliases', definition.routeSignatures.join(', '));
|
|
134
|
-
const query = new URL(c.req.url).search;
|
|
135
|
-
return c.redirect(`${definition.path}${query}`, 308);
|
|
136
|
-
};
|
|
137
|
-
|
|
138
|
-
for (const definition of methodDefinitions) {
|
|
139
|
-
const localCanonicalPath = toLocalPath(definition.path, basePath);
|
|
140
|
-
app.on(definition.httpMethod, localCanonicalPath, (c) =>
|
|
141
|
-
handleInvocation(c, definition.functionName, undefined, definition),
|
|
142
|
-
);
|
|
143
|
-
|
|
144
|
-
for (const aliasRoute of definition.aliasRoutes) {
|
|
145
|
-
const localAliasPath = toLocalPath(aliasRoute.path, basePath);
|
|
146
|
-
app.on(definition.httpMethod, localAliasPath, (c) => redirectToCanonical(definition, c));
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
app.post('/', (c) => handleInvocation(c, undefined));
|
|
151
|
-
app.post('/:method', (c) => handleInvocation(c, c.req.param('method')));
|
|
152
|
-
app.post('/:namespace/:method', (c) => handleInvocation(c, `${c.req.param('namespace')}.${c.req.param('method')}`));
|
|
153
|
-
|
|
154
|
-
if (useSessionIdInPath) {
|
|
155
|
-
app.post('/:sessionId', (c) => handleInvocation(c, undefined, c.req.param('sessionId')));
|
|
156
|
-
app.post('/:sessionId/:method', (c) =>
|
|
157
|
-
handleInvocation(c, c.req.param('method'), c.req.param('sessionId'))
|
|
158
|
-
);
|
|
159
|
-
app.post('/:sessionId/:namespace/:method', (c) =>
|
|
160
|
-
handleInvocation(
|
|
161
|
-
c,
|
|
162
|
-
`${c.req.param('namespace')}.${c.req.param('method')}`,
|
|
163
|
-
c.req.param('sessionId'),
|
|
164
|
-
)
|
|
165
|
-
);
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
app.get('/', (c) =>
|
|
169
|
-
c.json({
|
|
170
|
-
endpoints: methodDefinitions.map((def) => ({
|
|
171
|
-
method: def.httpMethod,
|
|
172
|
-
path: def.path,
|
|
173
|
-
name: def.functionName,
|
|
174
|
-
namespacedName: def.namespacedName,
|
|
175
|
-
description: def.description,
|
|
176
|
-
category: def.namespace,
|
|
177
|
-
aliases: def.aliases,
|
|
178
|
-
routeSignatures: def.routeSignatures,
|
|
179
|
-
})),
|
|
180
|
-
})
|
|
181
|
-
);
|
|
182
|
-
|
|
183
|
-
return app;
|
|
184
|
-
}
|
package/src/createApiServer.ts
DELETED
|
@@ -1,414 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,85 +0,0 @@
|
|
|
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
|
-
}
|