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