@gethmy/mcp 2.3.0 → 2.3.2

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 (38) hide show
  1. package/dist/cli.js +80 -23
  2. package/dist/index.js +80 -23
  3. package/dist/lib/active-learning.js +939 -787
  4. package/dist/lib/api-client.js +2527 -638
  5. package/dist/lib/auto-session.js +177 -196
  6. package/dist/lib/cli.js +34954 -128
  7. package/dist/lib/config.js +235 -201
  8. package/dist/lib/consolidation.js +374 -289
  9. package/dist/lib/context-assembly.js +1265 -838
  10. package/dist/lib/graph-expansion.js +139 -155
  11. package/dist/lib/http.js +1917 -130
  12. package/dist/lib/index.js +29525 -5
  13. package/dist/lib/lifecycle-maintenance.js +663 -79
  14. package/dist/lib/memory-cleanup.js +1316 -381
  15. package/dist/lib/onboard.js +2588 -32
  16. package/dist/lib/prompt-builder.js +438 -445
  17. package/dist/lib/remote.js +31733 -143
  18. package/dist/lib/server.js +29389 -3216
  19. package/dist/lib/skills.js +315 -132
  20. package/dist/lib/tui/agents.js +128 -107
  21. package/dist/lib/tui/docs.js +1590 -687
  22. package/dist/lib/tui/setup.js +5698 -804
  23. package/dist/lib/tui/theme.js +183 -86
  24. package/dist/lib/tui/writer.js +1149 -176
  25. package/package.json +2 -2
  26. package/src/api-client.ts +37 -1
  27. package/src/memory-cleanup.ts +92 -52
  28. package/src/server.ts +16 -1
  29. package/dist/lib/__tests__/active-learning.test.js +0 -386
  30. package/dist/lib/__tests__/agent-performance-profiles.test.js +0 -325
  31. package/dist/lib/__tests__/auto-session.test.js +0 -661
  32. package/dist/lib/__tests__/context-assembly.test.js +0 -362
  33. package/dist/lib/__tests__/graph-expansion.test.js +0 -150
  34. package/dist/lib/__tests__/integration-memory-crud.test.js +0 -797
  35. package/dist/lib/__tests__/integration-memory-system.test.js +0 -281
  36. package/dist/lib/__tests__/lifecycle-maintenance.test.js +0 -207
  37. package/dist/lib/__tests__/pattern-detection.test.js +0 -295
  38. package/dist/lib/__tests__/prompt-builder.test.js +0 -418
package/dist/lib/http.js CHANGED
@@ -1,145 +1,1938 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * HTTP REST Adapter for Harmony MCP
4
- *
5
- * This provides a REST API that forwards requests to the Harmony API.
6
- * It accepts Bearer tokens (JWT) or X-API-Key headers for authentication.
7
- *
8
- * This adapter is useful for non-MCP clients that want to interact with
9
- * Harmony via HTTP instead of the MCP stdio protocol.
10
- */
11
- import { serve } from "bun";
12
- import { Hono } from "hono";
13
- import { cors } from "hono/cors";
14
- import { loadConfig } from "./config.js";
15
- const app = new Hono();
16
- // CORS configuration
17
- app.use("/*", cors({
18
- origin: [
19
- "https://gethmy.com",
20
- "https://app.gethmy.com",
21
- "http://localhost:8080",
22
- "http://localhost:3000",
23
- ],
24
- allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
25
- allowHeaders: ["Content-Type", "Authorization", "X-API-Key"],
26
- }));
27
- // Get API URL from config or use default
2
+ import { createRequire } from "node:module";
3
+ var __create = Object.create;
4
+ var __getProtoOf = Object.getPrototypeOf;
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __toESM = (mod, isNodeMode, target) => {
9
+ target = mod != null ? __create(__getProtoOf(mod)) : {};
10
+ const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
11
+ for (let key of __getOwnPropNames(mod))
12
+ if (!__hasOwnProp.call(to, key))
13
+ __defProp(to, key, {
14
+ get: () => mod[key],
15
+ enumerable: true
16
+ });
17
+ return to;
18
+ };
19
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
20
+ var __export = (target, all) => {
21
+ for (var name in all)
22
+ __defProp(target, name, {
23
+ get: all[name],
24
+ enumerable: true,
25
+ configurable: true,
26
+ set: (newValue) => all[name] = () => newValue
27
+ });
28
+ };
29
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
30
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
31
+
32
+ // src/config.ts
33
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
34
+ import { homedir } from "node:os";
35
+ import { join } from "node:path";
36
+ var DEFAULT_API_URL = "https://app.gethmy.com/api";
37
+ var LOCAL_CONFIG_FILENAME = ".harmony-mcp.json";
38
+ function getConfigDir() {
39
+ return join(homedir(), ".harmony-mcp");
40
+ }
41
+ function getConfigPath() {
42
+ return join(getConfigDir(), "config.json");
43
+ }
44
+ function getLocalConfigPath(cwd) {
45
+ return join(cwd || process.cwd(), LOCAL_CONFIG_FILENAME);
46
+ }
47
+ function loadConfig() {
48
+ const configPath = getConfigPath();
49
+ if (!existsSync(configPath)) {
50
+ return {
51
+ apiKey: null,
52
+ apiUrl: DEFAULT_API_URL,
53
+ activeWorkspaceId: null,
54
+ activeProjectId: null,
55
+ userEmail: null,
56
+ memoryDir: null
57
+ };
58
+ }
59
+ try {
60
+ const data = readFileSync(configPath, "utf-8");
61
+ const config = JSON.parse(data);
62
+ return {
63
+ apiKey: config.apiKey || null,
64
+ apiUrl: config.apiUrl || DEFAULT_API_URL,
65
+ activeWorkspaceId: config.activeWorkspaceId || null,
66
+ activeProjectId: config.activeProjectId || null,
67
+ userEmail: config.userEmail || null,
68
+ memoryDir: config.memoryDir || null
69
+ };
70
+ } catch {
71
+ return {
72
+ apiKey: null,
73
+ apiUrl: DEFAULT_API_URL,
74
+ activeWorkspaceId: null,
75
+ activeProjectId: null,
76
+ userEmail: null,
77
+ memoryDir: null
78
+ };
79
+ }
80
+ }
81
+ function saveConfig(config) {
82
+ const configDir = getConfigDir();
83
+ const configPath = getConfigPath();
84
+ if (!existsSync(configDir)) {
85
+ mkdirSync(configDir, { recursive: true, mode: 448 });
86
+ }
87
+ const existingConfig = loadConfig();
88
+ const newConfig = { ...existingConfig, ...config };
89
+ writeFileSync(configPath, JSON.stringify(newConfig, null, 2), {
90
+ mode: 384
91
+ });
92
+ }
93
+ function loadLocalConfig(cwd) {
94
+ const localConfigPath = getLocalConfigPath(cwd);
95
+ if (!existsSync(localConfigPath)) {
96
+ return null;
97
+ }
98
+ try {
99
+ const data = readFileSync(localConfigPath, "utf-8");
100
+ const config = JSON.parse(data);
101
+ return {
102
+ workspaceId: config.workspaceId || null,
103
+ projectId: config.projectId || null
104
+ };
105
+ } catch {
106
+ return null;
107
+ }
108
+ }
109
+ function saveLocalConfig(config, cwd) {
110
+ const localConfigPath = getLocalConfigPath(cwd);
111
+ const existingConfig = loadLocalConfig(cwd) || {
112
+ workspaceId: null,
113
+ projectId: null
114
+ };
115
+ const newConfig = { ...existingConfig, ...config };
116
+ const cleanConfig = {};
117
+ if (newConfig.workspaceId)
118
+ cleanConfig.workspaceId = newConfig.workspaceId;
119
+ if (newConfig.projectId)
120
+ cleanConfig.projectId = newConfig.projectId;
121
+ writeFileSync(localConfigPath, JSON.stringify(cleanConfig, null, 2));
122
+ }
123
+ function hasLocalConfig(cwd) {
124
+ return existsSync(getLocalConfigPath(cwd));
125
+ }
126
+ function getApiKey() {
127
+ const config = loadConfig();
128
+ if (!config.apiKey) {
129
+ throw new Error(`Not configured. Run "npx @gethmy/mcp setup" to set your API key.
130
+ ` + "You can generate an API key at https://gethmy.com → Settings → API Keys.");
131
+ }
132
+ return config.apiKey;
133
+ }
28
134
  function getApiUrl() {
29
- const config = loadConfig();
30
- return config.apiUrl;
135
+ const config = loadConfig();
136
+ return config.apiUrl;
31
137
  }
32
- // Forward request to Harmony API
33
- async function forwardToApi(method, path, authHeader, apiKey, body) {
34
- const apiUrl = getApiUrl();
35
- const headers = {
36
- "Content-Type": "application/json",
138
+ function getUserEmail() {
139
+ const config = loadConfig();
140
+ return config.userEmail;
141
+ }
142
+ function setUserEmail(email) {
143
+ saveConfig({ userEmail: email });
144
+ }
145
+ function setActiveWorkspace(workspaceId, options) {
146
+ if (options?.local) {
147
+ saveLocalConfig({ workspaceId }, options.cwd);
148
+ } else {
149
+ saveConfig({ activeWorkspaceId: workspaceId });
150
+ }
151
+ }
152
+ function setActiveProject(projectId, options) {
153
+ if (options?.local) {
154
+ saveLocalConfig({ projectId }, options.cwd);
155
+ } else {
156
+ saveConfig({ activeProjectId: projectId });
157
+ }
158
+ }
159
+ function getActiveWorkspaceId(cwd) {
160
+ const localConfig = loadLocalConfig(cwd);
161
+ if (localConfig?.workspaceId) {
162
+ return localConfig.workspaceId;
163
+ }
164
+ return loadConfig().activeWorkspaceId;
165
+ }
166
+ function getActiveProjectId(cwd) {
167
+ const localConfig = loadLocalConfig(cwd);
168
+ if (localConfig?.projectId) {
169
+ return localConfig.projectId;
170
+ }
171
+ return loadConfig().activeProjectId;
172
+ }
173
+ function isConfigured() {
174
+ const config = loadConfig();
175
+ return !!config.apiKey;
176
+ }
177
+ function areSkillsInstalled(cwd) {
178
+ const home = homedir();
179
+ const workingDir = cwd || process.cwd();
180
+ const foundPaths = [];
181
+ const globalSkillsDir = join(home, ".agents", "skills");
182
+ const globalSkillPath = join(globalSkillsDir, "hmy", "SKILL.md");
183
+ if (existsSync(globalSkillPath)) {
184
+ foundPaths.push(globalSkillPath);
185
+ return { installed: true, location: "global", paths: foundPaths };
186
+ }
187
+ const claudeGlobalSkill = join(home, ".claude", "skills", "hmy.md");
188
+ if (existsSync(claudeGlobalSkill)) {
189
+ foundPaths.push(claudeGlobalSkill);
190
+ return { installed: true, location: "global", paths: foundPaths };
191
+ }
192
+ const claudeGlobalSkillAlt = join(home, ".claude", "skills", "hmy", "SKILL.md");
193
+ if (existsSync(claudeGlobalSkillAlt)) {
194
+ foundPaths.push(claudeGlobalSkillAlt);
195
+ return { installed: true, location: "global", paths: foundPaths };
196
+ }
197
+ const localSkillPath = join(workingDir, ".claude", "skills", "hmy.md");
198
+ if (existsSync(localSkillPath)) {
199
+ foundPaths.push(localSkillPath);
200
+ return { installed: true, location: "local", paths: foundPaths };
201
+ }
202
+ const localSkillPathAlt = join(workingDir, ".claude", "skills", "hmy", "SKILL.md");
203
+ if (existsSync(localSkillPathAlt)) {
204
+ foundPaths.push(localSkillPathAlt);
205
+ return { installed: true, location: "local", paths: foundPaths };
206
+ }
207
+ return { installed: false, location: null, paths: [] };
208
+ }
209
+ function hasProjectContext(cwd) {
210
+ const localConfig = loadLocalConfig(cwd);
211
+ return !!(localConfig?.workspaceId || localConfig?.projectId);
212
+ }
213
+ function getMemoryDir() {
214
+ const config = loadConfig();
215
+ if (config.memoryDir)
216
+ return config.memoryDir;
217
+ return join(homedir(), ".harmony", "memory");
218
+ }
219
+
220
+ // src/http.ts
221
+ import { serve } from "bun";
222
+
223
+ // ../../node_modules/hono/dist/compose.js
224
+ var compose = (middleware, onError, onNotFound) => {
225
+ return (context, next) => {
226
+ let index = -1;
227
+ return dispatch(0);
228
+ async function dispatch(i) {
229
+ if (i <= index) {
230
+ throw new Error("next() called multiple times");
231
+ }
232
+ index = i;
233
+ let res;
234
+ let isError = false;
235
+ let handler;
236
+ if (middleware[i]) {
237
+ handler = middleware[i][0][0];
238
+ context.req.routeIndex = i;
239
+ } else {
240
+ handler = i === middleware.length && next || undefined;
241
+ }
242
+ if (handler) {
243
+ try {
244
+ res = await handler(context, () => dispatch(i + 1));
245
+ } catch (err) {
246
+ if (err instanceof Error && onError) {
247
+ context.error = err;
248
+ res = await onError(err, context);
249
+ isError = true;
250
+ } else {
251
+ throw err;
252
+ }
253
+ }
254
+ } else {
255
+ if (context.finalized === false && onNotFound) {
256
+ res = await onNotFound(context);
257
+ }
258
+ }
259
+ if (res && (context.finalized === false || isError)) {
260
+ context.res = res;
261
+ }
262
+ return context;
263
+ }
264
+ };
265
+ };
266
+
267
+ // ../../node_modules/hono/dist/request/constants.js
268
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
269
+
270
+ // ../../node_modules/hono/dist/utils/body.js
271
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
272
+ const { all = false, dot = false } = options;
273
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
274
+ const contentType = headers.get("Content-Type");
275
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
276
+ return parseFormData(request, { all, dot });
277
+ }
278
+ return {};
279
+ };
280
+ async function parseFormData(request, options) {
281
+ const formData = await request.formData();
282
+ if (formData) {
283
+ return convertFormDataToBodyData(formData, options);
284
+ }
285
+ return {};
286
+ }
287
+ function convertFormDataToBodyData(formData, options) {
288
+ const form = /* @__PURE__ */ Object.create(null);
289
+ formData.forEach((value, key) => {
290
+ const shouldParseAllValues = options.all || key.endsWith("[]");
291
+ if (!shouldParseAllValues) {
292
+ form[key] = value;
293
+ } else {
294
+ handleParsingAllValues(form, key, value);
295
+ }
296
+ });
297
+ if (options.dot) {
298
+ Object.entries(form).forEach(([key, value]) => {
299
+ const shouldParseDotValues = key.includes(".");
300
+ if (shouldParseDotValues) {
301
+ handleParsingNestedValues(form, key, value);
302
+ delete form[key];
303
+ }
304
+ });
305
+ }
306
+ return form;
307
+ }
308
+ var handleParsingAllValues = (form, key, value) => {
309
+ if (form[key] !== undefined) {
310
+ if (Array.isArray(form[key])) {
311
+ form[key].push(value);
312
+ } else {
313
+ form[key] = [form[key], value];
314
+ }
315
+ } else {
316
+ if (!key.endsWith("[]")) {
317
+ form[key] = value;
318
+ } else {
319
+ form[key] = [value];
320
+ }
321
+ }
322
+ };
323
+ var handleParsingNestedValues = (form, key, value) => {
324
+ let nestedForm = form;
325
+ const keys = key.split(".");
326
+ keys.forEach((key2, index) => {
327
+ if (index === keys.length - 1) {
328
+ nestedForm[key2] = value;
329
+ } else {
330
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
331
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
332
+ }
333
+ nestedForm = nestedForm[key2];
334
+ }
335
+ });
336
+ };
337
+
338
+ // ../../node_modules/hono/dist/utils/url.js
339
+ var splitPath = (path) => {
340
+ const paths = path.split("/");
341
+ if (paths[0] === "") {
342
+ paths.shift();
343
+ }
344
+ return paths;
345
+ };
346
+ var splitRoutingPath = (routePath) => {
347
+ const { groups, path } = extractGroupsFromPath(routePath);
348
+ const paths = splitPath(path);
349
+ return replaceGroupMarks(paths, groups);
350
+ };
351
+ var extractGroupsFromPath = (path) => {
352
+ const groups = [];
353
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
354
+ const mark = `@${index}`;
355
+ groups.push([mark, match]);
356
+ return mark;
357
+ });
358
+ return { groups, path };
359
+ };
360
+ var replaceGroupMarks = (paths, groups) => {
361
+ for (let i = groups.length - 1;i >= 0; i--) {
362
+ const [mark] = groups[i];
363
+ for (let j = paths.length - 1;j >= 0; j--) {
364
+ if (paths[j].includes(mark)) {
365
+ paths[j] = paths[j].replace(mark, groups[i][1]);
366
+ break;
367
+ }
368
+ }
369
+ }
370
+ return paths;
371
+ };
372
+ var patternCache = {};
373
+ var getPattern = (label, next) => {
374
+ if (label === "*") {
375
+ return "*";
376
+ }
377
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
378
+ if (match) {
379
+ const cacheKey = `${label}#${next}`;
380
+ if (!patternCache[cacheKey]) {
381
+ if (match[2]) {
382
+ patternCache[cacheKey] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
383
+ } else {
384
+ patternCache[cacheKey] = [label, match[1], true];
385
+ }
386
+ }
387
+ return patternCache[cacheKey];
388
+ }
389
+ return null;
390
+ };
391
+ var tryDecode = (str, decoder) => {
392
+ try {
393
+ return decoder(str);
394
+ } catch {
395
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
396
+ try {
397
+ return decoder(match);
398
+ } catch {
399
+ return match;
400
+ }
401
+ });
402
+ }
403
+ };
404
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
405
+ var getPath = (request) => {
406
+ const url = request.url;
407
+ const start = url.indexOf("/", url.indexOf(":") + 4);
408
+ let i = start;
409
+ for (;i < url.length; i++) {
410
+ const charCode = url.charCodeAt(i);
411
+ if (charCode === 37) {
412
+ const queryIndex = url.indexOf("?", i);
413
+ const path = url.slice(start, queryIndex === -1 ? undefined : queryIndex);
414
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
415
+ } else if (charCode === 63) {
416
+ break;
417
+ }
418
+ }
419
+ return url.slice(start, i);
420
+ };
421
+ var getPathNoStrict = (request) => {
422
+ const result = getPath(request);
423
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
424
+ };
425
+ var mergePath = (base, sub, ...rest) => {
426
+ if (rest.length) {
427
+ sub = mergePath(sub, ...rest);
428
+ }
429
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
430
+ };
431
+ var checkOptionalParameter = (path) => {
432
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
433
+ return null;
434
+ }
435
+ const segments = path.split("/");
436
+ const results = [];
437
+ let basePath = "";
438
+ segments.forEach((segment) => {
439
+ if (segment !== "" && !/\:/.test(segment)) {
440
+ basePath += "/" + segment;
441
+ } else if (/\:/.test(segment)) {
442
+ if (/\?/.test(segment)) {
443
+ if (results.length === 0 && basePath === "") {
444
+ results.push("/");
445
+ } else {
446
+ results.push(basePath);
447
+ }
448
+ const optionalSegment = segment.replace("?", "");
449
+ basePath += "/" + optionalSegment;
450
+ results.push(basePath);
451
+ } else {
452
+ basePath += "/" + segment;
453
+ }
454
+ }
455
+ });
456
+ return results.filter((v, i, a) => a.indexOf(v) === i);
457
+ };
458
+ var _decodeURI = (value) => {
459
+ if (!/[%+]/.test(value)) {
460
+ return value;
461
+ }
462
+ if (value.indexOf("+") !== -1) {
463
+ value = value.replace(/\+/g, " ");
464
+ }
465
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
466
+ };
467
+ var _getQueryParam = (url, key, multiple) => {
468
+ let encoded;
469
+ if (!multiple && key && !/[%+]/.test(key)) {
470
+ let keyIndex2 = url.indexOf("?", 8);
471
+ if (keyIndex2 === -1) {
472
+ return;
473
+ }
474
+ if (!url.startsWith(key, keyIndex2 + 1)) {
475
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
476
+ }
477
+ while (keyIndex2 !== -1) {
478
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
479
+ if (trailingKeyCode === 61) {
480
+ const valueIndex = keyIndex2 + key.length + 2;
481
+ const endIndex = url.indexOf("&", valueIndex);
482
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
483
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
484
+ return "";
485
+ }
486
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
487
+ }
488
+ encoded = /[%+]/.test(url);
489
+ if (!encoded) {
490
+ return;
491
+ }
492
+ }
493
+ const results = {};
494
+ encoded ??= /[%+]/.test(url);
495
+ let keyIndex = url.indexOf("?", 8);
496
+ while (keyIndex !== -1) {
497
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
498
+ let valueIndex = url.indexOf("=", keyIndex);
499
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
500
+ valueIndex = -1;
501
+ }
502
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
503
+ if (encoded) {
504
+ name = _decodeURI(name);
505
+ }
506
+ keyIndex = nextKeyIndex;
507
+ if (name === "") {
508
+ continue;
509
+ }
510
+ let value;
511
+ if (valueIndex === -1) {
512
+ value = "";
513
+ } else {
514
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
515
+ if (encoded) {
516
+ value = _decodeURI(value);
517
+ }
518
+ }
519
+ if (multiple) {
520
+ if (!(results[name] && Array.isArray(results[name]))) {
521
+ results[name] = [];
522
+ }
523
+ results[name].push(value);
524
+ } else {
525
+ results[name] ??= value;
526
+ }
527
+ }
528
+ return key ? results[key] : results;
529
+ };
530
+ var getQueryParam = _getQueryParam;
531
+ var getQueryParams = (url, key) => {
532
+ return _getQueryParam(url, key, true);
533
+ };
534
+ var decodeURIComponent_ = decodeURIComponent;
535
+
536
+ // ../../node_modules/hono/dist/request.js
537
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
538
+ var HonoRequest = class {
539
+ raw;
540
+ #validatedData;
541
+ #matchResult;
542
+ routeIndex = 0;
543
+ path;
544
+ bodyCache = {};
545
+ constructor(request, path = "/", matchResult = [[]]) {
546
+ this.raw = request;
547
+ this.path = path;
548
+ this.#matchResult = matchResult;
549
+ this.#validatedData = {};
550
+ }
551
+ param(key) {
552
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
553
+ }
554
+ #getDecodedParam(key) {
555
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
556
+ const param = this.#getParamValue(paramKey);
557
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
558
+ }
559
+ #getAllDecodedParams() {
560
+ const decoded = {};
561
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
562
+ for (const key of keys) {
563
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
564
+ if (value !== undefined) {
565
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
566
+ }
567
+ }
568
+ return decoded;
569
+ }
570
+ #getParamValue(paramKey) {
571
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
572
+ }
573
+ query(key) {
574
+ return getQueryParam(this.url, key);
575
+ }
576
+ queries(key) {
577
+ return getQueryParams(this.url, key);
578
+ }
579
+ header(name) {
580
+ if (name) {
581
+ return this.raw.headers.get(name) ?? undefined;
582
+ }
583
+ const headerData = {};
584
+ this.raw.headers.forEach((value, key) => {
585
+ headerData[key] = value;
586
+ });
587
+ return headerData;
588
+ }
589
+ async parseBody(options) {
590
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
591
+ }
592
+ #cachedBody = (key) => {
593
+ const { bodyCache, raw } = this;
594
+ const cachedBody = bodyCache[key];
595
+ if (cachedBody) {
596
+ return cachedBody;
597
+ }
598
+ const anyCachedKey = Object.keys(bodyCache)[0];
599
+ if (anyCachedKey) {
600
+ return bodyCache[anyCachedKey].then((body) => {
601
+ if (anyCachedKey === "json") {
602
+ body = JSON.stringify(body);
603
+ }
604
+ return new Response(body)[key]();
605
+ });
606
+ }
607
+ return bodyCache[key] = raw[key]();
608
+ };
609
+ json() {
610
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
611
+ }
612
+ text() {
613
+ return this.#cachedBody("text");
614
+ }
615
+ arrayBuffer() {
616
+ return this.#cachedBody("arrayBuffer");
617
+ }
618
+ blob() {
619
+ return this.#cachedBody("blob");
620
+ }
621
+ formData() {
622
+ return this.#cachedBody("formData");
623
+ }
624
+ addValidatedData(target, data) {
625
+ this.#validatedData[target] = data;
626
+ }
627
+ valid(target) {
628
+ return this.#validatedData[target];
629
+ }
630
+ get url() {
631
+ return this.raw.url;
632
+ }
633
+ get method() {
634
+ return this.raw.method;
635
+ }
636
+ get [GET_MATCH_RESULT]() {
637
+ return this.#matchResult;
638
+ }
639
+ get matchedRoutes() {
640
+ return this.#matchResult[0].map(([[, route]]) => route);
641
+ }
642
+ get routePath() {
643
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
644
+ }
645
+ };
646
+
647
+ // ../../node_modules/hono/dist/utils/html.js
648
+ var HtmlEscapedCallbackPhase = {
649
+ Stringify: 1,
650
+ BeforeStream: 2,
651
+ Stream: 3
652
+ };
653
+ var raw = (value, callbacks) => {
654
+ const escapedString = new String(value);
655
+ escapedString.isEscaped = true;
656
+ escapedString.callbacks = callbacks;
657
+ return escapedString;
658
+ };
659
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
660
+ if (typeof str === "object" && !(str instanceof String)) {
661
+ if (!(str instanceof Promise)) {
662
+ str = str.toString();
663
+ }
664
+ if (str instanceof Promise) {
665
+ str = await str;
666
+ }
667
+ }
668
+ const callbacks = str.callbacks;
669
+ if (!callbacks?.length) {
670
+ return Promise.resolve(str);
671
+ }
672
+ if (buffer) {
673
+ buffer[0] += str;
674
+ } else {
675
+ buffer = [str];
676
+ }
677
+ const resStr = Promise.all(callbacks.map((c) => c({ phase, buffer, context }))).then((res) => Promise.all(res.filter(Boolean).map((str2) => resolveCallback(str2, phase, false, context, buffer))).then(() => buffer[0]));
678
+ if (preserveCallbacks) {
679
+ return raw(await resStr, callbacks);
680
+ } else {
681
+ return resStr;
682
+ }
683
+ };
684
+
685
+ // ../../node_modules/hono/dist/context.js
686
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
687
+ var setDefaultContentType = (contentType, headers) => {
688
+ return {
689
+ "Content-Type": contentType,
690
+ ...headers
691
+ };
692
+ };
693
+ var Context = class {
694
+ #rawRequest;
695
+ #req;
696
+ env = {};
697
+ #var;
698
+ finalized = false;
699
+ error;
700
+ #status;
701
+ #executionCtx;
702
+ #res;
703
+ #layout;
704
+ #renderer;
705
+ #notFoundHandler;
706
+ #preparedHeaders;
707
+ #matchResult;
708
+ #path;
709
+ constructor(req, options) {
710
+ this.#rawRequest = req;
711
+ if (options) {
712
+ this.#executionCtx = options.executionCtx;
713
+ this.env = options.env;
714
+ this.#notFoundHandler = options.notFoundHandler;
715
+ this.#path = options.path;
716
+ this.#matchResult = options.matchResult;
717
+ }
718
+ }
719
+ get req() {
720
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
721
+ return this.#req;
722
+ }
723
+ get event() {
724
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
725
+ return this.#executionCtx;
726
+ } else {
727
+ throw Error("This context has no FetchEvent");
728
+ }
729
+ }
730
+ get executionCtx() {
731
+ if (this.#executionCtx) {
732
+ return this.#executionCtx;
733
+ } else {
734
+ throw Error("This context has no ExecutionContext");
735
+ }
736
+ }
737
+ get res() {
738
+ return this.#res ||= new Response(null, {
739
+ headers: this.#preparedHeaders ??= new Headers
740
+ });
741
+ }
742
+ set res(_res) {
743
+ if (this.#res && _res) {
744
+ _res = new Response(_res.body, _res);
745
+ for (const [k, v] of this.#res.headers.entries()) {
746
+ if (k === "content-type") {
747
+ continue;
748
+ }
749
+ if (k === "set-cookie") {
750
+ const cookies = this.#res.headers.getSetCookie();
751
+ _res.headers.delete("set-cookie");
752
+ for (const cookie of cookies) {
753
+ _res.headers.append("set-cookie", cookie);
754
+ }
755
+ } else {
756
+ _res.headers.set(k, v);
757
+ }
758
+ }
759
+ }
760
+ this.#res = _res;
761
+ this.finalized = true;
762
+ }
763
+ render = (...args) => {
764
+ this.#renderer ??= (content) => this.html(content);
765
+ return this.#renderer(...args);
766
+ };
767
+ setLayout = (layout) => this.#layout = layout;
768
+ getLayout = () => this.#layout;
769
+ setRenderer = (renderer) => {
770
+ this.#renderer = renderer;
771
+ };
772
+ header = (name, value, options) => {
773
+ if (this.finalized) {
774
+ this.#res = new Response(this.#res.body, this.#res);
775
+ }
776
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
777
+ if (value === undefined) {
778
+ headers.delete(name);
779
+ } else if (options?.append) {
780
+ headers.append(name, value);
781
+ } else {
782
+ headers.set(name, value);
783
+ }
784
+ };
785
+ status = (status) => {
786
+ this.#status = status;
787
+ };
788
+ set = (key, value) => {
789
+ this.#var ??= /* @__PURE__ */ new Map;
790
+ this.#var.set(key, value);
791
+ };
792
+ get = (key) => {
793
+ return this.#var ? this.#var.get(key) : undefined;
794
+ };
795
+ get var() {
796
+ if (!this.#var) {
797
+ return {};
798
+ }
799
+ return Object.fromEntries(this.#var);
800
+ }
801
+ #newResponse(data, arg, headers) {
802
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
803
+ if (typeof arg === "object" && "headers" in arg) {
804
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
805
+ for (const [key, value] of argHeaders) {
806
+ if (key.toLowerCase() === "set-cookie") {
807
+ responseHeaders.append(key, value);
808
+ } else {
809
+ responseHeaders.set(key, value);
810
+ }
811
+ }
812
+ }
813
+ if (headers) {
814
+ for (const [k, v] of Object.entries(headers)) {
815
+ if (typeof v === "string") {
816
+ responseHeaders.set(k, v);
817
+ } else {
818
+ responseHeaders.delete(k);
819
+ for (const v2 of v) {
820
+ responseHeaders.append(k, v2);
821
+ }
822
+ }
823
+ }
824
+ }
825
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
826
+ return new Response(data, { status, headers: responseHeaders });
827
+ }
828
+ newResponse = (...args) => this.#newResponse(...args);
829
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
830
+ text = (text, arg, headers) => {
831
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
832
+ };
833
+ json = (object, arg, headers) => {
834
+ return this.#newResponse(JSON.stringify(object), arg, setDefaultContentType("application/json", headers));
835
+ };
836
+ html = (html, arg, headers) => {
837
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
838
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
839
+ };
840
+ redirect = (location, status) => {
841
+ const locationString = String(location);
842
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
843
+ return this.newResponse(null, status ?? 302);
844
+ };
845
+ notFound = () => {
846
+ this.#notFoundHandler ??= () => new Response;
847
+ return this.#notFoundHandler(this);
848
+ };
849
+ };
850
+
851
+ // ../../node_modules/hono/dist/router.js
852
+ var METHOD_NAME_ALL = "ALL";
853
+ var METHOD_NAME_ALL_LOWERCASE = "all";
854
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
855
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
856
+ var UnsupportedPathError = class extends Error {
857
+ };
858
+
859
+ // ../../node_modules/hono/dist/utils/constants.js
860
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
861
+
862
+ // ../../node_modules/hono/dist/hono-base.js
863
+ var notFoundHandler = (c) => {
864
+ return c.text("404 Not Found", 404);
865
+ };
866
+ var errorHandler = (err, c) => {
867
+ if ("getResponse" in err) {
868
+ const res = err.getResponse();
869
+ return c.newResponse(res.body, res);
870
+ }
871
+ console.error(err);
872
+ return c.text("Internal Server Error", 500);
873
+ };
874
+ var Hono = class _Hono {
875
+ get;
876
+ post;
877
+ put;
878
+ delete;
879
+ options;
880
+ patch;
881
+ all;
882
+ on;
883
+ use;
884
+ router;
885
+ getPath;
886
+ _basePath = "/";
887
+ #path = "/";
888
+ routes = [];
889
+ constructor(options = {}) {
890
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
891
+ allMethods.forEach((method) => {
892
+ this[method] = (args1, ...args) => {
893
+ if (typeof args1 === "string") {
894
+ this.#path = args1;
895
+ } else {
896
+ this.#addRoute(method, this.#path, args1);
897
+ }
898
+ args.forEach((handler) => {
899
+ this.#addRoute(method, this.#path, handler);
900
+ });
901
+ return this;
902
+ };
903
+ });
904
+ this.on = (method, path, ...handlers) => {
905
+ for (const p of [path].flat()) {
906
+ this.#path = p;
907
+ for (const m of [method].flat()) {
908
+ handlers.map((handler) => {
909
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
910
+ });
911
+ }
912
+ }
913
+ return this;
914
+ };
915
+ this.use = (arg1, ...handlers) => {
916
+ if (typeof arg1 === "string") {
917
+ this.#path = arg1;
918
+ } else {
919
+ this.#path = "*";
920
+ handlers.unshift(arg1);
921
+ }
922
+ handlers.forEach((handler) => {
923
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
924
+ });
925
+ return this;
926
+ };
927
+ const { strict, ...optionsWithoutStrict } = options;
928
+ Object.assign(this, optionsWithoutStrict);
929
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
930
+ }
931
+ #clone() {
932
+ const clone = new _Hono({
933
+ router: this.router,
934
+ getPath: this.getPath
935
+ });
936
+ clone.errorHandler = this.errorHandler;
937
+ clone.#notFoundHandler = this.#notFoundHandler;
938
+ clone.routes = this.routes;
939
+ return clone;
940
+ }
941
+ #notFoundHandler = notFoundHandler;
942
+ errorHandler = errorHandler;
943
+ route(path, app) {
944
+ const subApp = this.basePath(path);
945
+ app.routes.map((r) => {
946
+ let handler;
947
+ if (app.errorHandler === errorHandler) {
948
+ handler = r.handler;
949
+ } else {
950
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
951
+ handler[COMPOSED_HANDLER] = r.handler;
952
+ }
953
+ subApp.#addRoute(r.method, r.path, handler);
954
+ });
955
+ return this;
956
+ }
957
+ basePath(path) {
958
+ const subApp = this.#clone();
959
+ subApp._basePath = mergePath(this._basePath, path);
960
+ return subApp;
961
+ }
962
+ onError = (handler) => {
963
+ this.errorHandler = handler;
964
+ return this;
965
+ };
966
+ notFound = (handler) => {
967
+ this.#notFoundHandler = handler;
968
+ return this;
969
+ };
970
+ mount(path, applicationHandler, options) {
971
+ let replaceRequest;
972
+ let optionHandler;
973
+ if (options) {
974
+ if (typeof options === "function") {
975
+ optionHandler = options;
976
+ } else {
977
+ optionHandler = options.optionHandler;
978
+ if (options.replaceRequest === false) {
979
+ replaceRequest = (request) => request;
980
+ } else {
981
+ replaceRequest = options.replaceRequest;
982
+ }
983
+ }
984
+ }
985
+ const getOptions = optionHandler ? (c) => {
986
+ const options2 = optionHandler(c);
987
+ return Array.isArray(options2) ? options2 : [options2];
988
+ } : (c) => {
989
+ let executionContext = undefined;
990
+ try {
991
+ executionContext = c.executionCtx;
992
+ } catch {}
993
+ return [c.env, executionContext];
37
994
  };
38
- // Use API key if provided, otherwise forward the Authorization header
39
- if (apiKey) {
40
- headers["X-API-Key"] = apiKey;
995
+ replaceRequest ||= (() => {
996
+ const mergedPath = mergePath(this._basePath, path);
997
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
998
+ return (request) => {
999
+ const url = new URL(request.url);
1000
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
1001
+ return new Request(url, request);
1002
+ };
1003
+ })();
1004
+ const handler = async (c, next) => {
1005
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
1006
+ if (res) {
1007
+ return res;
1008
+ }
1009
+ await next();
1010
+ };
1011
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
1012
+ return this;
1013
+ }
1014
+ #addRoute(method, path, handler) {
1015
+ method = method.toUpperCase();
1016
+ path = mergePath(this._basePath, path);
1017
+ const r = { basePath: this._basePath, path, method, handler };
1018
+ this.router.add(method, path, [handler, r]);
1019
+ this.routes.push(r);
1020
+ }
1021
+ #handleError(err, c) {
1022
+ if (err instanceof Error) {
1023
+ return this.errorHandler(err, c);
1024
+ }
1025
+ throw err;
1026
+ }
1027
+ #dispatch(request, executionCtx, env, method) {
1028
+ if (method === "HEAD") {
1029
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
41
1030
  }
42
- else if (authHeader) {
43
- headers.Authorization = authHeader;
1031
+ const path = this.getPath(request, { env });
1032
+ const matchResult = this.router.match(method, path);
1033
+ const c = new Context(request, {
1034
+ path,
1035
+ matchResult,
1036
+ env,
1037
+ executionCtx,
1038
+ notFoundHandler: this.#notFoundHandler
1039
+ });
1040
+ if (matchResult[0].length === 1) {
1041
+ let res;
1042
+ try {
1043
+ res = matchResult[0][0][0][0](c, async () => {
1044
+ c.res = await this.#notFoundHandler(c);
1045
+ });
1046
+ } catch (err) {
1047
+ return this.#handleError(err, c);
1048
+ }
1049
+ return res instanceof Promise ? res.then((resolved) => resolved || (c.finalized ? c.res : this.#notFoundHandler(c))).catch((err) => this.#handleError(err, c)) : res ?? this.#notFoundHandler(c);
44
1050
  }
45
- else {
46
- throw new Error("Unauthorized: Missing API key or Authorization header");
1051
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
1052
+ return (async () => {
1053
+ try {
1054
+ const context = await composed(c);
1055
+ if (!context.finalized) {
1056
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
1057
+ }
1058
+ return context.res;
1059
+ } catch (err) {
1060
+ return this.#handleError(err, c);
1061
+ }
1062
+ })();
1063
+ }
1064
+ fetch = (request, ...rest) => {
1065
+ return this.#dispatch(request, rest[1], rest[0], request.method);
1066
+ };
1067
+ request = (input, requestInit, Env, executionCtx) => {
1068
+ if (input instanceof Request) {
1069
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
47
1070
  }
48
- const response = await fetch(`${apiUrl}${path}`, {
49
- method,
50
- headers,
51
- body: body ? JSON.stringify(body) : undefined,
1071
+ input = input.toString();
1072
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
1073
+ };
1074
+ fire = () => {
1075
+ addEventListener("fetch", (event) => {
1076
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
52
1077
  });
53
- const data = await response.json();
54
- return { data, status: response.status };
1078
+ };
1079
+ };
1080
+
1081
+ // ../../node_modules/hono/dist/router/reg-exp-router/matcher.js
1082
+ var emptyParam = [];
1083
+ function match(method, path) {
1084
+ const matchers = this.buildAllMatchers();
1085
+ const match2 = (method2, path2) => {
1086
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
1087
+ const staticMatch = matcher[2][path2];
1088
+ if (staticMatch) {
1089
+ return staticMatch;
1090
+ }
1091
+ const match3 = path2.match(matcher[0]);
1092
+ if (!match3) {
1093
+ return [[], emptyParam];
1094
+ }
1095
+ const index = match3.indexOf("", 1);
1096
+ return [matcher[1][index], match3];
1097
+ };
1098
+ this.match = match2;
1099
+ return match2(method, path);
55
1100
  }
56
- // Health check
57
- app.get("/health", (c) => c.json({ status: "ok", service: "harmony-mcp-http" }));
58
- // List available endpoints
59
- app.get("/", (c) => c.json({
60
- service: "Harmony MCP HTTP Adapter",
61
- endpoints: {
62
- workspaces: {
63
- list: "GET /workspaces",
64
- members: "GET /workspaces/:id/members",
65
- projects: "GET /workspaces/:id/projects",
66
- },
67
- board: {
68
- get: "GET /board/:projectId",
69
- },
70
- cards: {
71
- create: "POST /cards",
72
- get: "GET /cards/:id",
73
- getByShortId: "GET /projects/:projectId/cards/:shortId",
74
- update: "PATCH /cards/:id",
75
- delete: "DELETE /cards/:id",
76
- move: "POST /cards/:id/move",
77
- search: "GET /search?q=query",
78
- },
79
- columns: {
80
- create: "POST /columns",
81
- update: "PATCH /columns/:id",
82
- delete: "DELETE /columns/:id",
83
- },
84
- labels: {
85
- create: "POST /labels",
86
- addToCard: "POST /cards/:id/labels",
87
- removeFromCard: "DELETE /cards/:id/labels/:labelId",
88
- },
89
- subtasks: {
90
- create: "POST /subtasks",
91
- toggle: "POST /subtasks/:id/toggle",
92
- delete: "DELETE /subtasks/:id",
93
- },
94
- nlu: {
95
- process: "POST /nlu",
96
- },
97
- },
98
- authentication: "Include X-API-Key header or Authorization: Bearer <token>",
99
- }));
100
- // Generic proxy handler
101
- async function handleRequest(c, method, path) {
1101
+
1102
+ // ../../node_modules/hono/dist/router/reg-exp-router/node.js
1103
+ var LABEL_REG_EXP_STR = "[^/]+";
1104
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
1105
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
1106
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
1107
+ var regExpMetaChars = new Set(".\\+*[^]$()");
1108
+ function compareKey(a, b) {
1109
+ if (a.length === 1) {
1110
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
1111
+ }
1112
+ if (b.length === 1) {
1113
+ return 1;
1114
+ }
1115
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
1116
+ return 1;
1117
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
1118
+ return -1;
1119
+ }
1120
+ if (a === LABEL_REG_EXP_STR) {
1121
+ return 1;
1122
+ } else if (b === LABEL_REG_EXP_STR) {
1123
+ return -1;
1124
+ }
1125
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
1126
+ }
1127
+ var Node = class _Node {
1128
+ #index;
1129
+ #varIndex;
1130
+ #children = /* @__PURE__ */ Object.create(null);
1131
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
1132
+ if (tokens.length === 0) {
1133
+ if (this.#index !== undefined) {
1134
+ throw PATH_ERROR;
1135
+ }
1136
+ if (pathErrorCheckOnly) {
1137
+ return;
1138
+ }
1139
+ this.#index = index;
1140
+ return;
1141
+ }
1142
+ const [token, ...restTokens] = tokens;
1143
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
1144
+ let node;
1145
+ if (pattern) {
1146
+ const name = pattern[1];
1147
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
1148
+ if (name && pattern[2]) {
1149
+ if (regexpStr === ".*") {
1150
+ throw PATH_ERROR;
1151
+ }
1152
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
1153
+ if (/\((?!\?:)/.test(regexpStr)) {
1154
+ throw PATH_ERROR;
1155
+ }
1156
+ }
1157
+ node = this.#children[regexpStr];
1158
+ if (!node) {
1159
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1160
+ throw PATH_ERROR;
1161
+ }
1162
+ if (pathErrorCheckOnly) {
1163
+ return;
1164
+ }
1165
+ node = this.#children[regexpStr] = new _Node;
1166
+ if (name !== "") {
1167
+ node.#varIndex = context.varIndex++;
1168
+ }
1169
+ }
1170
+ if (!pathErrorCheckOnly && name !== "") {
1171
+ paramMap.push([name, node.#varIndex]);
1172
+ }
1173
+ } else {
1174
+ node = this.#children[token];
1175
+ if (!node) {
1176
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
1177
+ throw PATH_ERROR;
1178
+ }
1179
+ if (pathErrorCheckOnly) {
1180
+ return;
1181
+ }
1182
+ node = this.#children[token] = new _Node;
1183
+ }
1184
+ }
1185
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
1186
+ }
1187
+ buildRegExpStr() {
1188
+ const childKeys = Object.keys(this.#children).sort(compareKey);
1189
+ const strList = childKeys.map((k) => {
1190
+ const c = this.#children[k];
1191
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
1192
+ });
1193
+ if (typeof this.#index === "number") {
1194
+ strList.unshift(`#${this.#index}`);
1195
+ }
1196
+ if (strList.length === 0) {
1197
+ return "";
1198
+ }
1199
+ if (strList.length === 1) {
1200
+ return strList[0];
1201
+ }
1202
+ return "(?:" + strList.join("|") + ")";
1203
+ }
1204
+ };
1205
+
1206
+ // ../../node_modules/hono/dist/router/reg-exp-router/trie.js
1207
+ var Trie = class {
1208
+ #context = { varIndex: 0 };
1209
+ #root = new Node;
1210
+ insert(path, index, pathErrorCheckOnly) {
1211
+ const paramAssoc = [];
1212
+ const groups = [];
1213
+ for (let i = 0;; ) {
1214
+ let replaced = false;
1215
+ path = path.replace(/\{[^}]+\}/g, (m) => {
1216
+ const mark = `@\\${i}`;
1217
+ groups[i] = [mark, m];
1218
+ i++;
1219
+ replaced = true;
1220
+ return mark;
1221
+ });
1222
+ if (!replaced) {
1223
+ break;
1224
+ }
1225
+ }
1226
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
1227
+ for (let i = groups.length - 1;i >= 0; i--) {
1228
+ const [mark] = groups[i];
1229
+ for (let j = tokens.length - 1;j >= 0; j--) {
1230
+ if (tokens[j].indexOf(mark) !== -1) {
1231
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
1232
+ break;
1233
+ }
1234
+ }
1235
+ }
1236
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
1237
+ return paramAssoc;
1238
+ }
1239
+ buildRegExp() {
1240
+ let regexp = this.#root.buildRegExpStr();
1241
+ if (regexp === "") {
1242
+ return [/^$/, [], []];
1243
+ }
1244
+ let captureIndex = 0;
1245
+ const indexReplacementMap = [];
1246
+ const paramReplacementMap = [];
1247
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
1248
+ if (handlerIndex !== undefined) {
1249
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
1250
+ return "$()";
1251
+ }
1252
+ if (paramIndex !== undefined) {
1253
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
1254
+ return "";
1255
+ }
1256
+ return "";
1257
+ });
1258
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
1259
+ }
1260
+ };
1261
+
1262
+ // ../../node_modules/hono/dist/router/reg-exp-router/router.js
1263
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
1264
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1265
+ function buildWildcardRegExp(path) {
1266
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
1267
+ }
1268
+ function clearWildcardRegExpCache() {
1269
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
1270
+ }
1271
+ function buildMatcherFromPreprocessedRoutes(routes) {
1272
+ const trie = new Trie;
1273
+ const handlerData = [];
1274
+ if (routes.length === 0) {
1275
+ return nullMatcher;
1276
+ }
1277
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
1278
+ const staticMap = /* @__PURE__ */ Object.create(null);
1279
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
1280
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
1281
+ if (pathErrorCheckOnly) {
1282
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
1283
+ } else {
1284
+ j++;
1285
+ }
1286
+ let paramAssoc;
102
1287
  try {
103
- const authHeader = c.req.header("Authorization");
104
- const apiKey = c.req.header("X-API-Key");
105
- let body;
106
- if (["POST", "PATCH", "PUT"].includes(method)) {
107
- try {
108
- body = await c.json();
1288
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
1289
+ } catch (e) {
1290
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
1291
+ }
1292
+ if (pathErrorCheckOnly) {
1293
+ continue;
1294
+ }
1295
+ handlerData[j] = handlers.map(([h, paramCount]) => {
1296
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
1297
+ paramCount -= 1;
1298
+ for (;paramCount >= 0; paramCount--) {
1299
+ const [key, value] = paramAssoc[paramCount];
1300
+ paramIndexMap[key] = value;
1301
+ }
1302
+ return [h, paramIndexMap];
1303
+ });
1304
+ }
1305
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
1306
+ for (let i = 0, len = handlerData.length;i < len; i++) {
1307
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
1308
+ const map = handlerData[i][j]?.[1];
1309
+ if (!map) {
1310
+ continue;
1311
+ }
1312
+ const keys = Object.keys(map);
1313
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
1314
+ map[keys[k]] = paramReplacementMap[map[keys[k]]];
1315
+ }
1316
+ }
1317
+ }
1318
+ const handlerMap = [];
1319
+ for (const i in indexReplacementMap) {
1320
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
1321
+ }
1322
+ return [regexp, handlerMap, staticMap];
1323
+ }
1324
+ function findMiddleware(middleware, path) {
1325
+ if (!middleware) {
1326
+ return;
1327
+ }
1328
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
1329
+ if (buildWildcardRegExp(k).test(path)) {
1330
+ return [...middleware[k]];
1331
+ }
1332
+ }
1333
+ return;
1334
+ }
1335
+ var RegExpRouter = class {
1336
+ name = "RegExpRouter";
1337
+ #middleware;
1338
+ #routes;
1339
+ constructor() {
1340
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1341
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
1342
+ }
1343
+ add(method, path, handler) {
1344
+ const middleware = this.#middleware;
1345
+ const routes = this.#routes;
1346
+ if (!middleware || !routes) {
1347
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1348
+ }
1349
+ if (!middleware[method]) {
1350
+ [middleware, routes].forEach((handlerMap) => {
1351
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
1352
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
1353
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
1354
+ });
1355
+ });
1356
+ }
1357
+ if (path === "/*") {
1358
+ path = "*";
1359
+ }
1360
+ const paramCount = (path.match(/\/:/g) || []).length;
1361
+ if (/\*$/.test(path)) {
1362
+ const re = buildWildcardRegExp(path);
1363
+ if (method === METHOD_NAME_ALL) {
1364
+ Object.keys(middleware).forEach((m) => {
1365
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1366
+ });
1367
+ } else {
1368
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
1369
+ }
1370
+ Object.keys(middleware).forEach((m) => {
1371
+ if (method === METHOD_NAME_ALL || method === m) {
1372
+ Object.keys(middleware[m]).forEach((p) => {
1373
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
1374
+ });
1375
+ }
1376
+ });
1377
+ Object.keys(routes).forEach((m) => {
1378
+ if (method === METHOD_NAME_ALL || method === m) {
1379
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
1380
+ }
1381
+ });
1382
+ return;
1383
+ }
1384
+ const paths = checkOptionalParameter(path) || [path];
1385
+ for (let i = 0, len = paths.length;i < len; i++) {
1386
+ const path2 = paths[i];
1387
+ Object.keys(routes).forEach((m) => {
1388
+ if (method === METHOD_NAME_ALL || method === m) {
1389
+ routes[m][path2] ||= [
1390
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
1391
+ ];
1392
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
1393
+ }
1394
+ });
1395
+ }
1396
+ }
1397
+ match = match;
1398
+ buildAllMatchers() {
1399
+ const matchers = /* @__PURE__ */ Object.create(null);
1400
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
1401
+ matchers[method] ||= this.#buildMatcher(method);
1402
+ });
1403
+ this.#middleware = this.#routes = undefined;
1404
+ clearWildcardRegExpCache();
1405
+ return matchers;
1406
+ }
1407
+ #buildMatcher(method) {
1408
+ const routes = [];
1409
+ let hasOwnRoute = method === METHOD_NAME_ALL;
1410
+ [this.#middleware, this.#routes].forEach((r) => {
1411
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
1412
+ if (ownRoute.length !== 0) {
1413
+ hasOwnRoute ||= true;
1414
+ routes.push(...ownRoute);
1415
+ } else if (method !== METHOD_NAME_ALL) {
1416
+ routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
1417
+ }
1418
+ });
1419
+ if (!hasOwnRoute) {
1420
+ return null;
1421
+ } else {
1422
+ return buildMatcherFromPreprocessedRoutes(routes);
1423
+ }
1424
+ }
1425
+ };
1426
+
1427
+ // ../../node_modules/hono/dist/router/reg-exp-router/prepared-router.js
1428
+ var PreparedRegExpRouter = class {
1429
+ name = "PreparedRegExpRouter";
1430
+ #matchers;
1431
+ #relocateMap;
1432
+ constructor(matchers, relocateMap) {
1433
+ this.#matchers = matchers;
1434
+ this.#relocateMap = relocateMap;
1435
+ }
1436
+ #addWildcard(method, handlerData) {
1437
+ const matcher = this.#matchers[method];
1438
+ matcher[1].forEach((list) => list && list.push(handlerData));
1439
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
1440
+ }
1441
+ #addPath(method, path, handler, indexes, map) {
1442
+ const matcher = this.#matchers[method];
1443
+ if (!map) {
1444
+ matcher[2][path][0].push([handler, {}]);
1445
+ } else {
1446
+ indexes.forEach((index) => {
1447
+ if (typeof index === "number") {
1448
+ matcher[1][index].push([handler, map]);
1449
+ } else {
1450
+ matcher[2][index || path][0].push([handler, map]);
1451
+ }
1452
+ });
1453
+ }
1454
+ }
1455
+ add(method, path, handler) {
1456
+ if (!this.#matchers[method]) {
1457
+ const all = this.#matchers[METHOD_NAME_ALL];
1458
+ const staticMap = {};
1459
+ for (const key in all[2]) {
1460
+ staticMap[key] = [all[2][key][0].slice(), emptyParam];
1461
+ }
1462
+ this.#matchers[method] = [
1463
+ all[0],
1464
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
1465
+ staticMap
1466
+ ];
1467
+ }
1468
+ if (path === "/*" || path === "*") {
1469
+ const handlerData = [handler, {}];
1470
+ if (method === METHOD_NAME_ALL) {
1471
+ for (const m in this.#matchers) {
1472
+ this.#addWildcard(m, handlerData);
1473
+ }
1474
+ } else {
1475
+ this.#addWildcard(method, handlerData);
1476
+ }
1477
+ return;
1478
+ }
1479
+ const data = this.#relocateMap[path];
1480
+ if (!data) {
1481
+ throw new Error(`Path ${path} is not registered`);
1482
+ }
1483
+ for (const [indexes, map] of data) {
1484
+ if (method === METHOD_NAME_ALL) {
1485
+ for (const m in this.#matchers) {
1486
+ this.#addPath(m, path, handler, indexes, map);
1487
+ }
1488
+ } else {
1489
+ this.#addPath(method, path, handler, indexes, map);
1490
+ }
1491
+ }
1492
+ }
1493
+ buildAllMatchers() {
1494
+ return this.#matchers;
1495
+ }
1496
+ match = match;
1497
+ };
1498
+
1499
+ // ../../node_modules/hono/dist/router/smart-router/router.js
1500
+ var SmartRouter = class {
1501
+ name = "SmartRouter";
1502
+ #routers = [];
1503
+ #routes = [];
1504
+ constructor(init) {
1505
+ this.#routers = init.routers;
1506
+ }
1507
+ add(method, path, handler) {
1508
+ if (!this.#routes) {
1509
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
1510
+ }
1511
+ this.#routes.push([method, path, handler]);
1512
+ }
1513
+ match(method, path) {
1514
+ if (!this.#routes) {
1515
+ throw new Error("Fatal error");
1516
+ }
1517
+ const routers = this.#routers;
1518
+ const routes = this.#routes;
1519
+ const len = routers.length;
1520
+ let i = 0;
1521
+ let res;
1522
+ for (;i < len; i++) {
1523
+ const router = routers[i];
1524
+ try {
1525
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
1526
+ router.add(...routes[i2]);
1527
+ }
1528
+ res = router.match(method, path);
1529
+ } catch (e) {
1530
+ if (e instanceof UnsupportedPathError) {
1531
+ continue;
1532
+ }
1533
+ throw e;
1534
+ }
1535
+ this.match = router.match.bind(router);
1536
+ this.#routers = [router];
1537
+ this.#routes = undefined;
1538
+ break;
1539
+ }
1540
+ if (i === len) {
1541
+ throw new Error("Fatal error");
1542
+ }
1543
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
1544
+ return res;
1545
+ }
1546
+ get activeRouter() {
1547
+ if (this.#routes || this.#routers.length !== 1) {
1548
+ throw new Error("No active router has been determined yet.");
1549
+ }
1550
+ return this.#routers[0];
1551
+ }
1552
+ };
1553
+
1554
+ // ../../node_modules/hono/dist/router/trie-router/node.js
1555
+ var emptyParams = /* @__PURE__ */ Object.create(null);
1556
+ var Node2 = class _Node2 {
1557
+ #methods;
1558
+ #children;
1559
+ #patterns;
1560
+ #order = 0;
1561
+ #params = emptyParams;
1562
+ constructor(method, handler, children) {
1563
+ this.#children = children || /* @__PURE__ */ Object.create(null);
1564
+ this.#methods = [];
1565
+ if (method && handler) {
1566
+ const m = /* @__PURE__ */ Object.create(null);
1567
+ m[method] = { handler, possibleKeys: [], score: 0 };
1568
+ this.#methods = [m];
1569
+ }
1570
+ this.#patterns = [];
1571
+ }
1572
+ insert(method, path, handler) {
1573
+ this.#order = ++this.#order;
1574
+ let curNode = this;
1575
+ const parts = splitRoutingPath(path);
1576
+ const possibleKeys = [];
1577
+ for (let i = 0, len = parts.length;i < len; i++) {
1578
+ const p = parts[i];
1579
+ const nextP = parts[i + 1];
1580
+ const pattern = getPattern(p, nextP);
1581
+ const key = Array.isArray(pattern) ? pattern[0] : p;
1582
+ if (key in curNode.#children) {
1583
+ curNode = curNode.#children[key];
1584
+ if (pattern) {
1585
+ possibleKeys.push(pattern[1]);
1586
+ }
1587
+ continue;
1588
+ }
1589
+ curNode.#children[key] = new _Node2;
1590
+ if (pattern) {
1591
+ curNode.#patterns.push(pattern);
1592
+ possibleKeys.push(pattern[1]);
1593
+ }
1594
+ curNode = curNode.#children[key];
1595
+ }
1596
+ curNode.#methods.push({
1597
+ [method]: {
1598
+ handler,
1599
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
1600
+ score: this.#order
1601
+ }
1602
+ });
1603
+ return curNode;
1604
+ }
1605
+ #getHandlerSets(node, method, nodeParams, params) {
1606
+ const handlerSets = [];
1607
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
1608
+ const m = node.#methods[i];
1609
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
1610
+ const processedSet = {};
1611
+ if (handlerSet !== undefined) {
1612
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
1613
+ handlerSets.push(handlerSet);
1614
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
1615
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
1616
+ const key = handlerSet.possibleKeys[i2];
1617
+ const processed = processedSet[handlerSet.score];
1618
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
1619
+ processedSet[handlerSet.score] = true;
1620
+ }
1621
+ }
1622
+ }
1623
+ }
1624
+ return handlerSets;
1625
+ }
1626
+ search(method, path) {
1627
+ const handlerSets = [];
1628
+ this.#params = emptyParams;
1629
+ const curNode = this;
1630
+ let curNodes = [curNode];
1631
+ const parts = splitPath(path);
1632
+ const curNodesQueue = [];
1633
+ for (let i = 0, len = parts.length;i < len; i++) {
1634
+ const part = parts[i];
1635
+ const isLast = i === len - 1;
1636
+ const tempNodes = [];
1637
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
1638
+ const node = curNodes[j];
1639
+ const nextNode = node.#children[part];
1640
+ if (nextNode) {
1641
+ nextNode.#params = node.#params;
1642
+ if (isLast) {
1643
+ if (nextNode.#children["*"]) {
1644
+ handlerSets.push(...this.#getHandlerSets(nextNode.#children["*"], method, node.#params));
1645
+ }
1646
+ handlerSets.push(...this.#getHandlerSets(nextNode, method, node.#params));
1647
+ } else {
1648
+ tempNodes.push(nextNode);
1649
+ }
1650
+ }
1651
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
1652
+ const pattern = node.#patterns[k];
1653
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
1654
+ if (pattern === "*") {
1655
+ const astNode = node.#children["*"];
1656
+ if (astNode) {
1657
+ handlerSets.push(...this.#getHandlerSets(astNode, method, node.#params));
1658
+ astNode.#params = params;
1659
+ tempNodes.push(astNode);
109
1660
  }
110
- catch {
111
- // No body or invalid JSON
1661
+ continue;
1662
+ }
1663
+ const [key, name, matcher] = pattern;
1664
+ if (!part && !(matcher instanceof RegExp)) {
1665
+ continue;
1666
+ }
1667
+ const child = node.#children[key];
1668
+ const restPathString = parts.slice(i).join("/");
1669
+ if (matcher instanceof RegExp) {
1670
+ const m = matcher.exec(restPathString);
1671
+ if (m) {
1672
+ params[name] = m[0];
1673
+ handlerSets.push(...this.#getHandlerSets(child, method, node.#params, params));
1674
+ if (Object.keys(child.#children).length) {
1675
+ child.#params = params;
1676
+ const componentCount = m[0].match(/\//)?.length ?? 0;
1677
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
1678
+ targetCurNodes.push(child);
1679
+ }
1680
+ continue;
112
1681
  }
1682
+ }
1683
+ if (matcher === true || matcher.test(part)) {
1684
+ params[name] = part;
1685
+ if (isLast) {
1686
+ handlerSets.push(...this.#getHandlerSets(child, method, params, node.#params));
1687
+ if (child.#children["*"]) {
1688
+ handlerSets.push(...this.#getHandlerSets(child.#children["*"], method, params, node.#params));
1689
+ }
1690
+ } else {
1691
+ child.#params = params;
1692
+ tempNodes.push(child);
1693
+ }
1694
+ }
113
1695
  }
114
- const { data, status } = await forwardToApi(method, path, authHeader, apiKey, body);
115
- return new Response(JSON.stringify(data), {
116
- status,
117
- headers: { "Content-Type": "application/json" },
118
- });
1696
+ }
1697
+ curNodes = tempNodes.concat(curNodesQueue.shift() ?? []);
119
1698
  }
120
- catch (error) {
121
- const message = error instanceof Error ? error.message : String(error);
122
- const status = message.includes("Unauthorized") ? 401 : 500;
123
- return new Response(JSON.stringify({ error: message }), {
124
- status,
125
- headers: { "Content-Type": "application/json" },
126
- });
1699
+ if (handlerSets.length > 1) {
1700
+ handlerSets.sort((a, b) => {
1701
+ return a.score - b.score;
1702
+ });
1703
+ }
1704
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
1705
+ }
1706
+ };
1707
+
1708
+ // ../../node_modules/hono/dist/router/trie-router/router.js
1709
+ var TrieRouter = class {
1710
+ name = "TrieRouter";
1711
+ #node;
1712
+ constructor() {
1713
+ this.#node = new Node2;
1714
+ }
1715
+ add(method, path, handler) {
1716
+ const results = checkOptionalParameter(path);
1717
+ if (results) {
1718
+ for (let i = 0, len = results.length;i < len; i++) {
1719
+ this.#node.insert(method, results[i], handler);
1720
+ }
1721
+ return;
1722
+ }
1723
+ this.#node.insert(method, path, handler);
1724
+ }
1725
+ match(method, path) {
1726
+ return this.#node.search(method, path);
1727
+ }
1728
+ };
1729
+
1730
+ // ../../node_modules/hono/dist/hono.js
1731
+ var Hono2 = class extends Hono {
1732
+ constructor(options = {}) {
1733
+ super(options);
1734
+ this.router = options.router ?? new SmartRouter({
1735
+ routers: [new RegExpRouter, new TrieRouter]
1736
+ });
1737
+ }
1738
+ };
1739
+
1740
+ // ../../node_modules/hono/dist/middleware/cors/index.js
1741
+ var cors = (options) => {
1742
+ const defaults = {
1743
+ origin: "*",
1744
+ allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
1745
+ allowHeaders: [],
1746
+ exposeHeaders: []
1747
+ };
1748
+ const opts = {
1749
+ ...defaults,
1750
+ ...options
1751
+ };
1752
+ const findAllowOrigin = ((optsOrigin) => {
1753
+ if (typeof optsOrigin === "string") {
1754
+ if (optsOrigin === "*") {
1755
+ return () => optsOrigin;
1756
+ } else {
1757
+ return (origin) => optsOrigin === origin ? origin : null;
1758
+ }
1759
+ } else if (typeof optsOrigin === "function") {
1760
+ return optsOrigin;
1761
+ } else {
1762
+ return (origin) => optsOrigin.includes(origin) ? origin : null;
1763
+ }
1764
+ })(opts.origin);
1765
+ const findAllowMethods = ((optsAllowMethods) => {
1766
+ if (typeof optsAllowMethods === "function") {
1767
+ return optsAllowMethods;
1768
+ } else if (Array.isArray(optsAllowMethods)) {
1769
+ return () => optsAllowMethods;
1770
+ } else {
1771
+ return () => [];
1772
+ }
1773
+ })(opts.allowMethods);
1774
+ return async function cors2(c, next) {
1775
+ function set(key, value) {
1776
+ c.res.headers.set(key, value);
1777
+ }
1778
+ const allowOrigin = await findAllowOrigin(c.req.header("origin") || "", c);
1779
+ if (allowOrigin) {
1780
+ set("Access-Control-Allow-Origin", allowOrigin);
127
1781
  }
1782
+ if (opts.credentials) {
1783
+ set("Access-Control-Allow-Credentials", "true");
1784
+ }
1785
+ if (opts.exposeHeaders?.length) {
1786
+ set("Access-Control-Expose-Headers", opts.exposeHeaders.join(","));
1787
+ }
1788
+ if (c.req.method === "OPTIONS") {
1789
+ if (opts.origin !== "*") {
1790
+ set("Vary", "Origin");
1791
+ }
1792
+ if (opts.maxAge != null) {
1793
+ set("Access-Control-Max-Age", opts.maxAge.toString());
1794
+ }
1795
+ const allowMethods = await findAllowMethods(c.req.header("origin") || "", c);
1796
+ if (allowMethods.length) {
1797
+ set("Access-Control-Allow-Methods", allowMethods.join(","));
1798
+ }
1799
+ let headers = opts.allowHeaders;
1800
+ if (!headers?.length) {
1801
+ const requestHeaders = c.req.header("Access-Control-Request-Headers");
1802
+ if (requestHeaders) {
1803
+ headers = requestHeaders.split(/\s*,\s*/);
1804
+ }
1805
+ }
1806
+ if (headers?.length) {
1807
+ set("Access-Control-Allow-Headers", headers.join(","));
1808
+ c.res.headers.append("Vary", "Access-Control-Request-Headers");
1809
+ }
1810
+ c.res.headers.delete("Content-Length");
1811
+ c.res.headers.delete("Content-Type");
1812
+ return new Response(null, {
1813
+ headers: c.res.headers,
1814
+ status: 204,
1815
+ statusText: "No Content"
1816
+ });
1817
+ }
1818
+ await next();
1819
+ if (opts.origin !== "*") {
1820
+ c.header("Vary", "Origin", { append: true });
1821
+ }
1822
+ };
1823
+ };
1824
+
1825
+ // src/http.ts
1826
+ var app = new Hono2;
1827
+ app.use("/*", cors({
1828
+ origin: [
1829
+ "https://gethmy.com",
1830
+ "https://app.gethmy.com",
1831
+ "http://localhost:8080",
1832
+ "http://localhost:3000"
1833
+ ],
1834
+ allowMethods: ["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
1835
+ allowHeaders: ["Content-Type", "Authorization", "X-API-Key"]
1836
+ }));
1837
+ function getApiUrl2() {
1838
+ const config = loadConfig();
1839
+ return config.apiUrl;
1840
+ }
1841
+ async function forwardToApi(method, path, authHeader, apiKey, body) {
1842
+ const apiUrl = getApiUrl2();
1843
+ const headers = {
1844
+ "Content-Type": "application/json"
1845
+ };
1846
+ if (apiKey) {
1847
+ headers["X-API-Key"] = apiKey;
1848
+ } else if (authHeader) {
1849
+ headers.Authorization = authHeader;
1850
+ } else {
1851
+ throw new Error("Unauthorized: Missing API key or Authorization header");
1852
+ }
1853
+ const response = await fetch(`${apiUrl}${path}`, {
1854
+ method,
1855
+ headers,
1856
+ body: body ? JSON.stringify(body) : undefined
1857
+ });
1858
+ const data = await response.json();
1859
+ return { data, status: response.status };
1860
+ }
1861
+ app.get("/health", (c) => c.json({ status: "ok", service: "harmony-mcp-http" }));
1862
+ app.get("/", (c) => c.json({
1863
+ service: "Harmony MCP HTTP Adapter",
1864
+ endpoints: {
1865
+ workspaces: {
1866
+ list: "GET /workspaces",
1867
+ members: "GET /workspaces/:id/members",
1868
+ projects: "GET /workspaces/:id/projects"
1869
+ },
1870
+ board: {
1871
+ get: "GET /board/:projectId"
1872
+ },
1873
+ cards: {
1874
+ create: "POST /cards",
1875
+ get: "GET /cards/:id",
1876
+ getByShortId: "GET /projects/:projectId/cards/:shortId",
1877
+ update: "PATCH /cards/:id",
1878
+ delete: "DELETE /cards/:id",
1879
+ move: "POST /cards/:id/move",
1880
+ search: "GET /search?q=query"
1881
+ },
1882
+ columns: {
1883
+ create: "POST /columns",
1884
+ update: "PATCH /columns/:id",
1885
+ delete: "DELETE /columns/:id"
1886
+ },
1887
+ labels: {
1888
+ create: "POST /labels",
1889
+ addToCard: "POST /cards/:id/labels",
1890
+ removeFromCard: "DELETE /cards/:id/labels/:labelId"
1891
+ },
1892
+ subtasks: {
1893
+ create: "POST /subtasks",
1894
+ toggle: "POST /subtasks/:id/toggle",
1895
+ delete: "DELETE /subtasks/:id"
1896
+ },
1897
+ nlu: {
1898
+ process: "POST /nlu"
1899
+ }
1900
+ },
1901
+ authentication: "Include X-API-Key header or Authorization: Bearer <token>"
1902
+ }));
1903
+ async function handleRequest(c, method, path) {
1904
+ try {
1905
+ const authHeader = c.req.header("Authorization");
1906
+ const apiKey = c.req.header("X-API-Key");
1907
+ let body;
1908
+ if (["POST", "PATCH", "PUT"].includes(method)) {
1909
+ try {
1910
+ body = await c.json();
1911
+ } catch {}
1912
+ }
1913
+ const { data, status } = await forwardToApi(method, path, authHeader, apiKey, body);
1914
+ return new Response(JSON.stringify(data), {
1915
+ status,
1916
+ headers: { "Content-Type": "application/json" }
1917
+ });
1918
+ } catch (error) {
1919
+ const message = error instanceof Error ? error.message : String(error);
1920
+ const status = message.includes("Unauthorized") ? 401 : 500;
1921
+ return new Response(JSON.stringify({ error: message }), {
1922
+ status,
1923
+ headers: { "Content-Type": "application/json" }
1924
+ });
1925
+ }
128
1926
  }
129
- // Workspaces
130
1927
  app.get("/workspaces", (c) => handleRequest(c, "GET", "/workspaces"));
131
1928
  app.get("/workspaces/:id/members", (c) => handleRequest(c, "GET", `/workspaces/${c.req.param("id")}/members`));
132
1929
  app.get("/workspaces/:id/projects", (c) => handleRequest(c, "GET", `/workspaces/${c.req.param("id")}/projects`));
133
- // Projects
134
1930
  app.get("/projects", (c) => {
135
- const workspaceId = new URL(c.req.url).searchParams.get("workspace_id");
136
- return handleRequest(c, "GET", `/projects?workspace_id=${workspaceId}`);
1931
+ const workspaceId = new URL(c.req.url).searchParams.get("workspace_id");
1932
+ return handleRequest(c, "GET", `/projects?workspace_id=${workspaceId}`);
137
1933
  });
138
- // Get card by short ID: GET /projects/:projectId/cards/:shortId
139
1934
  app.get("/projects/:projectId/cards/:shortId", (c) => handleRequest(c, "GET", `/projects/${c.req.param("projectId")}/cards/${c.req.param("shortId")}`));
140
- // Board
141
1935
  app.get("/board/:projectId", (c) => handleRequest(c, "GET", `/board/${c.req.param("projectId")}`));
142
- // Cards
143
1936
  app.get("/cards/:id", (c) => handleRequest(c, "GET", `/cards/${c.req.param("id")}`));
144
1937
  app.post("/cards", (c) => handleRequest(c, "POST", "/cards"));
145
1938
  app.patch("/cards/:id", (c) => handleRequest(c, "PATCH", `/cards/${c.req.param("id")}`));
@@ -147,29 +1940,23 @@ app.delete("/cards/:id", (c) => handleRequest(c, "DELETE", `/cards/${c.req.param
147
1940
  app.post("/cards/:id/move", (c) => handleRequest(c, "POST", `/cards/${c.req.param("id")}/move`));
148
1941
  app.post("/cards/:id/labels", (c) => handleRequest(c, "POST", `/cards/${c.req.param("id")}/labels`));
149
1942
  app.delete("/cards/:id/labels/:labelId", (c) => handleRequest(c, "DELETE", `/cards/${c.req.param("id")}/labels/${c.req.param("labelId")}`));
150
- // Search
151
1943
  app.get("/search", (c) => {
152
- const params = new URL(c.req.url).searchParams;
153
- return handleRequest(c, "GET", `/search?${params.toString()}`);
1944
+ const params = new URL(c.req.url).searchParams;
1945
+ return handleRequest(c, "GET", `/search?${params.toString()}`);
154
1946
  });
155
- // Columns
156
1947
  app.post("/columns", (c) => handleRequest(c, "POST", "/columns"));
157
1948
  app.patch("/columns/:id", (c) => handleRequest(c, "PATCH", `/columns/${c.req.param("id")}`));
158
1949
  app.delete("/columns/:id", (c) => handleRequest(c, "DELETE", `/columns/${c.req.param("id")}`));
159
- // Labels
160
1950
  app.post("/labels", (c) => handleRequest(c, "POST", "/labels"));
161
- // Subtasks
162
1951
  app.post("/subtasks", (c) => handleRequest(c, "POST", "/subtasks"));
163
1952
  app.post("/subtasks/:id/toggle", (c) => handleRequest(c, "POST", `/subtasks/${c.req.param("id")}/toggle`));
164
1953
  app.delete("/subtasks/:id", (c) => handleRequest(c, "DELETE", `/subtasks/${c.req.param("id")}`));
165
- // NLU
166
1954
  app.post("/nlu", (c) => handleRequest(c, "POST", "/nlu"));
167
1955
  app.post("/nlu/process", (c) => handleRequest(c, "POST", "/nlu"));
168
- // Start server
169
- const port = parseInt(process.env.PORT || "3001", 10);
1956
+ var port = parseInt(process.env.PORT || "3001", 10);
170
1957
  console.log(`Starting Harmony MCP HTTP adapter on port ${port}...`);
171
1958
  serve({
172
- fetch: app.fetch,
173
- port,
1959
+ fetch: app.fetch,
1960
+ port
174
1961
  });
175
1962
  console.log(`Harmony MCP HTTP adapter running at http://localhost:${port}`);