@jcyamacho/agent-memory 0.0.6 → 0.0.8

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 (3) hide show
  1. package/README.md +17 -0
  2. package/dist/index.js +3588 -26
  3. package/package.json +3 -1
package/dist/index.js CHANGED
@@ -12464,15 +12464,29 @@ class StdioServerTransport {
12464
12464
  }
12465
12465
  }
12466
12466
  // package.json
12467
- var version2 = "0.0.6";
12467
+ var version2 = "0.0.8";
12468
12468
 
12469
12469
  // src/config.ts
12470
12470
  import { homedir } from "node:os";
12471
12471
  import { join } from "node:path";
12472
+ import { parseArgs } from "node:util";
12472
12473
  var AGENT_MEMORY_DB_PATH_ENV = "AGENT_MEMORY_DB_PATH";
12473
- var resolveConfig = (environment = process.env) => ({
12474
- databasePath: environment[AGENT_MEMORY_DB_PATH_ENV] || join(homedir(), ".config", "agent-memory", "memory.db")
12475
- });
12474
+ var DEFAULT_UI_PORT = 6580;
12475
+ var resolveConfig = (environment = process.env, argv = process.argv.slice(2)) => {
12476
+ const { values } = parseArgs({
12477
+ args: argv,
12478
+ options: {
12479
+ ui: { type: "boolean", default: false },
12480
+ port: { type: "string", default: String(DEFAULT_UI_PORT) }
12481
+ },
12482
+ strict: false
12483
+ });
12484
+ return {
12485
+ databasePath: environment[AGENT_MEMORY_DB_PATH_ENV] || join(homedir(), ".config", "agent-memory", "memory.db"),
12486
+ uiMode: Boolean(values.ui),
12487
+ uiPort: Number(values.port) || DEFAULT_UI_PORT
12488
+ };
12489
+ };
12476
12490
 
12477
12491
  // node_modules/zod/v3/helpers/util.js
12478
12492
  var util;
@@ -19901,6 +19915,13 @@ class ValidationError extends MemoryError {
19901
19915
  }
19902
19916
  }
19903
19917
 
19918
+ class NotFoundError extends MemoryError {
19919
+ constructor(message) {
19920
+ super("NOT_FOUND", message);
19921
+ this.name = "NotFoundError";
19922
+ }
19923
+ }
19924
+
19904
19925
  class PersistenceError extends MemoryError {
19905
19926
  constructor(message, options) {
19906
19927
  super("PERSISTENCE_ERROR", message, options);
@@ -19914,9 +19935,9 @@ var toNormalizedScore = (value) => value;
19914
19935
  // src/memory-service.ts
19915
19936
  var DEFAULT_LIMIT = 15;
19916
19937
  var MAX_LIMIT = 50;
19917
- var RECALL_CANDIDATE_LIMIT_MULTIPLIER = 2;
19938
+ var RECALL_CANDIDATE_LIMIT_MULTIPLIER = 3;
19918
19939
  var RETRIEVAL_SCORE_WEIGHT = 8;
19919
- var WORKSPACE_MATCH_WEIGHT = 2;
19940
+ var WORKSPACE_MATCH_WEIGHT = 4;
19920
19941
  var RECENCY_WEIGHT = 1;
19921
19942
  var MAX_COMPOSITE_SCORE = RETRIEVAL_SCORE_WEIGHT + WORKSPACE_MATCH_WEIGHT + RECENCY_WEIGHT;
19922
19943
 
@@ -19975,6 +19996,14 @@ var normalizeTerms = (terms) => {
19975
19996
  const normalizedTerms = terms.map((term) => term.trim()).filter(Boolean);
19976
19997
  return [...new Set(normalizedTerms)];
19977
19998
  };
19999
+ var GLOBAL_WORKSPACE_SCORE = 0.5;
20000
+ var computeWorkspaceScore = (memoryWs, queryWs) => {
20001
+ if (!memoryWs)
20002
+ return GLOBAL_WORKSPACE_SCORE;
20003
+ if (queryWs && memoryWs === queryWs)
20004
+ return 1;
20005
+ return 0;
20006
+ };
19978
20007
  var rerankSearchResults = (results, workspace) => {
19979
20008
  if (results.length <= 1) {
19980
20009
  return results;
@@ -19983,7 +20012,7 @@ var rerankSearchResults = (results, workspace) => {
19983
20012
  const minUpdatedAt = Math.min(...updatedAtTimes);
19984
20013
  const maxUpdatedAt = Math.max(...updatedAtTimes);
19985
20014
  return [...results].map((result) => {
19986
- const workspaceScore = workspace && result.workspace === workspace ? 1 : 0;
20015
+ const workspaceScore = computeWorkspaceScore(result.workspace, workspace);
19987
20016
  const recencyScore = maxUpdatedAt === minUpdatedAt ? 0 : (result.updatedAt.getTime() - minUpdatedAt) / (maxUpdatedAt - minUpdatedAt);
19988
20017
  const combinedScore = (result.score * RETRIEVAL_SCORE_WEIGHT + workspaceScore * WORKSPACE_MATCH_WEIGHT + recencyScore * RECENCY_WEIGHT) / MAX_COMPOSITE_SCORE;
19989
20018
  return {
@@ -20192,6 +20221,10 @@ var initializeMemoryDatabase = (database) => {
20192
20221
  class SqliteMemoryRepository {
20193
20222
  database;
20194
20223
  insertStatement;
20224
+ findByIdStatement;
20225
+ updateStatement;
20226
+ deleteStatement;
20227
+ listWorkspacesStatement;
20195
20228
  constructor(database) {
20196
20229
  this.database = database;
20197
20230
  this.insertStatement = database.prepare(`
@@ -20209,6 +20242,10 @@ class SqliteMemoryRepository {
20209
20242
  ?
20210
20243
  )
20211
20244
  `);
20245
+ this.findByIdStatement = database.prepare("SELECT id, content, workspace, created_at, updated_at FROM memories WHERE id = ?");
20246
+ this.updateStatement = database.prepare("UPDATE memories SET content = ?, updated_at = ? WHERE id = ?");
20247
+ this.deleteStatement = database.prepare("DELETE FROM memories WHERE id = ?");
20248
+ this.listWorkspacesStatement = database.prepare("SELECT DISTINCT workspace FROM memories WHERE workspace IS NOT NULL ORDER BY workspace");
20212
20249
  }
20213
20250
  async save(memory) {
20214
20251
  try {
@@ -20248,12 +20285,8 @@ class SqliteMemoryRepository {
20248
20285
  const rows = statement.all(...params);
20249
20286
  const maxScore = Math.max(...rows.map((row) => row.score), 0);
20250
20287
  return rows.map((row) => ({
20251
- id: row.id,
20252
- content: row.content,
20253
- score: toNormalizedScore(maxScore > 0 ? row.score / maxScore : 0),
20254
- workspace: row.workspace ?? undefined,
20255
- createdAt: new Date(row.created_at),
20256
- updatedAt: new Date(row.updated_at)
20288
+ ...toMemoryRecord(row),
20289
+ score: toNormalizedScore(maxScore > 0 ? row.score / maxScore : 0)
20257
20290
  }));
20258
20291
  } catch (error2) {
20259
20292
  throw new PersistenceError("Failed to search memories.", {
@@ -20261,7 +20294,87 @@ class SqliteMemoryRepository {
20261
20294
  });
20262
20295
  }
20263
20296
  }
20297
+ async findById(id) {
20298
+ try {
20299
+ const rows = this.findByIdStatement.all(id);
20300
+ const row = rows[0];
20301
+ return row ? toMemoryRecord(row) : undefined;
20302
+ } catch (error2) {
20303
+ throw new PersistenceError("Failed to find memory.", { cause: error2 });
20304
+ }
20305
+ }
20306
+ async findAll(options) {
20307
+ try {
20308
+ const whereClauses = [];
20309
+ const params = [];
20310
+ if (options.workspace) {
20311
+ whereClauses.push("workspace = ?");
20312
+ params.push(options.workspace);
20313
+ } else if (options.workspaceIsNull) {
20314
+ whereClauses.push("workspace IS NULL");
20315
+ }
20316
+ const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
20317
+ const limit = options.limit + 1;
20318
+ params.push(limit, options.offset);
20319
+ const statement = this.database.prepare(`
20320
+ SELECT id, content, workspace, created_at, updated_at
20321
+ FROM memories
20322
+ ${whereClause}
20323
+ ORDER BY created_at DESC
20324
+ LIMIT ? OFFSET ?
20325
+ `);
20326
+ const rows = statement.all(...params);
20327
+ const hasMore = rows.length > options.limit;
20328
+ const items = (hasMore ? rows.slice(0, options.limit) : rows).map(toMemoryRecord);
20329
+ return { items, hasMore };
20330
+ } catch (error2) {
20331
+ throw new PersistenceError("Failed to list memories.", { cause: error2 });
20332
+ }
20333
+ }
20334
+ async update(id, content) {
20335
+ let result;
20336
+ try {
20337
+ const now = Date.now();
20338
+ result = this.updateStatement.run(content, now, id);
20339
+ } catch (error2) {
20340
+ throw new PersistenceError("Failed to update memory.", { cause: error2 });
20341
+ }
20342
+ if (result.changes === 0) {
20343
+ throw new NotFoundError(`Memory not found: ${id}`);
20344
+ }
20345
+ const memory = await this.findById(id);
20346
+ if (!memory) {
20347
+ throw new NotFoundError(`Memory not found after update: ${id}`);
20348
+ }
20349
+ return memory;
20350
+ }
20351
+ async delete(id) {
20352
+ let result;
20353
+ try {
20354
+ result = this.deleteStatement.run(id);
20355
+ } catch (error2) {
20356
+ throw new PersistenceError("Failed to delete memory.", { cause: error2 });
20357
+ }
20358
+ if (result.changes === 0) {
20359
+ throw new NotFoundError(`Memory not found: ${id}`);
20360
+ }
20361
+ }
20362
+ async listWorkspaces() {
20363
+ try {
20364
+ const rows = this.listWorkspacesStatement.all();
20365
+ return rows.map((row) => row.workspace);
20366
+ } catch (error2) {
20367
+ throw new PersistenceError("Failed to list workspaces.", { cause: error2 });
20368
+ }
20369
+ }
20264
20370
  }
20371
+ var toMemoryRecord = (row) => ({
20372
+ id: row.id,
20373
+ content: row.content,
20374
+ workspace: row.workspace ?? undefined,
20375
+ createdAt: new Date(row.created_at),
20376
+ updatedAt: new Date(row.updated_at)
20377
+ });
20265
20378
  var toFtsQuery = (terms) => terms.map(toFtsTerm).join(" OR ");
20266
20379
  var toFtsTerm = (term) => {
20267
20380
  const escaped = term.replaceAll('"', '""');
@@ -20271,17 +20384,3466 @@ var toFtsTerm = (term) => {
20271
20384
  return `"${escaped}"*`;
20272
20385
  };
20273
20386
 
20274
- // src/index.ts
20275
- var { databasePath } = resolveConfig();
20276
- var database = openMemoryDatabase(databasePath);
20277
- var repository = new SqliteMemoryRepository(database);
20278
- var memoryService = new MemoryService(repository);
20279
- var server = createMcpServer(memoryService, version2);
20280
- var transport = new StdioServerTransport;
20281
- try {
20282
- await server.connect(transport);
20283
- } catch (error2) {
20284
- console.error(error2 instanceof Error ? error2.message : "Failed to start agent-memory.");
20285
- database.close();
20286
- process.exit(1);
20387
+ // src/ui/server.tsx
20388
+ import { randomUUID as randomUUID2 } from "node:crypto";
20389
+
20390
+ // node_modules/@hono/node-server/dist/index.mjs
20391
+ import { createServer as createServerHTTP } from "http";
20392
+ import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
20393
+ import { Http2ServerRequest } from "http2";
20394
+ import { Readable } from "stream";
20395
+ import crypto from "crypto";
20396
+ var RequestError = class extends Error {
20397
+ constructor(message, options) {
20398
+ super(message, options);
20399
+ this.name = "RequestError";
20400
+ }
20401
+ };
20402
+ var toRequestError = (e) => {
20403
+ if (e instanceof RequestError) {
20404
+ return e;
20405
+ }
20406
+ return new RequestError(e.message, { cause: e });
20407
+ };
20408
+ var GlobalRequest = global.Request;
20409
+ var Request2 = class extends GlobalRequest {
20410
+ constructor(input, options) {
20411
+ if (typeof input === "object" && getRequestCache in input) {
20412
+ input = input[getRequestCache]();
20413
+ }
20414
+ if (typeof options?.body?.getReader !== "undefined") {
20415
+ options.duplex ??= "half";
20416
+ }
20417
+ super(input, options);
20418
+ }
20419
+ };
20420
+ var newHeadersFromIncoming = (incoming) => {
20421
+ const headerRecord = [];
20422
+ const rawHeaders = incoming.rawHeaders;
20423
+ for (let i = 0;i < rawHeaders.length; i += 2) {
20424
+ const { [i]: key, [i + 1]: value } = rawHeaders;
20425
+ if (key.charCodeAt(0) !== 58) {
20426
+ headerRecord.push([key, value]);
20427
+ }
20428
+ }
20429
+ return new Headers(headerRecord);
20430
+ };
20431
+ var wrapBodyStream = Symbol("wrapBodyStream");
20432
+ var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
20433
+ const init = {
20434
+ method,
20435
+ headers,
20436
+ signal: abortController.signal
20437
+ };
20438
+ if (method === "TRACE") {
20439
+ init.method = "GET";
20440
+ const req = new Request2(url, init);
20441
+ Object.defineProperty(req, "method", {
20442
+ get() {
20443
+ return "TRACE";
20444
+ }
20445
+ });
20446
+ return req;
20447
+ }
20448
+ if (!(method === "GET" || method === "HEAD")) {
20449
+ if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
20450
+ init.body = new ReadableStream({
20451
+ start(controller) {
20452
+ controller.enqueue(incoming.rawBody);
20453
+ controller.close();
20454
+ }
20455
+ });
20456
+ } else if (incoming[wrapBodyStream]) {
20457
+ let reader;
20458
+ init.body = new ReadableStream({
20459
+ async pull(controller) {
20460
+ try {
20461
+ reader ||= Readable.toWeb(incoming).getReader();
20462
+ const { done, value } = await reader.read();
20463
+ if (done) {
20464
+ controller.close();
20465
+ } else {
20466
+ controller.enqueue(value);
20467
+ }
20468
+ } catch (error2) {
20469
+ controller.error(error2);
20470
+ }
20471
+ }
20472
+ });
20473
+ } else {
20474
+ init.body = Readable.toWeb(incoming);
20475
+ }
20476
+ }
20477
+ return new Request2(url, init);
20478
+ };
20479
+ var getRequestCache = Symbol("getRequestCache");
20480
+ var requestCache = Symbol("requestCache");
20481
+ var incomingKey = Symbol("incomingKey");
20482
+ var urlKey = Symbol("urlKey");
20483
+ var headersKey = Symbol("headersKey");
20484
+ var abortControllerKey = Symbol("abortControllerKey");
20485
+ var getAbortController = Symbol("getAbortController");
20486
+ var requestPrototype = {
20487
+ get method() {
20488
+ return this[incomingKey].method || "GET";
20489
+ },
20490
+ get url() {
20491
+ return this[urlKey];
20492
+ },
20493
+ get headers() {
20494
+ return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
20495
+ },
20496
+ [getAbortController]() {
20497
+ this[getRequestCache]();
20498
+ return this[abortControllerKey];
20499
+ },
20500
+ [getRequestCache]() {
20501
+ this[abortControllerKey] ||= new AbortController;
20502
+ return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
20503
+ }
20504
+ };
20505
+ [
20506
+ "body",
20507
+ "bodyUsed",
20508
+ "cache",
20509
+ "credentials",
20510
+ "destination",
20511
+ "integrity",
20512
+ "mode",
20513
+ "redirect",
20514
+ "referrer",
20515
+ "referrerPolicy",
20516
+ "signal",
20517
+ "keepalive"
20518
+ ].forEach((k) => {
20519
+ Object.defineProperty(requestPrototype, k, {
20520
+ get() {
20521
+ return this[getRequestCache]()[k];
20522
+ }
20523
+ });
20524
+ });
20525
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
20526
+ Object.defineProperty(requestPrototype, k, {
20527
+ value: function() {
20528
+ return this[getRequestCache]()[k]();
20529
+ }
20530
+ });
20531
+ });
20532
+ Object.setPrototypeOf(requestPrototype, Request2.prototype);
20533
+ var newRequest = (incoming, defaultHostname) => {
20534
+ const req = Object.create(requestPrototype);
20535
+ req[incomingKey] = incoming;
20536
+ const incomingUrl = incoming.url || "";
20537
+ if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
20538
+ if (incoming instanceof Http2ServerRequest) {
20539
+ throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
20540
+ }
20541
+ try {
20542
+ const url2 = new URL(incomingUrl);
20543
+ req[urlKey] = url2.href;
20544
+ } catch (e) {
20545
+ throw new RequestError("Invalid absolute URL", { cause: e });
20546
+ }
20547
+ return req;
20548
+ }
20549
+ const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
20550
+ if (!host) {
20551
+ throw new RequestError("Missing host header");
20552
+ }
20553
+ let scheme;
20554
+ if (incoming instanceof Http2ServerRequest) {
20555
+ scheme = incoming.scheme;
20556
+ if (!(scheme === "http" || scheme === "https")) {
20557
+ throw new RequestError("Unsupported scheme");
20558
+ }
20559
+ } else {
20560
+ scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
20561
+ }
20562
+ const url = new URL(`${scheme}://${host}${incomingUrl}`);
20563
+ if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
20564
+ throw new RequestError("Invalid host header");
20565
+ }
20566
+ req[urlKey] = url.href;
20567
+ return req;
20568
+ };
20569
+ var responseCache = Symbol("responseCache");
20570
+ var getResponseCache = Symbol("getResponseCache");
20571
+ var cacheKey = Symbol("cache");
20572
+ var GlobalResponse = global.Response;
20573
+ var Response2 = class _Response {
20574
+ #body;
20575
+ #init;
20576
+ [getResponseCache]() {
20577
+ delete this[cacheKey];
20578
+ return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
20579
+ }
20580
+ constructor(body, init) {
20581
+ let headers;
20582
+ this.#body = body;
20583
+ if (init instanceof _Response) {
20584
+ const cachedGlobalResponse = init[responseCache];
20585
+ if (cachedGlobalResponse) {
20586
+ this.#init = cachedGlobalResponse;
20587
+ this[getResponseCache]();
20588
+ return;
20589
+ } else {
20590
+ this.#init = init.#init;
20591
+ headers = new Headers(init.#init.headers);
20592
+ }
20593
+ } else {
20594
+ this.#init = init;
20595
+ }
20596
+ if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
20597
+ this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
20598
+ }
20599
+ }
20600
+ get headers() {
20601
+ const cache = this[cacheKey];
20602
+ if (cache) {
20603
+ if (!(cache[2] instanceof Headers)) {
20604
+ cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
20605
+ }
20606
+ return cache[2];
20607
+ }
20608
+ return this[getResponseCache]().headers;
20609
+ }
20610
+ get status() {
20611
+ return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
20612
+ }
20613
+ get ok() {
20614
+ const status = this.status;
20615
+ return status >= 200 && status < 300;
20616
+ }
20617
+ };
20618
+ ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
20619
+ Object.defineProperty(Response2.prototype, k, {
20620
+ get() {
20621
+ return this[getResponseCache]()[k];
20622
+ }
20623
+ });
20624
+ });
20625
+ ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
20626
+ Object.defineProperty(Response2.prototype, k, {
20627
+ value: function() {
20628
+ return this[getResponseCache]()[k]();
20629
+ }
20630
+ });
20631
+ });
20632
+ Object.setPrototypeOf(Response2, GlobalResponse);
20633
+ Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
20634
+ async function readWithoutBlocking(readPromise) {
20635
+ return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(undefined))]);
20636
+ }
20637
+ function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
20638
+ const cancel = (error2) => {
20639
+ reader.cancel(error2).catch(() => {});
20640
+ };
20641
+ writable.on("close", cancel);
20642
+ writable.on("error", cancel);
20643
+ (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
20644
+ return reader.closed.finally(() => {
20645
+ writable.off("close", cancel);
20646
+ writable.off("error", cancel);
20647
+ });
20648
+ function handleStreamError(error2) {
20649
+ if (error2) {
20650
+ writable.destroy(error2);
20651
+ }
20652
+ }
20653
+ function onDrain() {
20654
+ reader.read().then(flow, handleStreamError);
20655
+ }
20656
+ function flow({ done, value }) {
20657
+ try {
20658
+ if (done) {
20659
+ writable.end();
20660
+ } else if (!writable.write(value)) {
20661
+ writable.once("drain", onDrain);
20662
+ } else {
20663
+ return reader.read().then(flow, handleStreamError);
20664
+ }
20665
+ } catch (e) {
20666
+ handleStreamError(e);
20667
+ }
20668
+ }
20669
+ }
20670
+ function writeFromReadableStream(stream, writable) {
20671
+ if (stream.locked) {
20672
+ throw new TypeError("ReadableStream is locked.");
20673
+ } else if (writable.destroyed) {
20674
+ return;
20675
+ }
20676
+ return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
20677
+ }
20678
+ var buildOutgoingHttpHeaders = (headers) => {
20679
+ const res = {};
20680
+ if (!(headers instanceof Headers)) {
20681
+ headers = new Headers(headers ?? undefined);
20682
+ }
20683
+ const cookies = [];
20684
+ for (const [k, v] of headers) {
20685
+ if (k === "set-cookie") {
20686
+ cookies.push(v);
20687
+ } else {
20688
+ res[k] = v;
20689
+ }
20690
+ }
20691
+ if (cookies.length > 0) {
20692
+ res["set-cookie"] = cookies;
20693
+ }
20694
+ res["content-type"] ??= "text/plain; charset=UTF-8";
20695
+ return res;
20696
+ };
20697
+ var X_ALREADY_SENT = "x-hono-already-sent";
20698
+ if (typeof global.crypto === "undefined") {
20699
+ global.crypto = crypto;
20700
+ }
20701
+ var outgoingEnded = Symbol("outgoingEnded");
20702
+ var handleRequestError = () => new Response(null, {
20703
+ status: 400
20704
+ });
20705
+ var handleFetchError = (e) => new Response(null, {
20706
+ status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
20707
+ });
20708
+ var handleResponseError = (e, outgoing) => {
20709
+ const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
20710
+ if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
20711
+ console.info("The user aborted a request.");
20712
+ } else {
20713
+ console.error(e);
20714
+ if (!outgoing.headersSent) {
20715
+ outgoing.writeHead(500, { "Content-Type": "text/plain" });
20716
+ }
20717
+ outgoing.end(`Error: ${err.message}`);
20718
+ outgoing.destroy(err);
20719
+ }
20720
+ };
20721
+ var flushHeaders = (outgoing) => {
20722
+ if ("flushHeaders" in outgoing && outgoing.writable) {
20723
+ outgoing.flushHeaders();
20724
+ }
20725
+ };
20726
+ var responseViaCache = async (res, outgoing) => {
20727
+ let [status, body, header] = res[cacheKey];
20728
+ let hasContentLength = false;
20729
+ if (!header) {
20730
+ header = { "content-type": "text/plain; charset=UTF-8" };
20731
+ } else if (header instanceof Headers) {
20732
+ hasContentLength = header.has("content-length");
20733
+ header = buildOutgoingHttpHeaders(header);
20734
+ } else if (Array.isArray(header)) {
20735
+ const headerObj = new Headers(header);
20736
+ hasContentLength = headerObj.has("content-length");
20737
+ header = buildOutgoingHttpHeaders(headerObj);
20738
+ } else {
20739
+ for (const key in header) {
20740
+ if (key.length === 14 && key.toLowerCase() === "content-length") {
20741
+ hasContentLength = true;
20742
+ break;
20743
+ }
20744
+ }
20745
+ }
20746
+ if (!hasContentLength) {
20747
+ if (typeof body === "string") {
20748
+ header["Content-Length"] = Buffer.byteLength(body);
20749
+ } else if (body instanceof Uint8Array) {
20750
+ header["Content-Length"] = body.byteLength;
20751
+ } else if (body instanceof Blob) {
20752
+ header["Content-Length"] = body.size;
20753
+ }
20754
+ }
20755
+ outgoing.writeHead(status, header);
20756
+ if (typeof body === "string" || body instanceof Uint8Array) {
20757
+ outgoing.end(body);
20758
+ } else if (body instanceof Blob) {
20759
+ outgoing.end(new Uint8Array(await body.arrayBuffer()));
20760
+ } else {
20761
+ flushHeaders(outgoing);
20762
+ await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
20763
+ }
20764
+ outgoing[outgoingEnded]?.();
20765
+ };
20766
+ var isPromise = (res) => typeof res.then === "function";
20767
+ var responseViaResponseObject = async (res, outgoing, options = {}) => {
20768
+ if (isPromise(res)) {
20769
+ if (options.errorHandler) {
20770
+ try {
20771
+ res = await res;
20772
+ } catch (err) {
20773
+ const errRes = await options.errorHandler(err);
20774
+ if (!errRes) {
20775
+ return;
20776
+ }
20777
+ res = errRes;
20778
+ }
20779
+ } else {
20780
+ res = await res.catch(handleFetchError);
20781
+ }
20782
+ }
20783
+ if (cacheKey in res) {
20784
+ return responseViaCache(res, outgoing);
20785
+ }
20786
+ const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
20787
+ if (res.body) {
20788
+ const reader = res.body.getReader();
20789
+ const values = [];
20790
+ let done = false;
20791
+ let currentReadPromise = undefined;
20792
+ if (resHeaderRecord["transfer-encoding"] !== "chunked") {
20793
+ let maxReadCount = 2;
20794
+ for (let i = 0;i < maxReadCount; i++) {
20795
+ currentReadPromise ||= reader.read();
20796
+ const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
20797
+ console.error(e);
20798
+ done = true;
20799
+ });
20800
+ if (!chunk) {
20801
+ if (i === 1) {
20802
+ await new Promise((resolve) => setTimeout(resolve));
20803
+ maxReadCount = 3;
20804
+ continue;
20805
+ }
20806
+ break;
20807
+ }
20808
+ currentReadPromise = undefined;
20809
+ if (chunk.value) {
20810
+ values.push(chunk.value);
20811
+ }
20812
+ if (chunk.done) {
20813
+ done = true;
20814
+ break;
20815
+ }
20816
+ }
20817
+ if (done && !("content-length" in resHeaderRecord)) {
20818
+ resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
20819
+ }
20820
+ }
20821
+ outgoing.writeHead(res.status, resHeaderRecord);
20822
+ values.forEach((value) => {
20823
+ outgoing.write(value);
20824
+ });
20825
+ if (done) {
20826
+ outgoing.end();
20827
+ } else {
20828
+ if (values.length === 0) {
20829
+ flushHeaders(outgoing);
20830
+ }
20831
+ await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
20832
+ }
20833
+ } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
20834
+ outgoing.writeHead(res.status, resHeaderRecord);
20835
+ outgoing.end();
20836
+ }
20837
+ outgoing[outgoingEnded]?.();
20838
+ };
20839
+ var getRequestListener = (fetchCallback, options = {}) => {
20840
+ const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
20841
+ if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
20842
+ Object.defineProperty(global, "Request", {
20843
+ value: Request2
20844
+ });
20845
+ Object.defineProperty(global, "Response", {
20846
+ value: Response2
20847
+ });
20848
+ }
20849
+ return async (incoming, outgoing) => {
20850
+ let res, req;
20851
+ try {
20852
+ req = newRequest(incoming, options.hostname);
20853
+ let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
20854
+ if (!incomingEnded) {
20855
+ incoming[wrapBodyStream] = true;
20856
+ incoming.on("end", () => {
20857
+ incomingEnded = true;
20858
+ });
20859
+ if (incoming instanceof Http2ServerRequest2) {
20860
+ outgoing[outgoingEnded] = () => {
20861
+ if (!incomingEnded) {
20862
+ setTimeout(() => {
20863
+ if (!incomingEnded) {
20864
+ setTimeout(() => {
20865
+ incoming.destroy();
20866
+ outgoing.destroy();
20867
+ });
20868
+ }
20869
+ });
20870
+ }
20871
+ };
20872
+ }
20873
+ }
20874
+ outgoing.on("close", () => {
20875
+ const abortController = req[abortControllerKey];
20876
+ if (abortController) {
20877
+ if (incoming.errored) {
20878
+ req[abortControllerKey].abort(incoming.errored.toString());
20879
+ } else if (!outgoing.writableFinished) {
20880
+ req[abortControllerKey].abort("Client connection prematurely closed.");
20881
+ }
20882
+ }
20883
+ if (!incomingEnded) {
20884
+ setTimeout(() => {
20885
+ if (!incomingEnded) {
20886
+ setTimeout(() => {
20887
+ incoming.destroy();
20888
+ });
20889
+ }
20890
+ });
20891
+ }
20892
+ });
20893
+ res = fetchCallback(req, { incoming, outgoing });
20894
+ if (cacheKey in res) {
20895
+ return responseViaCache(res, outgoing);
20896
+ }
20897
+ } catch (e) {
20898
+ if (!res) {
20899
+ if (options.errorHandler) {
20900
+ res = await options.errorHandler(req ? e : toRequestError(e));
20901
+ if (!res) {
20902
+ return;
20903
+ }
20904
+ } else if (!req) {
20905
+ res = handleRequestError();
20906
+ } else {
20907
+ res = handleFetchError(e);
20908
+ }
20909
+ } else {
20910
+ return handleResponseError(e, outgoing);
20911
+ }
20912
+ }
20913
+ try {
20914
+ return await responseViaResponseObject(res, outgoing, options);
20915
+ } catch (e) {
20916
+ return handleResponseError(e, outgoing);
20917
+ }
20918
+ };
20919
+ };
20920
+ var createAdaptorServer = (options) => {
20921
+ const fetchCallback = options.fetch;
20922
+ const requestListener = getRequestListener(fetchCallback, {
20923
+ hostname: options.hostname,
20924
+ overrideGlobalObjects: options.overrideGlobalObjects,
20925
+ autoCleanupIncoming: options.autoCleanupIncoming
20926
+ });
20927
+ const createServer = options.createServer || createServerHTTP;
20928
+ const server = createServer(options.serverOptions || {}, requestListener);
20929
+ return server;
20930
+ };
20931
+ var serve = (options, listeningListener) => {
20932
+ const server = createAdaptorServer(options);
20933
+ server.listen(options?.port ?? 3000, options.hostname, () => {
20934
+ const serverInfo = server.address();
20935
+ listeningListener && listeningListener(serverInfo);
20936
+ });
20937
+ return server;
20938
+ };
20939
+
20940
+ // node_modules/hono/dist/compose.js
20941
+ var compose = (middleware, onError, onNotFound) => {
20942
+ return (context, next) => {
20943
+ let index = -1;
20944
+ return dispatch(0);
20945
+ async function dispatch(i) {
20946
+ if (i <= index) {
20947
+ throw new Error("next() called multiple times");
20948
+ }
20949
+ index = i;
20950
+ let res;
20951
+ let isError = false;
20952
+ let handler;
20953
+ if (middleware[i]) {
20954
+ handler = middleware[i][0][0];
20955
+ context.req.routeIndex = i;
20956
+ } else {
20957
+ handler = i === middleware.length && next || undefined;
20958
+ }
20959
+ if (handler) {
20960
+ try {
20961
+ res = await handler(context, () => dispatch(i + 1));
20962
+ } catch (err) {
20963
+ if (err instanceof Error && onError) {
20964
+ context.error = err;
20965
+ res = await onError(err, context);
20966
+ isError = true;
20967
+ } else {
20968
+ throw err;
20969
+ }
20970
+ }
20971
+ } else {
20972
+ if (context.finalized === false && onNotFound) {
20973
+ res = await onNotFound(context);
20974
+ }
20975
+ }
20976
+ if (res && (context.finalized === false || isError)) {
20977
+ context.res = res;
20978
+ }
20979
+ return context;
20980
+ }
20981
+ };
20982
+ };
20983
+
20984
+ // node_modules/hono/dist/request/constants.js
20985
+ var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
20986
+
20987
+ // node_modules/hono/dist/utils/body.js
20988
+ var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
20989
+ const { all = false, dot = false } = options;
20990
+ const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
20991
+ const contentType = headers.get("Content-Type");
20992
+ if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
20993
+ return parseFormData(request, { all, dot });
20994
+ }
20995
+ return {};
20996
+ };
20997
+ async function parseFormData(request, options) {
20998
+ const formData = await request.formData();
20999
+ if (formData) {
21000
+ return convertFormDataToBodyData(formData, options);
21001
+ }
21002
+ return {};
21003
+ }
21004
+ function convertFormDataToBodyData(formData, options) {
21005
+ const form = /* @__PURE__ */ Object.create(null);
21006
+ formData.forEach((value, key) => {
21007
+ const shouldParseAllValues = options.all || key.endsWith("[]");
21008
+ if (!shouldParseAllValues) {
21009
+ form[key] = value;
21010
+ } else {
21011
+ handleParsingAllValues(form, key, value);
21012
+ }
21013
+ });
21014
+ if (options.dot) {
21015
+ Object.entries(form).forEach(([key, value]) => {
21016
+ const shouldParseDotValues = key.includes(".");
21017
+ if (shouldParseDotValues) {
21018
+ handleParsingNestedValues(form, key, value);
21019
+ delete form[key];
21020
+ }
21021
+ });
21022
+ }
21023
+ return form;
21024
+ }
21025
+ var handleParsingAllValues = (form, key, value) => {
21026
+ if (form[key] !== undefined) {
21027
+ if (Array.isArray(form[key])) {
21028
+ form[key].push(value);
21029
+ } else {
21030
+ form[key] = [form[key], value];
21031
+ }
21032
+ } else {
21033
+ if (!key.endsWith("[]")) {
21034
+ form[key] = value;
21035
+ } else {
21036
+ form[key] = [value];
21037
+ }
21038
+ }
21039
+ };
21040
+ var handleParsingNestedValues = (form, key, value) => {
21041
+ if (/(?:^|\.)__proto__\./.test(key)) {
21042
+ return;
21043
+ }
21044
+ let nestedForm = form;
21045
+ const keys = key.split(".");
21046
+ keys.forEach((key2, index) => {
21047
+ if (index === keys.length - 1) {
21048
+ nestedForm[key2] = value;
21049
+ } else {
21050
+ if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
21051
+ nestedForm[key2] = /* @__PURE__ */ Object.create(null);
21052
+ }
21053
+ nestedForm = nestedForm[key2];
21054
+ }
21055
+ });
21056
+ };
21057
+
21058
+ // node_modules/hono/dist/utils/url.js
21059
+ var splitPath = (path) => {
21060
+ const paths = path.split("/");
21061
+ if (paths[0] === "") {
21062
+ paths.shift();
21063
+ }
21064
+ return paths;
21065
+ };
21066
+ var splitRoutingPath = (routePath) => {
21067
+ const { groups, path } = extractGroupsFromPath(routePath);
21068
+ const paths = splitPath(path);
21069
+ return replaceGroupMarks(paths, groups);
21070
+ };
21071
+ var extractGroupsFromPath = (path) => {
21072
+ const groups = [];
21073
+ path = path.replace(/\{[^}]+\}/g, (match, index) => {
21074
+ const mark = `@${index}`;
21075
+ groups.push([mark, match]);
21076
+ return mark;
21077
+ });
21078
+ return { groups, path };
21079
+ };
21080
+ var replaceGroupMarks = (paths, groups) => {
21081
+ for (let i = groups.length - 1;i >= 0; i--) {
21082
+ const [mark] = groups[i];
21083
+ for (let j = paths.length - 1;j >= 0; j--) {
21084
+ if (paths[j].includes(mark)) {
21085
+ paths[j] = paths[j].replace(mark, groups[i][1]);
21086
+ break;
21087
+ }
21088
+ }
21089
+ }
21090
+ return paths;
21091
+ };
21092
+ var patternCache = {};
21093
+ var getPattern = (label, next) => {
21094
+ if (label === "*") {
21095
+ return "*";
21096
+ }
21097
+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
21098
+ if (match) {
21099
+ const cacheKey2 = `${label}#${next}`;
21100
+ if (!patternCache[cacheKey2]) {
21101
+ if (match[2]) {
21102
+ patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
21103
+ } else {
21104
+ patternCache[cacheKey2] = [label, match[1], true];
21105
+ }
21106
+ }
21107
+ return patternCache[cacheKey2];
21108
+ }
21109
+ return null;
21110
+ };
21111
+ var tryDecode = (str, decoder) => {
21112
+ try {
21113
+ return decoder(str);
21114
+ } catch {
21115
+ return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
21116
+ try {
21117
+ return decoder(match);
21118
+ } catch {
21119
+ return match;
21120
+ }
21121
+ });
21122
+ }
21123
+ };
21124
+ var tryDecodeURI = (str) => tryDecode(str, decodeURI);
21125
+ var getPath = (request) => {
21126
+ const url = request.url;
21127
+ const start = url.indexOf("/", url.indexOf(":") + 4);
21128
+ let i = start;
21129
+ for (;i < url.length; i++) {
21130
+ const charCode = url.charCodeAt(i);
21131
+ if (charCode === 37) {
21132
+ const queryIndex = url.indexOf("?", i);
21133
+ const hashIndex = url.indexOf("#", i);
21134
+ const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
21135
+ const path = url.slice(start, end);
21136
+ return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
21137
+ } else if (charCode === 63 || charCode === 35) {
21138
+ break;
21139
+ }
21140
+ }
21141
+ return url.slice(start, i);
21142
+ };
21143
+ var getPathNoStrict = (request) => {
21144
+ const result = getPath(request);
21145
+ return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
21146
+ };
21147
+ var mergePath = (base, sub, ...rest) => {
21148
+ if (rest.length) {
21149
+ sub = mergePath(sub, ...rest);
21150
+ }
21151
+ return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
21152
+ };
21153
+ var checkOptionalParameter = (path) => {
21154
+ if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
21155
+ return null;
21156
+ }
21157
+ const segments = path.split("/");
21158
+ const results = [];
21159
+ let basePath = "";
21160
+ segments.forEach((segment) => {
21161
+ if (segment !== "" && !/\:/.test(segment)) {
21162
+ basePath += "/" + segment;
21163
+ } else if (/\:/.test(segment)) {
21164
+ if (/\?/.test(segment)) {
21165
+ if (results.length === 0 && basePath === "") {
21166
+ results.push("/");
21167
+ } else {
21168
+ results.push(basePath);
21169
+ }
21170
+ const optionalSegment = segment.replace("?", "");
21171
+ basePath += "/" + optionalSegment;
21172
+ results.push(basePath);
21173
+ } else {
21174
+ basePath += "/" + segment;
21175
+ }
21176
+ }
21177
+ });
21178
+ return results.filter((v, i, a) => a.indexOf(v) === i);
21179
+ };
21180
+ var _decodeURI = (value) => {
21181
+ if (!/[%+]/.test(value)) {
21182
+ return value;
21183
+ }
21184
+ if (value.indexOf("+") !== -1) {
21185
+ value = value.replace(/\+/g, " ");
21186
+ }
21187
+ return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
21188
+ };
21189
+ var _getQueryParam = (url, key, multiple) => {
21190
+ let encoded;
21191
+ if (!multiple && key && !/[%+]/.test(key)) {
21192
+ let keyIndex2 = url.indexOf("?", 8);
21193
+ if (keyIndex2 === -1) {
21194
+ return;
21195
+ }
21196
+ if (!url.startsWith(key, keyIndex2 + 1)) {
21197
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
21198
+ }
21199
+ while (keyIndex2 !== -1) {
21200
+ const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
21201
+ if (trailingKeyCode === 61) {
21202
+ const valueIndex = keyIndex2 + key.length + 2;
21203
+ const endIndex = url.indexOf("&", valueIndex);
21204
+ return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
21205
+ } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
21206
+ return "";
21207
+ }
21208
+ keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
21209
+ }
21210
+ encoded = /[%+]/.test(url);
21211
+ if (!encoded) {
21212
+ return;
21213
+ }
21214
+ }
21215
+ const results = {};
21216
+ encoded ??= /[%+]/.test(url);
21217
+ let keyIndex = url.indexOf("?", 8);
21218
+ while (keyIndex !== -1) {
21219
+ const nextKeyIndex = url.indexOf("&", keyIndex + 1);
21220
+ let valueIndex = url.indexOf("=", keyIndex);
21221
+ if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
21222
+ valueIndex = -1;
21223
+ }
21224
+ let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
21225
+ if (encoded) {
21226
+ name = _decodeURI(name);
21227
+ }
21228
+ keyIndex = nextKeyIndex;
21229
+ if (name === "") {
21230
+ continue;
21231
+ }
21232
+ let value;
21233
+ if (valueIndex === -1) {
21234
+ value = "";
21235
+ } else {
21236
+ value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
21237
+ if (encoded) {
21238
+ value = _decodeURI(value);
21239
+ }
21240
+ }
21241
+ if (multiple) {
21242
+ if (!(results[name] && Array.isArray(results[name]))) {
21243
+ results[name] = [];
21244
+ }
21245
+ results[name].push(value);
21246
+ } else {
21247
+ results[name] ??= value;
21248
+ }
21249
+ }
21250
+ return key ? results[key] : results;
21251
+ };
21252
+ var getQueryParam = _getQueryParam;
21253
+ var getQueryParams = (url, key) => {
21254
+ return _getQueryParam(url, key, true);
21255
+ };
21256
+ var decodeURIComponent_ = decodeURIComponent;
21257
+
21258
+ // node_modules/hono/dist/request.js
21259
+ var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
21260
+ var HonoRequest = class {
21261
+ raw;
21262
+ #validatedData;
21263
+ #matchResult;
21264
+ routeIndex = 0;
21265
+ path;
21266
+ bodyCache = {};
21267
+ constructor(request, path = "/", matchResult = [[]]) {
21268
+ this.raw = request;
21269
+ this.path = path;
21270
+ this.#matchResult = matchResult;
21271
+ this.#validatedData = {};
21272
+ }
21273
+ param(key) {
21274
+ return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
21275
+ }
21276
+ #getDecodedParam(key) {
21277
+ const paramKey = this.#matchResult[0][this.routeIndex][1][key];
21278
+ const param = this.#getParamValue(paramKey);
21279
+ return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
21280
+ }
21281
+ #getAllDecodedParams() {
21282
+ const decoded = {};
21283
+ const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
21284
+ for (const key of keys) {
21285
+ const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
21286
+ if (value !== undefined) {
21287
+ decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
21288
+ }
21289
+ }
21290
+ return decoded;
21291
+ }
21292
+ #getParamValue(paramKey) {
21293
+ return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
21294
+ }
21295
+ query(key) {
21296
+ return getQueryParam(this.url, key);
21297
+ }
21298
+ queries(key) {
21299
+ return getQueryParams(this.url, key);
21300
+ }
21301
+ header(name) {
21302
+ if (name) {
21303
+ return this.raw.headers.get(name) ?? undefined;
21304
+ }
21305
+ const headerData = {};
21306
+ this.raw.headers.forEach((value, key) => {
21307
+ headerData[key] = value;
21308
+ });
21309
+ return headerData;
21310
+ }
21311
+ async parseBody(options) {
21312
+ return this.bodyCache.parsedBody ??= await parseBody(this, options);
21313
+ }
21314
+ #cachedBody = (key) => {
21315
+ const { bodyCache, raw } = this;
21316
+ const cachedBody = bodyCache[key];
21317
+ if (cachedBody) {
21318
+ return cachedBody;
21319
+ }
21320
+ const anyCachedKey = Object.keys(bodyCache)[0];
21321
+ if (anyCachedKey) {
21322
+ return bodyCache[anyCachedKey].then((body) => {
21323
+ if (anyCachedKey === "json") {
21324
+ body = JSON.stringify(body);
21325
+ }
21326
+ return new Response(body)[key]();
21327
+ });
21328
+ }
21329
+ return bodyCache[key] = raw[key]();
21330
+ };
21331
+ json() {
21332
+ return this.#cachedBody("text").then((text) => JSON.parse(text));
21333
+ }
21334
+ text() {
21335
+ return this.#cachedBody("text");
21336
+ }
21337
+ arrayBuffer() {
21338
+ return this.#cachedBody("arrayBuffer");
21339
+ }
21340
+ blob() {
21341
+ return this.#cachedBody("blob");
21342
+ }
21343
+ formData() {
21344
+ return this.#cachedBody("formData");
21345
+ }
21346
+ addValidatedData(target, data) {
21347
+ this.#validatedData[target] = data;
21348
+ }
21349
+ valid(target) {
21350
+ return this.#validatedData[target];
21351
+ }
21352
+ get url() {
21353
+ return this.raw.url;
21354
+ }
21355
+ get method() {
21356
+ return this.raw.method;
21357
+ }
21358
+ get [GET_MATCH_RESULT]() {
21359
+ return this.#matchResult;
21360
+ }
21361
+ get matchedRoutes() {
21362
+ return this.#matchResult[0].map(([[, route]]) => route);
21363
+ }
21364
+ get routePath() {
21365
+ return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
21366
+ }
21367
+ };
21368
+
21369
+ // node_modules/hono/dist/utils/html.js
21370
+ var HtmlEscapedCallbackPhase = {
21371
+ Stringify: 1,
21372
+ BeforeStream: 2,
21373
+ Stream: 3
21374
+ };
21375
+ var raw = (value, callbacks) => {
21376
+ const escapedString = new String(value);
21377
+ escapedString.isEscaped = true;
21378
+ escapedString.callbacks = callbacks;
21379
+ return escapedString;
21380
+ };
21381
+ var escapeRe = /[&<>'"]/;
21382
+ var stringBufferToString = async (buffer, callbacks) => {
21383
+ let str = "";
21384
+ callbacks ||= [];
21385
+ const resolvedBuffer = await Promise.all(buffer);
21386
+ for (let i = resolvedBuffer.length - 1;; i--) {
21387
+ str += resolvedBuffer[i];
21388
+ i--;
21389
+ if (i < 0) {
21390
+ break;
21391
+ }
21392
+ let r = resolvedBuffer[i];
21393
+ if (typeof r === "object") {
21394
+ callbacks.push(...r.callbacks || []);
21395
+ }
21396
+ const isEscaped = r.isEscaped;
21397
+ r = await (typeof r === "object" ? r.toString() : r);
21398
+ if (typeof r === "object") {
21399
+ callbacks.push(...r.callbacks || []);
21400
+ }
21401
+ if (r.isEscaped ?? isEscaped) {
21402
+ str += r;
21403
+ } else {
21404
+ const buf = [str];
21405
+ escapeToBuffer(r, buf);
21406
+ str = buf[0];
21407
+ }
21408
+ }
21409
+ return raw(str, callbacks);
21410
+ };
21411
+ var escapeToBuffer = (str, buffer) => {
21412
+ const match = str.search(escapeRe);
21413
+ if (match === -1) {
21414
+ buffer[0] += str;
21415
+ return;
21416
+ }
21417
+ let escape2;
21418
+ let index;
21419
+ let lastIndex = 0;
21420
+ for (index = match;index < str.length; index++) {
21421
+ switch (str.charCodeAt(index)) {
21422
+ case 34:
21423
+ escape2 = "&quot;";
21424
+ break;
21425
+ case 39:
21426
+ escape2 = "&#39;";
21427
+ break;
21428
+ case 38:
21429
+ escape2 = "&amp;";
21430
+ break;
21431
+ case 60:
21432
+ escape2 = "&lt;";
21433
+ break;
21434
+ case 62:
21435
+ escape2 = "&gt;";
21436
+ break;
21437
+ default:
21438
+ continue;
21439
+ }
21440
+ buffer[0] += str.substring(lastIndex, index) + escape2;
21441
+ lastIndex = index + 1;
21442
+ }
21443
+ buffer[0] += str.substring(lastIndex, index);
21444
+ };
21445
+ var resolveCallbackSync = (str) => {
21446
+ const callbacks = str.callbacks;
21447
+ if (!callbacks?.length) {
21448
+ return str;
21449
+ }
21450
+ const buffer = [str];
21451
+ const context = {};
21452
+ callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));
21453
+ return buffer[0];
21454
+ };
21455
+ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
21456
+ if (typeof str === "object" && !(str instanceof String)) {
21457
+ if (!(str instanceof Promise)) {
21458
+ str = str.toString();
21459
+ }
21460
+ if (str instanceof Promise) {
21461
+ str = await str;
21462
+ }
21463
+ }
21464
+ const callbacks = str.callbacks;
21465
+ if (!callbacks?.length) {
21466
+ return Promise.resolve(str);
21467
+ }
21468
+ if (buffer) {
21469
+ buffer[0] += str;
21470
+ } else {
21471
+ buffer = [str];
21472
+ }
21473
+ 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]));
21474
+ if (preserveCallbacks) {
21475
+ return raw(await resStr, callbacks);
21476
+ } else {
21477
+ return resStr;
21478
+ }
21479
+ };
21480
+
21481
+ // node_modules/hono/dist/context.js
21482
+ var TEXT_PLAIN = "text/plain; charset=UTF-8";
21483
+ var setDefaultContentType = (contentType, headers) => {
21484
+ return {
21485
+ "Content-Type": contentType,
21486
+ ...headers
21487
+ };
21488
+ };
21489
+ var createResponseInstance = (body, init) => new Response(body, init);
21490
+ var Context = class {
21491
+ #rawRequest;
21492
+ #req;
21493
+ env = {};
21494
+ #var;
21495
+ finalized = false;
21496
+ error;
21497
+ #status;
21498
+ #executionCtx;
21499
+ #res;
21500
+ #layout;
21501
+ #renderer;
21502
+ #notFoundHandler;
21503
+ #preparedHeaders;
21504
+ #matchResult;
21505
+ #path;
21506
+ constructor(req, options) {
21507
+ this.#rawRequest = req;
21508
+ if (options) {
21509
+ this.#executionCtx = options.executionCtx;
21510
+ this.env = options.env;
21511
+ this.#notFoundHandler = options.notFoundHandler;
21512
+ this.#path = options.path;
21513
+ this.#matchResult = options.matchResult;
21514
+ }
21515
+ }
21516
+ get req() {
21517
+ this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
21518
+ return this.#req;
21519
+ }
21520
+ get event() {
21521
+ if (this.#executionCtx && "respondWith" in this.#executionCtx) {
21522
+ return this.#executionCtx;
21523
+ } else {
21524
+ throw Error("This context has no FetchEvent");
21525
+ }
21526
+ }
21527
+ get executionCtx() {
21528
+ if (this.#executionCtx) {
21529
+ return this.#executionCtx;
21530
+ } else {
21531
+ throw Error("This context has no ExecutionContext");
21532
+ }
21533
+ }
21534
+ get res() {
21535
+ return this.#res ||= createResponseInstance(null, {
21536
+ headers: this.#preparedHeaders ??= new Headers
21537
+ });
21538
+ }
21539
+ set res(_res) {
21540
+ if (this.#res && _res) {
21541
+ _res = createResponseInstance(_res.body, _res);
21542
+ for (const [k, v] of this.#res.headers.entries()) {
21543
+ if (k === "content-type") {
21544
+ continue;
21545
+ }
21546
+ if (k === "set-cookie") {
21547
+ const cookies = this.#res.headers.getSetCookie();
21548
+ _res.headers.delete("set-cookie");
21549
+ for (const cookie of cookies) {
21550
+ _res.headers.append("set-cookie", cookie);
21551
+ }
21552
+ } else {
21553
+ _res.headers.set(k, v);
21554
+ }
21555
+ }
21556
+ }
21557
+ this.#res = _res;
21558
+ this.finalized = true;
21559
+ }
21560
+ render = (...args) => {
21561
+ this.#renderer ??= (content) => this.html(content);
21562
+ return this.#renderer(...args);
21563
+ };
21564
+ setLayout = (layout) => this.#layout = layout;
21565
+ getLayout = () => this.#layout;
21566
+ setRenderer = (renderer) => {
21567
+ this.#renderer = renderer;
21568
+ };
21569
+ header = (name, value, options) => {
21570
+ if (this.finalized) {
21571
+ this.#res = createResponseInstance(this.#res.body, this.#res);
21572
+ }
21573
+ const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
21574
+ if (value === undefined) {
21575
+ headers.delete(name);
21576
+ } else if (options?.append) {
21577
+ headers.append(name, value);
21578
+ } else {
21579
+ headers.set(name, value);
21580
+ }
21581
+ };
21582
+ status = (status) => {
21583
+ this.#status = status;
21584
+ };
21585
+ set = (key, value) => {
21586
+ this.#var ??= /* @__PURE__ */ new Map;
21587
+ this.#var.set(key, value);
21588
+ };
21589
+ get = (key) => {
21590
+ return this.#var ? this.#var.get(key) : undefined;
21591
+ };
21592
+ get var() {
21593
+ if (!this.#var) {
21594
+ return {};
21595
+ }
21596
+ return Object.fromEntries(this.#var);
21597
+ }
21598
+ #newResponse(data, arg, headers) {
21599
+ const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
21600
+ if (typeof arg === "object" && "headers" in arg) {
21601
+ const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
21602
+ for (const [key, value] of argHeaders) {
21603
+ if (key.toLowerCase() === "set-cookie") {
21604
+ responseHeaders.append(key, value);
21605
+ } else {
21606
+ responseHeaders.set(key, value);
21607
+ }
21608
+ }
21609
+ }
21610
+ if (headers) {
21611
+ for (const [k, v] of Object.entries(headers)) {
21612
+ if (typeof v === "string") {
21613
+ responseHeaders.set(k, v);
21614
+ } else {
21615
+ responseHeaders.delete(k);
21616
+ for (const v2 of v) {
21617
+ responseHeaders.append(k, v2);
21618
+ }
21619
+ }
21620
+ }
21621
+ }
21622
+ const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
21623
+ return createResponseInstance(data, { status, headers: responseHeaders });
21624
+ }
21625
+ newResponse = (...args) => this.#newResponse(...args);
21626
+ body = (data, arg, headers) => this.#newResponse(data, arg, headers);
21627
+ text = (text, arg, headers) => {
21628
+ return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
21629
+ };
21630
+ json = (object4, arg, headers) => {
21631
+ return this.#newResponse(JSON.stringify(object4), arg, setDefaultContentType("application/json", headers));
21632
+ };
21633
+ html = (html, arg, headers) => {
21634
+ const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
21635
+ return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
21636
+ };
21637
+ redirect = (location, status) => {
21638
+ const locationString = String(location);
21639
+ this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
21640
+ return this.newResponse(null, status ?? 302);
21641
+ };
21642
+ notFound = () => {
21643
+ this.#notFoundHandler ??= () => createResponseInstance();
21644
+ return this.#notFoundHandler(this);
21645
+ };
21646
+ };
21647
+
21648
+ // node_modules/hono/dist/router.js
21649
+ var METHOD_NAME_ALL = "ALL";
21650
+ var METHOD_NAME_ALL_LOWERCASE = "all";
21651
+ var METHODS = ["get", "post", "put", "delete", "options", "patch"];
21652
+ var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
21653
+ var UnsupportedPathError = class extends Error {
21654
+ };
21655
+
21656
+ // node_modules/hono/dist/utils/constants.js
21657
+ var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
21658
+
21659
+ // node_modules/hono/dist/hono-base.js
21660
+ var notFoundHandler = (c) => {
21661
+ return c.text("404 Not Found", 404);
21662
+ };
21663
+ var errorHandler = (err, c) => {
21664
+ if ("getResponse" in err) {
21665
+ const res = err.getResponse();
21666
+ return c.newResponse(res.body, res);
21667
+ }
21668
+ console.error(err);
21669
+ return c.text("Internal Server Error", 500);
21670
+ };
21671
+ var Hono = class _Hono {
21672
+ get;
21673
+ post;
21674
+ put;
21675
+ delete;
21676
+ options;
21677
+ patch;
21678
+ all;
21679
+ on;
21680
+ use;
21681
+ router;
21682
+ getPath;
21683
+ _basePath = "/";
21684
+ #path = "/";
21685
+ routes = [];
21686
+ constructor(options = {}) {
21687
+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
21688
+ allMethods.forEach((method) => {
21689
+ this[method] = (args1, ...args) => {
21690
+ if (typeof args1 === "string") {
21691
+ this.#path = args1;
21692
+ } else {
21693
+ this.#addRoute(method, this.#path, args1);
21694
+ }
21695
+ args.forEach((handler) => {
21696
+ this.#addRoute(method, this.#path, handler);
21697
+ });
21698
+ return this;
21699
+ };
21700
+ });
21701
+ this.on = (method, path, ...handlers) => {
21702
+ for (const p of [path].flat()) {
21703
+ this.#path = p;
21704
+ for (const m of [method].flat()) {
21705
+ handlers.map((handler) => {
21706
+ this.#addRoute(m.toUpperCase(), this.#path, handler);
21707
+ });
21708
+ }
21709
+ }
21710
+ return this;
21711
+ };
21712
+ this.use = (arg1, ...handlers) => {
21713
+ if (typeof arg1 === "string") {
21714
+ this.#path = arg1;
21715
+ } else {
21716
+ this.#path = "*";
21717
+ handlers.unshift(arg1);
21718
+ }
21719
+ handlers.forEach((handler) => {
21720
+ this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
21721
+ });
21722
+ return this;
21723
+ };
21724
+ const { strict, ...optionsWithoutStrict } = options;
21725
+ Object.assign(this, optionsWithoutStrict);
21726
+ this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
21727
+ }
21728
+ #clone() {
21729
+ const clone2 = new _Hono({
21730
+ router: this.router,
21731
+ getPath: this.getPath
21732
+ });
21733
+ clone2.errorHandler = this.errorHandler;
21734
+ clone2.#notFoundHandler = this.#notFoundHandler;
21735
+ clone2.routes = this.routes;
21736
+ return clone2;
21737
+ }
21738
+ #notFoundHandler = notFoundHandler;
21739
+ errorHandler = errorHandler;
21740
+ route(path, app) {
21741
+ const subApp = this.basePath(path);
21742
+ app.routes.map((r) => {
21743
+ let handler;
21744
+ if (app.errorHandler === errorHandler) {
21745
+ handler = r.handler;
21746
+ } else {
21747
+ handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
21748
+ handler[COMPOSED_HANDLER] = r.handler;
21749
+ }
21750
+ subApp.#addRoute(r.method, r.path, handler);
21751
+ });
21752
+ return this;
21753
+ }
21754
+ basePath(path) {
21755
+ const subApp = this.#clone();
21756
+ subApp._basePath = mergePath(this._basePath, path);
21757
+ return subApp;
21758
+ }
21759
+ onError = (handler) => {
21760
+ this.errorHandler = handler;
21761
+ return this;
21762
+ };
21763
+ notFound = (handler) => {
21764
+ this.#notFoundHandler = handler;
21765
+ return this;
21766
+ };
21767
+ mount(path, applicationHandler, options) {
21768
+ let replaceRequest;
21769
+ let optionHandler;
21770
+ if (options) {
21771
+ if (typeof options === "function") {
21772
+ optionHandler = options;
21773
+ } else {
21774
+ optionHandler = options.optionHandler;
21775
+ if (options.replaceRequest === false) {
21776
+ replaceRequest = (request) => request;
21777
+ } else {
21778
+ replaceRequest = options.replaceRequest;
21779
+ }
21780
+ }
21781
+ }
21782
+ const getOptions = optionHandler ? (c) => {
21783
+ const options2 = optionHandler(c);
21784
+ return Array.isArray(options2) ? options2 : [options2];
21785
+ } : (c) => {
21786
+ let executionContext = undefined;
21787
+ try {
21788
+ executionContext = c.executionCtx;
21789
+ } catch {}
21790
+ return [c.env, executionContext];
21791
+ };
21792
+ replaceRequest ||= (() => {
21793
+ const mergedPath = mergePath(this._basePath, path);
21794
+ const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
21795
+ return (request) => {
21796
+ const url = new URL(request.url);
21797
+ url.pathname = url.pathname.slice(pathPrefixLength) || "/";
21798
+ return new Request(url, request);
21799
+ };
21800
+ })();
21801
+ const handler = async (c, next) => {
21802
+ const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
21803
+ if (res) {
21804
+ return res;
21805
+ }
21806
+ await next();
21807
+ };
21808
+ this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
21809
+ return this;
21810
+ }
21811
+ #addRoute(method, path, handler) {
21812
+ method = method.toUpperCase();
21813
+ path = mergePath(this._basePath, path);
21814
+ const r = { basePath: this._basePath, path, method, handler };
21815
+ this.router.add(method, path, [handler, r]);
21816
+ this.routes.push(r);
21817
+ }
21818
+ #handleError(err, c) {
21819
+ if (err instanceof Error) {
21820
+ return this.errorHandler(err, c);
21821
+ }
21822
+ throw err;
21823
+ }
21824
+ #dispatch(request, executionCtx, env, method) {
21825
+ if (method === "HEAD") {
21826
+ return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
21827
+ }
21828
+ const path = this.getPath(request, { env });
21829
+ const matchResult = this.router.match(method, path);
21830
+ const c = new Context(request, {
21831
+ path,
21832
+ matchResult,
21833
+ env,
21834
+ executionCtx,
21835
+ notFoundHandler: this.#notFoundHandler
21836
+ });
21837
+ if (matchResult[0].length === 1) {
21838
+ let res;
21839
+ try {
21840
+ res = matchResult[0][0][0][0](c, async () => {
21841
+ c.res = await this.#notFoundHandler(c);
21842
+ });
21843
+ } catch (err) {
21844
+ return this.#handleError(err, c);
21845
+ }
21846
+ 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);
21847
+ }
21848
+ const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
21849
+ return (async () => {
21850
+ try {
21851
+ const context = await composed(c);
21852
+ if (!context.finalized) {
21853
+ throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
21854
+ }
21855
+ return context.res;
21856
+ } catch (err) {
21857
+ return this.#handleError(err, c);
21858
+ }
21859
+ })();
21860
+ }
21861
+ fetch = (request, ...rest) => {
21862
+ return this.#dispatch(request, rest[1], rest[0], request.method);
21863
+ };
21864
+ request = (input, requestInit, Env, executionCtx) => {
21865
+ if (input instanceof Request) {
21866
+ return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
21867
+ }
21868
+ input = input.toString();
21869
+ return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
21870
+ };
21871
+ fire = () => {
21872
+ addEventListener("fetch", (event) => {
21873
+ event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
21874
+ });
21875
+ };
21876
+ };
21877
+
21878
+ // node_modules/hono/dist/router/reg-exp-router/matcher.js
21879
+ var emptyParam = [];
21880
+ function match(method, path) {
21881
+ const matchers = this.buildAllMatchers();
21882
+ const match2 = (method2, path2) => {
21883
+ const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
21884
+ const staticMatch = matcher[2][path2];
21885
+ if (staticMatch) {
21886
+ return staticMatch;
21887
+ }
21888
+ const match3 = path2.match(matcher[0]);
21889
+ if (!match3) {
21890
+ return [[], emptyParam];
21891
+ }
21892
+ const index = match3.indexOf("", 1);
21893
+ return [matcher[1][index], match3];
21894
+ };
21895
+ this.match = match2;
21896
+ return match2(method, path);
21897
+ }
21898
+
21899
+ // node_modules/hono/dist/router/reg-exp-router/node.js
21900
+ var LABEL_REG_EXP_STR = "[^/]+";
21901
+ var ONLY_WILDCARD_REG_EXP_STR = ".*";
21902
+ var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
21903
+ var PATH_ERROR = /* @__PURE__ */ Symbol();
21904
+ var regExpMetaChars = new Set(".\\+*[^]$()");
21905
+ function compareKey(a, b) {
21906
+ if (a.length === 1) {
21907
+ return b.length === 1 ? a < b ? -1 : 1 : -1;
21908
+ }
21909
+ if (b.length === 1) {
21910
+ return 1;
21911
+ }
21912
+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
21913
+ return 1;
21914
+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
21915
+ return -1;
21916
+ }
21917
+ if (a === LABEL_REG_EXP_STR) {
21918
+ return 1;
21919
+ } else if (b === LABEL_REG_EXP_STR) {
21920
+ return -1;
21921
+ }
21922
+ return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
21923
+ }
21924
+ var Node = class _Node {
21925
+ #index;
21926
+ #varIndex;
21927
+ #children = /* @__PURE__ */ Object.create(null);
21928
+ insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
21929
+ if (tokens.length === 0) {
21930
+ if (this.#index !== undefined) {
21931
+ throw PATH_ERROR;
21932
+ }
21933
+ if (pathErrorCheckOnly) {
21934
+ return;
21935
+ }
21936
+ this.#index = index;
21937
+ return;
21938
+ }
21939
+ const [token, ...restTokens] = tokens;
21940
+ const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
21941
+ let node;
21942
+ if (pattern) {
21943
+ const name = pattern[1];
21944
+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
21945
+ if (name && pattern[2]) {
21946
+ if (regexpStr === ".*") {
21947
+ throw PATH_ERROR;
21948
+ }
21949
+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
21950
+ if (/\((?!\?:)/.test(regexpStr)) {
21951
+ throw PATH_ERROR;
21952
+ }
21953
+ }
21954
+ node = this.#children[regexpStr];
21955
+ if (!node) {
21956
+ if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
21957
+ throw PATH_ERROR;
21958
+ }
21959
+ if (pathErrorCheckOnly) {
21960
+ return;
21961
+ }
21962
+ node = this.#children[regexpStr] = new _Node;
21963
+ if (name !== "") {
21964
+ node.#varIndex = context.varIndex++;
21965
+ }
21966
+ }
21967
+ if (!pathErrorCheckOnly && name !== "") {
21968
+ paramMap.push([name, node.#varIndex]);
21969
+ }
21970
+ } else {
21971
+ node = this.#children[token];
21972
+ if (!node) {
21973
+ if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
21974
+ throw PATH_ERROR;
21975
+ }
21976
+ if (pathErrorCheckOnly) {
21977
+ return;
21978
+ }
21979
+ node = this.#children[token] = new _Node;
21980
+ }
21981
+ }
21982
+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
21983
+ }
21984
+ buildRegExpStr() {
21985
+ const childKeys = Object.keys(this.#children).sort(compareKey);
21986
+ const strList = childKeys.map((k) => {
21987
+ const c = this.#children[k];
21988
+ return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
21989
+ });
21990
+ if (typeof this.#index === "number") {
21991
+ strList.unshift(`#${this.#index}`);
21992
+ }
21993
+ if (strList.length === 0) {
21994
+ return "";
21995
+ }
21996
+ if (strList.length === 1) {
21997
+ return strList[0];
21998
+ }
21999
+ return "(?:" + strList.join("|") + ")";
22000
+ }
22001
+ };
22002
+
22003
+ // node_modules/hono/dist/router/reg-exp-router/trie.js
22004
+ var Trie = class {
22005
+ #context = { varIndex: 0 };
22006
+ #root = new Node;
22007
+ insert(path, index, pathErrorCheckOnly) {
22008
+ const paramAssoc = [];
22009
+ const groups = [];
22010
+ for (let i = 0;; ) {
22011
+ let replaced = false;
22012
+ path = path.replace(/\{[^}]+\}/g, (m) => {
22013
+ const mark = `@\\${i}`;
22014
+ groups[i] = [mark, m];
22015
+ i++;
22016
+ replaced = true;
22017
+ return mark;
22018
+ });
22019
+ if (!replaced) {
22020
+ break;
22021
+ }
22022
+ }
22023
+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
22024
+ for (let i = groups.length - 1;i >= 0; i--) {
22025
+ const [mark] = groups[i];
22026
+ for (let j = tokens.length - 1;j >= 0; j--) {
22027
+ if (tokens[j].indexOf(mark) !== -1) {
22028
+ tokens[j] = tokens[j].replace(mark, groups[i][1]);
22029
+ break;
22030
+ }
22031
+ }
22032
+ }
22033
+ this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
22034
+ return paramAssoc;
22035
+ }
22036
+ buildRegExp() {
22037
+ let regexp = this.#root.buildRegExpStr();
22038
+ if (regexp === "") {
22039
+ return [/^$/, [], []];
22040
+ }
22041
+ let captureIndex = 0;
22042
+ const indexReplacementMap = [];
22043
+ const paramReplacementMap = [];
22044
+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
22045
+ if (handlerIndex !== undefined) {
22046
+ indexReplacementMap[++captureIndex] = Number(handlerIndex);
22047
+ return "$()";
22048
+ }
22049
+ if (paramIndex !== undefined) {
22050
+ paramReplacementMap[Number(paramIndex)] = ++captureIndex;
22051
+ return "";
22052
+ }
22053
+ return "";
22054
+ });
22055
+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
22056
+ }
22057
+ };
22058
+
22059
+ // node_modules/hono/dist/router/reg-exp-router/router.js
22060
+ var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
22061
+ var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
22062
+ function buildWildcardRegExp(path) {
22063
+ return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
22064
+ }
22065
+ function clearWildcardRegExpCache() {
22066
+ wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
22067
+ }
22068
+ function buildMatcherFromPreprocessedRoutes(routes) {
22069
+ const trie = new Trie;
22070
+ const handlerData = [];
22071
+ if (routes.length === 0) {
22072
+ return nullMatcher;
22073
+ }
22074
+ const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
22075
+ const staticMap = /* @__PURE__ */ Object.create(null);
22076
+ for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
22077
+ const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
22078
+ if (pathErrorCheckOnly) {
22079
+ staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
22080
+ } else {
22081
+ j++;
22082
+ }
22083
+ let paramAssoc;
22084
+ try {
22085
+ paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
22086
+ } catch (e) {
22087
+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
22088
+ }
22089
+ if (pathErrorCheckOnly) {
22090
+ continue;
22091
+ }
22092
+ handlerData[j] = handlers.map(([h, paramCount]) => {
22093
+ const paramIndexMap = /* @__PURE__ */ Object.create(null);
22094
+ paramCount -= 1;
22095
+ for (;paramCount >= 0; paramCount--) {
22096
+ const [key, value] = paramAssoc[paramCount];
22097
+ paramIndexMap[key] = value;
22098
+ }
22099
+ return [h, paramIndexMap];
22100
+ });
22101
+ }
22102
+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
22103
+ for (let i = 0, len = handlerData.length;i < len; i++) {
22104
+ for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
22105
+ const map2 = handlerData[i][j]?.[1];
22106
+ if (!map2) {
22107
+ continue;
22108
+ }
22109
+ const keys = Object.keys(map2);
22110
+ for (let k = 0, len3 = keys.length;k < len3; k++) {
22111
+ map2[keys[k]] = paramReplacementMap[map2[keys[k]]];
22112
+ }
22113
+ }
22114
+ }
22115
+ const handlerMap = [];
22116
+ for (const i in indexReplacementMap) {
22117
+ handlerMap[i] = handlerData[indexReplacementMap[i]];
22118
+ }
22119
+ return [regexp, handlerMap, staticMap];
22120
+ }
22121
+ function findMiddleware(middleware, path) {
22122
+ if (!middleware) {
22123
+ return;
22124
+ }
22125
+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
22126
+ if (buildWildcardRegExp(k).test(path)) {
22127
+ return [...middleware[k]];
22128
+ }
22129
+ }
22130
+ return;
22131
+ }
22132
+ var RegExpRouter = class {
22133
+ name = "RegExpRouter";
22134
+ #middleware;
22135
+ #routes;
22136
+ constructor() {
22137
+ this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
22138
+ this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
22139
+ }
22140
+ add(method, path, handler) {
22141
+ const middleware = this.#middleware;
22142
+ const routes = this.#routes;
22143
+ if (!middleware || !routes) {
22144
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
22145
+ }
22146
+ if (!middleware[method]) {
22147
+ [middleware, routes].forEach((handlerMap) => {
22148
+ handlerMap[method] = /* @__PURE__ */ Object.create(null);
22149
+ Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
22150
+ handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
22151
+ });
22152
+ });
22153
+ }
22154
+ if (path === "/*") {
22155
+ path = "*";
22156
+ }
22157
+ const paramCount = (path.match(/\/:/g) || []).length;
22158
+ if (/\*$/.test(path)) {
22159
+ const re = buildWildcardRegExp(path);
22160
+ if (method === METHOD_NAME_ALL) {
22161
+ Object.keys(middleware).forEach((m) => {
22162
+ middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
22163
+ });
22164
+ } else {
22165
+ middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
22166
+ }
22167
+ Object.keys(middleware).forEach((m) => {
22168
+ if (method === METHOD_NAME_ALL || method === m) {
22169
+ Object.keys(middleware[m]).forEach((p) => {
22170
+ re.test(p) && middleware[m][p].push([handler, paramCount]);
22171
+ });
22172
+ }
22173
+ });
22174
+ Object.keys(routes).forEach((m) => {
22175
+ if (method === METHOD_NAME_ALL || method === m) {
22176
+ Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
22177
+ }
22178
+ });
22179
+ return;
22180
+ }
22181
+ const paths = checkOptionalParameter(path) || [path];
22182
+ for (let i = 0, len = paths.length;i < len; i++) {
22183
+ const path2 = paths[i];
22184
+ Object.keys(routes).forEach((m) => {
22185
+ if (method === METHOD_NAME_ALL || method === m) {
22186
+ routes[m][path2] ||= [
22187
+ ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
22188
+ ];
22189
+ routes[m][path2].push([handler, paramCount - len + i + 1]);
22190
+ }
22191
+ });
22192
+ }
22193
+ }
22194
+ match = match;
22195
+ buildAllMatchers() {
22196
+ const matchers = /* @__PURE__ */ Object.create(null);
22197
+ Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
22198
+ matchers[method] ||= this.#buildMatcher(method);
22199
+ });
22200
+ this.#middleware = this.#routes = undefined;
22201
+ clearWildcardRegExpCache();
22202
+ return matchers;
22203
+ }
22204
+ #buildMatcher(method) {
22205
+ const routes = [];
22206
+ let hasOwnRoute = method === METHOD_NAME_ALL;
22207
+ [this.#middleware, this.#routes].forEach((r) => {
22208
+ const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
22209
+ if (ownRoute.length !== 0) {
22210
+ hasOwnRoute ||= true;
22211
+ routes.push(...ownRoute);
22212
+ } else if (method !== METHOD_NAME_ALL) {
22213
+ routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
22214
+ }
22215
+ });
22216
+ if (!hasOwnRoute) {
22217
+ return null;
22218
+ } else {
22219
+ return buildMatcherFromPreprocessedRoutes(routes);
22220
+ }
22221
+ }
22222
+ };
22223
+
22224
+ // node_modules/hono/dist/router/reg-exp-router/prepared-router.js
22225
+ var PreparedRegExpRouter = class {
22226
+ name = "PreparedRegExpRouter";
22227
+ #matchers;
22228
+ #relocateMap;
22229
+ constructor(matchers, relocateMap) {
22230
+ this.#matchers = matchers;
22231
+ this.#relocateMap = relocateMap;
22232
+ }
22233
+ #addWildcard(method, handlerData) {
22234
+ const matcher = this.#matchers[method];
22235
+ matcher[1].forEach((list) => list && list.push(handlerData));
22236
+ Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
22237
+ }
22238
+ #addPath(method, path, handler, indexes, map2) {
22239
+ const matcher = this.#matchers[method];
22240
+ if (!map2) {
22241
+ matcher[2][path][0].push([handler, {}]);
22242
+ } else {
22243
+ indexes.forEach((index) => {
22244
+ if (typeof index === "number") {
22245
+ matcher[1][index].push([handler, map2]);
22246
+ } else {
22247
+ matcher[2][index || path][0].push([handler, map2]);
22248
+ }
22249
+ });
22250
+ }
22251
+ }
22252
+ add(method, path, handler) {
22253
+ if (!this.#matchers[method]) {
22254
+ const all = this.#matchers[METHOD_NAME_ALL];
22255
+ const staticMap = {};
22256
+ for (const key in all[2]) {
22257
+ staticMap[key] = [all[2][key][0].slice(), emptyParam];
22258
+ }
22259
+ this.#matchers[method] = [
22260
+ all[0],
22261
+ all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
22262
+ staticMap
22263
+ ];
22264
+ }
22265
+ if (path === "/*" || path === "*") {
22266
+ const handlerData = [handler, {}];
22267
+ if (method === METHOD_NAME_ALL) {
22268
+ for (const m in this.#matchers) {
22269
+ this.#addWildcard(m, handlerData);
22270
+ }
22271
+ } else {
22272
+ this.#addWildcard(method, handlerData);
22273
+ }
22274
+ return;
22275
+ }
22276
+ const data = this.#relocateMap[path];
22277
+ if (!data) {
22278
+ throw new Error(`Path ${path} is not registered`);
22279
+ }
22280
+ for (const [indexes, map2] of data) {
22281
+ if (method === METHOD_NAME_ALL) {
22282
+ for (const m in this.#matchers) {
22283
+ this.#addPath(m, path, handler, indexes, map2);
22284
+ }
22285
+ } else {
22286
+ this.#addPath(method, path, handler, indexes, map2);
22287
+ }
22288
+ }
22289
+ }
22290
+ buildAllMatchers() {
22291
+ return this.#matchers;
22292
+ }
22293
+ match = match;
22294
+ };
22295
+
22296
+ // node_modules/hono/dist/router/smart-router/router.js
22297
+ var SmartRouter = class {
22298
+ name = "SmartRouter";
22299
+ #routers = [];
22300
+ #routes = [];
22301
+ constructor(init) {
22302
+ this.#routers = init.routers;
22303
+ }
22304
+ add(method, path, handler) {
22305
+ if (!this.#routes) {
22306
+ throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
22307
+ }
22308
+ this.#routes.push([method, path, handler]);
22309
+ }
22310
+ match(method, path) {
22311
+ if (!this.#routes) {
22312
+ throw new Error("Fatal error");
22313
+ }
22314
+ const routers = this.#routers;
22315
+ const routes = this.#routes;
22316
+ const len = routers.length;
22317
+ let i = 0;
22318
+ let res;
22319
+ for (;i < len; i++) {
22320
+ const router = routers[i];
22321
+ try {
22322
+ for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
22323
+ router.add(...routes[i2]);
22324
+ }
22325
+ res = router.match(method, path);
22326
+ } catch (e) {
22327
+ if (e instanceof UnsupportedPathError) {
22328
+ continue;
22329
+ }
22330
+ throw e;
22331
+ }
22332
+ this.match = router.match.bind(router);
22333
+ this.#routers = [router];
22334
+ this.#routes = undefined;
22335
+ break;
22336
+ }
22337
+ if (i === len) {
22338
+ throw new Error("Fatal error");
22339
+ }
22340
+ this.name = `SmartRouter + ${this.activeRouter.name}`;
22341
+ return res;
22342
+ }
22343
+ get activeRouter() {
22344
+ if (this.#routes || this.#routers.length !== 1) {
22345
+ throw new Error("No active router has been determined yet.");
22346
+ }
22347
+ return this.#routers[0];
22348
+ }
22349
+ };
22350
+
22351
+ // node_modules/hono/dist/router/trie-router/node.js
22352
+ var emptyParams = /* @__PURE__ */ Object.create(null);
22353
+ var hasChildren = (children) => {
22354
+ for (const _ in children) {
22355
+ return true;
22356
+ }
22357
+ return false;
22358
+ };
22359
+ var Node2 = class _Node2 {
22360
+ #methods;
22361
+ #children;
22362
+ #patterns;
22363
+ #order = 0;
22364
+ #params = emptyParams;
22365
+ constructor(method, handler, children) {
22366
+ this.#children = children || /* @__PURE__ */ Object.create(null);
22367
+ this.#methods = [];
22368
+ if (method && handler) {
22369
+ const m = /* @__PURE__ */ Object.create(null);
22370
+ m[method] = { handler, possibleKeys: [], score: 0 };
22371
+ this.#methods = [m];
22372
+ }
22373
+ this.#patterns = [];
22374
+ }
22375
+ insert(method, path, handler) {
22376
+ this.#order = ++this.#order;
22377
+ let curNode = this;
22378
+ const parts = splitRoutingPath(path);
22379
+ const possibleKeys = [];
22380
+ for (let i = 0, len = parts.length;i < len; i++) {
22381
+ const p = parts[i];
22382
+ const nextP = parts[i + 1];
22383
+ const pattern = getPattern(p, nextP);
22384
+ const key = Array.isArray(pattern) ? pattern[0] : p;
22385
+ if (key in curNode.#children) {
22386
+ curNode = curNode.#children[key];
22387
+ if (pattern) {
22388
+ possibleKeys.push(pattern[1]);
22389
+ }
22390
+ continue;
22391
+ }
22392
+ curNode.#children[key] = new _Node2;
22393
+ if (pattern) {
22394
+ curNode.#patterns.push(pattern);
22395
+ possibleKeys.push(pattern[1]);
22396
+ }
22397
+ curNode = curNode.#children[key];
22398
+ }
22399
+ curNode.#methods.push({
22400
+ [method]: {
22401
+ handler,
22402
+ possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
22403
+ score: this.#order
22404
+ }
22405
+ });
22406
+ return curNode;
22407
+ }
22408
+ #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
22409
+ for (let i = 0, len = node.#methods.length;i < len; i++) {
22410
+ const m = node.#methods[i];
22411
+ const handlerSet = m[method] || m[METHOD_NAME_ALL];
22412
+ const processedSet = {};
22413
+ if (handlerSet !== undefined) {
22414
+ handlerSet.params = /* @__PURE__ */ Object.create(null);
22415
+ handlerSets.push(handlerSet);
22416
+ if (nodeParams !== emptyParams || params && params !== emptyParams) {
22417
+ for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
22418
+ const key = handlerSet.possibleKeys[i2];
22419
+ const processed = processedSet[handlerSet.score];
22420
+ handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
22421
+ processedSet[handlerSet.score] = true;
22422
+ }
22423
+ }
22424
+ }
22425
+ }
22426
+ }
22427
+ search(method, path) {
22428
+ const handlerSets = [];
22429
+ this.#params = emptyParams;
22430
+ const curNode = this;
22431
+ let curNodes = [curNode];
22432
+ const parts = splitPath(path);
22433
+ const curNodesQueue = [];
22434
+ const len = parts.length;
22435
+ let partOffsets = null;
22436
+ for (let i = 0;i < len; i++) {
22437
+ const part = parts[i];
22438
+ const isLast = i === len - 1;
22439
+ const tempNodes = [];
22440
+ for (let j = 0, len2 = curNodes.length;j < len2; j++) {
22441
+ const node = curNodes[j];
22442
+ const nextNode = node.#children[part];
22443
+ if (nextNode) {
22444
+ nextNode.#params = node.#params;
22445
+ if (isLast) {
22446
+ if (nextNode.#children["*"]) {
22447
+ this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
22448
+ }
22449
+ this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
22450
+ } else {
22451
+ tempNodes.push(nextNode);
22452
+ }
22453
+ }
22454
+ for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
22455
+ const pattern = node.#patterns[k];
22456
+ const params = node.#params === emptyParams ? {} : { ...node.#params };
22457
+ if (pattern === "*") {
22458
+ const astNode = node.#children["*"];
22459
+ if (astNode) {
22460
+ this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
22461
+ astNode.#params = params;
22462
+ tempNodes.push(astNode);
22463
+ }
22464
+ continue;
22465
+ }
22466
+ const [key, name, matcher] = pattern;
22467
+ if (!part && !(matcher instanceof RegExp)) {
22468
+ continue;
22469
+ }
22470
+ const child = node.#children[key];
22471
+ if (matcher instanceof RegExp) {
22472
+ if (partOffsets === null) {
22473
+ partOffsets = new Array(len);
22474
+ let offset = path[0] === "/" ? 1 : 0;
22475
+ for (let p = 0;p < len; p++) {
22476
+ partOffsets[p] = offset;
22477
+ offset += parts[p].length + 1;
22478
+ }
22479
+ }
22480
+ const restPathString = path.substring(partOffsets[i]);
22481
+ const m = matcher.exec(restPathString);
22482
+ if (m) {
22483
+ params[name] = m[0];
22484
+ this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
22485
+ if (hasChildren(child.#children)) {
22486
+ child.#params = params;
22487
+ const componentCount = m[0].match(/\//)?.length ?? 0;
22488
+ const targetCurNodes = curNodesQueue[componentCount] ||= [];
22489
+ targetCurNodes.push(child);
22490
+ }
22491
+ continue;
22492
+ }
22493
+ }
22494
+ if (matcher === true || matcher.test(part)) {
22495
+ params[name] = part;
22496
+ if (isLast) {
22497
+ this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
22498
+ if (child.#children["*"]) {
22499
+ this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
22500
+ }
22501
+ } else {
22502
+ child.#params = params;
22503
+ tempNodes.push(child);
22504
+ }
22505
+ }
22506
+ }
22507
+ }
22508
+ const shifted = curNodesQueue.shift();
22509
+ curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
22510
+ }
22511
+ if (handlerSets.length > 1) {
22512
+ handlerSets.sort((a, b) => {
22513
+ return a.score - b.score;
22514
+ });
22515
+ }
22516
+ return [handlerSets.map(({ handler, params }) => [handler, params])];
22517
+ }
22518
+ };
22519
+
22520
+ // node_modules/hono/dist/router/trie-router/router.js
22521
+ var TrieRouter = class {
22522
+ name = "TrieRouter";
22523
+ #node;
22524
+ constructor() {
22525
+ this.#node = new Node2;
22526
+ }
22527
+ add(method, path, handler) {
22528
+ const results = checkOptionalParameter(path);
22529
+ if (results) {
22530
+ for (let i = 0, len = results.length;i < len; i++) {
22531
+ this.#node.insert(method, results[i], handler);
22532
+ }
22533
+ return;
22534
+ }
22535
+ this.#node.insert(method, path, handler);
22536
+ }
22537
+ match(method, path) {
22538
+ return this.#node.search(method, path);
22539
+ }
22540
+ };
22541
+
22542
+ // node_modules/hono/dist/hono.js
22543
+ var Hono2 = class extends Hono {
22544
+ constructor(options = {}) {
22545
+ super(options);
22546
+ this.router = options.router ?? new SmartRouter({
22547
+ routers: [new RegExpRouter, new TrieRouter]
22548
+ });
22549
+ }
22550
+ };
22551
+
22552
+ // src/ui/styles.css
22553
+ var styles_default = `*,
22554
+ *::before,
22555
+ *::after {
22556
+ box-sizing: border-box;
22557
+ margin: 0;
22558
+ padding: 0;
22559
+ }
22560
+
22561
+ :root {
22562
+ --bg: #fafafa;
22563
+ --surface: #fff;
22564
+ --border: #e0e0e0;
22565
+ --text: #1a1a1a;
22566
+ --text-muted: #666;
22567
+ --primary: #2563eb;
22568
+ --danger: #dc2626;
22569
+ --sidebar-w: 220px;
22570
+ --radius: 6px;
22571
+ --gap: 16px;
22572
+ }
22573
+
22574
+ @media (prefers-color-scheme: dark) {
22575
+ :root {
22576
+ --bg: #111;
22577
+ --surface: #1a1a1a;
22578
+ --border: #333;
22579
+ --text: #e5e5e5;
22580
+ --text-muted: #999;
22581
+ --primary: #60a5fa;
22582
+ --danger: #f87171;
22583
+ }
22584
+ }
22585
+
22586
+ body {
22587
+ font-family: system-ui, -apple-system, sans-serif;
22588
+ background: var(--bg);
22589
+ color: var(--text);
22590
+ line-height: 1.5;
22591
+ }
22592
+
22593
+ .layout {
22594
+ display: flex;
22595
+ min-height: 100vh;
22596
+ }
22597
+
22598
+ .sidebar {
22599
+ width: var(--sidebar-w);
22600
+ flex-shrink: 0;
22601
+ border-right: 1px solid var(--border);
22602
+ background: var(--surface);
22603
+ padding: var(--gap) 0;
22604
+ overflow-y: auto;
22605
+ }
22606
+
22607
+ @media (min-width: 1200px) {
22608
+ :root {
22609
+ --sidebar-w: 280px;
22610
+ }
22611
+ }
22612
+
22613
+ @media (min-width: 1600px) {
22614
+ :root {
22615
+ --sidebar-w: 340px;
22616
+ }
22617
+ }
22618
+
22619
+ .sidebar h2 {
22620
+ font-size: 0.75rem;
22621
+ text-transform: uppercase;
22622
+ color: var(--text-muted);
22623
+ padding: 0 var(--gap);
22624
+ margin-bottom: 8px;
22625
+ letter-spacing: 0.05em;
22626
+ }
22627
+
22628
+ .sidebar-item {
22629
+ display: block;
22630
+ width: 100%;
22631
+ padding: 6px var(--gap);
22632
+ font-size: 0.8125rem;
22633
+ color: var(--text);
22634
+ text-decoration: none;
22635
+ }
22636
+
22637
+ .sidebar-item.ws-item {
22638
+ direction: rtl;
22639
+ white-space: nowrap;
22640
+ overflow: hidden;
22641
+ text-overflow: ellipsis;
22642
+ text-align: left;
22643
+ }
22644
+
22645
+ .sidebar-item.ws-item span {
22646
+ unicode-bidi: plaintext;
22647
+ }
22648
+ .sidebar-item:hover {
22649
+ background: var(--bg);
22650
+ }
22651
+ .sidebar-item.active {
22652
+ background: var(--primary);
22653
+ color: #fff;
22654
+ }
22655
+ .sidebar-item.all-item {
22656
+ font-weight: 500;
22657
+ }
22658
+ .sidebar-item.no-ws-item {
22659
+ font-style: italic;
22660
+ color: var(--text-muted);
22661
+ }
22662
+ .sidebar-item.no-ws-item.active {
22663
+ color: #fff;
22664
+ }
22665
+
22666
+ .main {
22667
+ flex: 1;
22668
+ min-width: 0;
22669
+ padding: var(--gap);
22670
+ }
22671
+
22672
+ header {
22673
+ display: flex;
22674
+ align-items: center;
22675
+ justify-content: space-between;
22676
+ margin-bottom: var(--gap);
22677
+ }
22678
+
22679
+ h1 {
22680
+ font-size: 1.25rem;
22681
+ font-weight: 600;
22682
+ }
22683
+
22684
+ a.btn,
22685
+ button {
22686
+ cursor: pointer;
22687
+ border: 1px solid var(--border);
22688
+ border-radius: var(--radius);
22689
+ padding: 6px 12px;
22690
+ background: var(--surface);
22691
+ color: var(--text);
22692
+ font-size: 0.875rem;
22693
+ text-decoration: none;
22694
+ display: inline-block;
22695
+ }
22696
+
22697
+ a.btn:hover,
22698
+ button:hover {
22699
+ border-color: var(--primary);
22700
+ }
22701
+ .primary {
22702
+ background: var(--primary);
22703
+ color: #fff;
22704
+ border-color: var(--primary);
22705
+ }
22706
+ .danger {
22707
+ color: var(--danger);
22708
+ }
22709
+ .danger:hover {
22710
+ background: var(--danger);
22711
+ color: #fff;
22712
+ border-color: var(--danger);
22713
+ }
22714
+
22715
+ .card {
22716
+ border: 1px solid var(--border);
22717
+ border-radius: var(--radius);
22718
+ padding: var(--gap);
22719
+ margin-bottom: 12px;
22720
+ background: var(--surface);
22721
+ }
22722
+
22723
+ .card-header {
22724
+ display: flex;
22725
+ justify-content: space-between;
22726
+ align-items: flex-start;
22727
+ margin-bottom: 8px;
22728
+ }
22729
+
22730
+ .card-meta {
22731
+ font-size: 0.75rem;
22732
+ color: var(--text-muted);
22733
+ }
22734
+
22735
+ .badge {
22736
+ display: inline-block;
22737
+ background: var(--bg);
22738
+ border: 1px solid var(--border);
22739
+ border-radius: 3px;
22740
+ padding: 1px 6px;
22741
+ font-size: 0.75rem;
22742
+ color: var(--text-muted);
22743
+ }
22744
+
22745
+ .card-content {
22746
+ white-space: pre-wrap;
22747
+ word-break: break-word;
22748
+ font-size: 0.875rem;
22749
+ }
22750
+ .card-actions {
22751
+ display: flex;
22752
+ gap: 6px;
22753
+ margin-top: 10px;
22754
+ }
22755
+ .card-actions form {
22756
+ display: inline;
22757
+ }
22758
+
22759
+ textarea {
22760
+ width: 100%;
22761
+ min-height: 80px;
22762
+ border: 1px solid var(--border);
22763
+ border-radius: var(--radius);
22764
+ padding: 8px;
22765
+ background: var(--surface);
22766
+ color: var(--text);
22767
+ font-family: inherit;
22768
+ font-size: 0.875rem;
22769
+ resize: vertical;
22770
+ }
22771
+
22772
+ .form-card {
22773
+ border: 1px solid var(--border);
22774
+ border-radius: var(--radius);
22775
+ padding: var(--gap);
22776
+ margin-bottom: var(--gap);
22777
+ background: var(--surface);
22778
+ }
22779
+
22780
+ .field {
22781
+ margin-bottom: 10px;
22782
+ }
22783
+ .field label {
22784
+ display: block;
22785
+ font-size: 0.75rem;
22786
+ color: var(--text-muted);
22787
+ margin-bottom: 4px;
22788
+ }
22789
+
22790
+ .field input {
22791
+ width: 100%;
22792
+ border: 1px solid var(--border);
22793
+ border-radius: var(--radius);
22794
+ padding: 6px 10px;
22795
+ background: var(--surface);
22796
+ color: var(--text);
22797
+ font-size: 0.875rem;
22798
+ }
22799
+
22800
+ .form-actions {
22801
+ display: flex;
22802
+ gap: 6px;
22803
+ }
22804
+ .load-more {
22805
+ display: block;
22806
+ width: 100%;
22807
+ text-align: center;
22808
+ padding: 10px;
22809
+ margin-top: 8px;
22810
+ text-decoration: none;
22811
+ }
22812
+ .empty {
22813
+ text-align: center;
22814
+ color: var(--text-muted);
22815
+ padding: 40px 0;
22816
+ }
22817
+
22818
+ .ws-group-header {
22819
+ font-size: 0.75rem;
22820
+ color: var(--text-muted);
22821
+ margin: var(--gap) 0 8px;
22822
+ padding-bottom: 4px;
22823
+ border-bottom: 1px solid var(--border);
22824
+ }
22825
+
22826
+ .pagination {
22827
+ display: flex;
22828
+ justify-content: space-between;
22829
+ align-items: center;
22830
+ margin-top: var(--gap);
22831
+ padding-top: var(--gap);
22832
+ border-top: 1px solid var(--border);
22833
+ }
22834
+
22835
+ .page-info {
22836
+ font-size: 0.8125rem;
22837
+ color: var(--text-muted);
22838
+ }
22839
+
22840
+ @media (max-width: 640px) {
22841
+ .layout {
22842
+ flex-direction: column;
22843
+ }
22844
+
22845
+ .sidebar {
22846
+ width: 100%;
22847
+ border-right: none;
22848
+ border-bottom: 1px solid var(--border);
22849
+ padding: 12px 0;
22850
+ overflow-x: auto;
22851
+ overflow-y: hidden;
22852
+ white-space: nowrap;
22853
+ display: flex;
22854
+ flex-wrap: wrap;
22855
+ gap: 4px;
22856
+ }
22857
+
22858
+ .sidebar h2 {
22859
+ width: 100%;
22860
+ margin-bottom: 4px;
22861
+ }
22862
+
22863
+ .sidebar-item {
22864
+ width: auto;
22865
+ display: inline-block;
22866
+ padding: 4px 10px;
22867
+ border-radius: var(--radius);
22868
+ border: 1px solid var(--border);
22869
+ direction: ltr;
22870
+ }
22871
+ }
22872
+ `;
22873
+
22874
+ // src/ui/constants.ts
22875
+ var NO_WORKSPACE_FILTER = "__none__";
22876
+
22877
+ // node_modules/hono/dist/jsx/constants.js
22878
+ var DOM_RENDERER = /* @__PURE__ */ Symbol("RENDERER");
22879
+ var DOM_ERROR_HANDLER = /* @__PURE__ */ Symbol("ERROR_HANDLER");
22880
+ var DOM_INTERNAL_TAG = /* @__PURE__ */ Symbol("INTERNAL");
22881
+ var PERMALINK = /* @__PURE__ */ Symbol("PERMALINK");
22882
+
22883
+ // node_modules/hono/dist/jsx/dom/utils.js
22884
+ var setInternalTagFlag = (fn) => {
22885
+ fn[DOM_INTERNAL_TAG] = true;
22886
+ return fn;
22887
+ };
22888
+
22889
+ // node_modules/hono/dist/jsx/dom/context.js
22890
+ var createContextProviderFunction = (values) => ({ value, children }) => {
22891
+ if (!children) {
22892
+ return;
22893
+ }
22894
+ const props = {
22895
+ children: [
22896
+ {
22897
+ tag: setInternalTagFlag(() => {
22898
+ values.push(value);
22899
+ }),
22900
+ props: {}
22901
+ }
22902
+ ]
22903
+ };
22904
+ if (Array.isArray(children)) {
22905
+ props.children.push(...children.flat());
22906
+ } else {
22907
+ props.children.push(children);
22908
+ }
22909
+ props.children.push({
22910
+ tag: setInternalTagFlag(() => {
22911
+ values.pop();
22912
+ }),
22913
+ props: {}
22914
+ });
22915
+ const res = { tag: "", props, type: "" };
22916
+ res[DOM_ERROR_HANDLER] = (err) => {
22917
+ values.pop();
22918
+ throw err;
22919
+ };
22920
+ return res;
22921
+ };
22922
+
22923
+ // node_modules/hono/dist/jsx/context.js
22924
+ var globalContexts = [];
22925
+ var createContext = (defaultValue) => {
22926
+ const values = [defaultValue];
22927
+ const context = (props) => {
22928
+ values.push(props.value);
22929
+ let string4;
22930
+ try {
22931
+ string4 = props.children ? (Array.isArray(props.children) ? new JSXFragmentNode("", {}, props.children) : props.children).toString() : "";
22932
+ } catch (e) {
22933
+ values.pop();
22934
+ throw e;
22935
+ }
22936
+ if (string4 instanceof Promise) {
22937
+ return string4.finally(() => values.pop()).then((resString) => raw(resString, resString.callbacks));
22938
+ } else {
22939
+ values.pop();
22940
+ return raw(string4);
22941
+ }
22942
+ };
22943
+ context.values = values;
22944
+ context.Provider = context;
22945
+ context[DOM_RENDERER] = createContextProviderFunction(values);
22946
+ globalContexts.push(context);
22947
+ return context;
22948
+ };
22949
+ var useContext = (context) => {
22950
+ return context.values.at(-1);
22951
+ };
22952
+
22953
+ // node_modules/hono/dist/jsx/intrinsic-element/common.js
22954
+ var deDupeKeyMap = {
22955
+ title: [],
22956
+ script: ["src"],
22957
+ style: ["data-href"],
22958
+ link: ["href"],
22959
+ meta: ["name", "httpEquiv", "charset", "itemProp"]
22960
+ };
22961
+ var domRenderers = {};
22962
+ var dataPrecedenceAttr = "data-precedence";
22963
+ var isStylesheetLinkWithPrecedence = (props) => props.rel === "stylesheet" && ("precedence" in props);
22964
+ var shouldDeDupeByKey = (tagName, supportSort) => {
22965
+ if (tagName === "link") {
22966
+ return supportSort;
22967
+ }
22968
+ return deDupeKeyMap[tagName].length > 0;
22969
+ };
22970
+
22971
+ // node_modules/hono/dist/jsx/intrinsic-element/components.js
22972
+ var exports_components = {};
22973
+ __export(exports_components, {
22974
+ title: () => title,
22975
+ style: () => style,
22976
+ script: () => script,
22977
+ meta: () => meta2,
22978
+ link: () => link,
22979
+ input: () => input,
22980
+ form: () => form,
22981
+ button: () => button
22982
+ });
22983
+
22984
+ // node_modules/hono/dist/jsx/children.js
22985
+ var toArray = (children) => Array.isArray(children) ? children : [children];
22986
+
22987
+ // node_modules/hono/dist/jsx/intrinsic-element/components.js
22988
+ var metaTagMap = /* @__PURE__ */ new WeakMap;
22989
+ var insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context }) => {
22990
+ if (!buffer) {
22991
+ return;
22992
+ }
22993
+ const map2 = metaTagMap.get(context) || {};
22994
+ metaTagMap.set(context, map2);
22995
+ const tags = map2[tagName] ||= [];
22996
+ let duped = false;
22997
+ const deDupeKeys = deDupeKeyMap[tagName];
22998
+ const deDupeByKey = shouldDeDupeByKey(tagName, precedence !== undefined);
22999
+ if (deDupeByKey) {
23000
+ LOOP:
23001
+ for (const [, tagProps] of tags) {
23002
+ if (tagName === "link" && !(tagProps.rel === "stylesheet" && tagProps[dataPrecedenceAttr] !== undefined)) {
23003
+ continue;
23004
+ }
23005
+ for (const key of deDupeKeys) {
23006
+ if ((tagProps?.[key] ?? null) === props?.[key]) {
23007
+ duped = true;
23008
+ break LOOP;
23009
+ }
23010
+ }
23011
+ }
23012
+ }
23013
+ if (duped) {
23014
+ buffer[0] = buffer[0].replaceAll(tag, "");
23015
+ } else if (deDupeByKey || tagName === "link") {
23016
+ tags.push([tag, props, precedence]);
23017
+ } else {
23018
+ tags.unshift([tag, props, precedence]);
23019
+ }
23020
+ if (buffer[0].indexOf("</head>") !== -1) {
23021
+ let insertTags;
23022
+ if (tagName === "link" || precedence !== undefined) {
23023
+ const precedences = [];
23024
+ insertTags = tags.map(([tag2, , tagPrecedence], index) => {
23025
+ if (tagPrecedence === undefined) {
23026
+ return [tag2, Number.MAX_SAFE_INTEGER, index];
23027
+ }
23028
+ let order = precedences.indexOf(tagPrecedence);
23029
+ if (order === -1) {
23030
+ precedences.push(tagPrecedence);
23031
+ order = precedences.length - 1;
23032
+ }
23033
+ return [tag2, order, index];
23034
+ }).sort((a, b) => a[1] - b[1] || a[2] - b[2]).map(([tag2]) => tag2);
23035
+ } else {
23036
+ insertTags = tags.map(([tag2]) => tag2);
23037
+ }
23038
+ insertTags.forEach((tag2) => {
23039
+ buffer[0] = buffer[0].replaceAll(tag2, "");
23040
+ });
23041
+ buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join(""));
23042
+ }
23043
+ };
23044
+ var returnWithoutSpecialBehavior = (tag, children, props) => raw(new JSXNode(tag, props, toArray(children ?? [])).toString());
23045
+ var documentMetadataTag = (tag, children, props, sort) => {
23046
+ if ("itemProp" in props) {
23047
+ return returnWithoutSpecialBehavior(tag, children, props);
23048
+ }
23049
+ let { precedence, blocking, ...restProps } = props;
23050
+ precedence = sort ? precedence ?? "" : undefined;
23051
+ if (sort) {
23052
+ restProps[dataPrecedenceAttr] = precedence;
23053
+ }
23054
+ const string4 = new JSXNode(tag, restProps, toArray(children || [])).toString();
23055
+ if (string4 instanceof Promise) {
23056
+ return string4.then((resString) => raw(string4, [
23057
+ ...resString.callbacks || [],
23058
+ insertIntoHead(tag, resString, restProps, precedence)
23059
+ ]));
23060
+ } else {
23061
+ return raw(string4, [insertIntoHead(tag, string4, restProps, precedence)]);
23062
+ }
23063
+ };
23064
+ var title = ({ children, ...props }) => {
23065
+ const nameSpaceContext = getNameSpaceContext();
23066
+ if (nameSpaceContext) {
23067
+ const context = useContext(nameSpaceContext);
23068
+ if (context === "svg" || context === "head") {
23069
+ return new JSXNode("title", props, toArray(children ?? []));
23070
+ }
23071
+ }
23072
+ return documentMetadataTag("title", children, props, false);
23073
+ };
23074
+ var script = ({
23075
+ children,
23076
+ ...props
23077
+ }) => {
23078
+ const nameSpaceContext = getNameSpaceContext();
23079
+ if (["src", "async"].some((k) => !props[k]) || nameSpaceContext && useContext(nameSpaceContext) === "head") {
23080
+ return returnWithoutSpecialBehavior("script", children, props);
23081
+ }
23082
+ return documentMetadataTag("script", children, props, false);
23083
+ };
23084
+ var style = ({
23085
+ children,
23086
+ ...props
23087
+ }) => {
23088
+ if (!["href", "precedence"].every((k) => (k in props))) {
23089
+ return returnWithoutSpecialBehavior("style", children, props);
23090
+ }
23091
+ props["data-href"] = props.href;
23092
+ delete props.href;
23093
+ return documentMetadataTag("style", children, props, true);
23094
+ };
23095
+ var link = ({ children, ...props }) => {
23096
+ if (["onLoad", "onError"].some((k) => (k in props)) || props.rel === "stylesheet" && (!("precedence" in props) || ("disabled" in props))) {
23097
+ return returnWithoutSpecialBehavior("link", children, props);
23098
+ }
23099
+ return documentMetadataTag("link", children, props, isStylesheetLinkWithPrecedence(props));
23100
+ };
23101
+ var meta2 = ({ children, ...props }) => {
23102
+ const nameSpaceContext = getNameSpaceContext();
23103
+ if (nameSpaceContext && useContext(nameSpaceContext) === "head") {
23104
+ return returnWithoutSpecialBehavior("meta", children, props);
23105
+ }
23106
+ return documentMetadataTag("meta", children, props, false);
23107
+ };
23108
+ var newJSXNode = (tag, { children, ...props }) => new JSXNode(tag, props, toArray(children ?? []));
23109
+ var form = (props) => {
23110
+ if (typeof props.action === "function") {
23111
+ props.action = PERMALINK in props.action ? props.action[PERMALINK] : undefined;
23112
+ }
23113
+ return newJSXNode("form", props);
23114
+ };
23115
+ var formActionableElement = (tag, props) => {
23116
+ if (typeof props.formAction === "function") {
23117
+ props.formAction = PERMALINK in props.formAction ? props.formAction[PERMALINK] : undefined;
23118
+ }
23119
+ return newJSXNode(tag, props);
23120
+ };
23121
+ var input = (props) => formActionableElement("input", props);
23122
+ var button = (props) => formActionableElement("button", props);
23123
+
23124
+ // node_modules/hono/dist/jsx/utils.js
23125
+ var normalizeElementKeyMap = /* @__PURE__ */ new Map([
23126
+ ["className", "class"],
23127
+ ["htmlFor", "for"],
23128
+ ["crossOrigin", "crossorigin"],
23129
+ ["httpEquiv", "http-equiv"],
23130
+ ["itemProp", "itemprop"],
23131
+ ["fetchPriority", "fetchpriority"],
23132
+ ["noModule", "nomodule"],
23133
+ ["formAction", "formaction"]
23134
+ ]);
23135
+ var normalizeIntrinsicElementKey = (key) => normalizeElementKeyMap.get(key) || key;
23136
+ var styleObjectForEach = (style2, fn) => {
23137
+ for (const [k, v] of Object.entries(style2)) {
23138
+ const key = k[0] === "-" || !/[A-Z]/.test(k) ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
23139
+ fn(key, v == null ? null : typeof v === "number" ? !key.match(/^(?:a|border-im|column(?:-c|s)|flex(?:$|-[^b])|grid-(?:ar|[^a])|font-w|li|or|sca|st|ta|wido|z)|ty$/) ? `${v}px` : `${v}` : v);
23140
+ }
23141
+ };
23142
+
23143
+ // node_modules/hono/dist/jsx/base.js
23144
+ var nameSpaceContext = undefined;
23145
+ var getNameSpaceContext = () => nameSpaceContext;
23146
+ var toSVGAttributeName = (key) => /[A-Z]/.test(key) && key.match(/^(?:al|basel|clip(?:Path|Rule)$|co|do|fill|fl|fo|gl|let|lig|i|marker[EMS]|o|pai|pointe|sh|st[or]|text[^L]|tr|u|ve|w)/) ? key.replace(/([A-Z])/g, "-$1").toLowerCase() : key;
23147
+ var emptyTags = [
23148
+ "area",
23149
+ "base",
23150
+ "br",
23151
+ "col",
23152
+ "embed",
23153
+ "hr",
23154
+ "img",
23155
+ "input",
23156
+ "keygen",
23157
+ "link",
23158
+ "meta",
23159
+ "param",
23160
+ "source",
23161
+ "track",
23162
+ "wbr"
23163
+ ];
23164
+ var booleanAttributes = [
23165
+ "allowfullscreen",
23166
+ "async",
23167
+ "autofocus",
23168
+ "autoplay",
23169
+ "checked",
23170
+ "controls",
23171
+ "default",
23172
+ "defer",
23173
+ "disabled",
23174
+ "download",
23175
+ "formnovalidate",
23176
+ "hidden",
23177
+ "inert",
23178
+ "ismap",
23179
+ "itemscope",
23180
+ "loop",
23181
+ "multiple",
23182
+ "muted",
23183
+ "nomodule",
23184
+ "novalidate",
23185
+ "open",
23186
+ "playsinline",
23187
+ "readonly",
23188
+ "required",
23189
+ "reversed",
23190
+ "selected"
23191
+ ];
23192
+ var childrenToStringToBuffer = (children, buffer) => {
23193
+ for (let i = 0, len = children.length;i < len; i++) {
23194
+ const child = children[i];
23195
+ if (typeof child === "string") {
23196
+ escapeToBuffer(child, buffer);
23197
+ } else if (typeof child === "boolean" || child === null || child === undefined) {
23198
+ continue;
23199
+ } else if (child instanceof JSXNode) {
23200
+ child.toStringToBuffer(buffer);
23201
+ } else if (typeof child === "number" || child.isEscaped) {
23202
+ buffer[0] += child;
23203
+ } else if (child instanceof Promise) {
23204
+ buffer.unshift("", child);
23205
+ } else {
23206
+ childrenToStringToBuffer(child, buffer);
23207
+ }
23208
+ }
23209
+ };
23210
+ var JSXNode = class {
23211
+ tag;
23212
+ props;
23213
+ key;
23214
+ children;
23215
+ isEscaped = true;
23216
+ localContexts;
23217
+ constructor(tag, props, children) {
23218
+ this.tag = tag;
23219
+ this.props = props;
23220
+ this.children = children;
23221
+ }
23222
+ get type() {
23223
+ return this.tag;
23224
+ }
23225
+ get ref() {
23226
+ return this.props.ref || null;
23227
+ }
23228
+ toString() {
23229
+ const buffer = [""];
23230
+ this.localContexts?.forEach(([context, value]) => {
23231
+ context.values.push(value);
23232
+ });
23233
+ try {
23234
+ this.toStringToBuffer(buffer);
23235
+ } finally {
23236
+ this.localContexts?.forEach(([context]) => {
23237
+ context.values.pop();
23238
+ });
23239
+ }
23240
+ return buffer.length === 1 ? "callbacks" in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0] : stringBufferToString(buffer, buffer.callbacks);
23241
+ }
23242
+ toStringToBuffer(buffer) {
23243
+ const tag = this.tag;
23244
+ const props = this.props;
23245
+ let { children } = this;
23246
+ buffer[0] += `<${tag}`;
23247
+ const normalizeKey = nameSpaceContext && useContext(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key)) : (key) => normalizeIntrinsicElementKey(key);
23248
+ for (let [key, v] of Object.entries(props)) {
23249
+ key = normalizeKey(key);
23250
+ if (key === "children") {} else if (key === "style" && typeof v === "object") {
23251
+ let styleStr = "";
23252
+ styleObjectForEach(v, (property, value) => {
23253
+ if (value != null) {
23254
+ styleStr += `${styleStr ? ";" : ""}${property}:${value}`;
23255
+ }
23256
+ });
23257
+ buffer[0] += ' style="';
23258
+ escapeToBuffer(styleStr, buffer);
23259
+ buffer[0] += '"';
23260
+ } else if (typeof v === "string") {
23261
+ buffer[0] += ` ${key}="`;
23262
+ escapeToBuffer(v, buffer);
23263
+ buffer[0] += '"';
23264
+ } else if (v === null || v === undefined) {} else if (typeof v === "number" || v.isEscaped) {
23265
+ buffer[0] += ` ${key}="${v}"`;
23266
+ } else if (typeof v === "boolean" && booleanAttributes.includes(key)) {
23267
+ if (v) {
23268
+ buffer[0] += ` ${key}=""`;
23269
+ }
23270
+ } else if (key === "dangerouslySetInnerHTML") {
23271
+ if (children.length > 0) {
23272
+ throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
23273
+ }
23274
+ children = [raw(v.__html)];
23275
+ } else if (v instanceof Promise) {
23276
+ buffer[0] += ` ${key}="`;
23277
+ buffer.unshift('"', v);
23278
+ } else if (typeof v === "function") {
23279
+ if (!key.startsWith("on") && key !== "ref") {
23280
+ throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`);
23281
+ }
23282
+ } else {
23283
+ buffer[0] += ` ${key}="`;
23284
+ escapeToBuffer(v.toString(), buffer);
23285
+ buffer[0] += '"';
23286
+ }
23287
+ }
23288
+ if (emptyTags.includes(tag) && children.length === 0) {
23289
+ buffer[0] += "/>";
23290
+ return;
23291
+ }
23292
+ buffer[0] += ">";
23293
+ childrenToStringToBuffer(children, buffer);
23294
+ buffer[0] += `</${tag}>`;
23295
+ }
23296
+ };
23297
+ var JSXFunctionNode = class extends JSXNode {
23298
+ toStringToBuffer(buffer) {
23299
+ const { children } = this;
23300
+ const props = { ...this.props };
23301
+ if (children.length) {
23302
+ props.children = children.length === 1 ? children[0] : children;
23303
+ }
23304
+ const res = this.tag.call(null, props);
23305
+ if (typeof res === "boolean" || res == null) {
23306
+ return;
23307
+ } else if (res instanceof Promise) {
23308
+ if (globalContexts.length === 0) {
23309
+ buffer.unshift("", res);
23310
+ } else {
23311
+ const currentContexts = globalContexts.map((c) => [c, c.values.at(-1)]);
23312
+ buffer.unshift("", res.then((childRes) => {
23313
+ if (childRes instanceof JSXNode) {
23314
+ childRes.localContexts = currentContexts;
23315
+ }
23316
+ return childRes;
23317
+ }));
23318
+ }
23319
+ } else if (res instanceof JSXNode) {
23320
+ res.toStringToBuffer(buffer);
23321
+ } else if (typeof res === "number" || res.isEscaped) {
23322
+ buffer[0] += res;
23323
+ if (res.callbacks) {
23324
+ buffer.callbacks ||= [];
23325
+ buffer.callbacks.push(...res.callbacks);
23326
+ }
23327
+ } else {
23328
+ escapeToBuffer(res, buffer);
23329
+ }
23330
+ }
23331
+ };
23332
+ var JSXFragmentNode = class extends JSXNode {
23333
+ toStringToBuffer(buffer) {
23334
+ childrenToStringToBuffer(this.children, buffer);
23335
+ }
23336
+ };
23337
+ var initDomRenderer = false;
23338
+ var jsxFn = (tag, props, children) => {
23339
+ if (!initDomRenderer) {
23340
+ for (const k in domRenderers) {
23341
+ exports_components[k][DOM_RENDERER] = domRenderers[k];
23342
+ }
23343
+ initDomRenderer = true;
23344
+ }
23345
+ if (typeof tag === "function") {
23346
+ return new JSXFunctionNode(tag, props, children);
23347
+ } else if (exports_components[tag]) {
23348
+ return new JSXFunctionNode(exports_components[tag], props, children);
23349
+ } else if (tag === "svg" || tag === "head") {
23350
+ nameSpaceContext ||= createContext("");
23351
+ return new JSXNode(tag, props, [
23352
+ new JSXFunctionNode(nameSpaceContext, {
23353
+ value: tag
23354
+ }, children)
23355
+ ]);
23356
+ } else {
23357
+ return new JSXNode(tag, props, children);
23358
+ }
23359
+ };
23360
+ var Fragment = ({
23361
+ children
23362
+ }) => {
23363
+ return new JSXFragmentNode("", {
23364
+ children
23365
+ }, Array.isArray(children) ? children : children ? [children] : []);
23366
+ };
23367
+
23368
+ // node_modules/hono/dist/jsx/jsx-dev-runtime.js
23369
+ function jsxDEV(tag, props, key) {
23370
+ let node;
23371
+ if (!props || !("children" in props)) {
23372
+ node = jsxFn(tag, props, []);
23373
+ } else {
23374
+ const children = props.children;
23375
+ node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children]);
23376
+ }
23377
+ node.key = key;
23378
+ return node;
23379
+ }
23380
+
23381
+ // src/ui/components/create-form.tsx
23382
+ var CreateForm = ({ workspace }) => /* @__PURE__ */ jsxDEV("div", {
23383
+ class: "form-card",
23384
+ children: /* @__PURE__ */ jsxDEV("form", {
23385
+ method: "post",
23386
+ action: "/memories",
23387
+ children: [
23388
+ /* @__PURE__ */ jsxDEV("div", {
23389
+ class: "field",
23390
+ children: [
23391
+ /* @__PURE__ */ jsxDEV("label", {
23392
+ for: "new-content",
23393
+ children: "Content"
23394
+ }, undefined, false, undefined, this),
23395
+ /* @__PURE__ */ jsxDEV("textarea", {
23396
+ id: "new-content",
23397
+ name: "content",
23398
+ placeholder: "Fact, preference, decision...",
23399
+ required: true
23400
+ }, undefined, false, undefined, this)
23401
+ ]
23402
+ }, undefined, true, undefined, this),
23403
+ /* @__PURE__ */ jsxDEV("div", {
23404
+ class: "field",
23405
+ children: [
23406
+ /* @__PURE__ */ jsxDEV("label", {
23407
+ for: "new-workspace",
23408
+ children: "Workspace (optional)"
23409
+ }, undefined, false, undefined, this),
23410
+ /* @__PURE__ */ jsxDEV("input", {
23411
+ id: "new-workspace",
23412
+ name: "workspace",
23413
+ type: "text",
23414
+ placeholder: "/path/to/project",
23415
+ value: workspace && workspace !== NO_WORKSPACE_FILTER ? workspace : ""
23416
+ }, undefined, false, undefined, this)
23417
+ ]
23418
+ }, undefined, true, undefined, this),
23419
+ /* @__PURE__ */ jsxDEV("div", {
23420
+ class: "form-actions",
23421
+ children: /* @__PURE__ */ jsxDEV("button", {
23422
+ type: "submit",
23423
+ class: "primary",
23424
+ children: "Save"
23425
+ }, undefined, false, undefined, this)
23426
+ }, undefined, false, undefined, this)
23427
+ ]
23428
+ }, undefined, true, undefined, this)
23429
+ }, undefined, false, undefined, this);
23430
+
23431
+ // src/ui/components/memory-card.tsx
23432
+ var MemoryCard = ({ memory, editing, showWorkspace, returnUrl }) => /* @__PURE__ */ jsxDEV("div", {
23433
+ class: "card",
23434
+ children: [
23435
+ /* @__PURE__ */ jsxDEV("div", {
23436
+ class: "card-header",
23437
+ children: /* @__PURE__ */ jsxDEV("div", {
23438
+ class: "card-meta",
23439
+ children: [
23440
+ showWorkspace && memory.workspace && /* @__PURE__ */ jsxDEV(Fragment, {
23441
+ children: [
23442
+ /* @__PURE__ */ jsxDEV("span", {
23443
+ class: "badge",
23444
+ children: memory.workspace
23445
+ }, undefined, false, undefined, this),
23446
+ " "
23447
+ ]
23448
+ }, undefined, true, undefined, this),
23449
+ memory.updatedAt.toLocaleString()
23450
+ ]
23451
+ }, undefined, true, undefined, this)
23452
+ }, undefined, false, undefined, this),
23453
+ editing ? /* @__PURE__ */ jsxDEV("form", {
23454
+ method: "post",
23455
+ action: `/memories/${encodeURIComponent(memory.id)}/update`,
23456
+ children: [
23457
+ /* @__PURE__ */ jsxDEV("input", {
23458
+ type: "hidden",
23459
+ name: "returnUrl",
23460
+ value: returnUrl
23461
+ }, undefined, false, undefined, this),
23462
+ /* @__PURE__ */ jsxDEV("textarea", {
23463
+ name: "content",
23464
+ required: true,
23465
+ children: memory.content
23466
+ }, undefined, false, undefined, this),
23467
+ /* @__PURE__ */ jsxDEV("div", {
23468
+ class: "card-actions",
23469
+ children: [
23470
+ /* @__PURE__ */ jsxDEV("button", {
23471
+ type: "submit",
23472
+ class: "primary",
23473
+ children: "Save"
23474
+ }, undefined, false, undefined, this),
23475
+ /* @__PURE__ */ jsxDEV("a", {
23476
+ href: returnUrl,
23477
+ class: "btn",
23478
+ children: "Cancel"
23479
+ }, undefined, false, undefined, this)
23480
+ ]
23481
+ }, undefined, true, undefined, this)
23482
+ ]
23483
+ }, undefined, true, undefined, this) : /* @__PURE__ */ jsxDEV(Fragment, {
23484
+ children: [
23485
+ /* @__PURE__ */ jsxDEV("div", {
23486
+ class: "card-content",
23487
+ children: memory.content
23488
+ }, undefined, false, undefined, this),
23489
+ /* @__PURE__ */ jsxDEV("div", {
23490
+ class: "card-actions",
23491
+ children: [
23492
+ /* @__PURE__ */ jsxDEV("a", {
23493
+ href: `${returnUrl}${returnUrl.includes("?") ? "&" : "?"}edit=${encodeURIComponent(memory.id)}`,
23494
+ class: "btn",
23495
+ children: "Edit"
23496
+ }, undefined, false, undefined, this),
23497
+ /* @__PURE__ */ jsxDEV("form", {
23498
+ method: "post",
23499
+ action: `/memories/${encodeURIComponent(memory.id)}/delete`,
23500
+ onsubmit: "return confirm('Delete this memory?')",
23501
+ children: [
23502
+ /* @__PURE__ */ jsxDEV("input", {
23503
+ type: "hidden",
23504
+ name: "returnUrl",
23505
+ value: returnUrl
23506
+ }, undefined, false, undefined, this),
23507
+ /* @__PURE__ */ jsxDEV("button", {
23508
+ type: "submit",
23509
+ class: "danger",
23510
+ children: "Delete"
23511
+ }, undefined, false, undefined, this)
23512
+ ]
23513
+ }, undefined, true, undefined, this)
23514
+ ]
23515
+ }, undefined, true, undefined, this)
23516
+ ]
23517
+ }, undefined, true, undefined, this)
23518
+ ]
23519
+ }, undefined, true, undefined, this);
23520
+
23521
+ // src/ui/components/sidebar.tsx
23522
+ var Sidebar = ({ workspaces, selected }) => /* @__PURE__ */ jsxDEV("nav", {
23523
+ class: "sidebar",
23524
+ children: [
23525
+ /* @__PURE__ */ jsxDEV("h2", {
23526
+ children: "Workspaces"
23527
+ }, undefined, false, undefined, this),
23528
+ /* @__PURE__ */ jsxDEV("a", {
23529
+ href: "/",
23530
+ class: `sidebar-item all-item${selected === null ? " active" : ""}`,
23531
+ children: "All"
23532
+ }, undefined, false, undefined, this),
23533
+ /* @__PURE__ */ jsxDEV("a", {
23534
+ href: `/?workspace=${NO_WORKSPACE_FILTER}`,
23535
+ class: `sidebar-item no-ws-item${selected === NO_WORKSPACE_FILTER ? " active" : ""}`,
23536
+ children: "No workspace"
23537
+ }, undefined, false, undefined, this),
23538
+ workspaces.map((ws) => /* @__PURE__ */ jsxDEV("a", {
23539
+ href: `/?workspace=${encodeURIComponent(ws)}`,
23540
+ class: `sidebar-item ws-item${selected === ws ? " active" : ""}`,
23541
+ title: ws,
23542
+ children: /* @__PURE__ */ jsxDEV("span", {
23543
+ children: ws.replace(/\/$/, "")
23544
+ }, undefined, false, undefined, this)
23545
+ }, undefined, false, undefined, this))
23546
+ ]
23547
+ }, undefined, true, undefined, this);
23548
+
23549
+ // src/ui/components/page.tsx
23550
+ var buildUrl = (base, overrides) => {
23551
+ const url = new URL(base, "http://localhost");
23552
+ for (const [key, value] of Object.entries(overrides)) {
23553
+ url.searchParams.set(key, value);
23554
+ }
23555
+ return `${url.pathname}${url.search}`;
23556
+ };
23557
+ var Page = ({
23558
+ memories,
23559
+ workspaces,
23560
+ selectedWorkspace,
23561
+ editingId,
23562
+ currentPage,
23563
+ hasMore,
23564
+ showCreate
23565
+ }) => {
23566
+ const params = new URLSearchParams;
23567
+ if (selectedWorkspace)
23568
+ params.set("workspace", selectedWorkspace);
23569
+ if (currentPage > 1)
23570
+ params.set("page", String(currentPage));
23571
+ const baseUrl = params.size > 0 ? `/?${params.toString()}` : "/";
23572
+ const showGroupHeaders = selectedWorkspace === null && new Set(memories.map((m) => m.workspace ?? null)).size > 1;
23573
+ const grouped = [];
23574
+ for (const m of memories) {
23575
+ const key = m.workspace ?? "(no workspace)";
23576
+ const last = grouped[grouped.length - 1];
23577
+ if (last && last.key === key) {
23578
+ last.items.push(m);
23579
+ } else {
23580
+ grouped.push({ key, items: [m] });
23581
+ }
23582
+ }
23583
+ const hasPrev = currentPage > 1;
23584
+ return /* @__PURE__ */ jsxDEV("html", {
23585
+ lang: "en",
23586
+ children: [
23587
+ /* @__PURE__ */ jsxDEV("head", {
23588
+ children: [
23589
+ /* @__PURE__ */ jsxDEV("meta", {
23590
+ charset: "utf-8"
23591
+ }, undefined, false, undefined, this),
23592
+ /* @__PURE__ */ jsxDEV("meta", {
23593
+ name: "viewport",
23594
+ content: "width=device-width, initial-scale=1"
23595
+ }, undefined, false, undefined, this),
23596
+ /* @__PURE__ */ jsxDEV("title", {
23597
+ children: "agent-memory"
23598
+ }, undefined, false, undefined, this),
23599
+ /* @__PURE__ */ jsxDEV("style", {
23600
+ children: styles_default
23601
+ }, undefined, false, undefined, this)
23602
+ ]
23603
+ }, undefined, true, undefined, this),
23604
+ /* @__PURE__ */ jsxDEV("body", {
23605
+ children: /* @__PURE__ */ jsxDEV("div", {
23606
+ class: "layout",
23607
+ children: [
23608
+ /* @__PURE__ */ jsxDEV(Sidebar, {
23609
+ workspaces,
23610
+ selected: selectedWorkspace
23611
+ }, undefined, false, undefined, this),
23612
+ /* @__PURE__ */ jsxDEV("div", {
23613
+ class: "main",
23614
+ children: [
23615
+ /* @__PURE__ */ jsxDEV("header", {
23616
+ children: [
23617
+ /* @__PURE__ */ jsxDEV("h1", {
23618
+ children: "agent-memory"
23619
+ }, undefined, false, undefined, this),
23620
+ showCreate ? /* @__PURE__ */ jsxDEV("a", {
23621
+ href: baseUrl,
23622
+ class: "btn",
23623
+ children: "Cancel"
23624
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("a", {
23625
+ href: buildUrl(baseUrl, { create: "1" }),
23626
+ class: "btn primary",
23627
+ children: "New Memory"
23628
+ }, undefined, false, undefined, this)
23629
+ ]
23630
+ }, undefined, true, undefined, this),
23631
+ showCreate && /* @__PURE__ */ jsxDEV(CreateForm, {
23632
+ workspace: selectedWorkspace
23633
+ }, undefined, false, undefined, this),
23634
+ memories.length === 0 && !hasPrev ? /* @__PURE__ */ jsxDEV("div", {
23635
+ class: "empty",
23636
+ children: "No memories found."
23637
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV(Fragment, {
23638
+ children: [
23639
+ grouped.map(({ key, items }) => /* @__PURE__ */ jsxDEV(Fragment, {
23640
+ children: [
23641
+ showGroupHeaders && /* @__PURE__ */ jsxDEV("div", {
23642
+ class: "ws-group-header",
23643
+ children: key
23644
+ }, undefined, false, undefined, this),
23645
+ items.map((m) => /* @__PURE__ */ jsxDEV(MemoryCard, {
23646
+ memory: m,
23647
+ editing: editingId === m.id,
23648
+ showWorkspace: selectedWorkspace === null,
23649
+ returnUrl: baseUrl
23650
+ }, undefined, false, undefined, this))
23651
+ ]
23652
+ }, undefined, true, undefined, this)),
23653
+ (hasPrev || hasMore) && /* @__PURE__ */ jsxDEV("div", {
23654
+ class: "pagination",
23655
+ children: [
23656
+ hasPrev ? /* @__PURE__ */ jsxDEV("a", {
23657
+ href: buildUrl(baseUrl, { page: String(currentPage - 1) }),
23658
+ class: "btn",
23659
+ children: "Previous"
23660
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {}, undefined, false, undefined, this),
23661
+ /* @__PURE__ */ jsxDEV("span", {
23662
+ class: "page-info",
23663
+ children: [
23664
+ "Page ",
23665
+ currentPage
23666
+ ]
23667
+ }, undefined, true, undefined, this),
23668
+ hasMore ? /* @__PURE__ */ jsxDEV("a", {
23669
+ href: buildUrl(baseUrl, { page: String(currentPage + 1) }),
23670
+ class: "btn",
23671
+ children: "Next"
23672
+ }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {}, undefined, false, undefined, this)
23673
+ ]
23674
+ }, undefined, true, undefined, this)
23675
+ ]
23676
+ }, undefined, true, undefined, this)
23677
+ ]
23678
+ }, undefined, true, undefined, this)
23679
+ ]
23680
+ }, undefined, true, undefined, this)
23681
+ }, undefined, false, undefined, this)
23682
+ ]
23683
+ }, undefined, true, undefined, this);
23684
+ };
23685
+
23686
+ // src/ui/server.tsx
23687
+ var DEFAULT_LIST_LIMIT = 15;
23688
+ var MAX_LIST_LIMIT = 100;
23689
+ var startWebServer = (repository, options) => {
23690
+ const app = new Hono2;
23691
+ app.get("/", async (c) => {
23692
+ const workspace = c.req.query("workspace") ?? null;
23693
+ const pageNum = Math.max(Number(c.req.query("page")) || 1, 1);
23694
+ const editingId = c.req.query("edit") ?? null;
23695
+ const showCreate = c.req.query("create") === "1";
23696
+ const isNoWorkspace = workspace === NO_WORKSPACE_FILTER;
23697
+ const wsFilter = workspace && !isNoWorkspace ? workspace : undefined;
23698
+ const page = await repository.findAll({
23699
+ workspace: wsFilter,
23700
+ workspaceIsNull: isNoWorkspace,
23701
+ offset: (pageNum - 1) * DEFAULT_LIST_LIMIT,
23702
+ limit: DEFAULT_LIST_LIMIT
23703
+ });
23704
+ const workspaces = await repository.listWorkspaces();
23705
+ return c.html(/* @__PURE__ */ jsxDEV(Page, {
23706
+ memories: page.items,
23707
+ workspaces,
23708
+ selectedWorkspace: workspace,
23709
+ editingId,
23710
+ currentPage: pageNum,
23711
+ hasMore: page.hasMore,
23712
+ showCreate
23713
+ }, undefined, false, undefined, this));
23714
+ });
23715
+ app.post("/memories", async (c) => {
23716
+ const form2 = await c.req.parseBody();
23717
+ const content = typeof form2.content === "string" ? form2.content.trim() : "";
23718
+ const workspace = typeof form2.workspace === "string" ? form2.workspace.trim() || undefined : undefined;
23719
+ if (content) {
23720
+ const now = new Date;
23721
+ await repository.save({ id: randomUUID2(), content, workspace, createdAt: now, updatedAt: now });
23722
+ }
23723
+ const wsParam = workspace ? `/?workspace=${encodeURIComponent(workspace)}` : "/";
23724
+ return c.redirect(wsParam);
23725
+ });
23726
+ app.post("/memories/:id/update", async (c) => {
23727
+ const form2 = await c.req.parseBody();
23728
+ const content = typeof form2.content === "string" ? form2.content.trim() : "";
23729
+ const returnUrl = safeReturnUrl(form2.returnUrl);
23730
+ if (content) {
23731
+ try {
23732
+ await repository.update(c.req.param("id"), content);
23733
+ } catch (error2) {
23734
+ if (!(error2 instanceof NotFoundError))
23735
+ throw error2;
23736
+ }
23737
+ }
23738
+ return c.redirect(returnUrl);
23739
+ });
23740
+ app.post("/memories/:id/delete", async (c) => {
23741
+ const form2 = await c.req.parseBody();
23742
+ const returnUrl = safeReturnUrl(form2.returnUrl);
23743
+ try {
23744
+ await repository.delete(c.req.param("id"));
23745
+ } catch (error2) {
23746
+ if (!(error2 instanceof NotFoundError))
23747
+ throw error2;
23748
+ }
23749
+ return c.redirect(returnUrl);
23750
+ });
23751
+ app.get("/api/workspaces", async (c) => {
23752
+ const workspaces = await repository.listWorkspaces();
23753
+ return c.json({ workspaces });
23754
+ });
23755
+ app.get("/api/memories", async (c) => {
23756
+ const workspace = c.req.query("workspace");
23757
+ const limitParam = c.req.query("limit");
23758
+ const limit = Math.min(Math.max(Number(limitParam) || DEFAULT_LIST_LIMIT, 1), MAX_LIST_LIMIT);
23759
+ const offset = Math.max(Number(c.req.query("offset")) || 0, 0);
23760
+ const page = await repository.findAll({ workspace, offset, limit });
23761
+ return c.json({ items: page.items.map(toMemoryJson), hasMore: page.hasMore });
23762
+ });
23763
+ app.get("/api/memories/:id", async (c) => {
23764
+ const memory = await repository.findById(c.req.param("id"));
23765
+ if (!memory)
23766
+ return c.json({ error: "Memory not found." }, 404);
23767
+ return c.json(toMemoryJson(memory));
23768
+ });
23769
+ app.post("/api/memories", async (c) => {
23770
+ const body = await c.req.json().catch(() => null);
23771
+ if (!body)
23772
+ return c.json({ error: "Invalid JSON." }, 400);
23773
+ const content = typeof body.content === "string" ? body.content.trim() : "";
23774
+ if (!content)
23775
+ return c.json({ error: "Content is required." }, 400);
23776
+ const workspace = typeof body.workspace === "string" ? body.workspace.trim() || undefined : undefined;
23777
+ const now = new Date;
23778
+ const memory = await repository.save({ id: randomUUID2(), content, workspace, createdAt: now, updatedAt: now });
23779
+ return c.json(toMemoryJson(memory), 201);
23780
+ });
23781
+ app.patch("/api/memories/:id", async (c) => {
23782
+ const body = await c.req.json().catch(() => null);
23783
+ if (!body)
23784
+ return c.json({ error: "Invalid JSON." }, 400);
23785
+ const content = typeof body.content === "string" ? body.content.trim() : "";
23786
+ if (!content)
23787
+ return c.json({ error: "Content is required." }, 400);
23788
+ try {
23789
+ const updated = await repository.update(c.req.param("id"), content);
23790
+ return c.json(toMemoryJson(updated));
23791
+ } catch (error2) {
23792
+ if (error2 instanceof NotFoundError)
23793
+ return c.json({ error: "Memory not found." }, 404);
23794
+ throw error2;
23795
+ }
23796
+ });
23797
+ app.delete("/api/memories/:id", async (c) => {
23798
+ try {
23799
+ await repository.delete(c.req.param("id"));
23800
+ return c.body(null, 204);
23801
+ } catch (error2) {
23802
+ if (error2 instanceof NotFoundError)
23803
+ return c.json({ error: "Memory not found." }, 404);
23804
+ throw error2;
23805
+ }
23806
+ });
23807
+ return serve({ fetch: app.fetch, port: options.port });
23808
+ };
23809
+ var safeReturnUrl = (value) => {
23810
+ if (typeof value === "string" && value.startsWith("/"))
23811
+ return value;
23812
+ return "/";
23813
+ };
23814
+ var toMemoryJson = (memory) => ({
23815
+ id: memory.id,
23816
+ content: memory.content,
23817
+ workspace: memory.workspace ?? null,
23818
+ created_at: memory.createdAt.toISOString(),
23819
+ updated_at: memory.updatedAt.toISOString()
23820
+ });
23821
+
23822
+ // src/index.ts
23823
+ var config2 = resolveConfig();
23824
+ var database = openMemoryDatabase(config2.databasePath);
23825
+ var repository = new SqliteMemoryRepository(database);
23826
+ if (config2.uiMode) {
23827
+ const server = startWebServer(repository, { port: config2.uiPort });
23828
+ const addr = server.address();
23829
+ const port = typeof addr === "object" && addr ? addr.port : config2.uiPort;
23830
+ console.log(`agent-memory UI running at http://localhost:${port}`);
23831
+ const shutdown = () => {
23832
+ server.close();
23833
+ database.close();
23834
+ process.exit(0);
23835
+ };
23836
+ process.on("SIGINT", shutdown);
23837
+ process.on("SIGTERM", shutdown);
23838
+ } else {
23839
+ const memoryService = new MemoryService(repository);
23840
+ const server = createMcpServer(memoryService, version2);
23841
+ const transport = new StdioServerTransport;
23842
+ try {
23843
+ await server.connect(transport);
23844
+ } catch (error2) {
23845
+ console.error(error2 instanceof Error ? error2.message : "Failed to start agent-memory.");
23846
+ database.close();
23847
+ process.exit(1);
23848
+ }
20287
23849
  }