@open-wa/api 5.0.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dashboard-neo/dist/assets/{AgentScalarDrawer.vue-BGBDvSQB.js → AgentScalarDrawer.vue-Cly13x9l.js} +3 -3
  2. package/dashboard-neo/dist/assets/index-CP58_PDI.css +1 -0
  3. package/dashboard-neo/dist/assets/index-Dl0sJuu6.js +2162 -0
  4. package/dashboard-neo/dist/assets/{modal-CKSoZwLD.js → modal-BTlJ4pQT.js} +1 -1
  5. package/dashboard-neo/dist/index.html +2 -2
  6. package/dist/index.cjs +167 -8
  7. package/dist/index.d.cts +1 -0
  8. package/dist/index.d.cts.map +1 -1
  9. package/package.json +5 -4
  10. package/src/auth/api-key.ts +28 -0
  11. package/src/compat/args.ts +1 -0
  12. package/src/compat/deprecation.ts +35 -0
  13. package/src/compat/session-path.ts +19 -0
  14. package/src/createApiMiddleware.ts +184 -0
  15. package/src/createApiServer.ts +472 -0
  16. package/src/dashboard/middleware.ts +94 -0
  17. package/src/diagnostics/DiagnosticStore.ts +99 -0
  18. package/src/docs/openapi.ts +132 -0
  19. package/src/docs/postman.ts +42 -0
  20. package/src/events/EventBridge.ts +4 -0
  21. package/src/events/EventBroadcaster.ts +126 -0
  22. package/src/execution/kernel.ts +1 -0
  23. package/src/health/HealthStore.ts +252 -0
  24. package/src/index.ts +9 -0
  25. package/src/invoke-client-method.ts +1 -0
  26. package/src/middleware/rate-limit.ts +30 -0
  27. package/src/monitoring/elastic.ts +104 -0
  28. package/src/routes/agent-discovery.ts +150 -0
  29. package/src/routes/debug.ts +114 -0
  30. package/src/routes/meta.ts +512 -0
  31. package/src/types.ts +31 -0
  32. package/src/version.ts +4 -0
  33. package/dashboard-neo/dist/assets/index-DM5k7cbF.css +0 -1
  34. package/dashboard-neo/dist/assets/index-rjufqWkX.js +0 -2149
package/dist/index.cjs CHANGED
@@ -194,6 +194,10 @@ function createApiMiddleware(clientSource, options) {
194
194
  return app;
195
195
  }
196
196
  //#endregion
197
+ //#region src/version.ts
198
+ /** Version of the API package running the Easy API server. */
199
+ const API_VERSION = "5.2.0";
200
+ //#endregion
197
201
  //#region src/docs/openapi.ts
198
202
  function schemaToOpenApi(schema) {
199
203
  if (typeof schema?.toJSONSchema === "function") return schema.toJSONSchema({ target: "openapi-3.0" });
@@ -226,14 +230,76 @@ function createOpenApiDocument(methodDefinitions, options) {
226
230
  "x-openwa-aliases": def.routeSignatures.filter((signature) => signature !== `${def.httpMethod} ${def.path}`),
227
231
  responses: { "200": {
228
232
  description: "Successful response",
229
- content: { "application/json": { schema: schemaToOpenApi(def.outputSchema) } }
230
- } }
233
+ content: { "application/json": { schema: (0, _open_wa_schema.successResponseSchema)(def.outputSchema) } }
234
+ } },
235
+ "400": {
236
+ description: "Validation error",
237
+ content: { "application/json": {
238
+ schema: {
239
+ type: "object",
240
+ required: ["error", "details"],
241
+ properties: {
242
+ error: {
243
+ type: "string",
244
+ enum: ["Validation Error"]
245
+ },
246
+ details: {
247
+ type: "array",
248
+ items: {
249
+ type: "object",
250
+ required: [
251
+ "code",
252
+ "path",
253
+ "message"
254
+ ],
255
+ properties: {
256
+ code: { type: "string" },
257
+ path: {
258
+ type: "array",
259
+ items: { oneOf: [{ type: "string" }, { type: "integer" }] }
260
+ },
261
+ message: { type: "string" }
262
+ },
263
+ additionalProperties: true
264
+ }
265
+ }
266
+ },
267
+ additionalProperties: false
268
+ },
269
+ examples: { validationError: {
270
+ summary: "Input validation failed",
271
+ value: {
272
+ error: "Validation Error",
273
+ details: [{
274
+ code: "invalid_type",
275
+ path: ["to"],
276
+ message: "Invalid input"
277
+ }]
278
+ }
279
+ } }
280
+ } }
281
+ },
282
+ "500": {
283
+ description: "Internal server error",
284
+ content: { "application/json": {
285
+ schema: {
286
+ type: "object",
287
+ required: ["error"],
288
+ properties: { error: { type: "string" } },
289
+ additionalProperties: false
290
+ },
291
+ examples: { internalError: {
292
+ summary: "Execution failed",
293
+ value: { error: "Internal Server Error" }
294
+ } }
295
+ } }
296
+ }
231
297
  } }]));
232
298
  return {
233
299
  openapi: "3.0.3",
234
300
  info: {
235
301
  title: options.title || "open-wa Easy API",
236
- version: options.version || "5.0.0"
302
+ version: options.version || API_VERSION
237
303
  },
238
304
  servers: [{ url: options.origin }],
239
305
  paths
@@ -723,6 +789,14 @@ function registerMetaRoutes(app, options) {
723
789
  //#endregion
724
790
  //#region src/routes/debug.ts
725
791
  function registerDebugRoutes(app, options) {
792
+ app.get("/meta/debug/diagnostics", (c) => {
793
+ const apiKey = options.config.apiKey;
794
+ if (!apiKey || c.req.header("X-API-Key") !== apiKey) return c.json({
795
+ error: "Unauthorized",
796
+ details: "Invalid or missing API key"
797
+ }, 401);
798
+ return c.json(options.getDiagnostics());
799
+ });
726
800
  app.get("/meta/debug/memory", (c) => {
727
801
  const mem = process.memoryUsage();
728
802
  return c.json({
@@ -972,12 +1046,12 @@ var HealthStore = class {
972
1046
  const startTime = this.stepStarts.get(step);
973
1047
  const durationMs = startTime ? ts - startTime : 0;
974
1048
  this.stepStarts.delete(step);
975
- const details = data;
1049
+ const details = data?.details && typeof data.details === "object" ? data.details : data;
976
1050
  const hasFailed = details?.success === false || details?.blockingFailure === true;
977
1051
  this.addTimelineStep({
978
1052
  step,
979
1053
  status: hasFailed ? "failed" : "done",
980
- durationMs: details?.durationMs || durationMs,
1054
+ durationMs: data?.durationMs ?? durationMs,
981
1055
  details: details ? this.sanitizeDetails(details) : void 0,
982
1056
  timestamp: ts
983
1057
  });
@@ -985,6 +1059,11 @@ var HealthStore = class {
985
1059
  if (step === "launch.license.preload" || step === "launch.license.check") this.captureLicenseInfo(details);
986
1060
  return;
987
1061
  }
1062
+ if (event === "license.inject.after") {
1063
+ const details = data?.details;
1064
+ if (details && typeof details === "object") this.captureLicenseInfo(details);
1065
+ return;
1066
+ }
988
1067
  if (event === "launch.create.start") {
989
1068
  this.startedAt = ts;
990
1069
  this.addTimelineStep({
@@ -1074,8 +1153,8 @@ var HealthStore = class {
1074
1153
  if (!details) return;
1075
1154
  this.license = {
1076
1155
  status: details.status || "missing",
1077
- source: details.source || "unknown",
1078
- keyType: details.payloadSource || "unknown",
1156
+ source: details.source || this.license?.source || "unknown",
1157
+ keyType: details.keyType || this.license?.keyType || "unknown",
1079
1158
  detail: details.detail || `License ${details.status || "check complete"}`
1080
1159
  };
1081
1160
  }
@@ -1094,6 +1173,82 @@ var HealthStore = class {
1094
1173
  }
1095
1174
  };
1096
1175
  //#endregion
1176
+ //#region src/diagnostics/DiagnosticStore.ts
1177
+ const MAX_RECORDS = 100;
1178
+ const MAX_TEXT = 8e3;
1179
+ function text(value, limit = 500) {
1180
+ if (typeof value !== "string" || !value.trim()) return null;
1181
+ const clean = value.trim();
1182
+ if (clean.length <= limit) return clean;
1183
+ const notice = `\n[truncated at ${limit} characters]`;
1184
+ return `${clean.slice(0, limit - notice.length)}${notice}`;
1185
+ }
1186
+ function unwrap(payload) {
1187
+ if (!payload || typeof payload !== "object") return {};
1188
+ const record = payload;
1189
+ const nested = record.details ?? record.ctx ?? record.payload;
1190
+ return nested && typeof nested === "object" ? nested : record;
1191
+ }
1192
+ function isErrorEvent(event, payload) {
1193
+ const outer = payload && typeof payload === "object" ? payload : {};
1194
+ const nested = unwrap(payload);
1195
+ const records = outer === nested ? [outer] : [outer, nested];
1196
+ const levels = records.map((record) => String(record.level ?? record.severity ?? record.type ?? record.kind ?? "").toLowerCase());
1197
+ if (records.some((record) => record.warning === true) || levels.some((level) => [
1198
+ "warn",
1199
+ "warning",
1200
+ "info",
1201
+ "debug",
1202
+ "trace",
1203
+ "verbose"
1204
+ ].includes(level))) return false;
1205
+ if (event === "error") return true;
1206
+ const nestedError = nested.error && typeof nested.error === "object" ? nested.error : null;
1207
+ return event === "debug:log" && (levels.some((level) => level === "error" || level === "fatal") || payload instanceof Error || records.some((record) => record.error instanceof Error) || Boolean(nestedError && (typeof nestedError.message === "string" || typeof nestedError.stack === "string")) || records.some((record) => Boolean(record.stack) && record.fatal !== false));
1208
+ }
1209
+ /** Holds structured runtime errors observed on this API server's event bridge. */
1210
+ var DiagnosticStore = class {
1211
+ constructor() {
1212
+ this.nextId = 0;
1213
+ this.records = [];
1214
+ this.attached = false;
1215
+ }
1216
+ attach() {
1217
+ this.attached = true;
1218
+ }
1219
+ capture(event, payload) {
1220
+ if (!isErrorEvent(event, payload)) return;
1221
+ const outer = payload && typeof payload === "object" ? payload : {};
1222
+ const record = unwrap(payload);
1223
+ const error = record.error instanceof Error ? record.error : outer.error instanceof Error ? outer.error : null;
1224
+ const errorRecord = record.error && typeof record.error === "object" ? record.error : {};
1225
+ const stackValue = error?.stack ?? errorRecord.stack ?? record.stack ?? record.trace;
1226
+ const message = text(error?.message ?? errorRecord.message ?? record.message ?? record.msg ?? (typeof record.error === "string" ? record.error : void 0) ?? (event === "error" && typeof payload === "string" ? payload : void 0), 1500) ?? text(typeof stackValue === "string" ? stackValue.split(/\r?\n/, 1)[0] : null, 1500);
1227
+ if (!message) return;
1228
+ const stack = text(stackValue, MAX_TEXT);
1229
+ this.records.push({
1230
+ id: ++this.nextId,
1231
+ event,
1232
+ timestamp: Date.now(),
1233
+ message,
1234
+ stack,
1235
+ scope: text(record.scope ?? record.name, 240),
1236
+ method: text(record.method ?? record.operation, 240),
1237
+ route: text(record.route ?? record.path ?? record.endpoint, 240),
1238
+ component: text(record.component ?? record.source ?? record.module, 240)
1239
+ });
1240
+ if (this.records.length > MAX_RECORDS) this.records.splice(0, this.records.length - MAX_RECORDS);
1241
+ }
1242
+ getSnapshot() {
1243
+ return {
1244
+ available: this.attached,
1245
+ captureSource: "session event bridge",
1246
+ captureLimit: MAX_RECORDS,
1247
+ records: this.records.slice()
1248
+ };
1249
+ }
1250
+ };
1251
+ //#endregion
1097
1252
  //#region src/events/EventBroadcaster.ts
1098
1253
  const DEFAULT_KEEPALIVE_MS = 2e4;
1099
1254
  function normalizeTopics(topics) {
@@ -1290,6 +1445,7 @@ var ApiServer = class {
1290
1445
  this.latestQR = null;
1291
1446
  this.isDashboardActive = false;
1292
1447
  this.healthStore = new HealthStore();
1448
+ this.diagnosticStore = new DiagnosticStore();
1293
1449
  this.config = options.config;
1294
1450
  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.");
1295
1451
  this.app = new hono.Hono();
@@ -1315,9 +1471,11 @@ var ApiServer = class {
1315
1471
  this.eventBridge = bridge;
1316
1472
  this.eventBridgeListener = (event, payload) => {
1317
1473
  this.healthStore.processEvent(event, payload);
1474
+ this.diagnosticStore.capture(event, payload);
1318
1475
  this.eventBroadcaster.broadcast(event, payload);
1319
1476
  };
1320
1477
  bridge.onAny(this.eventBridgeListener);
1478
+ this.diagnosticStore.attach();
1321
1479
  }
1322
1480
  setReadinessProvider(provider) {
1323
1481
  this.readinessProvider = provider;
@@ -1437,7 +1595,7 @@ var ApiServer = class {
1437
1595
  const healthSnapshot = this.healthStore.getSnapshot();
1438
1596
  return c.json({
1439
1597
  status: "ok",
1440
- version: "5.0.0",
1598
+ version: API_VERSION,
1441
1599
  host: {
1442
1600
  available: true,
1443
1601
  api: true,
@@ -1514,6 +1672,7 @@ var ApiServer = class {
1514
1672
  registerDebugRoutes(this.app, {
1515
1673
  config: this.config,
1516
1674
  getConfig: () => this.config,
1675
+ getDiagnostics: () => this.diagnosticStore.getSnapshot(),
1517
1676
  setIntegration: (id, data) => {
1518
1677
  if (!this.config.integrations) this.config.integrations = {};
1519
1678
  this.config.integrations[id] = data;
package/dist/index.d.cts CHANGED
@@ -100,6 +100,7 @@ export declare class ApiServer {
100
100
  private isDashboardActive;
101
101
  private pluginHost?;
102
102
  private healthStore;
103
+ private diagnosticStore;
103
104
  private eventBroadcaster;
104
105
  private eventBridge?;
105
106
  private eventBridgeListener?;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/events/EventBridge.ts","../src/events/EventBroadcaster.ts","../src/monitoring/elastic.ts","../src/types.ts","../src/createApiServer.ts","../src/createApiMiddleware.ts","../src/auth/api-key.ts","../src/middleware/rate-limit.ts"],"mappings":";;;;;;;UAAiB;EACf,MAAM,WAAW,eAAe;EAChC,OAAO,WAAW,eAAe;;;;UCFlB;EACf;EACA;EACA;EACA;EACA;;UAQe;EACf;EACA,SAAS;EACT;;qBAiBW;mBACM;mBACA;UACT;UACA;UACA;EAER,YAAY;EAIL,UAAU,eAAe,mBAAmB;EAsB5C,aAAa,UAAS,qBAA0B,eAAe;EAwD/D;;;;UCxHQ;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;GACC;;qBAGU;UACH;UACA;UACA;UACA;EAER,YAAY,QAAQ;EAsBP,SAAS;EAOf,IAAI,UAAU,KAAK;EAYb,SAAS;EAmBT,QAAQ;;;;KC1FX,kBAAkB,mBAAmB,gBAAgB;KACrD,eAAe,qCAAqC;UAE/C;EACf,QAAQ;EACR;EACA;EACA,oBAAoB;EACpB,iBAAiB;EACjB;;UASe;EACf,QAAQ;;;;qBCqBG;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAWR,YAAY,SAAS;EAmCd,UAAU,QAAQ;EAIlB,eAAe,QAAQ;EAevB,qBACL;IAGU;IACA;IACA;IACA;IACA;IACA;;EAYC,QAAQ,MAAM,kBAAkB;EAOhC,aAAa;EAInB,MAAM;EAIN,UAAM,0BAAA,+BAAA;EAIN,uBAAmB;EAQnB,aAAa,YAAY;EASnB,SAAK;EAiDL,QAAI;EAcV;UAIC;UAeA;UAwCA;;wBAgKM,gBAAgB,QAAQ,SAAM;;;wBC9Y9B,oBAAoB,cAAc,cAAc,SAAS,uBAAoB,0BAAA,+BAAA;;;wBC9D7E,iBAAiB,kBAAc,GAC5B,SAAO,MAAQ,SAAI,gBAAA,0BAAA;;;;;;wBCUtB,oBAAoB,sBAAmB,qBAAgB,GACpD,SAAO,MAAQ,SAAI,gBAAA,0BAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/events/EventBridge.ts","../src/events/EventBroadcaster.ts","../src/monitoring/elastic.ts","../src/types.ts","../src/createApiServer.ts","../src/createApiMiddleware.ts","../src/auth/api-key.ts","../src/middleware/rate-limit.ts"],"mappings":";;;;;;;UAAiB;EACf,MAAM,WAAW,eAAe;EAChC,OAAO,WAAW,eAAe;;;;UCFlB;EACf;EACA;EACA;EACA;EACA;;UAQe;EACf;EACA,SAAS;EACT;;qBAiBW;mBACM;mBACA;UACT;UACA;UACA;EAER,YAAY;EAIL,UAAU,eAAe,mBAAmB;EAsB5C,aAAa,UAAS,qBAA0B,eAAe;EAwD/D;;;;UCxHQ;EACf;EACA;EACA;EACA;EACA;EACA;;UAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;GACC;;qBAGU;UACH;UACA;UACA;UACA;EAER,YAAY,QAAQ;EAsBP,SAAS;EAOf,IAAI,UAAU,KAAK;EAYb,SAAS;EAmBT,QAAQ;;;;KC1FX,kBAAkB,mBAAmB,gBAAgB;KACrD,eAAe,qCAAqC;UAE/C;EACf,QAAQ;EACR;EACA;EACA,oBAAoB;EACpB,iBAAiB;EACjB;;UASe;EACf,QAAQ;;;;qBCuBG;UACH;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAWR,YAAY,SAAS;EAmCd,UAAU,QAAQ;EAIlB,eAAe,QAAQ;EAiBvB,qBACL;IAGU;IACA;IACA;IACA;IACA;IACA;;EAYC,QAAQ,MAAM,kBAAkB;EAOhC,aAAa;EAInB,MAAM;EAIN,UAAM,0BAAA,+BAAA;EAIN,uBAAmB;EAQnB,aAAa,YAAY;EASnB,SAAK;EAiDL,QAAI;EAcV;UAIC;UAeA;UAwCA;;wBAiKM,gBAAgB,QAAQ,SAAM;;;wBCpZ9B,oBAAoB,cAAc,cAAc,SAAS,uBAAoB,0BAAA,+BAAA;;;wBC9D7E,iBAAiB,kBAAc,GAC5B,SAAO,MAAQ,SAAI,gBAAA,0BAAA;;;;;;wBCUtB,oBAAoB,sBAAmB,qBAAgB,GACpD,SAAO,MAAQ,SAAI,gBAAA,0BAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-wa/api",
3
- "version": "5.0.0",
3
+ "version": "5.2.0",
4
4
  "description": "Reusable Easy API transport and runtime explorer layer for open-wa",
5
5
  "main": "./dist/index.cjs",
6
6
  "types": "./dist/index.d.cts",
@@ -12,15 +12,16 @@
12
12
  }
13
13
  },
14
14
  "files": [
15
+ "src",
15
16
  "dist",
16
17
  "dashboard-neo/dist"
17
18
  ],
18
19
  "dependencies": {
19
20
  "@elastic/elasticsearch": "^9.5.1",
20
21
  "@hono/node-server": "^2.1.1",
21
- "@open-wa/mcp": "5.0.0",
22
- "@open-wa/schema": "5.0.0",
23
- "@open-wa/screencaster": "5.0.0",
22
+ "@open-wa/mcp": "5.2.0",
23
+ "@open-wa/schema": "5.2.0",
24
+ "@open-wa/screencaster": "5.2.0",
24
25
  "hono": "^4.13.9",
25
26
  "tree-kill": "^1.2.2",
26
27
  "ws": "^8.22.0"
@@ -0,0 +1,28 @@
1
+ import type { Context, Next } from 'hono';
2
+ import { applyDeprecationHeaders } from '../compat/deprecation';
3
+
4
+ export function apiKeyMiddleware(apiKey: string) {
5
+ return async (c: Context, next: Next) => {
6
+ const queryKey = c.req.query('api_key') || c.req.query('key');
7
+ const headerKey =
8
+ c.req.header('X-API-Key') ||
9
+ c.req.header('api_key') ||
10
+ c.req.header('key');
11
+
12
+ const resolvedKey = queryKey || headerKey;
13
+
14
+ if (c.req.query('api_key') || c.req.query('key') || c.req.header('api_key') || c.req.header('key')) {
15
+ applyDeprecationHeaders(c, {
16
+ route: 'legacy-api-key-alias',
17
+ message: 'Legacy API key aliases are deprecated.',
18
+ replacement: 'X-API-Key header',
19
+ });
20
+ }
21
+
22
+ if (!resolvedKey || resolvedKey !== apiKey) {
23
+ return c.json({ error: 'Unauthorized', details: 'Invalid or missing API key' }, 401);
24
+ }
25
+
26
+ return await next();
27
+ };
28
+ }
@@ -0,0 +1 @@
1
+ export { normalizeMethodPayload } from '@open-wa/mcp';
@@ -0,0 +1,35 @@
1
+ export interface DeprecationNotice {
2
+ route: string;
3
+ message: string;
4
+ replacement?: string;
5
+ }
6
+
7
+ export function applyDeprecationHeaders(c: any, notice: DeprecationNotice) {
8
+ const parts = [notice.message];
9
+
10
+ if (notice.replacement) {
11
+ parts.push(`Use ${notice.replacement} instead.`);
12
+ }
13
+
14
+ c.header('X-OpenWA-Deprecated', notice.route);
15
+ c.header('Warning', `299 open-wa "${parts.join(' ')}"`);
16
+ }
17
+
18
+ export function deprecatedJson(
19
+ c: any,
20
+ notice: DeprecationNotice,
21
+ status = 200,
22
+ extra: Record<string, unknown> = {}
23
+ ) {
24
+ applyDeprecationHeaders(c, notice);
25
+ return c.json(
26
+ {
27
+ deprecated: true,
28
+ route: notice.route,
29
+ message: notice.message,
30
+ replacement: notice.replacement,
31
+ ...extra,
32
+ },
33
+ status as any
34
+ );
35
+ }
@@ -0,0 +1,19 @@
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
+ }
@@ -0,0 +1,184 @@
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
+ }