@jcyamacho/agent-memory 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +29 -27
  2. package/dist/index.js +398 -3891
  3. package/package.json +5 -9
package/dist/index.js CHANGED
@@ -2431,9 +2431,9 @@ var require_validate = __commonJS((exports) => {
2431
2431
  }
2432
2432
  }
2433
2433
  function returnResults(it) {
2434
- const { gen, schemaEnv, validateName, ValidationError, opts } = it;
2434
+ const { gen, schemaEnv, validateName, ValidationError: ValidationError2, opts } = it;
2435
2435
  if (schemaEnv.$async) {
2436
- gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
2436
+ gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError2}(${names_1.default.vErrors})`));
2437
2437
  } else {
2438
2438
  gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
2439
2439
  if (opts.unevaluated)
@@ -2783,14 +2783,14 @@ var require_validate = __commonJS((exports) => {
2783
2783
  var require_validation_error = __commonJS((exports) => {
2784
2784
  Object.defineProperty(exports, "__esModule", { value: true });
2785
2785
 
2786
- class ValidationError extends Error {
2786
+ class ValidationError2 extends Error {
2787
2787
  constructor(errors3) {
2788
2788
  super("validation failed");
2789
2789
  this.errors = errors3;
2790
2790
  this.ajv = this.validation = true;
2791
2791
  }
2792
2792
  }
2793
- exports.default = ValidationError;
2793
+ exports.default = ValidationError2;
2794
2794
  });
2795
2795
 
2796
2796
  // node_modules/ajv/dist/compile/ref_error.js
@@ -11543,7 +11543,7 @@ var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || t
11543
11543
  var ProgressTokenSchema = union([string2(), number2().int()]);
11544
11544
  var CursorSchema = string2();
11545
11545
  var TaskCreationParamsSchema = looseObject({
11546
- ttl: union([number2(), _null3()]).optional(),
11546
+ ttl: number2().optional(),
11547
11547
  pollInterval: number2().optional()
11548
11548
  });
11549
11549
  var TaskMetadataSchema = object({
@@ -11697,7 +11697,8 @@ var ClientCapabilitiesSchema = object({
11697
11697
  roots: object({
11698
11698
  listChanged: boolean2().optional()
11699
11699
  }).optional(),
11700
- tasks: ClientTasksCapabilitySchema.optional()
11700
+ tasks: ClientTasksCapabilitySchema.optional(),
11701
+ extensions: record(string2(), AssertObjectSchema).optional()
11701
11702
  });
11702
11703
  var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
11703
11704
  protocolVersion: string2(),
@@ -11722,7 +11723,8 @@ var ServerCapabilitiesSchema = object({
11722
11723
  tools: object({
11723
11724
  listChanged: boolean2().optional()
11724
11725
  }).optional(),
11725
- tasks: ServerTasksCapabilitySchema.optional()
11726
+ tasks: ServerTasksCapabilitySchema.optional(),
11727
+ extensions: record(string2(), AssertObjectSchema).optional()
11726
11728
  });
11727
11729
  var InitializeResultSchema = ResultSchema.extend({
11728
11730
  protocolVersion: string2(),
@@ -11837,6 +11839,7 @@ var ResourceSchema = object({
11837
11839
  uri: string2(),
11838
11840
  description: optional(string2()),
11839
11841
  mimeType: optional(string2()),
11842
+ size: optional(number2()),
11840
11843
  annotations: AnnotationsSchema.optional(),
11841
11844
  _meta: optional(looseObject({}))
11842
11845
  });
@@ -12464,33 +12467,268 @@ class StdioServerTransport {
12464
12467
  }
12465
12468
  }
12466
12469
  // package.json
12467
- var version2 = "0.1.0";
12470
+ var version2 = "0.3.0";
12468
12471
 
12469
12472
  // src/config.ts
12470
12473
  import { homedir } from "node:os";
12471
12474
  import { join } from "node:path";
12472
- import { parseArgs } from "node:util";
12473
- var AGENT_MEMORY_DB_PATH_ENV = "AGENT_MEMORY_DB_PATH";
12474
- var DEFAULT_UI_PORT = 6580;
12475
- function 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
- });
12475
+ var AGENT_MEMORY_STORE_PATH_ENV = "AGENT_MEMORY_STORE_PATH";
12476
+ function resolveConfig(environment = process.env) {
12484
12477
  return {
12485
- databasePath: resolveDatabasePath(environment),
12486
- uiMode: Boolean(values.ui),
12487
- uiPort: Number(values.port) || DEFAULT_UI_PORT
12478
+ storePath: resolveStorePath(environment)
12488
12479
  };
12489
12480
  }
12490
- function resolveDatabasePath(environment = process.env) {
12491
- return environment[AGENT_MEMORY_DB_PATH_ENV] || join(homedir(), ".config", "agent-memory", "memory.db");
12481
+ function resolveStorePath(environment = process.env) {
12482
+ return environment[AGENT_MEMORY_STORE_PATH_ENV] || join(homedir(), ".config", "agent-memory");
12483
+ }
12484
+
12485
+ // src/filesystem/repository.ts
12486
+ import { randomUUID } from "node:crypto";
12487
+ import { access, mkdir, readdir, readFile, rename, rm, stat, unlink, utimes, writeFile } from "node:fs/promises";
12488
+ import { basename, dirname, join as join2 } from "node:path";
12489
+
12490
+ // src/errors.ts
12491
+ class MemoryError extends Error {
12492
+ code;
12493
+ constructor(code, message, options) {
12494
+ super(message, options);
12495
+ this.name = "MemoryError";
12496
+ this.code = code;
12497
+ }
12498
+ }
12499
+
12500
+ class ValidationError extends MemoryError {
12501
+ constructor(message) {
12502
+ super("VALIDATION_ERROR", message);
12503
+ this.name = "ValidationError";
12504
+ }
12505
+ }
12506
+
12507
+ class NotFoundError extends MemoryError {
12508
+ constructor(message) {
12509
+ super("NOT_FOUND", message);
12510
+ this.name = "NotFoundError";
12511
+ }
12512
+ }
12513
+
12514
+ class PersistenceError extends MemoryError {
12515
+ constructor(message, options) {
12516
+ super("PERSISTENCE_ERROR", message, options);
12517
+ this.name = "PersistenceError";
12518
+ }
12492
12519
  }
12493
12520
 
12521
+ // src/filesystem/repository.ts
12522
+ var DEFAULT_LIST_LIMIT = 15;
12523
+ var MARKDOWN_EXTENSION = ".md";
12524
+
12525
+ class FilesystemMemoryRepository {
12526
+ globalsDirectory;
12527
+ workspacesDirectory;
12528
+ constructor(storePath) {
12529
+ this.globalsDirectory = join2(storePath, "globals");
12530
+ this.workspacesDirectory = join2(storePath, "workspaces");
12531
+ }
12532
+ async create(input) {
12533
+ try {
12534
+ const id = randomUUID();
12535
+ const updatedAt = new Date;
12536
+ const targetPath = this.memoryPath(id, input.workspace);
12537
+ await this.writeFileAtomically(targetPath, input.content, updatedAt);
12538
+ return this.readRecord({ path: targetPath, workspace: input.workspace });
12539
+ } catch (error2) {
12540
+ throw asPersistenceError("Failed to save memory.", error2);
12541
+ }
12542
+ }
12543
+ async get(id) {
12544
+ try {
12545
+ const located = await this.findMemoryFile(id);
12546
+ if (!located) {
12547
+ return;
12548
+ }
12549
+ return this.readRecord(located);
12550
+ } catch (error2) {
12551
+ throw asPersistenceError("Failed to find memory.", error2);
12552
+ }
12553
+ }
12554
+ async list(options) {
12555
+ try {
12556
+ const offset = options.offset ?? 0;
12557
+ const limit = options.limit ?? DEFAULT_LIST_LIMIT;
12558
+ const targets = await this.resolveListTargets(options);
12559
+ const groups = await Promise.all(targets.map((target) => this.readDirectoryRecords(target)));
12560
+ const items = groups.flat().sort((left, right) => right.updatedAt.getTime() - left.updatedAt.getTime() || left.id.localeCompare(right.id));
12561
+ const pageItems = items.slice(offset, offset + limit);
12562
+ return {
12563
+ items: pageItems,
12564
+ hasMore: offset + limit < items.length
12565
+ };
12566
+ } catch (error2) {
12567
+ throw asPersistenceError("Failed to list memories.", error2);
12568
+ }
12569
+ }
12570
+ async update(input) {
12571
+ const existing = await this.get(input.id);
12572
+ if (!existing) {
12573
+ throw new NotFoundError(`Memory not found: ${input.id}`);
12574
+ }
12575
+ const nextContent = input.content ?? existing.content;
12576
+ const nextWorkspace = input.workspace === undefined ? existing.workspace : input.workspace ?? undefined;
12577
+ if (nextContent === existing.content && nextWorkspace === existing.workspace) {
12578
+ return existing;
12579
+ }
12580
+ const currentPath = this.memoryPath(existing.id, existing.workspace);
12581
+ const targetPath = this.memoryPath(existing.id, nextWorkspace);
12582
+ const updatedAt = new Date;
12583
+ try {
12584
+ await this.writeFileAtomically(targetPath, nextContent, updatedAt);
12585
+ if (targetPath !== currentPath) {
12586
+ await unlink(currentPath);
12587
+ await this.cleanupWorkspaceDirectory(existing.workspace);
12588
+ }
12589
+ return this.readRecord({ path: targetPath, workspace: nextWorkspace });
12590
+ } catch (error2) {
12591
+ throw asPersistenceError("Failed to update memory.", error2);
12592
+ }
12593
+ }
12594
+ async delete(input) {
12595
+ const located = await this.findMemoryFile(input.id);
12596
+ if (!located) {
12597
+ throw new NotFoundError(`Memory not found: ${input.id}`);
12598
+ }
12599
+ try {
12600
+ await unlink(located.path);
12601
+ await this.cleanupWorkspaceDirectory(located.workspace);
12602
+ } catch (error2) {
12603
+ throw asPersistenceError("Failed to delete memory.", error2);
12604
+ }
12605
+ }
12606
+ async listWorkspaces() {
12607
+ try {
12608
+ return (await this.listWorkspaceTargets()).map((target) => target.workspace).sort((left, right) => left.localeCompare(right));
12609
+ } catch (error2) {
12610
+ throw asPersistenceError("Failed to list workspaces.", error2);
12611
+ }
12612
+ }
12613
+ async resolveListTargets(options) {
12614
+ if (options.workspace && options.global) {
12615
+ return [
12616
+ { path: this.globalsDirectory },
12617
+ { path: this.workspaceDirectory(options.workspace), workspace: options.workspace }
12618
+ ];
12619
+ }
12620
+ if (options.workspace) {
12621
+ return [{ path: this.workspaceDirectory(options.workspace), workspace: options.workspace }];
12622
+ }
12623
+ if (options.global) {
12624
+ return [{ path: this.globalsDirectory }];
12625
+ }
12626
+ return [{ path: this.globalsDirectory }, ...await this.listWorkspaceTargets()];
12627
+ }
12628
+ async readDirectoryRecords(target) {
12629
+ const entries = await readDirectory(target.path);
12630
+ const memoryFiles = entries.filter((entry) => entry.isFile() && entry.name.endsWith(MARKDOWN_EXTENSION));
12631
+ return Promise.all(memoryFiles.map(async (entry) => this.readRecord({
12632
+ path: join2(target.path, entry.name),
12633
+ workspace: target.workspace
12634
+ })));
12635
+ }
12636
+ async findMemoryFile(id) {
12637
+ const globalPath = this.memoryPath(id, undefined);
12638
+ if (await pathExists(globalPath)) {
12639
+ return { path: globalPath };
12640
+ }
12641
+ for (const target of await this.listWorkspaceTargets()) {
12642
+ const filePath = join2(target.path, `${id}${MARKDOWN_EXTENSION}`);
12643
+ if (await pathExists(filePath)) {
12644
+ return { path: filePath, workspace: target.workspace };
12645
+ }
12646
+ }
12647
+ return;
12648
+ }
12649
+ async listWorkspaceTargets() {
12650
+ const entries = await readDirectory(this.workspacesDirectory);
12651
+ return entries.filter((entry) => entry.isDirectory()).map((entry) => ({
12652
+ path: join2(this.workspacesDirectory, entry.name),
12653
+ workspace: decodeWorkspaceSegment(entry.name)
12654
+ }));
12655
+ }
12656
+ async readRecord(located) {
12657
+ const [content, updatedAt] = await Promise.all([readFile(located.path, "utf8"), this.readUpdatedAt(located.path)]);
12658
+ return {
12659
+ id: basename(located.path, MARKDOWN_EXTENSION),
12660
+ content,
12661
+ workspace: located.workspace,
12662
+ updatedAt
12663
+ };
12664
+ }
12665
+ async readUpdatedAt(filePath) {
12666
+ const fileStats = await stat(filePath);
12667
+ return fileStats.mtime;
12668
+ }
12669
+ memoryPath(id, workspace) {
12670
+ return join2(workspace ? this.workspaceDirectory(workspace) : this.globalsDirectory, `${id}${MARKDOWN_EXTENSION}`);
12671
+ }
12672
+ workspaceDirectory(workspace) {
12673
+ return join2(this.workspacesDirectory, encodeWorkspaceSegment(workspace));
12674
+ }
12675
+ async writeFileAtomically(filePath, content, updatedAt) {
12676
+ const directoryPath = dirname(filePath);
12677
+ await mkdir(directoryPath, { recursive: true });
12678
+ const tempPath = join2(directoryPath, `.${basename(filePath)}.${randomUUID()}.tmp`);
12679
+ try {
12680
+ await writeFile(tempPath, content, "utf8");
12681
+ await rename(tempPath, filePath);
12682
+ await utimes(filePath, updatedAt, updatedAt);
12683
+ } catch (error2) {
12684
+ await rm(tempPath, { force: true });
12685
+ throw error2;
12686
+ }
12687
+ }
12688
+ async cleanupWorkspaceDirectory(workspace) {
12689
+ if (!workspace) {
12690
+ return;
12691
+ }
12692
+ const directoryPath = this.workspaceDirectory(workspace);
12693
+ const entries = await readDirectory(directoryPath);
12694
+ if (entries.length === 0) {
12695
+ await rm(directoryPath, { recursive: true, force: true });
12696
+ }
12697
+ }
12698
+ }
12699
+ function encodeWorkspaceSegment(workspace) {
12700
+ return encodeURIComponent(workspace);
12701
+ }
12702
+ function decodeWorkspaceSegment(segment) {
12703
+ return decodeURIComponent(segment);
12704
+ }
12705
+ async function pathExists(path) {
12706
+ try {
12707
+ await access(path);
12708
+ return true;
12709
+ } catch {
12710
+ return false;
12711
+ }
12712
+ }
12713
+ async function readDirectory(path) {
12714
+ try {
12715
+ return await readdir(path, { withFileTypes: true });
12716
+ } catch (error2) {
12717
+ if (isMissingPathError(error2)) {
12718
+ return [];
12719
+ }
12720
+ throw error2;
12721
+ }
12722
+ }
12723
+ function isMissingPathError(error2) {
12724
+ return error2 instanceof Error && "code" in error2 && error2.code === "ENOENT";
12725
+ }
12726
+ function asPersistenceError(message, error2) {
12727
+ if (error2 instanceof NotFoundError || error2 instanceof PersistenceError) {
12728
+ return error2;
12729
+ }
12730
+ return new PersistenceError(message, { cause: error2 });
12731
+ }
12494
12732
  // node_modules/zod/v3/helpers/util.js
12495
12733
  var util;
12496
12734
  (function(util2) {
@@ -17974,6 +18212,10 @@ class Protocol {
17974
18212
  this._progressHandlers.clear();
17975
18213
  this._taskProgressTokens.clear();
17976
18214
  this._pendingDebouncedNotifications.clear();
18215
+ for (const info of this._timeoutInfo.values()) {
18216
+ clearTimeout(info.timeoutId);
18217
+ }
18218
+ this._timeoutInfo.clear();
17977
18219
  for (const controller of this._requestHandlerAbortControllers.values()) {
17978
18220
  controller.abort();
17979
18221
  }
@@ -18104,7 +18346,9 @@ class Protocol {
18104
18346
  await capturedTransport?.send(errorResponse);
18105
18347
  }
18106
18348
  }).catch((error2) => this._onerror(new Error(`Failed to send response: ${error2}`))).finally(() => {
18107
- this._requestHandlerAbortControllers.delete(request.id);
18349
+ if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
18350
+ this._requestHandlerAbortControllers.delete(request.id);
18351
+ }
18108
18352
  });
18109
18353
  }
18110
18354
  _onprogress(notification) {
@@ -19762,6 +20006,9 @@ class McpServer {
19762
20006
  annotations = rest.shift();
19763
20007
  }
19764
20008
  } else if (typeof firstArg === "object" && firstArg !== null) {
20009
+ if (Object.values(firstArg).some((v) => typeof v === "object" && v !== null)) {
20010
+ throw new Error(`Tool ${name} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);
20011
+ }
19765
20012
  annotations = rest.shift();
19766
20013
  }
19767
20014
  }
@@ -19854,6 +20101,9 @@ function getZodSchemaObject(schema) {
19854
20101
  if (isZodRawShapeCompat(schema)) {
19855
20102
  return objectFromShape(schema);
19856
20103
  }
20104
+ if (!isZodSchemaInstance(schema)) {
20105
+ throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");
20106
+ }
19857
20107
  return schema;
19858
20108
  }
19859
20109
  function promptArgumentsFromSchema(schema) {
@@ -19898,37 +20148,6 @@ var EMPTY_COMPLETION_RESULT = {
19898
20148
  }
19899
20149
  };
19900
20150
 
19901
- // src/errors.ts
19902
- class MemoryError extends Error {
19903
- code;
19904
- constructor(code, message, options) {
19905
- super(message, options);
19906
- this.name = "MemoryError";
19907
- this.code = code;
19908
- }
19909
- }
19910
-
19911
- class ValidationError extends MemoryError {
19912
- constructor(message) {
19913
- super("VALIDATION_ERROR", message);
19914
- this.name = "ValidationError";
19915
- }
19916
- }
19917
-
19918
- class NotFoundError extends MemoryError {
19919
- constructor(message) {
19920
- super("NOT_FOUND", message);
19921
- this.name = "NotFoundError";
19922
- }
19923
- }
19924
-
19925
- class PersistenceError extends MemoryError {
19926
- constructor(message, options) {
19927
- super("PERSISTENCE_ERROR", message, options);
19928
- this.name = "PersistenceError";
19929
- }
19930
- }
19931
-
19932
20151
  // src/mcp/tools/shared.ts
19933
20152
  function toMcpError(error2) {
19934
20153
  if (error2 instanceof McpError) {
@@ -19944,6 +20163,27 @@ function toMcpError(error2) {
19944
20163
  return new McpError(ErrorCode.InternalError, message);
19945
20164
  }
19946
20165
  var escapeXml = (value) => value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
20166
+ function toMemoryXml(record3, options) {
20167
+ const scopeAttribute = getMemoryScopeAttribute(record3, options?.skipWorkspaceIfEquals);
20168
+ const attributes = [
20169
+ `id="${escapeXml(record3.id)}"`,
20170
+ `updated_at="${record3.updatedAt.toISOString()}"`,
20171
+ scopeAttribute,
20172
+ options?.deleted ? 'deleted="true"' : undefined
20173
+ ].filter((value) => value).join(" ");
20174
+ return `<memory ${attributes}>
20175
+ ${escapeXml(record3.content)}
20176
+ </memory>`;
20177
+ }
20178
+ function getMemoryScopeAttribute(record3, skipWorkspaceIfEquals) {
20179
+ if (record3.workspace === undefined) {
20180
+ return 'global="true"';
20181
+ }
20182
+ if (record3.workspace === skipWorkspaceIfEquals) {
20183
+ return;
20184
+ }
20185
+ return `workspace="${escapeXml(record3.workspace)}"`;
20186
+ }
19947
20187
 
19948
20188
  // src/mcp/tools/forget.ts
19949
20189
  var forgetInputSchema = {
@@ -19957,13 +20197,13 @@ function registerForgetTool(server, memory) {
19957
20197
  idempotentHint: true,
19958
20198
  openWorldHint: false
19959
20199
  },
19960
- description: 'Delete a memory that is wrong or obsolete. Use after `review` when you have the memory id. Use `revise` instead if the fact should remain with corrected wording. Returns `<memory id="..." deleted="true" />`.',
20200
+ description: 'Delete a memory that is wrong or obsolete. Use after `review` when you have the memory id. Use `revise` instead if the fact should remain with corrected wording. Returns the deleted memory as `<memory ... deleted="true">...</memory>`.',
19961
20201
  inputSchema: forgetInputSchema
19962
20202
  }, async ({ id }) => {
19963
20203
  try {
19964
- await memory.delete({ id });
20204
+ const deletedMemory = await memory.delete({ id });
19965
20205
  return {
19966
- content: [{ type: "text", text: `<memory id="${id.trim()}" deleted="true" />` }]
20206
+ content: [{ type: "text", text: toMemoryXml(deletedMemory, { deleted: true }) }]
19967
20207
  };
19968
20208
  } catch (error2) {
19969
20209
  throw toMcpError(error2);
@@ -19984,7 +20224,7 @@ function registerRememberTool(server, memory) {
19984
20224
  idempotentHint: false,
19985
20225
  openWorldHint: false
19986
20226
  },
19987
- description: 'Save one new durable fact. Use for stable preferences, reusable decisions, and project context not obvious from code or git history. If the fact already exists, use `revise` instead. Returns `<memory id="..." />`.',
20227
+ description: "Save one new durable fact. Use for stable preferences, reusable decisions, and project context not obvious from code or git history. If the fact already exists, use `revise` instead. Returns the saved memory as `<memory ...>...</memory>`.",
19988
20228
  inputSchema: rememberInputSchema
19989
20229
  }, async ({ content, workspace }) => {
19990
20230
  try {
@@ -19993,7 +20233,7 @@ function registerRememberTool(server, memory) {
19993
20233
  workspace
19994
20234
  });
19995
20235
  return {
19996
- content: [{ type: "text", text: `<memory id="${savedMemory.id}" />` }]
20236
+ content: [{ type: "text", text: toMemoryXml(savedMemory) }]
19997
20237
  };
19998
20238
  } catch (error2) {
19999
20239
  throw toMcpError(error2);
@@ -20007,13 +20247,6 @@ var reviewInputSchema = {
20007
20247
  workspace: string2().describe("Current working directory for project-scoped listing."),
20008
20248
  page: number2().int().min(0).optional().describe("Zero-based page number. Defaults to 0.")
20009
20249
  };
20010
- function toMemoryXml(record3, workspace) {
20011
- const global2 = record3.workspace !== workspace ? ' global="true"' : "";
20012
- const content = escapeXml(record3.content);
20013
- return `<memory id="${record3.id}"${global2} updated_at="${record3.updatedAt.toISOString()}">
20014
- ${content}
20015
- </memory>`;
20016
- }
20017
20250
  function registerReviewTool(server, memory) {
20018
20251
  server.registerTool("review", {
20019
20252
  annotations: {
@@ -20038,7 +20271,7 @@ function registerReviewTool(server, memory) {
20038
20271
  };
20039
20272
  }
20040
20273
  const escapedWorkspace = escapeXml(workspace);
20041
- const memories = result.items.map((item) => toMemoryXml(item, workspace)).join(`
20274
+ const memories = result.items.map((item) => toMemoryXml(item, { skipWorkspaceIfEquals: workspace })).join(`
20042
20275
  `);
20043
20276
  const text = `<memories workspace="${escapedWorkspace}" has_more="${result.hasMore}">
20044
20277
  ${memories}
@@ -20055,7 +20288,8 @@ ${memories}
20055
20288
  // src/mcp/tools/revise.ts
20056
20289
  var reviseInputSchema = {
20057
20290
  id: string2().describe("Memory id to update. Use an id returned by `review`."),
20058
- content: string2().describe("Corrected replacement text for that memory.")
20291
+ content: string2().optional().describe("Corrected replacement text for that memory. Omit to keep the current content."),
20292
+ global: boolean2().optional().describe("Set to true to move a project-scoped memory to global scope.")
20059
20293
  };
20060
20294
  function registerReviseTool(server, memory) {
20061
20295
  server.registerTool("revise", {
@@ -20065,16 +20299,23 @@ function registerReviseTool(server, memory) {
20065
20299
  idempotentHint: false,
20066
20300
  openWorldHint: false
20067
20301
  },
20068
- description: 'Update one existing memory when the same fact still applies but its wording or details changed. Use after `review` when you already have the memory id. Returns `<memory id="..." updated_at="..." />`.',
20302
+ description: "Update one existing memory when the same fact still applies but its wording changed, or when a project-scoped memory should become global. Use after `review` when you already have the memory id. Omit fields you do not want to change. Returns the revised memory as `<memory ...>...</memory>`.",
20069
20303
  inputSchema: reviseInputSchema
20070
- }, async ({ id, content }) => {
20304
+ }, async ({ id, content, global }) => {
20071
20305
  try {
20072
- const revisedMemory = await memory.update({ id, content });
20306
+ if (content === undefined && global !== true) {
20307
+ throw new ValidationError("Provide at least one field to revise.");
20308
+ }
20309
+ const revisedMemory = await memory.update({
20310
+ id,
20311
+ content,
20312
+ workspace: global === true ? null : undefined
20313
+ });
20073
20314
  return {
20074
20315
  content: [
20075
20316
  {
20076
20317
  type: "text",
20077
- text: `<memory id="${revisedMemory.id}" updated_at="${revisedMemory.updatedAt.toISOString()}" />`
20318
+ text: toMemoryXml(revisedMemory)
20078
20319
  }
20079
20320
  ]
20080
20321
  };
@@ -20088,7 +20329,7 @@ function registerReviseTool(server, memory) {
20088
20329
  var SERVER_INSTRUCTIONS = [
20089
20330
  "Durable memory for stable preferences, corrections, reusable decisions, and project context not obvious from code or git history.",
20090
20331
  "Workflow: (1) Call `review` with the current workspace at conversation start -- this loads workspace and global memories into context.",
20091
- "(2) During the session, call `remember` to save a new fact, `revise` to correct an existing one, or `forget` to remove one that is wrong or obsolete.",
20332
+ "(2) During the session, call `remember` to save a new fact, `revise` to correct content or promote a project-scoped memory to global scope, and call `forget` to remove one that is wrong or obsolete.",
20092
20333
  "Always check loaded memories before calling `remember` to avoid duplicates -- use `revise` instead when the fact already exists.",
20093
20334
  "Pass workspace on `remember` for project-scoped memory. Omit it only for facts that apply across all projects.",
20094
20335
  "Never store secrets, temporary task state, or facts obvious from current code or git history."
@@ -20108,14 +20349,14 @@ function createMcpServer(memory, version3) {
20108
20349
  }
20109
20350
 
20110
20351
  // src/memory-service.ts
20111
- var DEFAULT_LIST_LIMIT = 15;
20352
+ var DEFAULT_LIST_LIMIT2 = 15;
20112
20353
  var MAX_LIST_LIMIT = 100;
20113
20354
 
20114
20355
  class MemoryService {
20115
20356
  repository;
20116
20357
  workspaceResolver;
20117
- constructor(repository, workspaceResolver) {
20118
- this.repository = repository;
20358
+ constructor(repository2, workspaceResolver) {
20359
+ this.repository = repository2;
20119
20360
  this.workspaceResolver = workspaceResolver;
20120
20361
  }
20121
20362
  async create(input) {
@@ -20123,27 +20364,31 @@ class MemoryService {
20123
20364
  if (!content) {
20124
20365
  throw new ValidationError("Memory content is required.");
20125
20366
  }
20126
- const workspace = await this.workspaceResolver.resolve(input.workspace);
20367
+ const workspace = await this.normalizeWorkspaceInput(input.workspace);
20127
20368
  return this.repository.create({ content, workspace });
20128
20369
  }
20129
20370
  async update(input) {
20130
- const content = input.content.trim();
20131
- if (!content)
20132
- throw new ValidationError("Memory content is required.");
20133
- return this.repository.update({ id: input.id, content });
20371
+ const content = this.normalizeUpdateContent(input.content);
20372
+ const workspace = await this.normalizeUpdateWorkspace(input.workspace);
20373
+ return this.repository.update({ id: input.id, content, workspace });
20134
20374
  }
20135
20375
  async delete(input) {
20136
20376
  const id = input.id.trim();
20137
20377
  if (!id)
20138
20378
  throw new ValidationError("Memory id is required.");
20139
- return this.repository.delete({ id });
20379
+ const existingMemory = await this.repository.get(id);
20380
+ if (!existingMemory) {
20381
+ throw new NotFoundError(`Memory not found: ${id}`);
20382
+ }
20383
+ await this.repository.delete({ id });
20384
+ return existingMemory;
20140
20385
  }
20141
20386
  async get(id) {
20142
20387
  return this.repository.get(id);
20143
20388
  }
20144
20389
  async list(input) {
20145
- const queryWorkspace = normalizeOptionalString(input.workspace);
20146
- const workspace = await this.workspaceResolver.resolve(input.workspace);
20390
+ const queryWorkspace = input.workspace?.trim() || undefined;
20391
+ const workspace = queryWorkspace ? await this.workspaceResolver.resolve(queryWorkspace) : undefined;
20147
20392
  const page = await this.repository.list({
20148
20393
  workspace,
20149
20394
  global: input.global,
@@ -20158,20 +20403,42 @@ class MemoryService {
20158
20403
  async listWorkspaces() {
20159
20404
  return this.repository.listWorkspaces();
20160
20405
  }
20406
+ normalizeUpdateContent(value) {
20407
+ if (value === undefined) {
20408
+ return;
20409
+ }
20410
+ const trimmed = value.trim();
20411
+ if (!trimmed) {
20412
+ throw new ValidationError("Memory content is required.");
20413
+ }
20414
+ return trimmed;
20415
+ }
20416
+ async normalizeUpdateWorkspace(value) {
20417
+ if (value === undefined || value === null) {
20418
+ return value;
20419
+ }
20420
+ return this.normalizeWorkspaceInput(value);
20421
+ }
20422
+ async normalizeWorkspaceInput(value) {
20423
+ if (value === undefined) {
20424
+ return;
20425
+ }
20426
+ const trimmed = value.trim();
20427
+ if (!trimmed) {
20428
+ throw new ValidationError("Workspace is required.");
20429
+ }
20430
+ return this.workspaceResolver.resolve(trimmed);
20431
+ }
20161
20432
  }
20162
20433
  function normalizeOffset(value) {
20163
20434
  return Number.isInteger(value) && value && value > 0 ? value : 0;
20164
20435
  }
20165
20436
  function normalizeListLimit(value) {
20166
20437
  if (!Number.isInteger(value) || value === undefined) {
20167
- return DEFAULT_LIST_LIMIT;
20438
+ return DEFAULT_LIST_LIMIT2;
20168
20439
  }
20169
20440
  return Math.min(Math.max(value, 1), MAX_LIST_LIMIT);
20170
20441
  }
20171
- function normalizeOptionalString(value) {
20172
- const trimmed = value?.trim();
20173
- return trimmed ? trimmed : undefined;
20174
- }
20175
20442
  function remapWorkspace(record3, canonicalWorkspace, queryWorkspace) {
20176
20443
  if (record3.workspace !== canonicalWorkspace) {
20177
20444
  return record3;
@@ -20179,3818 +20446,58 @@ function remapWorkspace(record3, canonicalWorkspace, queryWorkspace) {
20179
20446
  return { ...record3, workspace: queryWorkspace };
20180
20447
  }
20181
20448
 
20182
- // src/sqlite/db.ts
20183
- import { mkdirSync } from "node:fs";
20184
- import { dirname } from "node:path";
20185
- import Database from "better-sqlite3";
20186
-
20187
- // src/sqlite/memory-schema.ts
20188
- function createMemoriesTable(database) {
20189
- database.exec(`
20190
- CREATE TABLE IF NOT EXISTS memories (
20191
- id TEXT PRIMARY KEY,
20192
- content TEXT NOT NULL,
20193
- workspace TEXT,
20194
- created_at INTEGER NOT NULL,
20195
- updated_at INTEGER NOT NULL
20196
- );
20197
- `);
20198
- }
20199
- function createMemoryIndexes(database) {
20200
- database.exec(`
20201
- CREATE INDEX IF NOT EXISTS idx_memories_updated_at ON memories(updated_at);
20202
- CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace);
20203
- `);
20204
- }
20205
- function createMemorySearchArtifacts(database, rebuild = false) {
20206
- database.exec(`
20207
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
20208
- content,
20209
- content = 'memories',
20210
- content_rowid = 'rowid',
20211
- tokenize = 'porter unicode61'
20212
- );
20213
-
20214
- CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
20215
- INSERT INTO memories_fts(rowid, content) VALUES (new.rowid, new.content);
20216
- END;
20217
-
20218
- CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
20219
- INSERT INTO memories_fts(memories_fts, rowid, content)
20220
- VALUES ('delete', old.rowid, old.content);
20221
- END;
20222
-
20223
- CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
20224
- INSERT INTO memories_fts(memories_fts, rowid, content)
20225
- VALUES ('delete', old.rowid, old.content);
20226
- INSERT INTO memories_fts(rowid, content) VALUES (new.rowid, new.content);
20227
- END;
20228
- `);
20229
- if (rebuild) {
20230
- database.exec("INSERT INTO memories_fts(memories_fts) VALUES ('rebuild')");
20231
- }
20232
- }
20233
- function dropMemorySearchArtifacts(database) {
20234
- database.exec(`
20235
- DROP TRIGGER IF EXISTS memories_ai;
20236
- DROP TRIGGER IF EXISTS memories_ad;
20237
- DROP TRIGGER IF EXISTS memories_au;
20238
- DROP TABLE IF EXISTS memories_fts;
20239
- `);
20240
- }
20241
-
20242
- // src/sqlite/migrations/001-create-memory-schema.ts
20243
- var createMemorySchemaMigration = {
20244
- version: 1,
20245
- async up(database) {
20246
- createMemoriesTable(database);
20247
- createMemoryIndexes(database);
20248
- createMemorySearchArtifacts(database);
20249
- }
20250
- };
20251
-
20252
- // src/sqlite/migrations/002-add-memory-embedding.ts
20253
- function createAddMemoryEmbeddingMigration() {
20254
- return {
20255
- version: 2,
20256
- async up(database) {
20257
- database.exec("ALTER TABLE memories ADD COLUMN embedding BLOB");
20258
- dropMemorySearchArtifacts(database);
20259
- database.exec("ALTER TABLE memories RENAME TO memories_old");
20260
- database.exec(`
20261
- CREATE TABLE IF NOT EXISTS memories (
20262
- id TEXT PRIMARY KEY,
20263
- content TEXT NOT NULL,
20264
- workspace TEXT,
20265
- embedding BLOB NOT NULL,
20266
- created_at INTEGER NOT NULL,
20267
- updated_at INTEGER NOT NULL
20268
- );
20269
- `);
20270
- database.exec(`
20271
- INSERT INTO memories (id, content, workspace, embedding, created_at, updated_at)
20272
- SELECT id, content, workspace, COALESCE(embedding, X'00000000'), created_at, updated_at
20273
- FROM memories_old
20274
- `);
20275
- database.exec("DROP TABLE memories_old");
20276
- createMemoryIndexes(database);
20277
- createMemorySearchArtifacts(database, true);
20278
- }
20279
- };
20280
- }
20281
-
20282
- // src/sqlite/migrations/003-normalize-workspaces.ts
20283
- function createNormalizeWorkspaceMigration(workspaceResolver) {
20449
+ // src/workspace-resolver.ts
20450
+ import { execFile } from "node:child_process";
20451
+ import { basename as basename2, dirname as dirname2 } from "node:path";
20452
+ import { promisify } from "node:util";
20453
+ var execFileAsync = promisify(execFile);
20454
+ function createGitWorkspaceResolver(options = {}) {
20455
+ const getGitCommonDir = options.getGitCommonDir ?? defaultGetGitCommonDir;
20456
+ const cache = new Map;
20284
20457
  return {
20285
- version: 3,
20286
- async up(database) {
20287
- const rows = database.prepare("SELECT DISTINCT workspace FROM memories WHERE workspace IS NOT NULL ORDER BY workspace").all();
20288
- const updateStatement = database.prepare("UPDATE memories SET workspace = ? WHERE workspace = ?");
20289
- for (const row of rows) {
20290
- const normalizedWorkspace = await workspaceResolver.resolve(row.workspace);
20291
- if (!normalizedWorkspace || normalizedWorkspace === row.workspace) {
20292
- continue;
20293
- }
20294
- updateStatement.run(normalizedWorkspace, row.workspace);
20458
+ async resolve(workspace) {
20459
+ const trimmed = workspace.trim();
20460
+ if (!trimmed) {
20461
+ throw new ValidationError("Workspace is required.");
20462
+ }
20463
+ const cached2 = cache.get(trimmed);
20464
+ if (cached2) {
20465
+ return cached2;
20295
20466
  }
20467
+ const pending = resolveWorkspace(trimmed, getGitCommonDir);
20468
+ cache.set(trimmed, pending);
20469
+ return pending;
20296
20470
  }
20297
20471
  };
20298
20472
  }
20299
-
20300
- // src/sqlite/migrations/004-remove-memory-embedding.ts
20301
- var removeMemoryEmbeddingMigration = {
20302
- version: 4,
20303
- async up(database) {
20304
- dropMemorySearchArtifacts(database);
20305
- database.exec("ALTER TABLE memories RENAME TO memories_old");
20306
- createMemoriesTable(database);
20307
- database.exec(`
20308
- INSERT INTO memories (id, content, workspace, created_at, updated_at)
20309
- SELECT id, content, workspace, created_at, updated_at
20310
- FROM memories_old
20311
- `);
20312
- database.exec("DROP TABLE memories_old");
20313
- createMemoryIndexes(database);
20314
- createMemorySearchArtifacts(database, true);
20315
- }
20316
- };
20317
-
20318
- // src/sqlite/migrations/index.ts
20319
- function createMemoryMigrations(options) {
20320
- return [
20321
- createMemorySchemaMigration,
20322
- createAddMemoryEmbeddingMigration(),
20323
- createNormalizeWorkspaceMigration(options.workspaceResolver),
20324
- removeMemoryEmbeddingMigration
20325
- ];
20326
- }
20327
-
20328
- // src/sqlite/db.ts
20329
- var PRAGMA_STATEMENTS = [
20330
- "journal_mode = WAL",
20331
- "synchronous = NORMAL",
20332
- "foreign_keys = ON",
20333
- "busy_timeout = 5000"
20334
- ];
20335
- async function openMemoryDatabase(databasePath, options) {
20336
- let database;
20473
+ async function resolveWorkspace(workspace, getGitCommonDir) {
20337
20474
  try {
20338
- mkdirSync(dirname(databasePath), { recursive: true });
20339
- database = new Database(databasePath);
20340
- await initializeMemoryDatabase(database, createMemoryMigrations(options));
20341
- return database;
20342
- } catch (error2) {
20343
- database?.close();
20344
- if (error2 instanceof PersistenceError) {
20345
- throw error2;
20475
+ const gitCommonDir = (await getGitCommonDir(workspace)).trim();
20476
+ if (basename2(gitCommonDir) !== ".git") {
20477
+ return workspace;
20346
20478
  }
20347
- throw new PersistenceError("Failed to initialize the SQLite database.", {
20348
- cause: error2
20349
- });
20479
+ return dirname2(gitCommonDir);
20480
+ } catch {
20481
+ return workspace;
20350
20482
  }
20351
20483
  }
20352
- async function initializeMemoryDatabase(database, migrations) {
20353
- try {
20354
- applyPragmas(database);
20355
- await runSqliteMigrations(database, migrations);
20356
- } catch (error2) {
20357
- throw new PersistenceError("Failed to initialize the SQLite database.", {
20358
- cause: error2
20359
- });
20360
- }
20361
- }
20362
- async function runSqliteMigrations(database, migrations) {
20363
- validateMigrations(migrations);
20364
- let currentVersion = getUserVersion(database);
20365
- for (const migration of migrations) {
20366
- if (migration.version <= currentVersion) {
20367
- continue;
20368
- }
20369
- database.exec("BEGIN");
20370
- try {
20371
- await migration.up(database);
20372
- setUserVersion(database, migration.version);
20373
- database.exec("COMMIT");
20374
- currentVersion = migration.version;
20375
- } catch (error2) {
20376
- try {
20377
- database.exec("ROLLBACK");
20378
- } catch {}
20379
- throw error2;
20380
- }
20381
- }
20382
- }
20383
- function applyPragmas(database) {
20384
- if (database.pragma) {
20385
- for (const statement of PRAGMA_STATEMENTS) {
20386
- database.pragma(statement);
20387
- }
20388
- return;
20389
- }
20390
- for (const statement of PRAGMA_STATEMENTS) {
20391
- database.exec(`PRAGMA ${statement}`);
20392
- }
20393
- }
20394
- function getUserVersion(database) {
20395
- const rows = database.prepare("PRAGMA user_version").all();
20396
- return rows[0]?.user_version ?? 0;
20397
- }
20398
- function setUserVersion(database, version3) {
20399
- database.exec(`PRAGMA user_version = ${version3}`);
20400
- }
20401
- function validateMigrations(migrations) {
20402
- let previousVersion = 0;
20403
- for (const migration of migrations) {
20404
- if (!Number.isInteger(migration.version) || migration.version <= previousVersion) {
20405
- throw new Error("SQLite migrations must use strictly increasing versions.");
20406
- }
20407
- previousVersion = migration.version;
20408
- }
20409
- }
20410
- // src/sqlite/repository.ts
20411
- import { randomUUID } from "node:crypto";
20412
- var DEFAULT_LIST_LIMIT2 = 15;
20413
-
20414
- class SqliteMemoryRepository {
20415
- database;
20416
- insertStatement;
20417
- getStatement;
20418
- updateStatement;
20419
- deleteStatement;
20420
- listWorkspacesStatement;
20421
- constructor(database) {
20422
- this.database = database;
20423
- this.insertStatement = database.prepare(`
20424
- INSERT INTO memories (id, content, workspace, created_at, updated_at)
20425
- VALUES (?, ?, ?, ?, ?)
20426
- `);
20427
- this.getStatement = database.prepare("SELECT id, content, workspace, created_at, updated_at FROM memories WHERE id = ?");
20428
- this.updateStatement = database.prepare("UPDATE memories SET content = ?, updated_at = ? WHERE id = ?");
20429
- this.deleteStatement = database.prepare("DELETE FROM memories WHERE id = ?");
20430
- this.listWorkspacesStatement = database.prepare("SELECT DISTINCT workspace FROM memories WHERE workspace IS NOT NULL ORDER BY workspace");
20431
- }
20432
- async create(input) {
20433
- try {
20434
- const now = new Date;
20435
- const memory = {
20436
- id: randomUUID(),
20437
- content: input.content,
20438
- workspace: input.workspace,
20439
- createdAt: now,
20440
- updatedAt: now
20441
- };
20442
- this.insertStatement.run(memory.id, memory.content, memory.workspace, memory.createdAt.getTime(), memory.updatedAt.getTime());
20443
- return memory;
20444
- } catch (error2) {
20445
- throw new PersistenceError("Failed to save memory.", { cause: error2 });
20446
- }
20447
- }
20448
- async get(id) {
20449
- try {
20450
- const rows = this.getStatement.all(id);
20451
- const row = rows[0];
20452
- return row ? toMemoryRecord(row) : undefined;
20453
- } catch (error2) {
20454
- throw new PersistenceError("Failed to find memory.", { cause: error2 });
20455
- }
20456
- }
20457
- async list(options) {
20458
- try {
20459
- const whereClauses = [];
20460
- const params = [];
20461
- const offset = options.offset ?? 0;
20462
- const limit = options.limit ?? DEFAULT_LIST_LIMIT2;
20463
- if (options.workspace && options.global) {
20464
- whereClauses.push("(workspace = ? OR workspace IS NULL)");
20465
- params.push(options.workspace);
20466
- } else if (options.workspace) {
20467
- whereClauses.push("workspace = ?");
20468
- params.push(options.workspace);
20469
- } else if (options.global) {
20470
- whereClauses.push("workspace IS NULL");
20471
- }
20472
- const whereClause = whereClauses.length > 0 ? `WHERE ${whereClauses.join(" AND ")}` : "";
20473
- const queryLimit = limit + 1;
20474
- params.push(queryLimit, offset);
20475
- const statement = this.database.prepare(`
20476
- SELECT id, content, workspace, created_at, updated_at
20477
- FROM memories
20478
- ${whereClause}
20479
- ORDER BY updated_at DESC
20480
- LIMIT ? OFFSET ?
20481
- `);
20482
- const rows = statement.all(...params);
20483
- const hasMore = rows.length > limit;
20484
- const items = (hasMore ? rows.slice(0, limit) : rows).map(toMemoryRecord);
20485
- return { items, hasMore };
20486
- } catch (error2) {
20487
- throw new PersistenceError("Failed to list memories.", { cause: error2 });
20488
- }
20489
- }
20490
- async update(input) {
20491
- let result;
20492
- try {
20493
- const now = Date.now();
20494
- result = this.updateStatement.run(input.content, now, input.id);
20495
- } catch (error2) {
20496
- throw new PersistenceError("Failed to update memory.", { cause: error2 });
20497
- }
20498
- if (result.changes === 0) {
20499
- throw new NotFoundError(`Memory not found: ${input.id}`);
20500
- }
20501
- const memory = await this.get(input.id);
20502
- if (!memory) {
20503
- throw new NotFoundError(`Memory not found after update: ${input.id}`);
20504
- }
20505
- return memory;
20506
- }
20507
- async delete(input) {
20508
- let result;
20509
- try {
20510
- result = this.deleteStatement.run(input.id);
20511
- } catch (error2) {
20512
- throw new PersistenceError("Failed to delete memory.", { cause: error2 });
20513
- }
20514
- if (result.changes === 0) {
20515
- throw new NotFoundError(`Memory not found: ${input.id}`);
20516
- }
20517
- }
20518
- async listWorkspaces() {
20519
- try {
20520
- const rows = this.listWorkspacesStatement.all();
20521
- return rows.map((row) => row.workspace);
20522
- } catch (error2) {
20523
- throw new PersistenceError("Failed to list workspaces.", { cause: error2 });
20524
- }
20525
- }
20526
- }
20527
- var toMemoryRecord = (row) => ({
20528
- id: row.id,
20529
- content: row.content,
20530
- workspace: row.workspace ?? undefined,
20531
- createdAt: new Date(row.created_at),
20532
- updatedAt: new Date(row.updated_at)
20533
- });
20534
- // node_modules/@hono/node-server/dist/index.mjs
20535
- import { createServer as createServerHTTP } from "http";
20536
- import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
20537
- import { Http2ServerRequest } from "http2";
20538
- import { Readable } from "stream";
20539
- import crypto from "crypto";
20540
- var RequestError = class extends Error {
20541
- constructor(message, options) {
20542
- super(message, options);
20543
- this.name = "RequestError";
20544
- }
20545
- };
20546
- var toRequestError = (e) => {
20547
- if (e instanceof RequestError) {
20548
- return e;
20549
- }
20550
- return new RequestError(e.message, { cause: e });
20551
- };
20552
- var GlobalRequest = global.Request;
20553
- var Request2 = class extends GlobalRequest {
20554
- constructor(input, options) {
20555
- if (typeof input === "object" && getRequestCache in input) {
20556
- input = input[getRequestCache]();
20557
- }
20558
- if (typeof options?.body?.getReader !== "undefined") {
20559
- options.duplex ??= "half";
20560
- }
20561
- super(input, options);
20562
- }
20563
- };
20564
- var newHeadersFromIncoming = (incoming) => {
20565
- const headerRecord = [];
20566
- const rawHeaders = incoming.rawHeaders;
20567
- for (let i = 0;i < rawHeaders.length; i += 2) {
20568
- const { [i]: key, [i + 1]: value } = rawHeaders;
20569
- if (key.charCodeAt(0) !== 58) {
20570
- headerRecord.push([key, value]);
20571
- }
20572
- }
20573
- return new Headers(headerRecord);
20574
- };
20575
- var wrapBodyStream = Symbol("wrapBodyStream");
20576
- var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
20577
- const init = {
20578
- method,
20579
- headers,
20580
- signal: abortController.signal
20581
- };
20582
- if (method === "TRACE") {
20583
- init.method = "GET";
20584
- const req = new Request2(url, init);
20585
- Object.defineProperty(req, "method", {
20586
- get() {
20587
- return "TRACE";
20588
- }
20589
- });
20590
- return req;
20591
- }
20592
- if (!(method === "GET" || method === "HEAD")) {
20593
- if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
20594
- init.body = new ReadableStream({
20595
- start(controller) {
20596
- controller.enqueue(incoming.rawBody);
20597
- controller.close();
20598
- }
20599
- });
20600
- } else if (incoming[wrapBodyStream]) {
20601
- let reader;
20602
- init.body = new ReadableStream({
20603
- async pull(controller) {
20604
- try {
20605
- reader ||= Readable.toWeb(incoming).getReader();
20606
- const { done, value } = await reader.read();
20607
- if (done) {
20608
- controller.close();
20609
- } else {
20610
- controller.enqueue(value);
20611
- }
20612
- } catch (error2) {
20613
- controller.error(error2);
20614
- }
20615
- }
20616
- });
20617
- } else {
20618
- init.body = Readable.toWeb(incoming);
20619
- }
20620
- }
20621
- return new Request2(url, init);
20622
- };
20623
- var getRequestCache = Symbol("getRequestCache");
20624
- var requestCache = Symbol("requestCache");
20625
- var incomingKey = Symbol("incomingKey");
20626
- var urlKey = Symbol("urlKey");
20627
- var headersKey = Symbol("headersKey");
20628
- var abortControllerKey = Symbol("abortControllerKey");
20629
- var getAbortController = Symbol("getAbortController");
20630
- var requestPrototype = {
20631
- get method() {
20632
- return this[incomingKey].method || "GET";
20633
- },
20634
- get url() {
20635
- return this[urlKey];
20636
- },
20637
- get headers() {
20638
- return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
20639
- },
20640
- [getAbortController]() {
20641
- this[getRequestCache]();
20642
- return this[abortControllerKey];
20643
- },
20644
- [getRequestCache]() {
20645
- this[abortControllerKey] ||= new AbortController;
20646
- return this[requestCache] ||= newRequestFromIncoming(this.method, this[urlKey], this.headers, this[incomingKey], this[abortControllerKey]);
20647
- }
20648
- };
20649
- [
20650
- "body",
20651
- "bodyUsed",
20652
- "cache",
20653
- "credentials",
20654
- "destination",
20655
- "integrity",
20656
- "mode",
20657
- "redirect",
20658
- "referrer",
20659
- "referrerPolicy",
20660
- "signal",
20661
- "keepalive"
20662
- ].forEach((k) => {
20663
- Object.defineProperty(requestPrototype, k, {
20664
- get() {
20665
- return this[getRequestCache]()[k];
20666
- }
20667
- });
20668
- });
20669
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
20670
- Object.defineProperty(requestPrototype, k, {
20671
- value: function() {
20672
- return this[getRequestCache]()[k]();
20673
- }
20674
- });
20675
- });
20676
- Object.setPrototypeOf(requestPrototype, Request2.prototype);
20677
- var newRequest = (incoming, defaultHostname) => {
20678
- const req = Object.create(requestPrototype);
20679
- req[incomingKey] = incoming;
20680
- const incomingUrl = incoming.url || "";
20681
- if (incomingUrl[0] !== "/" && (incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
20682
- if (incoming instanceof Http2ServerRequest) {
20683
- throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
20684
- }
20685
- try {
20686
- const url2 = new URL(incomingUrl);
20687
- req[urlKey] = url2.href;
20688
- } catch (e) {
20689
- throw new RequestError("Invalid absolute URL", { cause: e });
20690
- }
20691
- return req;
20692
- }
20693
- const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
20694
- if (!host) {
20695
- throw new RequestError("Missing host header");
20696
- }
20697
- let scheme;
20698
- if (incoming instanceof Http2ServerRequest) {
20699
- scheme = incoming.scheme;
20700
- if (!(scheme === "http" || scheme === "https")) {
20701
- throw new RequestError("Unsupported scheme");
20702
- }
20703
- } else {
20704
- scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
20705
- }
20706
- const url = new URL(`${scheme}://${host}${incomingUrl}`);
20707
- if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
20708
- throw new RequestError("Invalid host header");
20709
- }
20710
- req[urlKey] = url.href;
20711
- return req;
20712
- };
20713
- var responseCache = Symbol("responseCache");
20714
- var getResponseCache = Symbol("getResponseCache");
20715
- var cacheKey = Symbol("cache");
20716
- var GlobalResponse = global.Response;
20717
- var Response2 = class _Response {
20718
- #body;
20719
- #init;
20720
- [getResponseCache]() {
20721
- delete this[cacheKey];
20722
- return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
20723
- }
20724
- constructor(body, init) {
20725
- let headers;
20726
- this.#body = body;
20727
- if (init instanceof _Response) {
20728
- const cachedGlobalResponse = init[responseCache];
20729
- if (cachedGlobalResponse) {
20730
- this.#init = cachedGlobalResponse;
20731
- this[getResponseCache]();
20732
- return;
20733
- } else {
20734
- this.#init = init.#init;
20735
- headers = new Headers(init.#init.headers);
20736
- }
20737
- } else {
20738
- this.#init = init;
20739
- }
20740
- if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
20741
- this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
20742
- }
20743
- }
20744
- get headers() {
20745
- const cache = this[cacheKey];
20746
- if (cache) {
20747
- if (!(cache[2] instanceof Headers)) {
20748
- cache[2] = new Headers(cache[2] || { "content-type": "text/plain; charset=UTF-8" });
20749
- }
20750
- return cache[2];
20751
- }
20752
- return this[getResponseCache]().headers;
20753
- }
20754
- get status() {
20755
- return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
20756
- }
20757
- get ok() {
20758
- const status = this.status;
20759
- return status >= 200 && status < 300;
20760
- }
20761
- };
20762
- ["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
20763
- Object.defineProperty(Response2.prototype, k, {
20764
- get() {
20765
- return this[getResponseCache]()[k];
20766
- }
20767
- });
20768
- });
20769
- ["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
20770
- Object.defineProperty(Response2.prototype, k, {
20771
- value: function() {
20772
- return this[getResponseCache]()[k]();
20773
- }
20774
- });
20775
- });
20776
- Object.setPrototypeOf(Response2, GlobalResponse);
20777
- Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
20778
- async function readWithoutBlocking(readPromise) {
20779
- return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(undefined))]);
20780
- }
20781
- function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
20782
- const cancel = (error2) => {
20783
- reader.cancel(error2).catch(() => {});
20784
- };
20785
- writable.on("close", cancel);
20786
- writable.on("error", cancel);
20787
- (currentReadPromise ?? reader.read()).then(flow, handleStreamError);
20788
- return reader.closed.finally(() => {
20789
- writable.off("close", cancel);
20790
- writable.off("error", cancel);
20791
- });
20792
- function handleStreamError(error2) {
20793
- if (error2) {
20794
- writable.destroy(error2);
20795
- }
20796
- }
20797
- function onDrain() {
20798
- reader.read().then(flow, handleStreamError);
20799
- }
20800
- function flow({ done, value }) {
20801
- try {
20802
- if (done) {
20803
- writable.end();
20804
- } else if (!writable.write(value)) {
20805
- writable.once("drain", onDrain);
20806
- } else {
20807
- return reader.read().then(flow, handleStreamError);
20808
- }
20809
- } catch (e) {
20810
- handleStreamError(e);
20811
- }
20812
- }
20813
- }
20814
- function writeFromReadableStream(stream, writable) {
20815
- if (stream.locked) {
20816
- throw new TypeError("ReadableStream is locked.");
20817
- } else if (writable.destroyed) {
20818
- return;
20819
- }
20820
- return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
20821
- }
20822
- var buildOutgoingHttpHeaders = (headers) => {
20823
- const res = {};
20824
- if (!(headers instanceof Headers)) {
20825
- headers = new Headers(headers ?? undefined);
20826
- }
20827
- const cookies = [];
20828
- for (const [k, v] of headers) {
20829
- if (k === "set-cookie") {
20830
- cookies.push(v);
20831
- } else {
20832
- res[k] = v;
20833
- }
20834
- }
20835
- if (cookies.length > 0) {
20836
- res["set-cookie"] = cookies;
20837
- }
20838
- res["content-type"] ??= "text/plain; charset=UTF-8";
20839
- return res;
20840
- };
20841
- var X_ALREADY_SENT = "x-hono-already-sent";
20842
- if (typeof global.crypto === "undefined") {
20843
- global.crypto = crypto;
20844
- }
20845
- var outgoingEnded = Symbol("outgoingEnded");
20846
- var handleRequestError = () => new Response(null, {
20847
- status: 400
20848
- });
20849
- var handleFetchError = (e) => new Response(null, {
20850
- status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
20851
- });
20852
- var handleResponseError = (e, outgoing) => {
20853
- const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
20854
- if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
20855
- console.info("The user aborted a request.");
20856
- } else {
20857
- console.error(e);
20858
- if (!outgoing.headersSent) {
20859
- outgoing.writeHead(500, { "Content-Type": "text/plain" });
20860
- }
20861
- outgoing.end(`Error: ${err.message}`);
20862
- outgoing.destroy(err);
20863
- }
20864
- };
20865
- var flushHeaders = (outgoing) => {
20866
- if ("flushHeaders" in outgoing && outgoing.writable) {
20867
- outgoing.flushHeaders();
20868
- }
20869
- };
20870
- var responseViaCache = async (res, outgoing) => {
20871
- let [status, body, header] = res[cacheKey];
20872
- let hasContentLength = false;
20873
- if (!header) {
20874
- header = { "content-type": "text/plain; charset=UTF-8" };
20875
- } else if (header instanceof Headers) {
20876
- hasContentLength = header.has("content-length");
20877
- header = buildOutgoingHttpHeaders(header);
20878
- } else if (Array.isArray(header)) {
20879
- const headerObj = new Headers(header);
20880
- hasContentLength = headerObj.has("content-length");
20881
- header = buildOutgoingHttpHeaders(headerObj);
20882
- } else {
20883
- for (const key in header) {
20884
- if (key.length === 14 && key.toLowerCase() === "content-length") {
20885
- hasContentLength = true;
20886
- break;
20887
- }
20888
- }
20889
- }
20890
- if (!hasContentLength) {
20891
- if (typeof body === "string") {
20892
- header["Content-Length"] = Buffer.byteLength(body);
20893
- } else if (body instanceof Uint8Array) {
20894
- header["Content-Length"] = body.byteLength;
20895
- } else if (body instanceof Blob) {
20896
- header["Content-Length"] = body.size;
20897
- }
20898
- }
20899
- outgoing.writeHead(status, header);
20900
- if (typeof body === "string" || body instanceof Uint8Array) {
20901
- outgoing.end(body);
20902
- } else if (body instanceof Blob) {
20903
- outgoing.end(new Uint8Array(await body.arrayBuffer()));
20904
- } else {
20905
- flushHeaders(outgoing);
20906
- await writeFromReadableStream(body, outgoing)?.catch((e) => handleResponseError(e, outgoing));
20907
- }
20908
- outgoing[outgoingEnded]?.();
20909
- };
20910
- var isPromise = (res) => typeof res.then === "function";
20911
- var responseViaResponseObject = async (res, outgoing, options = {}) => {
20912
- if (isPromise(res)) {
20913
- if (options.errorHandler) {
20914
- try {
20915
- res = await res;
20916
- } catch (err) {
20917
- const errRes = await options.errorHandler(err);
20918
- if (!errRes) {
20919
- return;
20920
- }
20921
- res = errRes;
20922
- }
20923
- } else {
20924
- res = await res.catch(handleFetchError);
20925
- }
20926
- }
20927
- if (cacheKey in res) {
20928
- return responseViaCache(res, outgoing);
20929
- }
20930
- const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
20931
- if (res.body) {
20932
- const reader = res.body.getReader();
20933
- const values = [];
20934
- let done = false;
20935
- let currentReadPromise = undefined;
20936
- if (resHeaderRecord["transfer-encoding"] !== "chunked") {
20937
- let maxReadCount = 2;
20938
- for (let i = 0;i < maxReadCount; i++) {
20939
- currentReadPromise ||= reader.read();
20940
- const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
20941
- console.error(e);
20942
- done = true;
20943
- });
20944
- if (!chunk) {
20945
- if (i === 1) {
20946
- await new Promise((resolve) => setTimeout(resolve));
20947
- maxReadCount = 3;
20948
- continue;
20949
- }
20950
- break;
20951
- }
20952
- currentReadPromise = undefined;
20953
- if (chunk.value) {
20954
- values.push(chunk.value);
20955
- }
20956
- if (chunk.done) {
20957
- done = true;
20958
- break;
20959
- }
20960
- }
20961
- if (done && !("content-length" in resHeaderRecord)) {
20962
- resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
20963
- }
20964
- }
20965
- outgoing.writeHead(res.status, resHeaderRecord);
20966
- values.forEach((value) => {
20967
- outgoing.write(value);
20968
- });
20969
- if (done) {
20970
- outgoing.end();
20971
- } else {
20972
- if (values.length === 0) {
20973
- flushHeaders(outgoing);
20974
- }
20975
- await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
20976
- }
20977
- } else if (resHeaderRecord[X_ALREADY_SENT]) {} else {
20978
- outgoing.writeHead(res.status, resHeaderRecord);
20979
- outgoing.end();
20980
- }
20981
- outgoing[outgoingEnded]?.();
20982
- };
20983
- var getRequestListener = (fetchCallback, options = {}) => {
20984
- const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
20985
- if (options.overrideGlobalObjects !== false && global.Request !== Request2) {
20986
- Object.defineProperty(global, "Request", {
20987
- value: Request2
20988
- });
20989
- Object.defineProperty(global, "Response", {
20990
- value: Response2
20991
- });
20992
- }
20993
- return async (incoming, outgoing) => {
20994
- let res, req;
20995
- try {
20996
- req = newRequest(incoming, options.hostname);
20997
- let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
20998
- if (!incomingEnded) {
20999
- incoming[wrapBodyStream] = true;
21000
- incoming.on("end", () => {
21001
- incomingEnded = true;
21002
- });
21003
- if (incoming instanceof Http2ServerRequest2) {
21004
- outgoing[outgoingEnded] = () => {
21005
- if (!incomingEnded) {
21006
- setTimeout(() => {
21007
- if (!incomingEnded) {
21008
- setTimeout(() => {
21009
- incoming.destroy();
21010
- outgoing.destroy();
21011
- });
21012
- }
21013
- });
21014
- }
21015
- };
21016
- }
21017
- }
21018
- outgoing.on("close", () => {
21019
- const abortController = req[abortControllerKey];
21020
- if (abortController) {
21021
- if (incoming.errored) {
21022
- req[abortControllerKey].abort(incoming.errored.toString());
21023
- } else if (!outgoing.writableFinished) {
21024
- req[abortControllerKey].abort("Client connection prematurely closed.");
21025
- }
21026
- }
21027
- if (!incomingEnded) {
21028
- setTimeout(() => {
21029
- if (!incomingEnded) {
21030
- setTimeout(() => {
21031
- incoming.destroy();
21032
- });
21033
- }
21034
- });
21035
- }
21036
- });
21037
- res = fetchCallback(req, { incoming, outgoing });
21038
- if (cacheKey in res) {
21039
- return responseViaCache(res, outgoing);
21040
- }
21041
- } catch (e) {
21042
- if (!res) {
21043
- if (options.errorHandler) {
21044
- res = await options.errorHandler(req ? e : toRequestError(e));
21045
- if (!res) {
21046
- return;
21047
- }
21048
- } else if (!req) {
21049
- res = handleRequestError();
21050
- } else {
21051
- res = handleFetchError(e);
21052
- }
21053
- } else {
21054
- return handleResponseError(e, outgoing);
21055
- }
21056
- }
21057
- try {
21058
- return await responseViaResponseObject(res, outgoing, options);
21059
- } catch (e) {
21060
- return handleResponseError(e, outgoing);
21061
- }
21062
- };
21063
- };
21064
- var createAdaptorServer = (options) => {
21065
- const fetchCallback = options.fetch;
21066
- const requestListener = getRequestListener(fetchCallback, {
21067
- hostname: options.hostname,
21068
- overrideGlobalObjects: options.overrideGlobalObjects,
21069
- autoCleanupIncoming: options.autoCleanupIncoming
21070
- });
21071
- const createServer = options.createServer || createServerHTTP;
21072
- const server = createServer(options.serverOptions || {}, requestListener);
21073
- return server;
21074
- };
21075
- var serve = (options, listeningListener) => {
21076
- const server = createAdaptorServer(options);
21077
- server.listen(options?.port ?? 3000, options.hostname, () => {
21078
- const serverInfo = server.address();
21079
- listeningListener && listeningListener(serverInfo);
21080
- });
21081
- return server;
21082
- };
21083
-
21084
- // node_modules/hono/dist/compose.js
21085
- var compose = (middleware, onError, onNotFound) => {
21086
- return (context, next) => {
21087
- let index = -1;
21088
- return dispatch(0);
21089
- async function dispatch(i) {
21090
- if (i <= index) {
21091
- throw new Error("next() called multiple times");
21092
- }
21093
- index = i;
21094
- let res;
21095
- let isError = false;
21096
- let handler;
21097
- if (middleware[i]) {
21098
- handler = middleware[i][0][0];
21099
- context.req.routeIndex = i;
21100
- } else {
21101
- handler = i === middleware.length && next || undefined;
21102
- }
21103
- if (handler) {
21104
- try {
21105
- res = await handler(context, () => dispatch(i + 1));
21106
- } catch (err) {
21107
- if (err instanceof Error && onError) {
21108
- context.error = err;
21109
- res = await onError(err, context);
21110
- isError = true;
21111
- } else {
21112
- throw err;
21113
- }
21114
- }
21115
- } else {
21116
- if (context.finalized === false && onNotFound) {
21117
- res = await onNotFound(context);
21118
- }
21119
- }
21120
- if (res && (context.finalized === false || isError)) {
21121
- context.res = res;
21122
- }
21123
- return context;
21124
- }
21125
- };
21126
- };
21127
-
21128
- // node_modules/hono/dist/request/constants.js
21129
- var GET_MATCH_RESULT = /* @__PURE__ */ Symbol();
21130
-
21131
- // node_modules/hono/dist/utils/body.js
21132
- var parseBody = async (request, options = /* @__PURE__ */ Object.create(null)) => {
21133
- const { all = false, dot = false } = options;
21134
- const headers = request instanceof HonoRequest ? request.raw.headers : request.headers;
21135
- const contentType = headers.get("Content-Type");
21136
- if (contentType?.startsWith("multipart/form-data") || contentType?.startsWith("application/x-www-form-urlencoded")) {
21137
- return parseFormData(request, { all, dot });
21138
- }
21139
- return {};
21140
- };
21141
- async function parseFormData(request, options) {
21142
- const formData = await request.formData();
21143
- if (formData) {
21144
- return convertFormDataToBodyData(formData, options);
21145
- }
21146
- return {};
21147
- }
21148
- function convertFormDataToBodyData(formData, options) {
21149
- const form = /* @__PURE__ */ Object.create(null);
21150
- formData.forEach((value, key) => {
21151
- const shouldParseAllValues = options.all || key.endsWith("[]");
21152
- if (!shouldParseAllValues) {
21153
- form[key] = value;
21154
- } else {
21155
- handleParsingAllValues(form, key, value);
21156
- }
21157
- });
21158
- if (options.dot) {
21159
- Object.entries(form).forEach(([key, value]) => {
21160
- const shouldParseDotValues = key.includes(".");
21161
- if (shouldParseDotValues) {
21162
- handleParsingNestedValues(form, key, value);
21163
- delete form[key];
21164
- }
21165
- });
21166
- }
21167
- return form;
21168
- }
21169
- var handleParsingAllValues = (form, key, value) => {
21170
- if (form[key] !== undefined) {
21171
- if (Array.isArray(form[key])) {
21172
- form[key].push(value);
21173
- } else {
21174
- form[key] = [form[key], value];
21175
- }
21176
- } else {
21177
- if (!key.endsWith("[]")) {
21178
- form[key] = value;
21179
- } else {
21180
- form[key] = [value];
21181
- }
21182
- }
21183
- };
21184
- var handleParsingNestedValues = (form, key, value) => {
21185
- if (/(?:^|\.)__proto__\./.test(key)) {
21186
- return;
21187
- }
21188
- let nestedForm = form;
21189
- const keys = key.split(".");
21190
- keys.forEach((key2, index) => {
21191
- if (index === keys.length - 1) {
21192
- nestedForm[key2] = value;
21193
- } else {
21194
- if (!nestedForm[key2] || typeof nestedForm[key2] !== "object" || Array.isArray(nestedForm[key2]) || nestedForm[key2] instanceof File) {
21195
- nestedForm[key2] = /* @__PURE__ */ Object.create(null);
21196
- }
21197
- nestedForm = nestedForm[key2];
21198
- }
21199
- });
21200
- };
21201
-
21202
- // node_modules/hono/dist/utils/url.js
21203
- var splitPath = (path) => {
21204
- const paths = path.split("/");
21205
- if (paths[0] === "") {
21206
- paths.shift();
21207
- }
21208
- return paths;
21209
- };
21210
- var splitRoutingPath = (routePath) => {
21211
- const { groups, path } = extractGroupsFromPath(routePath);
21212
- const paths = splitPath(path);
21213
- return replaceGroupMarks(paths, groups);
21214
- };
21215
- var extractGroupsFromPath = (path) => {
21216
- const groups = [];
21217
- path = path.replace(/\{[^}]+\}/g, (match, index) => {
21218
- const mark = `@${index}`;
21219
- groups.push([mark, match]);
21220
- return mark;
21221
- });
21222
- return { groups, path };
21223
- };
21224
- var replaceGroupMarks = (paths, groups) => {
21225
- for (let i = groups.length - 1;i >= 0; i--) {
21226
- const [mark] = groups[i];
21227
- for (let j = paths.length - 1;j >= 0; j--) {
21228
- if (paths[j].includes(mark)) {
21229
- paths[j] = paths[j].replace(mark, groups[i][1]);
21230
- break;
21231
- }
21232
- }
21233
- }
21234
- return paths;
21235
- };
21236
- var patternCache = {};
21237
- var getPattern = (label, next) => {
21238
- if (label === "*") {
21239
- return "*";
21240
- }
21241
- const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
21242
- if (match) {
21243
- const cacheKey2 = `${label}#${next}`;
21244
- if (!patternCache[cacheKey2]) {
21245
- if (match[2]) {
21246
- patternCache[cacheKey2] = next && next[0] !== ":" && next[0] !== "*" ? [cacheKey2, match[1], new RegExp(`^${match[2]}(?=/${next})`)] : [label, match[1], new RegExp(`^${match[2]}$`)];
21247
- } else {
21248
- patternCache[cacheKey2] = [label, match[1], true];
21249
- }
21250
- }
21251
- return patternCache[cacheKey2];
21252
- }
21253
- return null;
21254
- };
21255
- var tryDecode = (str, decoder) => {
21256
- try {
21257
- return decoder(str);
21258
- } catch {
21259
- return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
21260
- try {
21261
- return decoder(match);
21262
- } catch {
21263
- return match;
21264
- }
21265
- });
21266
- }
21267
- };
21268
- var tryDecodeURI = (str) => tryDecode(str, decodeURI);
21269
- var getPath = (request) => {
21270
- const url = request.url;
21271
- const start = url.indexOf("/", url.indexOf(":") + 4);
21272
- let i = start;
21273
- for (;i < url.length; i++) {
21274
- const charCode = url.charCodeAt(i);
21275
- if (charCode === 37) {
21276
- const queryIndex = url.indexOf("?", i);
21277
- const hashIndex = url.indexOf("#", i);
21278
- const end = queryIndex === -1 ? hashIndex === -1 ? undefined : hashIndex : hashIndex === -1 ? queryIndex : Math.min(queryIndex, hashIndex);
21279
- const path = url.slice(start, end);
21280
- return tryDecodeURI(path.includes("%25") ? path.replace(/%25/g, "%2525") : path);
21281
- } else if (charCode === 63 || charCode === 35) {
21282
- break;
21283
- }
21284
- }
21285
- return url.slice(start, i);
21286
- };
21287
- var getPathNoStrict = (request) => {
21288
- const result = getPath(request);
21289
- return result.length > 1 && result.at(-1) === "/" ? result.slice(0, -1) : result;
21290
- };
21291
- var mergePath = (base, sub, ...rest) => {
21292
- if (rest.length) {
21293
- sub = mergePath(sub, ...rest);
21294
- }
21295
- return `${base?.[0] === "/" ? "" : "/"}${base}${sub === "/" ? "" : `${base?.at(-1) === "/" ? "" : "/"}${sub?.[0] === "/" ? sub.slice(1) : sub}`}`;
21296
- };
21297
- var checkOptionalParameter = (path) => {
21298
- if (path.charCodeAt(path.length - 1) !== 63 || !path.includes(":")) {
21299
- return null;
21300
- }
21301
- const segments = path.split("/");
21302
- const results = [];
21303
- let basePath = "";
21304
- segments.forEach((segment) => {
21305
- if (segment !== "" && !/\:/.test(segment)) {
21306
- basePath += "/" + segment;
21307
- } else if (/\:/.test(segment)) {
21308
- if (/\?/.test(segment)) {
21309
- if (results.length === 0 && basePath === "") {
21310
- results.push("/");
21311
- } else {
21312
- results.push(basePath);
21313
- }
21314
- const optionalSegment = segment.replace("?", "");
21315
- basePath += "/" + optionalSegment;
21316
- results.push(basePath);
21317
- } else {
21318
- basePath += "/" + segment;
21319
- }
21320
- }
21321
- });
21322
- return results.filter((v, i, a) => a.indexOf(v) === i);
21323
- };
21324
- var _decodeURI = (value) => {
21325
- if (!/[%+]/.test(value)) {
21326
- return value;
21327
- }
21328
- if (value.indexOf("+") !== -1) {
21329
- value = value.replace(/\+/g, " ");
21330
- }
21331
- return value.indexOf("%") !== -1 ? tryDecode(value, decodeURIComponent_) : value;
21332
- };
21333
- var _getQueryParam = (url, key, multiple) => {
21334
- let encoded;
21335
- if (!multiple && key && !/[%+]/.test(key)) {
21336
- let keyIndex2 = url.indexOf("?", 8);
21337
- if (keyIndex2 === -1) {
21338
- return;
21339
- }
21340
- if (!url.startsWith(key, keyIndex2 + 1)) {
21341
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
21342
- }
21343
- while (keyIndex2 !== -1) {
21344
- const trailingKeyCode = url.charCodeAt(keyIndex2 + key.length + 1);
21345
- if (trailingKeyCode === 61) {
21346
- const valueIndex = keyIndex2 + key.length + 2;
21347
- const endIndex = url.indexOf("&", valueIndex);
21348
- return _decodeURI(url.slice(valueIndex, endIndex === -1 ? undefined : endIndex));
21349
- } else if (trailingKeyCode == 38 || isNaN(trailingKeyCode)) {
21350
- return "";
21351
- }
21352
- keyIndex2 = url.indexOf(`&${key}`, keyIndex2 + 1);
21353
- }
21354
- encoded = /[%+]/.test(url);
21355
- if (!encoded) {
21356
- return;
21357
- }
21358
- }
21359
- const results = {};
21360
- encoded ??= /[%+]/.test(url);
21361
- let keyIndex = url.indexOf("?", 8);
21362
- while (keyIndex !== -1) {
21363
- const nextKeyIndex = url.indexOf("&", keyIndex + 1);
21364
- let valueIndex = url.indexOf("=", keyIndex);
21365
- if (valueIndex > nextKeyIndex && nextKeyIndex !== -1) {
21366
- valueIndex = -1;
21367
- }
21368
- let name = url.slice(keyIndex + 1, valueIndex === -1 ? nextKeyIndex === -1 ? undefined : nextKeyIndex : valueIndex);
21369
- if (encoded) {
21370
- name = _decodeURI(name);
21371
- }
21372
- keyIndex = nextKeyIndex;
21373
- if (name === "") {
21374
- continue;
21375
- }
21376
- let value;
21377
- if (valueIndex === -1) {
21378
- value = "";
21379
- } else {
21380
- value = url.slice(valueIndex + 1, nextKeyIndex === -1 ? undefined : nextKeyIndex);
21381
- if (encoded) {
21382
- value = _decodeURI(value);
21383
- }
21384
- }
21385
- if (multiple) {
21386
- if (!(results[name] && Array.isArray(results[name]))) {
21387
- results[name] = [];
21388
- }
21389
- results[name].push(value);
21390
- } else {
21391
- results[name] ??= value;
21392
- }
21393
- }
21394
- return key ? results[key] : results;
21395
- };
21396
- var getQueryParam = _getQueryParam;
21397
- var getQueryParams = (url, key) => {
21398
- return _getQueryParam(url, key, true);
21399
- };
21400
- var decodeURIComponent_ = decodeURIComponent;
21401
-
21402
- // node_modules/hono/dist/request.js
21403
- var tryDecodeURIComponent = (str) => tryDecode(str, decodeURIComponent_);
21404
- var HonoRequest = class {
21405
- raw;
21406
- #validatedData;
21407
- #matchResult;
21408
- routeIndex = 0;
21409
- path;
21410
- bodyCache = {};
21411
- constructor(request, path = "/", matchResult = [[]]) {
21412
- this.raw = request;
21413
- this.path = path;
21414
- this.#matchResult = matchResult;
21415
- this.#validatedData = {};
21416
- }
21417
- param(key) {
21418
- return key ? this.#getDecodedParam(key) : this.#getAllDecodedParams();
21419
- }
21420
- #getDecodedParam(key) {
21421
- const paramKey = this.#matchResult[0][this.routeIndex][1][key];
21422
- const param = this.#getParamValue(paramKey);
21423
- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param;
21424
- }
21425
- #getAllDecodedParams() {
21426
- const decoded = {};
21427
- const keys = Object.keys(this.#matchResult[0][this.routeIndex][1]);
21428
- for (const key of keys) {
21429
- const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key]);
21430
- if (value !== undefined) {
21431
- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value;
21432
- }
21433
- }
21434
- return decoded;
21435
- }
21436
- #getParamValue(paramKey) {
21437
- return this.#matchResult[1] ? this.#matchResult[1][paramKey] : paramKey;
21438
- }
21439
- query(key) {
21440
- return getQueryParam(this.url, key);
21441
- }
21442
- queries(key) {
21443
- return getQueryParams(this.url, key);
21444
- }
21445
- header(name) {
21446
- if (name) {
21447
- return this.raw.headers.get(name) ?? undefined;
21448
- }
21449
- const headerData = {};
21450
- this.raw.headers.forEach((value, key) => {
21451
- headerData[key] = value;
21452
- });
21453
- return headerData;
21454
- }
21455
- async parseBody(options) {
21456
- return this.bodyCache.parsedBody ??= await parseBody(this, options);
21457
- }
21458
- #cachedBody = (key) => {
21459
- const { bodyCache, raw } = this;
21460
- const cachedBody = bodyCache[key];
21461
- if (cachedBody) {
21462
- return cachedBody;
21463
- }
21464
- const anyCachedKey = Object.keys(bodyCache)[0];
21465
- if (anyCachedKey) {
21466
- return bodyCache[anyCachedKey].then((body) => {
21467
- if (anyCachedKey === "json") {
21468
- body = JSON.stringify(body);
21469
- }
21470
- return new Response(body)[key]();
21471
- });
21472
- }
21473
- return bodyCache[key] = raw[key]();
21474
- };
21475
- json() {
21476
- return this.#cachedBody("text").then((text) => JSON.parse(text));
21477
- }
21478
- text() {
21479
- return this.#cachedBody("text");
21480
- }
21481
- arrayBuffer() {
21482
- return this.#cachedBody("arrayBuffer");
21483
- }
21484
- blob() {
21485
- return this.#cachedBody("blob");
21486
- }
21487
- formData() {
21488
- return this.#cachedBody("formData");
21489
- }
21490
- addValidatedData(target, data) {
21491
- this.#validatedData[target] = data;
21492
- }
21493
- valid(target) {
21494
- return this.#validatedData[target];
21495
- }
21496
- get url() {
21497
- return this.raw.url;
21498
- }
21499
- get method() {
21500
- return this.raw.method;
21501
- }
21502
- get [GET_MATCH_RESULT]() {
21503
- return this.#matchResult;
21504
- }
21505
- get matchedRoutes() {
21506
- return this.#matchResult[0].map(([[, route]]) => route);
21507
- }
21508
- get routePath() {
21509
- return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path;
21510
- }
21511
- };
21512
-
21513
- // node_modules/hono/dist/utils/html.js
21514
- var HtmlEscapedCallbackPhase = {
21515
- Stringify: 1,
21516
- BeforeStream: 2,
21517
- Stream: 3
21518
- };
21519
- var raw = (value, callbacks) => {
21520
- const escapedString = new String(value);
21521
- escapedString.isEscaped = true;
21522
- escapedString.callbacks = callbacks;
21523
- return escapedString;
21524
- };
21525
- var escapeRe = /[&<>'"]/;
21526
- var stringBufferToString = async (buffer, callbacks) => {
21527
- let str = "";
21528
- callbacks ||= [];
21529
- const resolvedBuffer = await Promise.all(buffer);
21530
- for (let i = resolvedBuffer.length - 1;; i--) {
21531
- str += resolvedBuffer[i];
21532
- i--;
21533
- if (i < 0) {
21534
- break;
21535
- }
21536
- let r = resolvedBuffer[i];
21537
- if (typeof r === "object") {
21538
- callbacks.push(...r.callbacks || []);
21539
- }
21540
- const isEscaped = r.isEscaped;
21541
- r = await (typeof r === "object" ? r.toString() : r);
21542
- if (typeof r === "object") {
21543
- callbacks.push(...r.callbacks || []);
21544
- }
21545
- if (r.isEscaped ?? isEscaped) {
21546
- str += r;
21547
- } else {
21548
- const buf = [str];
21549
- escapeToBuffer(r, buf);
21550
- str = buf[0];
21551
- }
21552
- }
21553
- return raw(str, callbacks);
21554
- };
21555
- var escapeToBuffer = (str, buffer) => {
21556
- const match = str.search(escapeRe);
21557
- if (match === -1) {
21558
- buffer[0] += str;
21559
- return;
21560
- }
21561
- let escape2;
21562
- let index;
21563
- let lastIndex = 0;
21564
- for (index = match;index < str.length; index++) {
21565
- switch (str.charCodeAt(index)) {
21566
- case 34:
21567
- escape2 = "&quot;";
21568
- break;
21569
- case 39:
21570
- escape2 = "&#39;";
21571
- break;
21572
- case 38:
21573
- escape2 = "&amp;";
21574
- break;
21575
- case 60:
21576
- escape2 = "&lt;";
21577
- break;
21578
- case 62:
21579
- escape2 = "&gt;";
21580
- break;
21581
- default:
21582
- continue;
21583
- }
21584
- buffer[0] += str.substring(lastIndex, index) + escape2;
21585
- lastIndex = index + 1;
21586
- }
21587
- buffer[0] += str.substring(lastIndex, index);
21588
- };
21589
- var resolveCallbackSync = (str) => {
21590
- const callbacks = str.callbacks;
21591
- if (!callbacks?.length) {
21592
- return str;
21593
- }
21594
- const buffer = [str];
21595
- const context = {};
21596
- callbacks.forEach((c) => c({ phase: HtmlEscapedCallbackPhase.Stringify, buffer, context }));
21597
- return buffer[0];
21598
- };
21599
- var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
21600
- if (typeof str === "object" && !(str instanceof String)) {
21601
- if (!(str instanceof Promise)) {
21602
- str = str.toString();
21603
- }
21604
- if (str instanceof Promise) {
21605
- str = await str;
21606
- }
21607
- }
21608
- const callbacks = str.callbacks;
21609
- if (!callbacks?.length) {
21610
- return Promise.resolve(str);
21611
- }
21612
- if (buffer) {
21613
- buffer[0] += str;
21614
- } else {
21615
- buffer = [str];
21616
- }
21617
- 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]));
21618
- if (preserveCallbacks) {
21619
- return raw(await resStr, callbacks);
21620
- } else {
21621
- return resStr;
21622
- }
21623
- };
21624
-
21625
- // node_modules/hono/dist/context.js
21626
- var TEXT_PLAIN = "text/plain; charset=UTF-8";
21627
- var setDefaultContentType = (contentType, headers) => {
21628
- return {
21629
- "Content-Type": contentType,
21630
- ...headers
21631
- };
21632
- };
21633
- var createResponseInstance = (body, init) => new Response(body, init);
21634
- var Context = class {
21635
- #rawRequest;
21636
- #req;
21637
- env = {};
21638
- #var;
21639
- finalized = false;
21640
- error;
21641
- #status;
21642
- #executionCtx;
21643
- #res;
21644
- #layout;
21645
- #renderer;
21646
- #notFoundHandler;
21647
- #preparedHeaders;
21648
- #matchResult;
21649
- #path;
21650
- constructor(req, options) {
21651
- this.#rawRequest = req;
21652
- if (options) {
21653
- this.#executionCtx = options.executionCtx;
21654
- this.env = options.env;
21655
- this.#notFoundHandler = options.notFoundHandler;
21656
- this.#path = options.path;
21657
- this.#matchResult = options.matchResult;
21658
- }
21659
- }
21660
- get req() {
21661
- this.#req ??= new HonoRequest(this.#rawRequest, this.#path, this.#matchResult);
21662
- return this.#req;
21663
- }
21664
- get event() {
21665
- if (this.#executionCtx && "respondWith" in this.#executionCtx) {
21666
- return this.#executionCtx;
21667
- } else {
21668
- throw Error("This context has no FetchEvent");
21669
- }
21670
- }
21671
- get executionCtx() {
21672
- if (this.#executionCtx) {
21673
- return this.#executionCtx;
21674
- } else {
21675
- throw Error("This context has no ExecutionContext");
21676
- }
21677
- }
21678
- get res() {
21679
- return this.#res ||= createResponseInstance(null, {
21680
- headers: this.#preparedHeaders ??= new Headers
21681
- });
21682
- }
21683
- set res(_res) {
21684
- if (this.#res && _res) {
21685
- _res = createResponseInstance(_res.body, _res);
21686
- for (const [k, v] of this.#res.headers.entries()) {
21687
- if (k === "content-type") {
21688
- continue;
21689
- }
21690
- if (k === "set-cookie") {
21691
- const cookies = this.#res.headers.getSetCookie();
21692
- _res.headers.delete("set-cookie");
21693
- for (const cookie of cookies) {
21694
- _res.headers.append("set-cookie", cookie);
21695
- }
21696
- } else {
21697
- _res.headers.set(k, v);
21698
- }
21699
- }
21700
- }
21701
- this.#res = _res;
21702
- this.finalized = true;
21703
- }
21704
- render = (...args) => {
21705
- this.#renderer ??= (content) => this.html(content);
21706
- return this.#renderer(...args);
21707
- };
21708
- setLayout = (layout) => this.#layout = layout;
21709
- getLayout = () => this.#layout;
21710
- setRenderer = (renderer) => {
21711
- this.#renderer = renderer;
21712
- };
21713
- header = (name, value, options) => {
21714
- if (this.finalized) {
21715
- this.#res = createResponseInstance(this.#res.body, this.#res);
21716
- }
21717
- const headers = this.#res ? this.#res.headers : this.#preparedHeaders ??= new Headers;
21718
- if (value === undefined) {
21719
- headers.delete(name);
21720
- } else if (options?.append) {
21721
- headers.append(name, value);
21722
- } else {
21723
- headers.set(name, value);
21724
- }
21725
- };
21726
- status = (status) => {
21727
- this.#status = status;
21728
- };
21729
- set = (key, value) => {
21730
- this.#var ??= /* @__PURE__ */ new Map;
21731
- this.#var.set(key, value);
21732
- };
21733
- get = (key) => {
21734
- return this.#var ? this.#var.get(key) : undefined;
21735
- };
21736
- get var() {
21737
- if (!this.#var) {
21738
- return {};
21739
- }
21740
- return Object.fromEntries(this.#var);
21741
- }
21742
- #newResponse(data, arg, headers) {
21743
- const responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders ?? new Headers;
21744
- if (typeof arg === "object" && "headers" in arg) {
21745
- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers);
21746
- for (const [key, value] of argHeaders) {
21747
- if (key.toLowerCase() === "set-cookie") {
21748
- responseHeaders.append(key, value);
21749
- } else {
21750
- responseHeaders.set(key, value);
21751
- }
21752
- }
21753
- }
21754
- if (headers) {
21755
- for (const [k, v] of Object.entries(headers)) {
21756
- if (typeof v === "string") {
21757
- responseHeaders.set(k, v);
21758
- } else {
21759
- responseHeaders.delete(k);
21760
- for (const v2 of v) {
21761
- responseHeaders.append(k, v2);
21762
- }
21763
- }
21764
- }
21765
- }
21766
- const status = typeof arg === "number" ? arg : arg?.status ?? this.#status;
21767
- return createResponseInstance(data, { status, headers: responseHeaders });
21768
- }
21769
- newResponse = (...args) => this.#newResponse(...args);
21770
- body = (data, arg, headers) => this.#newResponse(data, arg, headers);
21771
- text = (text, arg, headers) => {
21772
- return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized ? new Response(text) : this.#newResponse(text, arg, setDefaultContentType(TEXT_PLAIN, headers));
21773
- };
21774
- json = (object4, arg, headers) => {
21775
- return this.#newResponse(JSON.stringify(object4), arg, setDefaultContentType("application/json", headers));
21776
- };
21777
- html = (html, arg, headers) => {
21778
- const res = (html2) => this.#newResponse(html2, arg, setDefaultContentType("text/html; charset=UTF-8", headers));
21779
- return typeof html === "object" ? resolveCallback(html, HtmlEscapedCallbackPhase.Stringify, false, {}).then(res) : res(html);
21780
- };
21781
- redirect = (location, status) => {
21782
- const locationString = String(location);
21783
- this.header("Location", !/[^\x00-\xFF]/.test(locationString) ? locationString : encodeURI(locationString));
21784
- return this.newResponse(null, status ?? 302);
21785
- };
21786
- notFound = () => {
21787
- this.#notFoundHandler ??= () => createResponseInstance();
21788
- return this.#notFoundHandler(this);
21789
- };
21790
- };
21791
-
21792
- // node_modules/hono/dist/router.js
21793
- var METHOD_NAME_ALL = "ALL";
21794
- var METHOD_NAME_ALL_LOWERCASE = "all";
21795
- var METHODS = ["get", "post", "put", "delete", "options", "patch"];
21796
- var MESSAGE_MATCHER_IS_ALREADY_BUILT = "Can not add a route since the matcher is already built.";
21797
- var UnsupportedPathError = class extends Error {
21798
- };
21799
-
21800
- // node_modules/hono/dist/utils/constants.js
21801
- var COMPOSED_HANDLER = "__COMPOSED_HANDLER";
21802
-
21803
- // node_modules/hono/dist/hono-base.js
21804
- var notFoundHandler = (c) => {
21805
- return c.text("404 Not Found", 404);
21806
- };
21807
- var errorHandler = (err, c) => {
21808
- if ("getResponse" in err) {
21809
- const res = err.getResponse();
21810
- return c.newResponse(res.body, res);
21811
- }
21812
- console.error(err);
21813
- return c.text("Internal Server Error", 500);
21814
- };
21815
- var Hono = class _Hono {
21816
- get;
21817
- post;
21818
- put;
21819
- delete;
21820
- options;
21821
- patch;
21822
- all;
21823
- on;
21824
- use;
21825
- router;
21826
- getPath;
21827
- _basePath = "/";
21828
- #path = "/";
21829
- routes = [];
21830
- constructor(options = {}) {
21831
- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE];
21832
- allMethods.forEach((method) => {
21833
- this[method] = (args1, ...args) => {
21834
- if (typeof args1 === "string") {
21835
- this.#path = args1;
21836
- } else {
21837
- this.#addRoute(method, this.#path, args1);
21838
- }
21839
- args.forEach((handler) => {
21840
- this.#addRoute(method, this.#path, handler);
21841
- });
21842
- return this;
21843
- };
21844
- });
21845
- this.on = (method, path, ...handlers) => {
21846
- for (const p of [path].flat()) {
21847
- this.#path = p;
21848
- for (const m of [method].flat()) {
21849
- handlers.map((handler) => {
21850
- this.#addRoute(m.toUpperCase(), this.#path, handler);
21851
- });
21852
- }
21853
- }
21854
- return this;
21855
- };
21856
- this.use = (arg1, ...handlers) => {
21857
- if (typeof arg1 === "string") {
21858
- this.#path = arg1;
21859
- } else {
21860
- this.#path = "*";
21861
- handlers.unshift(arg1);
21862
- }
21863
- handlers.forEach((handler) => {
21864
- this.#addRoute(METHOD_NAME_ALL, this.#path, handler);
21865
- });
21866
- return this;
21867
- };
21868
- const { strict, ...optionsWithoutStrict } = options;
21869
- Object.assign(this, optionsWithoutStrict);
21870
- this.getPath = strict ?? true ? options.getPath ?? getPath : getPathNoStrict;
21871
- }
21872
- #clone() {
21873
- const clone2 = new _Hono({
21874
- router: this.router,
21875
- getPath: this.getPath
21876
- });
21877
- clone2.errorHandler = this.errorHandler;
21878
- clone2.#notFoundHandler = this.#notFoundHandler;
21879
- clone2.routes = this.routes;
21880
- return clone2;
21881
- }
21882
- #notFoundHandler = notFoundHandler;
21883
- errorHandler = errorHandler;
21884
- route(path, app) {
21885
- const subApp = this.basePath(path);
21886
- app.routes.map((r) => {
21887
- let handler;
21888
- if (app.errorHandler === errorHandler) {
21889
- handler = r.handler;
21890
- } else {
21891
- handler = async (c, next) => (await compose([], app.errorHandler)(c, () => r.handler(c, next))).res;
21892
- handler[COMPOSED_HANDLER] = r.handler;
21893
- }
21894
- subApp.#addRoute(r.method, r.path, handler);
21895
- });
21896
- return this;
21897
- }
21898
- basePath(path) {
21899
- const subApp = this.#clone();
21900
- subApp._basePath = mergePath(this._basePath, path);
21901
- return subApp;
21902
- }
21903
- onError = (handler) => {
21904
- this.errorHandler = handler;
21905
- return this;
21906
- };
21907
- notFound = (handler) => {
21908
- this.#notFoundHandler = handler;
21909
- return this;
21910
- };
21911
- mount(path, applicationHandler, options) {
21912
- let replaceRequest;
21913
- let optionHandler;
21914
- if (options) {
21915
- if (typeof options === "function") {
21916
- optionHandler = options;
21917
- } else {
21918
- optionHandler = options.optionHandler;
21919
- if (options.replaceRequest === false) {
21920
- replaceRequest = (request) => request;
21921
- } else {
21922
- replaceRequest = options.replaceRequest;
21923
- }
21924
- }
21925
- }
21926
- const getOptions = optionHandler ? (c) => {
21927
- const options2 = optionHandler(c);
21928
- return Array.isArray(options2) ? options2 : [options2];
21929
- } : (c) => {
21930
- let executionContext = undefined;
21931
- try {
21932
- executionContext = c.executionCtx;
21933
- } catch {}
21934
- return [c.env, executionContext];
21935
- };
21936
- replaceRequest ||= (() => {
21937
- const mergedPath = mergePath(this._basePath, path);
21938
- const pathPrefixLength = mergedPath === "/" ? 0 : mergedPath.length;
21939
- return (request) => {
21940
- const url = new URL(request.url);
21941
- url.pathname = url.pathname.slice(pathPrefixLength) || "/";
21942
- return new Request(url, request);
21943
- };
21944
- })();
21945
- const handler = async (c, next) => {
21946
- const res = await applicationHandler(replaceRequest(c.req.raw), ...getOptions(c));
21947
- if (res) {
21948
- return res;
21949
- }
21950
- await next();
21951
- };
21952
- this.#addRoute(METHOD_NAME_ALL, mergePath(path, "*"), handler);
21953
- return this;
21954
- }
21955
- #addRoute(method, path, handler) {
21956
- method = method.toUpperCase();
21957
- path = mergePath(this._basePath, path);
21958
- const r = { basePath: this._basePath, path, method, handler };
21959
- this.router.add(method, path, [handler, r]);
21960
- this.routes.push(r);
21961
- }
21962
- #handleError(err, c) {
21963
- if (err instanceof Error) {
21964
- return this.errorHandler(err, c);
21965
- }
21966
- throw err;
21967
- }
21968
- #dispatch(request, executionCtx, env, method) {
21969
- if (method === "HEAD") {
21970
- return (async () => new Response(null, await this.#dispatch(request, executionCtx, env, "GET")))();
21971
- }
21972
- const path = this.getPath(request, { env });
21973
- const matchResult = this.router.match(method, path);
21974
- const c = new Context(request, {
21975
- path,
21976
- matchResult,
21977
- env,
21978
- executionCtx,
21979
- notFoundHandler: this.#notFoundHandler
21980
- });
21981
- if (matchResult[0].length === 1) {
21982
- let res;
21983
- try {
21984
- res = matchResult[0][0][0][0](c, async () => {
21985
- c.res = await this.#notFoundHandler(c);
21986
- });
21987
- } catch (err) {
21988
- return this.#handleError(err, c);
21989
- }
21990
- 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);
21991
- }
21992
- const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
21993
- return (async () => {
21994
- try {
21995
- const context = await composed(c);
21996
- if (!context.finalized) {
21997
- throw new Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");
21998
- }
21999
- return context.res;
22000
- } catch (err) {
22001
- return this.#handleError(err, c);
22002
- }
22003
- })();
22004
- }
22005
- fetch = (request, ...rest) => {
22006
- return this.#dispatch(request, rest[1], rest[0], request.method);
22007
- };
22008
- request = (input, requestInit, Env, executionCtx) => {
22009
- if (input instanceof Request) {
22010
- return this.fetch(requestInit ? new Request(input, requestInit) : input, Env, executionCtx);
22011
- }
22012
- input = input.toString();
22013
- return this.fetch(new Request(/^https?:\/\//.test(input) ? input : `http://localhost${mergePath("/", input)}`, requestInit), Env, executionCtx);
22014
- };
22015
- fire = () => {
22016
- addEventListener("fetch", (event) => {
22017
- event.respondWith(this.#dispatch(event.request, event, undefined, event.request.method));
22018
- });
22019
- };
22020
- };
22021
-
22022
- // node_modules/hono/dist/router/reg-exp-router/matcher.js
22023
- var emptyParam = [];
22024
- function match(method, path) {
22025
- const matchers = this.buildAllMatchers();
22026
- const match2 = (method2, path2) => {
22027
- const matcher = matchers[method2] || matchers[METHOD_NAME_ALL];
22028
- const staticMatch = matcher[2][path2];
22029
- if (staticMatch) {
22030
- return staticMatch;
22031
- }
22032
- const match3 = path2.match(matcher[0]);
22033
- if (!match3) {
22034
- return [[], emptyParam];
22035
- }
22036
- const index = match3.indexOf("", 1);
22037
- return [matcher[1][index], match3];
22038
- };
22039
- this.match = match2;
22040
- return match2(method, path);
22041
- }
22042
-
22043
- // node_modules/hono/dist/router/reg-exp-router/node.js
22044
- var LABEL_REG_EXP_STR = "[^/]+";
22045
- var ONLY_WILDCARD_REG_EXP_STR = ".*";
22046
- var TAIL_WILDCARD_REG_EXP_STR = "(?:|/.*)";
22047
- var PATH_ERROR = /* @__PURE__ */ Symbol();
22048
- var regExpMetaChars = new Set(".\\+*[^]$()");
22049
- function compareKey(a, b) {
22050
- if (a.length === 1) {
22051
- return b.length === 1 ? a < b ? -1 : 1 : -1;
22052
- }
22053
- if (b.length === 1) {
22054
- return 1;
22055
- }
22056
- if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {
22057
- return 1;
22058
- } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {
22059
- return -1;
22060
- }
22061
- if (a === LABEL_REG_EXP_STR) {
22062
- return 1;
22063
- } else if (b === LABEL_REG_EXP_STR) {
22064
- return -1;
22065
- }
22066
- return a.length === b.length ? a < b ? -1 : 1 : b.length - a.length;
22067
- }
22068
- var Node = class _Node {
22069
- #index;
22070
- #varIndex;
22071
- #children = /* @__PURE__ */ Object.create(null);
22072
- insert(tokens, index, paramMap, context, pathErrorCheckOnly) {
22073
- if (tokens.length === 0) {
22074
- if (this.#index !== undefined) {
22075
- throw PATH_ERROR;
22076
- }
22077
- if (pathErrorCheckOnly) {
22078
- return;
22079
- }
22080
- this.#index = index;
22081
- return;
22082
- }
22083
- const [token, ...restTokens] = tokens;
22084
- const pattern = token === "*" ? restTokens.length === 0 ? ["", "", ONLY_WILDCARD_REG_EXP_STR] : ["", "", LABEL_REG_EXP_STR] : token === "/*" ? ["", "", TAIL_WILDCARD_REG_EXP_STR] : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);
22085
- let node;
22086
- if (pattern) {
22087
- const name = pattern[1];
22088
- let regexpStr = pattern[2] || LABEL_REG_EXP_STR;
22089
- if (name && pattern[2]) {
22090
- if (regexpStr === ".*") {
22091
- throw PATH_ERROR;
22092
- }
22093
- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, "(?:");
22094
- if (/\((?!\?:)/.test(regexpStr)) {
22095
- throw PATH_ERROR;
22096
- }
22097
- }
22098
- node = this.#children[regexpStr];
22099
- if (!node) {
22100
- if (Object.keys(this.#children).some((k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
22101
- throw PATH_ERROR;
22102
- }
22103
- if (pathErrorCheckOnly) {
22104
- return;
22105
- }
22106
- node = this.#children[regexpStr] = new _Node;
22107
- if (name !== "") {
22108
- node.#varIndex = context.varIndex++;
22109
- }
22110
- }
22111
- if (!pathErrorCheckOnly && name !== "") {
22112
- paramMap.push([name, node.#varIndex]);
22113
- }
22114
- } else {
22115
- node = this.#children[token];
22116
- if (!node) {
22117
- if (Object.keys(this.#children).some((k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR)) {
22118
- throw PATH_ERROR;
22119
- }
22120
- if (pathErrorCheckOnly) {
22121
- return;
22122
- }
22123
- node = this.#children[token] = new _Node;
22124
- }
22125
- }
22126
- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly);
22127
- }
22128
- buildRegExpStr() {
22129
- const childKeys = Object.keys(this.#children).sort(compareKey);
22130
- const strList = childKeys.map((k) => {
22131
- const c = this.#children[k];
22132
- return (typeof c.#varIndex === "number" ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr();
22133
- });
22134
- if (typeof this.#index === "number") {
22135
- strList.unshift(`#${this.#index}`);
22136
- }
22137
- if (strList.length === 0) {
22138
- return "";
22139
- }
22140
- if (strList.length === 1) {
22141
- return strList[0];
22142
- }
22143
- return "(?:" + strList.join("|") + ")";
22144
- }
22145
- };
22146
-
22147
- // node_modules/hono/dist/router/reg-exp-router/trie.js
22148
- var Trie = class {
22149
- #context = { varIndex: 0 };
22150
- #root = new Node;
22151
- insert(path, index, pathErrorCheckOnly) {
22152
- const paramAssoc = [];
22153
- const groups = [];
22154
- for (let i = 0;; ) {
22155
- let replaced = false;
22156
- path = path.replace(/\{[^}]+\}/g, (m) => {
22157
- const mark = `@\\${i}`;
22158
- groups[i] = [mark, m];
22159
- i++;
22160
- replaced = true;
22161
- return mark;
22162
- });
22163
- if (!replaced) {
22164
- break;
22165
- }
22166
- }
22167
- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || [];
22168
- for (let i = groups.length - 1;i >= 0; i--) {
22169
- const [mark] = groups[i];
22170
- for (let j = tokens.length - 1;j >= 0; j--) {
22171
- if (tokens[j].indexOf(mark) !== -1) {
22172
- tokens[j] = tokens[j].replace(mark, groups[i][1]);
22173
- break;
22174
- }
22175
- }
22176
- }
22177
- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly);
22178
- return paramAssoc;
22179
- }
22180
- buildRegExp() {
22181
- let regexp = this.#root.buildRegExpStr();
22182
- if (regexp === "") {
22183
- return [/^$/, [], []];
22184
- }
22185
- let captureIndex = 0;
22186
- const indexReplacementMap = [];
22187
- const paramReplacementMap = [];
22188
- regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {
22189
- if (handlerIndex !== undefined) {
22190
- indexReplacementMap[++captureIndex] = Number(handlerIndex);
22191
- return "$()";
22192
- }
22193
- if (paramIndex !== undefined) {
22194
- paramReplacementMap[Number(paramIndex)] = ++captureIndex;
22195
- return "";
22196
- }
22197
- return "";
22198
- });
22199
- return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap];
22200
- }
22201
- };
22202
-
22203
- // node_modules/hono/dist/router/reg-exp-router/router.js
22204
- var nullMatcher = [/^$/, [], /* @__PURE__ */ Object.create(null)];
22205
- var wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
22206
- function buildWildcardRegExp(path) {
22207
- return wildcardRegExpCache[path] ??= new RegExp(path === "*" ? "" : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) => metaChar ? `\\${metaChar}` : "(?:|/.*)")}$`);
22208
- }
22209
- function clearWildcardRegExpCache() {
22210
- wildcardRegExpCache = /* @__PURE__ */ Object.create(null);
22211
- }
22212
- function buildMatcherFromPreprocessedRoutes(routes) {
22213
- const trie = new Trie;
22214
- const handlerData = [];
22215
- if (routes.length === 0) {
22216
- return nullMatcher;
22217
- }
22218
- const routesWithStaticPathFlag = routes.map((route) => [!/\*|\/:/.test(route[0]), ...route]).sort(([isStaticA, pathA], [isStaticB, pathB]) => isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length);
22219
- const staticMap = /* @__PURE__ */ Object.create(null);
22220
- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length;i < len; i++) {
22221
- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i];
22222
- if (pathErrorCheckOnly) {
22223
- staticMap[path] = [handlers.map(([h]) => [h, /* @__PURE__ */ Object.create(null)]), emptyParam];
22224
- } else {
22225
- j++;
22226
- }
22227
- let paramAssoc;
22228
- try {
22229
- paramAssoc = trie.insert(path, j, pathErrorCheckOnly);
22230
- } catch (e) {
22231
- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e;
22232
- }
22233
- if (pathErrorCheckOnly) {
22234
- continue;
22235
- }
22236
- handlerData[j] = handlers.map(([h, paramCount]) => {
22237
- const paramIndexMap = /* @__PURE__ */ Object.create(null);
22238
- paramCount -= 1;
22239
- for (;paramCount >= 0; paramCount--) {
22240
- const [key, value] = paramAssoc[paramCount];
22241
- paramIndexMap[key] = value;
22242
- }
22243
- return [h, paramIndexMap];
22244
- });
22245
- }
22246
- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp();
22247
- for (let i = 0, len = handlerData.length;i < len; i++) {
22248
- for (let j = 0, len2 = handlerData[i].length;j < len2; j++) {
22249
- const map2 = handlerData[i][j]?.[1];
22250
- if (!map2) {
22251
- continue;
22252
- }
22253
- const keys = Object.keys(map2);
22254
- for (let k = 0, len3 = keys.length;k < len3; k++) {
22255
- map2[keys[k]] = paramReplacementMap[map2[keys[k]]];
22256
- }
22257
- }
22258
- }
22259
- const handlerMap = [];
22260
- for (const i in indexReplacementMap) {
22261
- handlerMap[i] = handlerData[indexReplacementMap[i]];
22262
- }
22263
- return [regexp, handlerMap, staticMap];
22264
- }
22265
- function findMiddleware(middleware, path) {
22266
- if (!middleware) {
22267
- return;
22268
- }
22269
- for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {
22270
- if (buildWildcardRegExp(k).test(path)) {
22271
- return [...middleware[k]];
22272
- }
22273
- }
22274
- return;
22275
- }
22276
- var RegExpRouter = class {
22277
- name = "RegExpRouter";
22278
- #middleware;
22279
- #routes;
22280
- constructor() {
22281
- this.#middleware = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
22282
- this.#routes = { [METHOD_NAME_ALL]: /* @__PURE__ */ Object.create(null) };
22283
- }
22284
- add(method, path, handler) {
22285
- const middleware = this.#middleware;
22286
- const routes = this.#routes;
22287
- if (!middleware || !routes) {
22288
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
22289
- }
22290
- if (!middleware[method]) {
22291
- [middleware, routes].forEach((handlerMap) => {
22292
- handlerMap[method] = /* @__PURE__ */ Object.create(null);
22293
- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {
22294
- handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]];
22295
- });
22296
- });
22297
- }
22298
- if (path === "/*") {
22299
- path = "*";
22300
- }
22301
- const paramCount = (path.match(/\/:/g) || []).length;
22302
- if (/\*$/.test(path)) {
22303
- const re = buildWildcardRegExp(path);
22304
- if (method === METHOD_NAME_ALL) {
22305
- Object.keys(middleware).forEach((m) => {
22306
- middleware[m][path] ||= findMiddleware(middleware[m], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
22307
- });
22308
- } else {
22309
- middleware[method][path] ||= findMiddleware(middleware[method], path) || findMiddleware(middleware[METHOD_NAME_ALL], path) || [];
22310
- }
22311
- Object.keys(middleware).forEach((m) => {
22312
- if (method === METHOD_NAME_ALL || method === m) {
22313
- Object.keys(middleware[m]).forEach((p) => {
22314
- re.test(p) && middleware[m][p].push([handler, paramCount]);
22315
- });
22316
- }
22317
- });
22318
- Object.keys(routes).forEach((m) => {
22319
- if (method === METHOD_NAME_ALL || method === m) {
22320
- Object.keys(routes[m]).forEach((p) => re.test(p) && routes[m][p].push([handler, paramCount]));
22321
- }
22322
- });
22323
- return;
22324
- }
22325
- const paths = checkOptionalParameter(path) || [path];
22326
- for (let i = 0, len = paths.length;i < len; i++) {
22327
- const path2 = paths[i];
22328
- Object.keys(routes).forEach((m) => {
22329
- if (method === METHOD_NAME_ALL || method === m) {
22330
- routes[m][path2] ||= [
22331
- ...findMiddleware(middleware[m], path2) || findMiddleware(middleware[METHOD_NAME_ALL], path2) || []
22332
- ];
22333
- routes[m][path2].push([handler, paramCount - len + i + 1]);
22334
- }
22335
- });
22336
- }
22337
- }
22338
- match = match;
22339
- buildAllMatchers() {
22340
- const matchers = /* @__PURE__ */ Object.create(null);
22341
- Object.keys(this.#routes).concat(Object.keys(this.#middleware)).forEach((method) => {
22342
- matchers[method] ||= this.#buildMatcher(method);
22343
- });
22344
- this.#middleware = this.#routes = undefined;
22345
- clearWildcardRegExpCache();
22346
- return matchers;
22347
- }
22348
- #buildMatcher(method) {
22349
- const routes = [];
22350
- let hasOwnRoute = method === METHOD_NAME_ALL;
22351
- [this.#middleware, this.#routes].forEach((r) => {
22352
- const ownRoute = r[method] ? Object.keys(r[method]).map((path) => [path, r[method][path]]) : [];
22353
- if (ownRoute.length !== 0) {
22354
- hasOwnRoute ||= true;
22355
- routes.push(...ownRoute);
22356
- } else if (method !== METHOD_NAME_ALL) {
22357
- routes.push(...Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]));
22358
- }
22359
- });
22360
- if (!hasOwnRoute) {
22361
- return null;
22362
- } else {
22363
- return buildMatcherFromPreprocessedRoutes(routes);
22364
- }
22365
- }
22366
- };
22367
-
22368
- // node_modules/hono/dist/router/reg-exp-router/prepared-router.js
22369
- var PreparedRegExpRouter = class {
22370
- name = "PreparedRegExpRouter";
22371
- #matchers;
22372
- #relocateMap;
22373
- constructor(matchers, relocateMap) {
22374
- this.#matchers = matchers;
22375
- this.#relocateMap = relocateMap;
22376
- }
22377
- #addWildcard(method, handlerData) {
22378
- const matcher = this.#matchers[method];
22379
- matcher[1].forEach((list) => list && list.push(handlerData));
22380
- Object.values(matcher[2]).forEach((list) => list[0].push(handlerData));
22381
- }
22382
- #addPath(method, path, handler, indexes, map2) {
22383
- const matcher = this.#matchers[method];
22384
- if (!map2) {
22385
- matcher[2][path][0].push([handler, {}]);
22386
- } else {
22387
- indexes.forEach((index) => {
22388
- if (typeof index === "number") {
22389
- matcher[1][index].push([handler, map2]);
22390
- } else {
22391
- matcher[2][index || path][0].push([handler, map2]);
22392
- }
22393
- });
22394
- }
22395
- }
22396
- add(method, path, handler) {
22397
- if (!this.#matchers[method]) {
22398
- const all = this.#matchers[METHOD_NAME_ALL];
22399
- const staticMap = {};
22400
- for (const key in all[2]) {
22401
- staticMap[key] = [all[2][key][0].slice(), emptyParam];
22402
- }
22403
- this.#matchers[method] = [
22404
- all[0],
22405
- all[1].map((list) => Array.isArray(list) ? list.slice() : 0),
22406
- staticMap
22407
- ];
22408
- }
22409
- if (path === "/*" || path === "*") {
22410
- const handlerData = [handler, {}];
22411
- if (method === METHOD_NAME_ALL) {
22412
- for (const m in this.#matchers) {
22413
- this.#addWildcard(m, handlerData);
22414
- }
22415
- } else {
22416
- this.#addWildcard(method, handlerData);
22417
- }
22418
- return;
22419
- }
22420
- const data = this.#relocateMap[path];
22421
- if (!data) {
22422
- throw new Error(`Path ${path} is not registered`);
22423
- }
22424
- for (const [indexes, map2] of data) {
22425
- if (method === METHOD_NAME_ALL) {
22426
- for (const m in this.#matchers) {
22427
- this.#addPath(m, path, handler, indexes, map2);
22428
- }
22429
- } else {
22430
- this.#addPath(method, path, handler, indexes, map2);
22431
- }
22432
- }
22433
- }
22434
- buildAllMatchers() {
22435
- return this.#matchers;
22436
- }
22437
- match = match;
22438
- };
22439
-
22440
- // node_modules/hono/dist/router/smart-router/router.js
22441
- var SmartRouter = class {
22442
- name = "SmartRouter";
22443
- #routers = [];
22444
- #routes = [];
22445
- constructor(init) {
22446
- this.#routers = init.routers;
22447
- }
22448
- add(method, path, handler) {
22449
- if (!this.#routes) {
22450
- throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT);
22451
- }
22452
- this.#routes.push([method, path, handler]);
22453
- }
22454
- match(method, path) {
22455
- if (!this.#routes) {
22456
- throw new Error("Fatal error");
22457
- }
22458
- const routers = this.#routers;
22459
- const routes = this.#routes;
22460
- const len = routers.length;
22461
- let i = 0;
22462
- let res;
22463
- for (;i < len; i++) {
22464
- const router = routers[i];
22465
- try {
22466
- for (let i2 = 0, len2 = routes.length;i2 < len2; i2++) {
22467
- router.add(...routes[i2]);
22468
- }
22469
- res = router.match(method, path);
22470
- } catch (e) {
22471
- if (e instanceof UnsupportedPathError) {
22472
- continue;
22473
- }
22474
- throw e;
22475
- }
22476
- this.match = router.match.bind(router);
22477
- this.#routers = [router];
22478
- this.#routes = undefined;
22479
- break;
22480
- }
22481
- if (i === len) {
22482
- throw new Error("Fatal error");
22483
- }
22484
- this.name = `SmartRouter + ${this.activeRouter.name}`;
22485
- return res;
22486
- }
22487
- get activeRouter() {
22488
- if (this.#routes || this.#routers.length !== 1) {
22489
- throw new Error("No active router has been determined yet.");
22490
- }
22491
- return this.#routers[0];
22492
- }
22493
- };
22494
-
22495
- // node_modules/hono/dist/router/trie-router/node.js
22496
- var emptyParams = /* @__PURE__ */ Object.create(null);
22497
- var hasChildren = (children) => {
22498
- for (const _ in children) {
22499
- return true;
22500
- }
22501
- return false;
22502
- };
22503
- var Node2 = class _Node2 {
22504
- #methods;
22505
- #children;
22506
- #patterns;
22507
- #order = 0;
22508
- #params = emptyParams;
22509
- constructor(method, handler, children) {
22510
- this.#children = children || /* @__PURE__ */ Object.create(null);
22511
- this.#methods = [];
22512
- if (method && handler) {
22513
- const m = /* @__PURE__ */ Object.create(null);
22514
- m[method] = { handler, possibleKeys: [], score: 0 };
22515
- this.#methods = [m];
22516
- }
22517
- this.#patterns = [];
22518
- }
22519
- insert(method, path, handler) {
22520
- this.#order = ++this.#order;
22521
- let curNode = this;
22522
- const parts = splitRoutingPath(path);
22523
- const possibleKeys = [];
22524
- for (let i = 0, len = parts.length;i < len; i++) {
22525
- const p = parts[i];
22526
- const nextP = parts[i + 1];
22527
- const pattern = getPattern(p, nextP);
22528
- const key = Array.isArray(pattern) ? pattern[0] : p;
22529
- if (key in curNode.#children) {
22530
- curNode = curNode.#children[key];
22531
- if (pattern) {
22532
- possibleKeys.push(pattern[1]);
22533
- }
22534
- continue;
22535
- }
22536
- curNode.#children[key] = new _Node2;
22537
- if (pattern) {
22538
- curNode.#patterns.push(pattern);
22539
- possibleKeys.push(pattern[1]);
22540
- }
22541
- curNode = curNode.#children[key];
22542
- }
22543
- curNode.#methods.push({
22544
- [method]: {
22545
- handler,
22546
- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),
22547
- score: this.#order
22548
- }
22549
- });
22550
- return curNode;
22551
- }
22552
- #pushHandlerSets(handlerSets, node, method, nodeParams, params) {
22553
- for (let i = 0, len = node.#methods.length;i < len; i++) {
22554
- const m = node.#methods[i];
22555
- const handlerSet = m[method] || m[METHOD_NAME_ALL];
22556
- const processedSet = {};
22557
- if (handlerSet !== undefined) {
22558
- handlerSet.params = /* @__PURE__ */ Object.create(null);
22559
- handlerSets.push(handlerSet);
22560
- if (nodeParams !== emptyParams || params && params !== emptyParams) {
22561
- for (let i2 = 0, len2 = handlerSet.possibleKeys.length;i2 < len2; i2++) {
22562
- const key = handlerSet.possibleKeys[i2];
22563
- const processed = processedSet[handlerSet.score];
22564
- handlerSet.params[key] = params?.[key] && !processed ? params[key] : nodeParams[key] ?? params?.[key];
22565
- processedSet[handlerSet.score] = true;
22566
- }
22567
- }
22568
- }
22569
- }
22570
- }
22571
- search(method, path) {
22572
- const handlerSets = [];
22573
- this.#params = emptyParams;
22574
- const curNode = this;
22575
- let curNodes = [curNode];
22576
- const parts = splitPath(path);
22577
- const curNodesQueue = [];
22578
- const len = parts.length;
22579
- let partOffsets = null;
22580
- for (let i = 0;i < len; i++) {
22581
- const part = parts[i];
22582
- const isLast = i === len - 1;
22583
- const tempNodes = [];
22584
- for (let j = 0, len2 = curNodes.length;j < len2; j++) {
22585
- const node = curNodes[j];
22586
- const nextNode = node.#children[part];
22587
- if (nextNode) {
22588
- nextNode.#params = node.#params;
22589
- if (isLast) {
22590
- if (nextNode.#children["*"]) {
22591
- this.#pushHandlerSets(handlerSets, nextNode.#children["*"], method, node.#params);
22592
- }
22593
- this.#pushHandlerSets(handlerSets, nextNode, method, node.#params);
22594
- } else {
22595
- tempNodes.push(nextNode);
22596
- }
22597
- }
22598
- for (let k = 0, len3 = node.#patterns.length;k < len3; k++) {
22599
- const pattern = node.#patterns[k];
22600
- const params = node.#params === emptyParams ? {} : { ...node.#params };
22601
- if (pattern === "*") {
22602
- const astNode = node.#children["*"];
22603
- if (astNode) {
22604
- this.#pushHandlerSets(handlerSets, astNode, method, node.#params);
22605
- astNode.#params = params;
22606
- tempNodes.push(astNode);
22607
- }
22608
- continue;
22609
- }
22610
- const [key, name, matcher] = pattern;
22611
- if (!part && !(matcher instanceof RegExp)) {
22612
- continue;
22613
- }
22614
- const child = node.#children[key];
22615
- if (matcher instanceof RegExp) {
22616
- if (partOffsets === null) {
22617
- partOffsets = new Array(len);
22618
- let offset = path[0] === "/" ? 1 : 0;
22619
- for (let p = 0;p < len; p++) {
22620
- partOffsets[p] = offset;
22621
- offset += parts[p].length + 1;
22622
- }
22623
- }
22624
- const restPathString = path.substring(partOffsets[i]);
22625
- const m = matcher.exec(restPathString);
22626
- if (m) {
22627
- params[name] = m[0];
22628
- this.#pushHandlerSets(handlerSets, child, method, node.#params, params);
22629
- if (hasChildren(child.#children)) {
22630
- child.#params = params;
22631
- const componentCount = m[0].match(/\//)?.length ?? 0;
22632
- const targetCurNodes = curNodesQueue[componentCount] ||= [];
22633
- targetCurNodes.push(child);
22634
- }
22635
- continue;
22636
- }
22637
- }
22638
- if (matcher === true || matcher.test(part)) {
22639
- params[name] = part;
22640
- if (isLast) {
22641
- this.#pushHandlerSets(handlerSets, child, method, params, node.#params);
22642
- if (child.#children["*"]) {
22643
- this.#pushHandlerSets(handlerSets, child.#children["*"], method, params, node.#params);
22644
- }
22645
- } else {
22646
- child.#params = params;
22647
- tempNodes.push(child);
22648
- }
22649
- }
22650
- }
22651
- }
22652
- const shifted = curNodesQueue.shift();
22653
- curNodes = shifted ? tempNodes.concat(shifted) : tempNodes;
22654
- }
22655
- if (handlerSets.length > 1) {
22656
- handlerSets.sort((a, b) => {
22657
- return a.score - b.score;
22658
- });
22659
- }
22660
- return [handlerSets.map(({ handler, params }) => [handler, params])];
22661
- }
22662
- };
22663
-
22664
- // node_modules/hono/dist/router/trie-router/router.js
22665
- var TrieRouter = class {
22666
- name = "TrieRouter";
22667
- #node;
22668
- constructor() {
22669
- this.#node = new Node2;
22670
- }
22671
- add(method, path, handler) {
22672
- const results = checkOptionalParameter(path);
22673
- if (results) {
22674
- for (let i = 0, len = results.length;i < len; i++) {
22675
- this.#node.insert(method, results[i], handler);
22676
- }
22677
- return;
22678
- }
22679
- this.#node.insert(method, path, handler);
22680
- }
22681
- match(method, path) {
22682
- return this.#node.search(method, path);
22683
- }
22684
- };
22685
-
22686
- // node_modules/hono/dist/hono.js
22687
- var Hono2 = class extends Hono {
22688
- constructor(options = {}) {
22689
- super(options);
22690
- this.router = options.router ?? new SmartRouter({
22691
- routers: [new RegExpRouter, new TrieRouter]
22692
- });
22693
- }
22694
- };
22695
-
22696
- // src/ui/styles.css
22697
- var styles_default = `*,
22698
- *::before,
22699
- *::after {
22700
- box-sizing: border-box;
22701
- margin: 0;
22702
- padding: 0;
22703
- }
22704
-
22705
- :root {
22706
- --bg: #fafafa;
22707
- --surface: #fff;
22708
- --border: #e0e0e0;
22709
- --text: #1a1a1a;
22710
- --text-muted: #666;
22711
- --primary: #2563eb;
22712
- --danger: #dc2626;
22713
- --sidebar-w: 220px;
22714
- --radius: 6px;
22715
- --gap: 16px;
22716
- }
22717
-
22718
- @media (prefers-color-scheme: dark) {
22719
- :root {
22720
- --bg: #111;
22721
- --surface: #1a1a1a;
22722
- --border: #333;
22723
- --text: #e5e5e5;
22724
- --text-muted: #999;
22725
- --primary: #60a5fa;
22726
- --danger: #f87171;
22727
- }
22728
- }
22729
-
22730
- body {
22731
- font-family: system-ui, -apple-system, sans-serif;
22732
- background: var(--bg);
22733
- color: var(--text);
22734
- line-height: 1.5;
22735
- }
22736
-
22737
- .layout {
22738
- display: flex;
22739
- min-height: 100vh;
22740
- }
22741
-
22742
- .sidebar {
22743
- width: var(--sidebar-w);
22744
- flex-shrink: 0;
22745
- border-right: 1px solid var(--border);
22746
- background: var(--surface);
22747
- padding: var(--gap) 0;
22748
- overflow-y: auto;
22749
- }
22750
-
22751
- @media (min-width: 1200px) {
22752
- :root {
22753
- --sidebar-w: 280px;
22754
- }
22755
- }
22756
-
22757
- @media (min-width: 1600px) {
22758
- :root {
22759
- --sidebar-w: 340px;
22760
- }
22761
- }
22762
-
22763
- .sidebar h2 {
22764
- font-size: 0.75rem;
22765
- text-transform: uppercase;
22766
- color: var(--text-muted);
22767
- padding: 0 var(--gap);
22768
- margin-bottom: 8px;
22769
- letter-spacing: 0.05em;
22770
- }
22771
-
22772
- .sidebar-item {
22773
- display: block;
22774
- width: 100%;
22775
- padding: 6px var(--gap);
22776
- font-size: 0.8125rem;
22777
- color: var(--text);
22778
- text-decoration: none;
22779
- }
22780
-
22781
- .sidebar-item.ws-item {
22782
- direction: rtl;
22783
- white-space: nowrap;
22784
- overflow: hidden;
22785
- text-overflow: ellipsis;
22786
- text-align: left;
22787
- }
22788
-
22789
- .sidebar-item.ws-item span {
22790
- unicode-bidi: plaintext;
22791
- }
22792
- .sidebar-item:hover {
22793
- background: var(--bg);
22794
- }
22795
- .sidebar-item.active {
22796
- background: var(--primary);
22797
- color: #fff;
22798
- }
22799
- .sidebar-item.all-item {
22800
- font-weight: 500;
22801
- }
22802
- .sidebar-item.no-ws-item {
22803
- font-style: italic;
22804
- color: var(--text-muted);
22805
- }
22806
- .sidebar-item.no-ws-item.active {
22807
- color: #fff;
22808
- }
22809
-
22810
- .main {
22811
- flex: 1;
22812
- min-width: 0;
22813
- padding: var(--gap);
22814
- }
22815
-
22816
- header {
22817
- display: flex;
22818
- align-items: center;
22819
- justify-content: space-between;
22820
- margin-bottom: var(--gap);
22821
- }
22822
-
22823
- h1 {
22824
- font-size: 1.25rem;
22825
- font-weight: 600;
22826
- }
22827
-
22828
- a.btn,
22829
- button {
22830
- cursor: pointer;
22831
- border: 1px solid var(--border);
22832
- border-radius: var(--radius);
22833
- padding: 6px 12px;
22834
- background: var(--surface);
22835
- color: var(--text);
22836
- font-size: 0.875rem;
22837
- text-decoration: none;
22838
- display: inline-block;
22839
- }
22840
-
22841
- a.btn:hover,
22842
- button:hover {
22843
- border-color: var(--primary);
22844
- }
22845
- .primary {
22846
- background: var(--primary);
22847
- color: #fff;
22848
- border-color: var(--primary);
22849
- }
22850
- .danger {
22851
- color: var(--danger);
22852
- }
22853
- .danger:hover {
22854
- background: var(--danger);
22855
- color: #fff;
22856
- border-color: var(--danger);
22857
- }
22858
-
22859
- .card {
22860
- border: 1px solid var(--border);
22861
- border-radius: var(--radius);
22862
- padding: var(--gap);
22863
- margin-bottom: 12px;
22864
- background: var(--surface);
22865
- }
22866
-
22867
- .card-header {
22868
- display: flex;
22869
- justify-content: space-between;
22870
- align-items: flex-start;
22871
- margin-bottom: 8px;
22872
- }
22873
-
22874
- .card-meta {
22875
- font-size: 0.75rem;
22876
- color: var(--text-muted);
22877
- }
22878
-
22879
- .badge {
22880
- display: inline-block;
22881
- background: var(--bg);
22882
- border: 1px solid var(--border);
22883
- border-radius: 3px;
22884
- padding: 1px 6px;
22885
- font-size: 0.75rem;
22886
- color: var(--text-muted);
22887
- }
22888
-
22889
- .card-content {
22890
- white-space: pre-wrap;
22891
- word-break: break-word;
22892
- font-size: 0.875rem;
22893
- }
22894
- .card-actions {
22895
- display: flex;
22896
- gap: 6px;
22897
- margin-top: 10px;
22898
- }
22899
- .card-actions form {
22900
- display: inline;
22901
- }
22902
-
22903
- textarea {
22904
- width: 100%;
22905
- min-height: 80px;
22906
- border: 1px solid var(--border);
22907
- border-radius: var(--radius);
22908
- padding: 8px;
22909
- background: var(--surface);
22910
- color: var(--text);
22911
- font-family: inherit;
22912
- font-size: 0.875rem;
22913
- resize: vertical;
22914
- }
22915
-
22916
- .form-card {
22917
- border: 1px solid var(--border);
22918
- border-radius: var(--radius);
22919
- padding: var(--gap);
22920
- margin-bottom: var(--gap);
22921
- background: var(--surface);
22922
- }
22923
-
22924
- .field {
22925
- margin-bottom: 10px;
22926
- }
22927
- .field label {
22928
- display: block;
22929
- font-size: 0.75rem;
22930
- color: var(--text-muted);
22931
- margin-bottom: 4px;
22932
- }
22933
-
22934
- .field input {
22935
- width: 100%;
22936
- border: 1px solid var(--border);
22937
- border-radius: var(--radius);
22938
- padding: 6px 10px;
22939
- background: var(--surface);
22940
- color: var(--text);
22941
- font-size: 0.875rem;
22942
- }
22943
-
22944
- .form-actions {
22945
- display: flex;
22946
- gap: 6px;
22947
- }
22948
- .load-more {
22949
- display: block;
22950
- width: 100%;
22951
- text-align: center;
22952
- padding: 10px;
22953
- margin-top: 8px;
22954
- text-decoration: none;
22955
- }
22956
- .empty {
22957
- text-align: center;
22958
- color: var(--text-muted);
22959
- padding: 40px 0;
22960
- }
22961
-
22962
- .ws-group-header {
22963
- font-size: 0.75rem;
22964
- color: var(--text-muted);
22965
- margin: var(--gap) 0 8px;
22966
- padding-bottom: 4px;
22967
- border-bottom: 1px solid var(--border);
22968
- }
22969
-
22970
- .pagination {
22971
- display: flex;
22972
- justify-content: space-between;
22973
- align-items: center;
22974
- margin-top: var(--gap);
22975
- padding-top: var(--gap);
22976
- border-top: 1px solid var(--border);
22977
- }
22978
-
22979
- .page-info {
22980
- font-size: 0.8125rem;
22981
- color: var(--text-muted);
22982
- }
22983
-
22984
- @media (max-width: 640px) {
22985
- .layout {
22986
- flex-direction: column;
22987
- }
22988
-
22989
- .sidebar {
22990
- width: 100%;
22991
- border-right: none;
22992
- border-bottom: 1px solid var(--border);
22993
- padding: 12px 0;
22994
- overflow-x: auto;
22995
- overflow-y: hidden;
22996
- white-space: nowrap;
22997
- display: flex;
22998
- flex-wrap: wrap;
22999
- gap: 4px;
23000
- }
23001
-
23002
- .sidebar h2 {
23003
- width: 100%;
23004
- margin-bottom: 4px;
23005
- }
23006
-
23007
- .sidebar-item {
23008
- width: auto;
23009
- display: inline-block;
23010
- padding: 4px 10px;
23011
- border-radius: var(--radius);
23012
- border: 1px solid var(--border);
23013
- direction: ltr;
23014
- }
23015
- }
23016
- `;
23017
-
23018
- // src/ui/constants.ts
23019
- var NO_WORKSPACE_FILTER = "__none__";
23020
-
23021
- // node_modules/hono/dist/jsx/constants.js
23022
- var DOM_RENDERER = /* @__PURE__ */ Symbol("RENDERER");
23023
- var DOM_ERROR_HANDLER = /* @__PURE__ */ Symbol("ERROR_HANDLER");
23024
- var DOM_INTERNAL_TAG = /* @__PURE__ */ Symbol("INTERNAL");
23025
- var PERMALINK = /* @__PURE__ */ Symbol("PERMALINK");
23026
-
23027
- // node_modules/hono/dist/jsx/dom/utils.js
23028
- var setInternalTagFlag = (fn) => {
23029
- fn[DOM_INTERNAL_TAG] = true;
23030
- return fn;
23031
- };
23032
-
23033
- // node_modules/hono/dist/jsx/dom/context.js
23034
- var createContextProviderFunction = (values) => ({ value, children }) => {
23035
- if (!children) {
23036
- return;
23037
- }
23038
- const props = {
23039
- children: [
23040
- {
23041
- tag: setInternalTagFlag(() => {
23042
- values.push(value);
23043
- }),
23044
- props: {}
23045
- }
23046
- ]
23047
- };
23048
- if (Array.isArray(children)) {
23049
- props.children.push(...children.flat());
23050
- } else {
23051
- props.children.push(children);
23052
- }
23053
- props.children.push({
23054
- tag: setInternalTagFlag(() => {
23055
- values.pop();
23056
- }),
23057
- props: {}
23058
- });
23059
- const res = { tag: "", props, type: "" };
23060
- res[DOM_ERROR_HANDLER] = (err) => {
23061
- values.pop();
23062
- throw err;
23063
- };
23064
- return res;
23065
- };
23066
-
23067
- // node_modules/hono/dist/jsx/context.js
23068
- var globalContexts = [];
23069
- var createContext = (defaultValue) => {
23070
- const values = [defaultValue];
23071
- const context = (props) => {
23072
- values.push(props.value);
23073
- let string4;
23074
- try {
23075
- string4 = props.children ? (Array.isArray(props.children) ? new JSXFragmentNode("", {}, props.children) : props.children).toString() : "";
23076
- } catch (e) {
23077
- values.pop();
23078
- throw e;
23079
- }
23080
- if (string4 instanceof Promise) {
23081
- return string4.finally(() => values.pop()).then((resString) => raw(resString, resString.callbacks));
23082
- } else {
23083
- values.pop();
23084
- return raw(string4);
23085
- }
23086
- };
23087
- context.values = values;
23088
- context.Provider = context;
23089
- context[DOM_RENDERER] = createContextProviderFunction(values);
23090
- globalContexts.push(context);
23091
- return context;
23092
- };
23093
- var useContext = (context) => {
23094
- return context.values.at(-1);
23095
- };
23096
-
23097
- // node_modules/hono/dist/jsx/intrinsic-element/common.js
23098
- var deDupeKeyMap = {
23099
- title: [],
23100
- script: ["src"],
23101
- style: ["data-href"],
23102
- link: ["href"],
23103
- meta: ["name", "httpEquiv", "charset", "itemProp"]
23104
- };
23105
- var domRenderers = {};
23106
- var dataPrecedenceAttr = "data-precedence";
23107
- var isStylesheetLinkWithPrecedence = (props) => props.rel === "stylesheet" && ("precedence" in props);
23108
- var shouldDeDupeByKey = (tagName, supportSort) => {
23109
- if (tagName === "link") {
23110
- return supportSort;
23111
- }
23112
- return deDupeKeyMap[tagName].length > 0;
23113
- };
23114
-
23115
- // node_modules/hono/dist/jsx/intrinsic-element/components.js
23116
- var exports_components = {};
23117
- __export(exports_components, {
23118
- title: () => title,
23119
- style: () => style,
23120
- script: () => script,
23121
- meta: () => meta2,
23122
- link: () => link,
23123
- input: () => input,
23124
- form: () => form,
23125
- button: () => button
23126
- });
23127
-
23128
- // node_modules/hono/dist/jsx/children.js
23129
- var toArray = (children) => Array.isArray(children) ? children : [children];
23130
-
23131
- // node_modules/hono/dist/jsx/intrinsic-element/components.js
23132
- var metaTagMap = /* @__PURE__ */ new WeakMap;
23133
- var insertIntoHead = (tagName, tag, props, precedence) => ({ buffer, context }) => {
23134
- if (!buffer) {
23135
- return;
23136
- }
23137
- const map2 = metaTagMap.get(context) || {};
23138
- metaTagMap.set(context, map2);
23139
- const tags = map2[tagName] ||= [];
23140
- let duped = false;
23141
- const deDupeKeys = deDupeKeyMap[tagName];
23142
- const deDupeByKey = shouldDeDupeByKey(tagName, precedence !== undefined);
23143
- if (deDupeByKey) {
23144
- LOOP:
23145
- for (const [, tagProps] of tags) {
23146
- if (tagName === "link" && !(tagProps.rel === "stylesheet" && tagProps[dataPrecedenceAttr] !== undefined)) {
23147
- continue;
23148
- }
23149
- for (const key of deDupeKeys) {
23150
- if ((tagProps?.[key] ?? null) === props?.[key]) {
23151
- duped = true;
23152
- break LOOP;
23153
- }
23154
- }
23155
- }
23156
- }
23157
- if (duped) {
23158
- buffer[0] = buffer[0].replaceAll(tag, "");
23159
- } else if (deDupeByKey || tagName === "link") {
23160
- tags.push([tag, props, precedence]);
23161
- } else {
23162
- tags.unshift([tag, props, precedence]);
23163
- }
23164
- if (buffer[0].indexOf("</head>") !== -1) {
23165
- let insertTags;
23166
- if (tagName === "link" || precedence !== undefined) {
23167
- const precedences = [];
23168
- insertTags = tags.map(([tag2, , tagPrecedence], index) => {
23169
- if (tagPrecedence === undefined) {
23170
- return [tag2, Number.MAX_SAFE_INTEGER, index];
23171
- }
23172
- let order = precedences.indexOf(tagPrecedence);
23173
- if (order === -1) {
23174
- precedences.push(tagPrecedence);
23175
- order = precedences.length - 1;
23176
- }
23177
- return [tag2, order, index];
23178
- }).sort((a, b) => a[1] - b[1] || a[2] - b[2]).map(([tag2]) => tag2);
23179
- } else {
23180
- insertTags = tags.map(([tag2]) => tag2);
23181
- }
23182
- insertTags.forEach((tag2) => {
23183
- buffer[0] = buffer[0].replaceAll(tag2, "");
23184
- });
23185
- buffer[0] = buffer[0].replace(/(?=<\/head>)/, insertTags.join(""));
23186
- }
23187
- };
23188
- var returnWithoutSpecialBehavior = (tag, children, props) => raw(new JSXNode(tag, props, toArray(children ?? [])).toString());
23189
- var documentMetadataTag = (tag, children, props, sort) => {
23190
- if ("itemProp" in props) {
23191
- return returnWithoutSpecialBehavior(tag, children, props);
23192
- }
23193
- let { precedence, blocking, ...restProps } = props;
23194
- precedence = sort ? precedence ?? "" : undefined;
23195
- if (sort) {
23196
- restProps[dataPrecedenceAttr] = precedence;
23197
- }
23198
- const string4 = new JSXNode(tag, restProps, toArray(children || [])).toString();
23199
- if (string4 instanceof Promise) {
23200
- return string4.then((resString) => raw(string4, [
23201
- ...resString.callbacks || [],
23202
- insertIntoHead(tag, resString, restProps, precedence)
23203
- ]));
23204
- } else {
23205
- return raw(string4, [insertIntoHead(tag, string4, restProps, precedence)]);
23206
- }
23207
- };
23208
- var title = ({ children, ...props }) => {
23209
- const nameSpaceContext = getNameSpaceContext();
23210
- if (nameSpaceContext) {
23211
- const context = useContext(nameSpaceContext);
23212
- if (context === "svg" || context === "head") {
23213
- return new JSXNode("title", props, toArray(children ?? []));
23214
- }
23215
- }
23216
- return documentMetadataTag("title", children, props, false);
23217
- };
23218
- var script = ({
23219
- children,
23220
- ...props
23221
- }) => {
23222
- const nameSpaceContext = getNameSpaceContext();
23223
- if (["src", "async"].some((k) => !props[k]) || nameSpaceContext && useContext(nameSpaceContext) === "head") {
23224
- return returnWithoutSpecialBehavior("script", children, props);
23225
- }
23226
- return documentMetadataTag("script", children, props, false);
23227
- };
23228
- var style = ({
23229
- children,
23230
- ...props
23231
- }) => {
23232
- if (!["href", "precedence"].every((k) => (k in props))) {
23233
- return returnWithoutSpecialBehavior("style", children, props);
23234
- }
23235
- props["data-href"] = props.href;
23236
- delete props.href;
23237
- return documentMetadataTag("style", children, props, true);
23238
- };
23239
- var link = ({ children, ...props }) => {
23240
- if (["onLoad", "onError"].some((k) => (k in props)) || props.rel === "stylesheet" && (!("precedence" in props) || ("disabled" in props))) {
23241
- return returnWithoutSpecialBehavior("link", children, props);
23242
- }
23243
- return documentMetadataTag("link", children, props, isStylesheetLinkWithPrecedence(props));
23244
- };
23245
- var meta2 = ({ children, ...props }) => {
23246
- const nameSpaceContext = getNameSpaceContext();
23247
- if (nameSpaceContext && useContext(nameSpaceContext) === "head") {
23248
- return returnWithoutSpecialBehavior("meta", children, props);
23249
- }
23250
- return documentMetadataTag("meta", children, props, false);
23251
- };
23252
- var newJSXNode = (tag, { children, ...props }) => new JSXNode(tag, props, toArray(children ?? []));
23253
- var form = (props) => {
23254
- if (typeof props.action === "function") {
23255
- props.action = PERMALINK in props.action ? props.action[PERMALINK] : undefined;
23256
- }
23257
- return newJSXNode("form", props);
23258
- };
23259
- var formActionableElement = (tag, props) => {
23260
- if (typeof props.formAction === "function") {
23261
- props.formAction = PERMALINK in props.formAction ? props.formAction[PERMALINK] : undefined;
23262
- }
23263
- return newJSXNode(tag, props);
23264
- };
23265
- var input = (props) => formActionableElement("input", props);
23266
- var button = (props) => formActionableElement("button", props);
23267
-
23268
- // node_modules/hono/dist/jsx/utils.js
23269
- var normalizeElementKeyMap = /* @__PURE__ */ new Map([
23270
- ["className", "class"],
23271
- ["htmlFor", "for"],
23272
- ["crossOrigin", "crossorigin"],
23273
- ["httpEquiv", "http-equiv"],
23274
- ["itemProp", "itemprop"],
23275
- ["fetchPriority", "fetchpriority"],
23276
- ["noModule", "nomodule"],
23277
- ["formAction", "formaction"]
23278
- ]);
23279
- var normalizeIntrinsicElementKey = (key) => normalizeElementKeyMap.get(key) || key;
23280
- var styleObjectForEach = (style2, fn) => {
23281
- for (const [k, v] of Object.entries(style2)) {
23282
- const key = k[0] === "-" || !/[A-Z]/.test(k) ? k : k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`);
23283
- 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);
23284
- }
23285
- };
23286
-
23287
- // node_modules/hono/dist/jsx/base.js
23288
- var nameSpaceContext = undefined;
23289
- var getNameSpaceContext = () => nameSpaceContext;
23290
- 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;
23291
- var emptyTags = [
23292
- "area",
23293
- "base",
23294
- "br",
23295
- "col",
23296
- "embed",
23297
- "hr",
23298
- "img",
23299
- "input",
23300
- "keygen",
23301
- "link",
23302
- "meta",
23303
- "param",
23304
- "source",
23305
- "track",
23306
- "wbr"
23307
- ];
23308
- var booleanAttributes = [
23309
- "allowfullscreen",
23310
- "async",
23311
- "autofocus",
23312
- "autoplay",
23313
- "checked",
23314
- "controls",
23315
- "default",
23316
- "defer",
23317
- "disabled",
23318
- "download",
23319
- "formnovalidate",
23320
- "hidden",
23321
- "inert",
23322
- "ismap",
23323
- "itemscope",
23324
- "loop",
23325
- "multiple",
23326
- "muted",
23327
- "nomodule",
23328
- "novalidate",
23329
- "open",
23330
- "playsinline",
23331
- "readonly",
23332
- "required",
23333
- "reversed",
23334
- "selected"
23335
- ];
23336
- var childrenToStringToBuffer = (children, buffer) => {
23337
- for (let i = 0, len = children.length;i < len; i++) {
23338
- const child = children[i];
23339
- if (typeof child === "string") {
23340
- escapeToBuffer(child, buffer);
23341
- } else if (typeof child === "boolean" || child === null || child === undefined) {
23342
- continue;
23343
- } else if (child instanceof JSXNode) {
23344
- child.toStringToBuffer(buffer);
23345
- } else if (typeof child === "number" || child.isEscaped) {
23346
- buffer[0] += child;
23347
- } else if (child instanceof Promise) {
23348
- buffer.unshift("", child);
23349
- } else {
23350
- childrenToStringToBuffer(child, buffer);
23351
- }
23352
- }
23353
- };
23354
- var JSXNode = class {
23355
- tag;
23356
- props;
23357
- key;
23358
- children;
23359
- isEscaped = true;
23360
- localContexts;
23361
- constructor(tag, props, children) {
23362
- this.tag = tag;
23363
- this.props = props;
23364
- this.children = children;
23365
- }
23366
- get type() {
23367
- return this.tag;
23368
- }
23369
- get ref() {
23370
- return this.props.ref || null;
23371
- }
23372
- toString() {
23373
- const buffer = [""];
23374
- this.localContexts?.forEach(([context, value]) => {
23375
- context.values.push(value);
23376
- });
23377
- try {
23378
- this.toStringToBuffer(buffer);
23379
- } finally {
23380
- this.localContexts?.forEach(([context]) => {
23381
- context.values.pop();
23382
- });
23383
- }
23384
- return buffer.length === 1 ? "callbacks" in buffer ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString() : buffer[0] : stringBufferToString(buffer, buffer.callbacks);
23385
- }
23386
- toStringToBuffer(buffer) {
23387
- const tag = this.tag;
23388
- const props = this.props;
23389
- let { children } = this;
23390
- buffer[0] += `<${tag}`;
23391
- const normalizeKey = nameSpaceContext && useContext(nameSpaceContext) === "svg" ? (key) => toSVGAttributeName(normalizeIntrinsicElementKey(key)) : (key) => normalizeIntrinsicElementKey(key);
23392
- for (let [key, v] of Object.entries(props)) {
23393
- key = normalizeKey(key);
23394
- if (key === "children") {} else if (key === "style" && typeof v === "object") {
23395
- let styleStr = "";
23396
- styleObjectForEach(v, (property, value) => {
23397
- if (value != null) {
23398
- styleStr += `${styleStr ? ";" : ""}${property}:${value}`;
23399
- }
23400
- });
23401
- buffer[0] += ' style="';
23402
- escapeToBuffer(styleStr, buffer);
23403
- buffer[0] += '"';
23404
- } else if (typeof v === "string") {
23405
- buffer[0] += ` ${key}="`;
23406
- escapeToBuffer(v, buffer);
23407
- buffer[0] += '"';
23408
- } else if (v === null || v === undefined) {} else if (typeof v === "number" || v.isEscaped) {
23409
- buffer[0] += ` ${key}="${v}"`;
23410
- } else if (typeof v === "boolean" && booleanAttributes.includes(key)) {
23411
- if (v) {
23412
- buffer[0] += ` ${key}=""`;
23413
- }
23414
- } else if (key === "dangerouslySetInnerHTML") {
23415
- if (children.length > 0) {
23416
- throw new Error("Can only set one of `children` or `props.dangerouslySetInnerHTML`.");
23417
- }
23418
- children = [raw(v.__html)];
23419
- } else if (v instanceof Promise) {
23420
- buffer[0] += ` ${key}="`;
23421
- buffer.unshift('"', v);
23422
- } else if (typeof v === "function") {
23423
- if (!key.startsWith("on") && key !== "ref") {
23424
- throw new Error(`Invalid prop '${key}' of type 'function' supplied to '${tag}'.`);
23425
- }
23426
- } else {
23427
- buffer[0] += ` ${key}="`;
23428
- escapeToBuffer(v.toString(), buffer);
23429
- buffer[0] += '"';
23430
- }
23431
- }
23432
- if (emptyTags.includes(tag) && children.length === 0) {
23433
- buffer[0] += "/>";
23434
- return;
23435
- }
23436
- buffer[0] += ">";
23437
- childrenToStringToBuffer(children, buffer);
23438
- buffer[0] += `</${tag}>`;
23439
- }
23440
- };
23441
- var JSXFunctionNode = class extends JSXNode {
23442
- toStringToBuffer(buffer) {
23443
- const { children } = this;
23444
- const props = { ...this.props };
23445
- if (children.length) {
23446
- props.children = children.length === 1 ? children[0] : children;
23447
- }
23448
- const res = this.tag.call(null, props);
23449
- if (typeof res === "boolean" || res == null) {
23450
- return;
23451
- } else if (res instanceof Promise) {
23452
- if (globalContexts.length === 0) {
23453
- buffer.unshift("", res);
23454
- } else {
23455
- const currentContexts = globalContexts.map((c) => [c, c.values.at(-1)]);
23456
- buffer.unshift("", res.then((childRes) => {
23457
- if (childRes instanceof JSXNode) {
23458
- childRes.localContexts = currentContexts;
23459
- }
23460
- return childRes;
23461
- }));
23462
- }
23463
- } else if (res instanceof JSXNode) {
23464
- res.toStringToBuffer(buffer);
23465
- } else if (typeof res === "number" || res.isEscaped) {
23466
- buffer[0] += res;
23467
- if (res.callbacks) {
23468
- buffer.callbacks ||= [];
23469
- buffer.callbacks.push(...res.callbacks);
23470
- }
23471
- } else {
23472
- escapeToBuffer(res, buffer);
23473
- }
23474
- }
23475
- };
23476
- var JSXFragmentNode = class extends JSXNode {
23477
- toStringToBuffer(buffer) {
23478
- childrenToStringToBuffer(this.children, buffer);
23479
- }
23480
- };
23481
- var initDomRenderer = false;
23482
- var jsxFn = (tag, props, children) => {
23483
- if (!initDomRenderer) {
23484
- for (const k in domRenderers) {
23485
- exports_components[k][DOM_RENDERER] = domRenderers[k];
23486
- }
23487
- initDomRenderer = true;
23488
- }
23489
- if (typeof tag === "function") {
23490
- return new JSXFunctionNode(tag, props, children);
23491
- } else if (exports_components[tag]) {
23492
- return new JSXFunctionNode(exports_components[tag], props, children);
23493
- } else if (tag === "svg" || tag === "head") {
23494
- nameSpaceContext ||= createContext("");
23495
- return new JSXNode(tag, props, [
23496
- new JSXFunctionNode(nameSpaceContext, {
23497
- value: tag
23498
- }, children)
23499
- ]);
23500
- } else {
23501
- return new JSXNode(tag, props, children);
23502
- }
23503
- };
23504
- var Fragment = ({
23505
- children
23506
- }) => {
23507
- return new JSXFragmentNode("", {
23508
- children
23509
- }, Array.isArray(children) ? children : children ? [children] : []);
23510
- };
23511
-
23512
- // node_modules/hono/dist/jsx/jsx-dev-runtime.js
23513
- function jsxDEV(tag, props, key) {
23514
- let node;
23515
- if (!props || !("children" in props)) {
23516
- node = jsxFn(tag, props, []);
23517
- } else {
23518
- const children = props.children;
23519
- node = Array.isArray(children) ? jsxFn(tag, props, children) : jsxFn(tag, props, [children]);
23520
- }
23521
- node.key = key;
23522
- return node;
23523
- }
23524
-
23525
- // src/ui/components/create-form.tsx
23526
- function CreateForm({ workspace }) {
23527
- return /* @__PURE__ */ jsxDEV("div", {
23528
- class: "form-card",
23529
- children: /* @__PURE__ */ jsxDEV("form", {
23530
- method: "post",
23531
- action: "/memories",
23532
- children: [
23533
- /* @__PURE__ */ jsxDEV("div", {
23534
- class: "field",
23535
- children: [
23536
- /* @__PURE__ */ jsxDEV("label", {
23537
- for: "new-content",
23538
- children: "Content"
23539
- }, undefined, false, undefined, this),
23540
- /* @__PURE__ */ jsxDEV("textarea", {
23541
- id: "new-content",
23542
- name: "content",
23543
- placeholder: "Fact, preference, decision...",
23544
- required: true
23545
- }, undefined, false, undefined, this)
23546
- ]
23547
- }, undefined, true, undefined, this),
23548
- /* @__PURE__ */ jsxDEV("div", {
23549
- class: "field",
23550
- children: [
23551
- /* @__PURE__ */ jsxDEV("label", {
23552
- for: "new-workspace",
23553
- children: "Workspace (optional)"
23554
- }, undefined, false, undefined, this),
23555
- /* @__PURE__ */ jsxDEV("input", {
23556
- id: "new-workspace",
23557
- name: "workspace",
23558
- type: "text",
23559
- placeholder: "/path/to/project",
23560
- value: workspace && workspace !== NO_WORKSPACE_FILTER ? workspace : ""
23561
- }, undefined, false, undefined, this)
23562
- ]
23563
- }, undefined, true, undefined, this),
23564
- /* @__PURE__ */ jsxDEV("div", {
23565
- class: "form-actions",
23566
- children: /* @__PURE__ */ jsxDEV("button", {
23567
- type: "submit",
23568
- class: "primary",
23569
- children: "Save"
23570
- }, undefined, false, undefined, this)
23571
- }, undefined, false, undefined, this)
23572
- ]
23573
- }, undefined, true, undefined, this)
23574
- }, undefined, false, undefined, this);
23575
- }
23576
-
23577
- // src/ui/components/memory-card.tsx
23578
- function MemoryCard({ memory, editing, showWorkspace, returnUrl }) {
23579
- return /* @__PURE__ */ jsxDEV("div", {
23580
- class: "card",
23581
- children: [
23582
- /* @__PURE__ */ jsxDEV("div", {
23583
- class: "card-header",
23584
- children: /* @__PURE__ */ jsxDEV("div", {
23585
- class: "card-meta",
23586
- children: [
23587
- showWorkspace && memory.workspace && /* @__PURE__ */ jsxDEV(Fragment, {
23588
- children: [
23589
- /* @__PURE__ */ jsxDEV("span", {
23590
- class: "badge",
23591
- children: memory.workspace
23592
- }, undefined, false, undefined, this),
23593
- " "
23594
- ]
23595
- }, undefined, true, undefined, this),
23596
- memory.updatedAt.toLocaleString()
23597
- ]
23598
- }, undefined, true, undefined, this)
23599
- }, undefined, false, undefined, this),
23600
- editing ? /* @__PURE__ */ jsxDEV("form", {
23601
- method: "post",
23602
- action: `/memories/${encodeURIComponent(memory.id)}/update`,
23603
- children: [
23604
- /* @__PURE__ */ jsxDEV("input", {
23605
- type: "hidden",
23606
- name: "returnUrl",
23607
- value: returnUrl
23608
- }, undefined, false, undefined, this),
23609
- /* @__PURE__ */ jsxDEV("textarea", {
23610
- name: "content",
23611
- required: true,
23612
- children: memory.content
23613
- }, undefined, false, undefined, this),
23614
- /* @__PURE__ */ jsxDEV("div", {
23615
- class: "card-actions",
23616
- children: [
23617
- /* @__PURE__ */ jsxDEV("button", {
23618
- type: "submit",
23619
- class: "primary",
23620
- children: "Save"
23621
- }, undefined, false, undefined, this),
23622
- /* @__PURE__ */ jsxDEV("a", {
23623
- href: returnUrl,
23624
- class: "btn",
23625
- children: "Cancel"
23626
- }, undefined, false, undefined, this)
23627
- ]
23628
- }, undefined, true, undefined, this)
23629
- ]
23630
- }, undefined, true, undefined, this) : /* @__PURE__ */ jsxDEV(Fragment, {
23631
- children: [
23632
- /* @__PURE__ */ jsxDEV("div", {
23633
- class: "card-content",
23634
- children: memory.content
23635
- }, undefined, false, undefined, this),
23636
- /* @__PURE__ */ jsxDEV("div", {
23637
- class: "card-actions",
23638
- children: [
23639
- /* @__PURE__ */ jsxDEV("a", {
23640
- href: `${returnUrl}${returnUrl.includes("?") ? "&" : "?"}edit=${encodeURIComponent(memory.id)}`,
23641
- class: "btn",
23642
- children: "Edit"
23643
- }, undefined, false, undefined, this),
23644
- /* @__PURE__ */ jsxDEV("form", {
23645
- method: "post",
23646
- action: `/memories/${encodeURIComponent(memory.id)}/delete`,
23647
- onsubmit: "return confirm('Delete this memory?')",
23648
- children: [
23649
- /* @__PURE__ */ jsxDEV("input", {
23650
- type: "hidden",
23651
- name: "returnUrl",
23652
- value: returnUrl
23653
- }, undefined, false, undefined, this),
23654
- /* @__PURE__ */ jsxDEV("button", {
23655
- type: "submit",
23656
- class: "danger",
23657
- children: "Delete"
23658
- }, undefined, false, undefined, this)
23659
- ]
23660
- }, undefined, true, undefined, this)
23661
- ]
23662
- }, undefined, true, undefined, this)
23663
- ]
23664
- }, undefined, true, undefined, this)
23665
- ]
23666
- }, undefined, true, undefined, this);
23667
- }
23668
-
23669
- // src/ui/components/sidebar.tsx
23670
- function Sidebar({ workspaces, selected }) {
23671
- return /* @__PURE__ */ jsxDEV("nav", {
23672
- class: "sidebar",
23673
- children: [
23674
- /* @__PURE__ */ jsxDEV("h2", {
23675
- children: "Workspaces"
23676
- }, undefined, false, undefined, this),
23677
- /* @__PURE__ */ jsxDEV("a", {
23678
- href: "/",
23679
- class: `sidebar-item all-item${selected === null ? " active" : ""}`,
23680
- children: "All"
23681
- }, undefined, false, undefined, this),
23682
- /* @__PURE__ */ jsxDEV("a", {
23683
- href: `/?workspace=${NO_WORKSPACE_FILTER}`,
23684
- class: `sidebar-item no-ws-item${selected === NO_WORKSPACE_FILTER ? " active" : ""}`,
23685
- children: "No workspace"
23686
- }, undefined, false, undefined, this),
23687
- workspaces.map((ws) => /* @__PURE__ */ jsxDEV("a", {
23688
- href: `/?workspace=${encodeURIComponent(ws)}`,
23689
- class: `sidebar-item ws-item${selected === ws ? " active" : ""}`,
23690
- title: ws,
23691
- children: /* @__PURE__ */ jsxDEV("span", {
23692
- children: ws.replace(/\/$/, "")
23693
- }, undefined, false, undefined, this)
23694
- }, undefined, false, undefined, this))
23695
- ]
23696
- }, undefined, true, undefined, this);
23697
- }
23698
-
23699
- // src/ui/components/page.tsx
23700
- function buildUrl(base, overrides) {
23701
- const url = new URL(base, "http://localhost");
23702
- for (const [key, value] of Object.entries(overrides)) {
23703
- url.searchParams.set(key, value);
23704
- }
23705
- return `${url.pathname}${url.search}`;
23706
- }
23707
- function Page({
23708
- memories,
23709
- workspaces,
23710
- selectedWorkspace,
23711
- editingId,
23712
- currentPage,
23713
- hasMore,
23714
- showCreate
23715
- }) {
23716
- const params = new URLSearchParams;
23717
- if (selectedWorkspace)
23718
- params.set("workspace", selectedWorkspace);
23719
- if (currentPage > 1)
23720
- params.set("page", String(currentPage));
23721
- const baseUrl = params.size > 0 ? `/?${params.toString()}` : "/";
23722
- const showGroupHeaders = selectedWorkspace === null && new Set(memories.map((m) => m.workspace ?? null)).size > 1;
23723
- const grouped = [];
23724
- for (const m of memories) {
23725
- const key = m.workspace ?? "(no workspace)";
23726
- const last = grouped[grouped.length - 1];
23727
- if (last && last.key === key) {
23728
- last.items.push(m);
23729
- } else {
23730
- grouped.push({ key, items: [m] });
23731
- }
23732
- }
23733
- const hasPrev = currentPage > 1;
23734
- return /* @__PURE__ */ jsxDEV("html", {
23735
- lang: "en",
23736
- children: [
23737
- /* @__PURE__ */ jsxDEV("head", {
23738
- children: [
23739
- /* @__PURE__ */ jsxDEV("meta", {
23740
- charset: "utf-8"
23741
- }, undefined, false, undefined, this),
23742
- /* @__PURE__ */ jsxDEV("meta", {
23743
- name: "viewport",
23744
- content: "width=device-width, initial-scale=1"
23745
- }, undefined, false, undefined, this),
23746
- /* @__PURE__ */ jsxDEV("title", {
23747
- children: "agent-memory"
23748
- }, undefined, false, undefined, this),
23749
- /* @__PURE__ */ jsxDEV("style", {
23750
- children: styles_default
23751
- }, undefined, false, undefined, this)
23752
- ]
23753
- }, undefined, true, undefined, this),
23754
- /* @__PURE__ */ jsxDEV("body", {
23755
- children: /* @__PURE__ */ jsxDEV("div", {
23756
- class: "layout",
23757
- children: [
23758
- /* @__PURE__ */ jsxDEV(Sidebar, {
23759
- workspaces,
23760
- selected: selectedWorkspace
23761
- }, undefined, false, undefined, this),
23762
- /* @__PURE__ */ jsxDEV("div", {
23763
- class: "main",
23764
- children: [
23765
- /* @__PURE__ */ jsxDEV("header", {
23766
- children: [
23767
- /* @__PURE__ */ jsxDEV("h1", {
23768
- children: "agent-memory"
23769
- }, undefined, false, undefined, this),
23770
- showCreate ? /* @__PURE__ */ jsxDEV("a", {
23771
- href: baseUrl,
23772
- class: "btn",
23773
- children: "Cancel"
23774
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("a", {
23775
- href: buildUrl(baseUrl, { create: "1" }),
23776
- class: "btn primary",
23777
- children: "New Memory"
23778
- }, undefined, false, undefined, this)
23779
- ]
23780
- }, undefined, true, undefined, this),
23781
- showCreate && /* @__PURE__ */ jsxDEV(CreateForm, {
23782
- workspace: selectedWorkspace
23783
- }, undefined, false, undefined, this),
23784
- memories.length === 0 && !hasPrev ? /* @__PURE__ */ jsxDEV("div", {
23785
- class: "empty",
23786
- children: "No memories found."
23787
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV(Fragment, {
23788
- children: [
23789
- grouped.map(({ key, items }) => /* @__PURE__ */ jsxDEV(Fragment, {
23790
- children: [
23791
- showGroupHeaders && /* @__PURE__ */ jsxDEV("div", {
23792
- class: "ws-group-header",
23793
- children: key
23794
- }, undefined, false, undefined, this),
23795
- items.map((m) => /* @__PURE__ */ jsxDEV(MemoryCard, {
23796
- memory: m,
23797
- editing: editingId === m.id,
23798
- showWorkspace: selectedWorkspace === null,
23799
- returnUrl: baseUrl
23800
- }, undefined, false, undefined, this))
23801
- ]
23802
- }, undefined, true, undefined, this)),
23803
- (hasPrev || hasMore) && /* @__PURE__ */ jsxDEV("div", {
23804
- class: "pagination",
23805
- children: [
23806
- hasPrev ? /* @__PURE__ */ jsxDEV("a", {
23807
- href: buildUrl(baseUrl, { page: String(currentPage - 1) }),
23808
- class: "btn",
23809
- children: "Previous"
23810
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {}, undefined, false, undefined, this),
23811
- /* @__PURE__ */ jsxDEV("span", {
23812
- class: "page-info",
23813
- children: [
23814
- "Page ",
23815
- currentPage
23816
- ]
23817
- }, undefined, true, undefined, this),
23818
- hasMore ? /* @__PURE__ */ jsxDEV("a", {
23819
- href: buildUrl(baseUrl, { page: String(currentPage + 1) }),
23820
- class: "btn",
23821
- children: "Next"
23822
- }, undefined, false, undefined, this) : /* @__PURE__ */ jsxDEV("span", {}, undefined, false, undefined, this)
23823
- ]
23824
- }, undefined, true, undefined, this)
23825
- ]
23826
- }, undefined, true, undefined, this)
23827
- ]
23828
- }, undefined, true, undefined, this)
23829
- ]
23830
- }, undefined, true, undefined, this)
23831
- }, undefined, false, undefined, this)
23832
- ]
23833
- }, undefined, true, undefined, this);
23834
- }
23835
-
23836
- // src/ui/routes/page-routes.tsx
23837
- var DEFAULT_LIST_LIMIT3 = 15;
23838
- function createPageRoutes(memory) {
23839
- const app = new Hono2;
23840
- async function renderPage(c) {
23841
- const workspace = c.req.query("workspace") ?? null;
23842
- const pageNum = Math.max(Number(c.req.query("page")) || 1, 1);
23843
- const editingId = c.req.query("edit") ?? null;
23844
- const showCreate = c.req.query("create") === "1";
23845
- const isNoWorkspace = workspace === NO_WORKSPACE_FILTER;
23846
- const wsFilter = workspace && !isNoWorkspace ? workspace : undefined;
23847
- const page = await memory.list({
23848
- workspace: wsFilter,
23849
- global: isNoWorkspace,
23850
- offset: (pageNum - 1) * DEFAULT_LIST_LIMIT3,
23851
- limit: DEFAULT_LIST_LIMIT3
23852
- });
23853
- const workspaces = await memory.listWorkspaces();
23854
- return c.html(/* @__PURE__ */ jsxDEV(Page, {
23855
- memories: page.items,
23856
- workspaces,
23857
- selectedWorkspace: workspace,
23858
- editingId,
23859
- currentPage: pageNum,
23860
- hasMore: page.hasMore,
23861
- showCreate
23862
- }, undefined, false, undefined, this));
23863
- }
23864
- async function createMemory(c) {
23865
- const form2 = await c.req.parseBody();
23866
- const content = typeof form2.content === "string" ? form2.content : "";
23867
- const workspace = typeof form2.workspace === "string" ? form2.workspace : undefined;
23868
- try {
23869
- await memory.create({ content, workspace });
23870
- } catch (error2) {
23871
- if (!(error2 instanceof ValidationError)) {
23872
- throw error2;
23873
- }
23874
- }
23875
- const wsParam = workspace?.trim() ? `/?workspace=${encodeURIComponent(workspace.trim())}` : "/";
23876
- return c.redirect(wsParam);
23877
- }
23878
- async function updateMemory(c) {
23879
- const form2 = await c.req.parseBody();
23880
- const content = typeof form2.content === "string" ? form2.content : "";
23881
- const returnUrl = safeReturnUrl(form2.returnUrl);
23882
- const id = c.req.param("id") ?? "";
23883
- try {
23884
- await memory.update({ id, content });
23885
- } catch (error2) {
23886
- if (!(error2 instanceof NotFoundError) && !(error2 instanceof ValidationError))
23887
- throw error2;
23888
- }
23889
- return c.redirect(returnUrl);
23890
- }
23891
- async function deleteMemory(c) {
23892
- const form2 = await c.req.parseBody();
23893
- const returnUrl = safeReturnUrl(form2.returnUrl);
23894
- const id = c.req.param("id") ?? "";
23895
- try {
23896
- await memory.delete({ id });
23897
- } catch (error2) {
23898
- if (!(error2 instanceof NotFoundError))
23899
- throw error2;
23900
- }
23901
- return c.redirect(returnUrl);
23902
- }
23903
- app.get("/", renderPage);
23904
- app.post("/memories", createMemory);
23905
- app.post("/memories/:id/update", updateMemory);
23906
- app.post("/memories/:id/delete", deleteMemory);
23907
- return app;
23908
- }
23909
- function safeReturnUrl(value) {
23910
- if (typeof value === "string" && value.startsWith("/"))
23911
- return value;
23912
- return "/";
23913
- }
23914
-
23915
- // src/ui/server.tsx
23916
- function startWebServer(memory, options) {
23917
- const app = new Hono2;
23918
- app.route("/", createPageRoutes(memory));
23919
- return serve({ fetch: app.fetch, port: options.port });
23920
- }
23921
-
23922
- // src/workspace-resolver.ts
23923
- import { execFile } from "node:child_process";
23924
- import { basename, dirname as dirname2 } from "node:path";
23925
- import { promisify } from "node:util";
23926
- var execFileAsync = promisify(execFile);
23927
- function createGitWorkspaceResolver(options = {}) {
23928
- const getGitCommonDir = options.getGitCommonDir ?? defaultGetGitCommonDir;
23929
- const cache = new Map;
23930
- return {
23931
- async resolve(workspace) {
23932
- const trimmed = normalizeOptionalString2(workspace);
23933
- if (!trimmed) {
23934
- return;
23935
- }
23936
- const cached2 = cache.get(trimmed);
23937
- if (cached2) {
23938
- return cached2;
23939
- }
23940
- const pending = resolveWorkspace(trimmed, getGitCommonDir);
23941
- cache.set(trimmed, pending);
23942
- return pending;
23943
- }
23944
- };
23945
- }
23946
- async function resolveWorkspace(workspace, getGitCommonDir) {
23947
- try {
23948
- const gitCommonDir = (await getGitCommonDir(workspace)).trim();
23949
- if (basename(gitCommonDir) !== ".git") {
23950
- return workspace;
23951
- }
23952
- return dirname2(gitCommonDir);
23953
- } catch {
23954
- return workspace;
23955
- }
23956
- }
23957
- async function defaultGetGitCommonDir(cwd) {
23958
- const { stdout } = await execFileAsync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
23959
- cwd
23960
- });
23961
- return stdout.trim();
23962
- }
23963
- function normalizeOptionalString2(value) {
23964
- const trimmed = value?.trim();
23965
- return trimmed ? trimmed : undefined;
20484
+ async function defaultGetGitCommonDir(cwd) {
20485
+ const { stdout } = await execFileAsync("git", ["rev-parse", "--path-format=absolute", "--git-common-dir"], {
20486
+ cwd
20487
+ });
20488
+ return stdout.trim();
23966
20489
  }
23967
20490
 
23968
20491
  // src/index.ts
23969
20492
  var config2 = resolveConfig();
23970
20493
  var workspaceResolver = createGitWorkspaceResolver();
23971
- var database = await openMemoryDatabase(config2.databasePath, { workspaceResolver });
23972
- var repository2 = new SqliteMemoryRepository(database);
20494
+ var repository2 = new FilesystemMemoryRepository(config2.storePath);
23973
20495
  var memoryService = new MemoryService(repository2, workspaceResolver);
23974
- if (config2.uiMode) {
23975
- let shutdown = function() {
23976
- server.close();
23977
- database.close();
23978
- process.exit(0);
23979
- };
23980
- const server = startWebServer(memoryService, { port: config2.uiPort });
23981
- const addr = server.address();
23982
- const port = typeof addr === "object" && addr ? addr.port : config2.uiPort;
23983
- console.log(`agent-memory UI running at http://localhost:${port}`);
23984
- process.on("SIGINT", shutdown);
23985
- process.on("SIGTERM", shutdown);
23986
- } else {
23987
- const server = createMcpServer(memoryService, version2);
23988
- const transport = new StdioServerTransport;
23989
- try {
23990
- await server.connect(transport);
23991
- } catch (error2) {
23992
- console.error(error2 instanceof Error ? error2.message : "Failed to start agent-memory.");
23993
- database.close();
23994
- process.exit(1);
23995
- }
20496
+ var server = createMcpServer(memoryService, version2);
20497
+ var transport = new StdioServerTransport;
20498
+ try {
20499
+ await server.connect(transport);
20500
+ } catch (error2) {
20501
+ console.error(error2 instanceof Error ? error2.message : "Failed to start agent-memory.");
20502
+ process.exit(1);
23996
20503
  }