sessiongraph-app-darwin-arm64 1.0.20 → 1.0.22

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 (18) hide show
  1. package/package.json +2 -2
  2. package/payload/SessionGraph.app/Contents/Info.plist +2 -2
  3. package/payload/SessionGraph.app/Contents/MacOS/sessiongraph +0 -0
  4. package/payload/SessionGraph.app/Contents/Resources/resources/cli-launcher.mjs +2 -1
  5. package/payload/SessionGraph.app/Contents/Resources/resources/cli-package.json +1 -1
  6. package/payload/SessionGraph.app/Contents/Resources/resources/cli.mjs +58 -27
  7. package/payload/SessionGraph.app/Contents/Resources/resources/server.mjs +2575 -85
  8. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{index-CxnS4waR.css → index-BROemBuT.css} +1 -1
  9. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{index-BwNazXTF.js → index-ClDHxy66.js} +1 -1
  10. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/index-DK0pBf-7.js +192 -0
  11. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{index-nDYf67iK.js → index-DWWZZL6C.js} +1 -1
  12. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{index-CUSJvhgf.js → index-tIWYckIn.js} +1 -1
  13. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{public-viewer-BMIcmydl.js → public-viewer-B1aKDYpa.js} +1 -1
  14. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{scene-oSl4S0W6.js → scene-BCuZ73oU.js} +1 -1
  15. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/{share-D7wrWEkV.js → share-mJrTMarx.js} +3 -3
  16. package/payload/SessionGraph.app/Contents/Resources/resources/web/index.html +2 -2
  17. package/payload/SessionGraph.app/Contents/_CodeSignature/CodeResources +42 -42
  18. package/payload/SessionGraph.app/Contents/Resources/resources/web/assets/index-TSi2Km_w.js +0 -186
@@ -2139,7 +2139,7 @@ import { createServer } from "node:http";
2139
2139
  import { createReadStream } from "node:fs";
2140
2140
  import { stat as stat5 } from "node:fs/promises";
2141
2141
  import { fileURLToPath as fileURLToPath5 } from "node:url";
2142
- import { resolve as resolve4, extname, sep as sep4 } from "node:path";
2142
+ import { resolve as resolve5, extname, sep as sep5 } from "node:path";
2143
2143
  import { randomBytes as randomBytes2, timingSafeEqual } from "node:crypto";
2144
2144
 
2145
2145
  // server/adapters/opencode.ts
@@ -2615,7 +2615,7 @@ async function terminate(info, options, timing) {
2615
2615
  await rm2(options.file ?? fallback2(), { force: true });
2616
2616
  }
2617
2617
  function delay(milliseconds) {
2618
- return new Promise((resolve5) => setTimeout(resolve5, milliseconds));
2618
+ return new Promise((resolve6) => setTimeout(resolve6, milliseconds));
2619
2619
  }
2620
2620
  var Service = { discover, ensure, stop, headers: headers2 };
2621
2621
 
@@ -3141,10 +3141,10 @@ function blockEvents(message2, content, transform = (v3) => v3) {
3141
3141
  return [eventFor(message2, id2, "event", `${part.type || "Unknown"} content`, "This content type is not represented as text.", { ...fields3, partial: true })];
3142
3142
  });
3143
3143
  }
3144
- function userBlockEvents(message2, content, normalize) {
3144
+ function userBlockEvents(message2, content, normalize2) {
3145
3145
  const context2 = [];
3146
3146
  return blockEvents(message2, content, (value) => {
3147
- const text2 = normalize(value);
3147
+ const text2 = normalize2(value);
3148
3148
  context2.push(Boolean(value && !text2));
3149
3149
  return text2 || value;
3150
3150
  }).map((event) => event.kind === "message" && context2.shift() ? { ...event, kind: "event", role: "system", name: "Session context", nativeType: "user-context" } : event);
@@ -3214,10 +3214,10 @@ function directory(path, base) {
3214
3214
  return flavor ? flavor.resolve(base || path, path) : void 0;
3215
3215
  }
3216
3216
  function commands(command) {
3217
- const result = [], words = [];
3217
+ const result = [], words2 = [];
3218
3218
  let word = "", active = false, quote = "";
3219
3219
  const flush = () => {
3220
- if (active) words.push(word);
3220
+ if (active) words2.push(word);
3221
3221
  word = "";
3222
3222
  active = false;
3223
3223
  };
@@ -3241,8 +3241,8 @@ function commands(command) {
3241
3241
  if (c === "&" && command[i + 1] !== "&") return;
3242
3242
  if (c === "&") {
3243
3243
  flush();
3244
- if (!words.length) return;
3245
- result.push(words.splice(0));
3244
+ if (!words2.length) return;
3245
+ result.push(words2.splice(0));
3246
3246
  i++;
3247
3247
  } else if (/\s/.test(c)) flush();
3248
3248
  else {
@@ -3252,8 +3252,8 @@ function commands(command) {
3252
3252
  }
3253
3253
  if (quote) return;
3254
3254
  flush();
3255
- if (!words.length && result.length) return;
3256
- if (words.length) result.push(words);
3255
+ if (!words2.length && result.length) return;
3256
+ if (words2.length) result.push(words2);
3257
3257
  return result;
3258
3258
  }
3259
3259
  function invocation(input, cwd2) {
@@ -3262,8 +3262,8 @@ function invocation(input, cwd2) {
3262
3262
  const explicit = string2(args.workdir ?? args.cwd ?? args.working_directory);
3263
3263
  return { command, cwd: explicit !== void 0 ? directory(explicit) : directory(cwd2) };
3264
3264
  }
3265
- function operation(words) {
3266
- const [verb, ...args] = words;
3265
+ function operation(words2) {
3266
+ const [verb, ...args] = words2;
3267
3267
  if (verb === "commit") {
3268
3268
  let amend = false;
3269
3269
  for (let i = 0; i < args.length; i++) {
@@ -3392,6 +3392,25 @@ function withSourcePaths(adapter, configured) {
3392
3392
  })
3393
3393
  };
3394
3394
  }
3395
+ function sourcePathHint(id2) {
3396
+ const hints = {
3397
+ opencode: "OpenCode data directory or SQLite file (normally ~/.local/share/opencode/opencode.db). Supports V1 and V2 offline.",
3398
+ "claude-code": "Claude home containing projects/ and transcripts/. Automatic discovery searches accessible locations across the computer; a custom path restricts it to this home.",
3399
+ codex: "Codex home containing sessions/ and archived_sessions/ (normally ~/.codex).",
3400
+ "t3-code": "T3 home containing its local server history (normally ~/.t3).",
3401
+ cursor: "Cursor CLI home (normally ~/.cursor); IDE data still uses SESSIONGRAPH_CURSOR_USER_DATA_DIR.",
3402
+ gemini: "Gemini home containing tmp/ (normally ~/.gemini).",
3403
+ "qwen-code": "Qwen home containing projects/ (normally ~/.qwen).",
3404
+ pi: "Pi sessions directory (normally ~/.pi/agent/sessions).",
3405
+ copilot: "Copilot home containing session-state/ (normally ~/.copilot).",
3406
+ "copilot-chat": "VS Code user-data directory containing User/.",
3407
+ cline: "Extension home containing tasks/, or CLI home containing data/sessions/.",
3408
+ "roo-code": "Extension global-storage directory containing tasks/.",
3409
+ "kilo-code": "Extension global-storage directory containing tasks/.",
3410
+ continue: "Continue home containing sessions/ (normally ~/.continue)."
3411
+ };
3412
+ return hints[id2] || "History root, as for SESSIONGRAPH_<SOURCE_ID>_HISTORY_DIR; native formats and discovery bounds still apply.";
3413
+ }
3395
3414
 
3396
3415
  // server/adapters/harness-paths.ts
3397
3416
  var homePath = (...parts) => join3(homedir3(), ...parts);
@@ -3762,6 +3781,12 @@ function hasTable(db2, name) {
3762
3781
  return typeof row?.sql === "string" && !/CREATE\s+VIRTUAL/i.test(row.sql);
3763
3782
  }
3764
3783
 
3784
+ // server/sqlite.ts
3785
+ function iterate(db2, sql, ...values) {
3786
+ const statement = db2.prepare(sql);
3787
+ return Object.assign(statement.iterate(...values), { retainedStatement: statement });
3788
+ }
3789
+
3765
3790
  // server/adapters/sqlite-histories.ts
3766
3791
  var budget;
3767
3792
  var rowBytes = (row) => Object.values(row).reduce((n, v3) => n + (typeof v3 === "string" ? Buffer.byteLength(v3) : v3 instanceof Uint8Array ? v3.byteLength : 8), 0);
@@ -3792,14 +3817,18 @@ function rows(db2, table, fields3, filter, order, limit = 5e4) {
3792
3817
  for (const name of [...fields3, ...filter ? [filter[0]] : [], ...order ? [order] : []]) if (!/^[a-zA-Z_][\w]*$/.test(name)) throw new Error("Invalid history column.");
3793
3818
  if (filter && !available.has(filter[0])) throw new Error("Unsupported history relation.");
3794
3819
  const size = (f) => `length(CAST("${f}" AS BLOB))`;
3795
- const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN "${f}" END AS "${f}"` : `NULL AS "${f}"`).join(",");
3820
+ const select = fields3.map((f) => available.has(f) ? `CASE WHEN ${size(f)}<=32000000 THEN CASE WHEN typeof("${f}")='text' THEN CAST("${f}" AS BLOB) ELSE "${f}" END END AS "${f}", typeof("${f}")='text' AS "__sessiongraph_text_${f}"` : `NULL AS "${f}"`).join(",");
3796
3821
  const oversized = fields3.filter((f) => available.has(f)).map((f) => `COALESCE(${size(f)},0)>32000000`).join(" OR ") || "0";
3797
3822
  const query = `SELECT ${select}, (${oversized}) AS __sessiongraph_oversized FROM "${table}"${filter ? ` WHERE "${filter[0]}"=?` : ""}${order && available.has(order) ? ` ORDER BY "${order}"` : ""} LIMIT ${limit + 1}`;
3798
3823
  const result = [];
3799
3824
  let bytes2 = 0;
3800
- for (const row of db2.prepare(query).iterate(...filter ? [filter[1]] : [])) {
3825
+ for (const row of iterate(db2, query, ...filter ? [filter[1]] : [])) {
3801
3826
  if (row.__sessiongraph_oversized) throw new Error("History field exceeds the 32 MB snapshot limit.");
3802
3827
  delete row.__sessiongraph_oversized;
3828
+ for (const field of fields3) {
3829
+ if (row[`__sessiongraph_text_${field}`] && row[field] instanceof Uint8Array) row[field] = Buffer.from(row[field]).toString("utf8");
3830
+ delete row[`__sessiongraph_text_${field}`];
3831
+ }
3803
3832
  const size2 = rowBytes(row);
3804
3833
  bytes2 += size2;
3805
3834
  consume(size2, 1);
@@ -4086,7 +4115,7 @@ function historyRevisions(db2, schema) {
4086
4115
  const names = columns(db2, table);
4087
4116
  if (!names.has("session_id")) continue;
4088
4117
  const updated = names.has("time_updated") ? "MAX(time_updated)" : "NULL";
4089
- for (const row of db2.prepare(`SELECT session_id, COUNT(*) AS count, ${updated} AS updated FROM "${table}" GROUP BY session_id`).iterate()) {
4118
+ for (const row of iterate(db2, `SELECT session_id, COUNT(*) AS count, ${updated} AS updated FROM "${table}" GROUP BY session_id`)) {
4090
4119
  const id2 = text(row.session_id);
4091
4120
  result.set(id2, [...result.get(id2) || [], row.count, row.updated]);
4092
4121
  }
@@ -4175,7 +4204,7 @@ function discoverDatabase(db2, path, snapshot2) {
4175
4204
  }
4176
4205
  function payloadRows(db2, query, values, budget2) {
4177
4206
  const result = [];
4178
- for (const row of db2.prepare(query).iterate(...values)) {
4207
+ for (const row of iterate(db2, query, ...values)) {
4179
4208
  if (typeof row.data !== "string") throw new Error("OpenCode history contains a missing or oversized JSON field (4 MB limit).");
4180
4209
  budget2.bytes += Buffer.byteLength(row.data);
4181
4210
  budget2.records++;
@@ -4187,7 +4216,7 @@ function payloadRows(db2, query, values, budget2) {
4187
4216
  var opencodeAdapter = {
4188
4217
  id: "opencode",
4189
4218
  name: "OpenCode",
4190
- description: "Local SQLite history \xB7 V1 and V2 \xB7 no running service needed",
4219
+ description: "Local SQLite history \xB7 V1 and V2",
4191
4220
  capabilities: { history: true, forks: true, children: true, files: true },
4192
4221
  async detect() {
4193
4222
  return (await openCodeDatabases()).length > 0;
@@ -4218,14 +4247,14 @@ var opencodeAdapter = {
4218
4247
  if (!schema) throw new Error("OpenCode history schema changed.");
4219
4248
  const budget2 = { bytes: 0, records: 0 };
4220
4249
  const data = `CASE WHEN length(CAST(data AS BLOB))<=${MAX_JSON} THEN data END AS data`;
4221
- const page = payloadRows(
4250
+ const page2 = payloadRows(
4222
4251
  db2,
4223
4252
  `SELECT id, time_created, ${schema.version === "2" ? "type" : "NULL AS type"}, ${data}
4224
4253
  FROM "${schema.message}" WHERE session_id=? ORDER BY ${schema.version === "2" ? "seq DESC" : "time_created DESC, id DESC"} LIMIT ${PAGE + 1} OFFSET ?`,
4225
4254
  [candidate.session.nativeID, offset],
4226
4255
  budget2
4227
4256
  );
4228
- const messages = page.slice(0, PAGE).map((row) => {
4257
+ const messages = page2.slice(0, PAGE).map((row) => {
4229
4258
  const body2 = object3(sqliteJSON(row.data));
4230
4259
  if (schema.version === "1" && !["user", "assistant"].includes(body2.role)) throw new Error("Unsupported OpenCode V1 message.");
4231
4260
  if (schema.version === "2" && !text(row.type)) throw new Error("Missing OpenCode message type.");
@@ -4243,7 +4272,7 @@ var opencodeAdapter = {
4243
4272
  }
4244
4273
  return message2;
4245
4274
  });
4246
- return { messages, cursor: page.length > PAGE ? String(offset + PAGE) : void 0 };
4275
+ return { messages, cursor: page2.length > PAGE ? String(offset + PAGE) : void 0 };
4247
4276
  }, candidate.locator.snapshot, true);
4248
4277
  }
4249
4278
  };
@@ -31209,12 +31238,12 @@ function envelopeHistory(path, value) {
31209
31238
  });
31210
31239
  if (!messages.length) throw new Error("No readable conversation records.");
31211
31240
  const meta = rows2.find((r) => r.cwd) || header;
31212
- const last = [...rows2].reverse().find((r) => r.message?.model || typeof r.model === "string");
31241
+ const last2 = [...rows2].reverse().find((r) => r.message?.model || typeof r.model === "string");
31213
31242
  return {
31214
31243
  nativeID,
31215
31244
  messages,
31216
31245
  partial: true,
31217
- session: { directory: text(meta.cwd), created: time(header.timestamp), title: text(header.title), model: text(last?.message?.model || last?.model) || "Unknown model" },
31246
+ session: { directory: text(meta.cwd), created: time(header.timestamp), title: text(header.title), model: text(last2?.message?.model || last2?.model) || "Unknown model" },
31218
31247
  note: partial ? "Some transcript records could not be imported." : void 0
31219
31248
  };
31220
31249
  }
@@ -31353,7 +31382,7 @@ function createClaudeLocationScanner(options) {
31353
31382
  const homes2 = /* @__PURE__ */ new Set();
31354
31383
  let queue = [], index = 0;
31355
31384
  let visited = /* @__PURE__ */ new Set(), skipped = /* @__PURE__ */ new Set(), limited = false, initialized = false, finishedAt;
31356
- let last, lastAt = -Infinity, job;
31385
+ let last2, lastAt = -Infinity, job;
31357
31386
  async function scan() {
31358
31387
  const started = now();
31359
31388
  if (!initialized || finishedAt !== void 0 && started - finishedAt >= (options.refreshMs ?? 3e5)) {
@@ -31444,9 +31473,9 @@ function createClaudeLocationScanner(options) {
31444
31473
  }
31445
31474
  return () => {
31446
31475
  if (job) return job;
31447
- if (last && now() - lastAt < 1e3) return Promise.resolve(last);
31476
+ if (last2 && now() - lastAt < 1e3) return Promise.resolve(last2);
31448
31477
  job = scan().then((result) => {
31449
- last = result;
31478
+ last2 = result;
31450
31479
  lastAt = now();
31451
31480
  return result;
31452
31481
  }).finally(() => {
@@ -31786,10 +31815,10 @@ async function sessionNames() {
31786
31815
  let cursor, count = 0;
31787
31816
  try {
31788
31817
  do {
31789
- const page = await readJSONL(join13(root(), "session_index.jsonl"), cursor, 2e6, 1e3);
31790
- for (const { value } of page.rows) if (typeof value.id === "string" && typeof value.thread_name === "string" && value.thread_name.trim()) names.set(value.id, value.thread_name.trim().slice(0, 300));
31791
- cursor = page.cursor;
31792
- count += page.rows.length;
31818
+ const page2 = await readJSONL(join13(root(), "session_index.jsonl"), cursor, 2e6, 1e3);
31819
+ for (const { value } of page2.rows) if (typeof value.id === "string" && typeof value.thread_name === "string" && value.thread_name.trim()) names.set(value.id, value.thread_name.trim().slice(0, 300));
31820
+ cursor = page2.cursor;
31821
+ count += page2.rows.length;
31793
31822
  } while (cursor !== void 0 && count < 1e5);
31794
31823
  } catch (error) {
31795
31824
  if (error.code !== "ENOENT") throw error;
@@ -31920,12 +31949,12 @@ var codexAdapter = {
31920
31949
  },
31921
31950
  async read(candidate, cursor) {
31922
31951
  if (!cursor) candidate.locator.executionCwd = "";
31923
- const page = await readJSONL(candidate.locator.path, Number(cursor || 0));
31924
- if (page.cursor === void 0 && await revision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
31925
- return { messages: page.rows.flatMap((r) => {
31952
+ const page2 = await readJSONL(candidate.locator.path, Number(cursor || 0));
31953
+ if (page2.cursor === void 0 && await revision(candidate.locator.path) !== candidate.revision) throw new Error("Session changed during import; import again to capture the latest messages.");
31954
+ return { messages: page2.rows.flatMap((r) => {
31926
31955
  const msg = codexRecord(r.value, r.offset, candidate);
31927
31956
  return msg ? [msg] : [];
31928
- }), cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: page.partial };
31957
+ }), cursor: page2.cursor === void 0 ? void 0 : String(page2.cursor), partial: page2.partial };
31929
31958
  }
31930
31959
  };
31931
31960
 
@@ -32189,11 +32218,11 @@ function readV2(db2, candidate, cursor) {
32189
32218
  FROM orchestration_v2_projection_turn_items
32190
32219
  WHERE thread_id=? AND (ordinal>? OR (ordinal=? AND turn_item_id>?))
32191
32220
  ORDER BY ordinal, turn_item_id LIMIT ?`).all(MAX_ITEM_JSON, candidate.locator.threadID, ordinal, ordinal, id2, PAGE2 + 1);
32192
- const page = rows2.slice(0, PAGE2), last = page.at(-1);
32221
+ const page2 = rows2.slice(0, PAGE2), last2 = page2.at(-1);
32193
32222
  return {
32194
- messages: page.map((row) => v2Message(row, candidate.session.directory)),
32195
- cursor: rows2.length > PAGE2 && last ? `${last.ordinal}:${last.turn_item_id}` : void 0,
32196
- partial: candidate.locator.metadataPartial === "1" || page.some((row) => !parsedObject(row.payload_json))
32223
+ messages: page2.map((row) => v2Message(row, candidate.session.directory)),
32224
+ cursor: rows2.length > PAGE2 && last2 ? `${last2.ordinal}:${last2.turn_item_id}` : void 0,
32225
+ partial: candidate.locator.metadataPartial === "1" || page2.some((row) => !parsedObject(row.payload_json))
32197
32226
  };
32198
32227
  }
32199
32228
  function readV1(db2, candidate, cursor) {
@@ -32530,7 +32559,7 @@ function discoverComposers(path, workspace = "") {
32530
32559
  for (const table of ["cursorDiskKV", "ItemTable"]) {
32531
32560
  if (!hasTable(db2, table)) continue;
32532
32561
  let failed = 0, count = 0;
32533
- const rows2 = db2.prepare(`SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table} WHERE key LIKE 'composerData:%' AND value IS NOT NULL ORDER BY key LIMIT 20001`).iterate(MAX_VALUE2);
32562
+ const rows2 = iterate(db2, `SELECT key, CASE WHEN length(value)<=? THEN value END AS value FROM ${table} WHERE key LIKE 'composerData:%' AND value IS NOT NULL ORDER BY key LIMIT 20001`, MAX_VALUE2);
32534
32563
  for (const row of rows2) {
32535
32564
  if (++count > 2e4) {
32536
32565
  warnings.push("Cursor Composer listing reached its 20,000-session limit.");
@@ -32756,9 +32785,9 @@ function createCursorAdapter(options = {}) {
32756
32785
  session.created = cursorTime(meta.createdAt) || cursorTime(extra2.createdAtMs);
32757
32786
  session.updated = cursorTime(extra2.updatedAtMs) || stats.mtimeMs;
32758
32787
  if (kind === "transcript") {
32759
- const page = await readJSONL(path, 0, 2e6, 100);
32788
+ const page2 = await readJSONL(path, 0, 2e6, 100);
32760
32789
  let first = 0;
32761
- for (const row of page.rows) {
32790
+ for (const row of page2.rows) {
32762
32791
  const message2 = cursorMessage(row.value, `offset:${row.offset}`);
32763
32792
  if (message2?.time && (!first || message2.time < first)) first = message2.time;
32764
32793
  if (session.title === "Cursor session" && message2?.role === "user") {
@@ -32868,15 +32897,15 @@ function createCursorAdapter(options = {}) {
32868
32897
  }
32869
32898
  const offset = Number(cursor || 0);
32870
32899
  if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid Cursor transcript cursor.");
32871
- const page = await readJSONL(locator.path, offset);
32872
- const messages = page.rows.flatMap((row) => {
32900
+ const page2 = await readJSONL(locator.path, offset);
32901
+ const messages = page2.rows.flatMap((row) => {
32873
32902
  const message2 = cursorMessage(row.value, `offset:${row.offset}`);
32874
- if (!message2) page.partial = true;
32903
+ if (!message2) page2.partial = true;
32875
32904
  return message2 && (message2.role !== "system" || row.value?.type === "turn_ended") ? [message2] : [];
32876
32905
  });
32877
32906
  await verify();
32878
- if (!offset && page.cursor === void 0 && !messages.length) throw new Error("Transcript has no readable messages.");
32879
- return { messages, cursor: page.cursor === void 0 ? void 0 : String(page.cursor), partial: true, note: [...notes, page.partial ? "Some transcript records could not be imported." : void 0].filter(Boolean).join(" ") };
32907
+ if (!offset && page2.cursor === void 0 && !messages.length) throw new Error("Transcript has no readable messages.");
32908
+ return { messages, cursor: page2.cursor === void 0 ? void 0 : String(page2.cursor), partial: true, note: [...notes, page2.partial ? "Some transcript records could not be imported." : void 0].filter(Boolean).join(" ") };
32880
32909
  }
32881
32910
  };
32882
32911
  }
@@ -34094,10 +34123,141 @@ var abbreviatedSHA = (sha) => sha.length !== 40 && sha.length !== 64;
34094
34123
 
34095
34124
  // server/library-query.ts
34096
34125
  import { createHash as createHash3 } from "node:crypto";
34126
+ import { homedir as homedir14 } from "node:os";
34127
+ import { resolve as resolve4, relative as relative2, isAbsolute as isAbsolute6, sep as sep4 } from "node:path";
34097
34128
 
34098
34129
  // packages/core/src/layout.ts
34130
+ var PALETTE = ["#b0e9d6", "#8eaff4", "#d7a1f1", "#eac594", "#8cdbdf", "#e7a3b8", "#a8ca91"];
34131
+ function hash(text2) {
34132
+ let value = 2166136261;
34133
+ for (let i = 0; i < text2.length; i++) value = Math.imul(value ^ text2.charCodeAt(i), 16777619);
34134
+ value = Math.imul(value ^ value >>> 16, 2246822507);
34135
+ value = Math.imul(value ^ value >>> 13, 3266489909);
34136
+ value ^= value >>> 16;
34137
+ return (value >>> 0) / 4294967295;
34138
+ }
34139
+ function directoryLabel(directory3) {
34140
+ return directoryPath(directory3).split("/").at(-1) || "/";
34141
+ }
34099
34142
  var directoryPath = (directory3) => (/^(?:[a-z]:[\\/]|\\\\)/i.test(directory3) ? directory3.replace(/\\/g, "/") : directory3).replace(/\/+$/, "") || (directory3.startsWith("/") ? "/" : "");
34100
34143
  var laneKey = (session) => session.directory ? JSON.stringify(["directory", directoryPath(session.directory)]) : JSON.stringify(["project", session.source || "opencode", session.projectID || session.id]);
34144
+ var sessionEnd = (session) => Math.max(session.created, session.activity?.lastMessageAt || session.created);
34145
+ var timeX = (time4, graph) => {
34146
+ const frame = graph.timeFrame || graph;
34147
+ return (time4 - frame.start) / Math.max(1, frame.end - frame.start) * 300 - 150;
34148
+ };
34149
+ var trailPosition = (node, x3) => [x3, node.position[1], node.position[2]];
34150
+ function makeGraph(sessions, projects, previous, grouping) {
34151
+ if (!sessions.length) return { nodes: [], edges: [], lanes: [], start: 0, end: 0 };
34152
+ const keyFor = (session) => {
34153
+ if (!grouping) return laneKey(session);
34154
+ const checkout = grouping === "repository" ? session.checkout?.repository : session.checkout?.worktree;
34155
+ if (checkout) return JSON.stringify([grouping, checkout]);
34156
+ return session.directory ? JSON.stringify(["directory", directoryPath(session.directory)]) : JSON.stringify([grouping, null]);
34157
+ };
34158
+ const ordered = [...sessions].sort((a, b) => a.created - b.created || a.id.localeCompare(b.id));
34159
+ const start = ordered[0].created;
34160
+ const end = ordered.reduce((latest, session) => Math.max(latest, sessionEnd(session)), start + 36e5);
34161
+ const timeFrame = previous?.nodes.length ? previous.timeFrame || { start: previous.start, end: previous.end } : { start, end };
34162
+ const groups = /* @__PURE__ */ new Map();
34163
+ for (const session of ordered) {
34164
+ const key = keyFor(session);
34165
+ const group = groups.get(key) || [];
34166
+ group.push(session);
34167
+ groups.set(key, group);
34168
+ }
34169
+ const sortedGroups = [...groups].sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]));
34170
+ const slots = new Map(previous?.lanes.map((lane, index) => [lane.key, lane.slot ?? index]));
34171
+ let nextSlot = Math.max(-1, ...slots.values()) + 1;
34172
+ for (const [key] of sortedGroups) if (!slots.has(key)) slots.set(key, nextSlot++);
34173
+ sortedGroups.sort((a, b) => slots.get(a[0]) - slots.get(b[0]));
34174
+ const lanes = [];
34175
+ const nodes = [];
34176
+ const worktrees = new Set(projects.flatMap((project2) => project2.worktrees.map(directoryPath)));
34177
+ sortedGroups.forEach(([key, group]) => {
34178
+ const index = slots.get(key);
34179
+ const angle = index * 2.399963;
34180
+ const distance = index === 0 ? 0 : 15 + Math.sqrt(index) * 14;
34181
+ const y = Math.cos(angle) * distance;
34182
+ const z4 = Math.sin(angle) * distance * 0.7;
34183
+ const color = PALETTE[index % PALETTE.length];
34184
+ const project2 = projects.find((p) => p.id === group[0].projectID);
34185
+ const directory3 = group[0].directory;
34186
+ const lane = {
34187
+ key,
34188
+ slot: index,
34189
+ color,
34190
+ label: grouping === "repository" ? group[0].checkout?.repositoryLabel || (directory3 ? directoryLabel(directory3) : "Unknown repository") : grouping === "worktree" ? group[0].checkout ? directoryLabel(group[0].checkout.worktree) : directory3 ? directoryLabel(directory3) : "Unknown worktree" : directory3 ? directoryLabel(directory3) : project2?.name || group[0].projectID || "Unknown directory",
34191
+ kind: grouping === "worktree" && group[0].checkout || !grouping && directory3 && worktrees.has(directoryPath(directory3)) ? "worktree" : "directory",
34192
+ y,
34193
+ z: z4,
34194
+ nodes: []
34195
+ };
34196
+ for (const session of group) {
34197
+ const x3 = timeX(sessionEnd(session), timeFrame);
34198
+ const startX = timeX(session.created, timeFrame);
34199
+ const seed = hash(session.id);
34200
+ const isBranch = Boolean(session.parentID || session.forkID);
34201
+ const spread = isBranch ? 12 : 6;
34202
+ const wave = Math.sin((startX + 150) / 65 + index * 0.7) * 3.5;
34203
+ const tokens = typeof session.tokens === "number" && Number.isFinite(session.tokens) ? Math.max(0, session.tokens) : 0;
34204
+ const node = {
34205
+ session,
34206
+ position: [x3, y + wave + (seed - 0.5) * spread, z4 + (hash(session.id + "z") - 0.5) * spread],
34207
+ startPosition: [startX, 0, 0],
34208
+ color,
34209
+ // Usage adds a restrained cube-root weight without oversized outliers.
34210
+ // Keep an absolute scale across filters and cap the full radius at 1.4.
34211
+ radius: 0.35 + Math.min(1.05, Math.cbrt(tokens / 1e5) * 0.3)
34212
+ };
34213
+ nodes.push(node);
34214
+ lane.nodes.push(node);
34215
+ }
34216
+ lanes.push(lane);
34217
+ });
34218
+ const ids = new Set(ordered.map((s) => s.id));
34219
+ const edges = [];
34220
+ for (const session of ordered) {
34221
+ if (session.forkID && ids.has(session.forkID)) edges.push({ from: session.forkID, to: session.id, kind: "fork" });
34222
+ else if (session.parentID && ids.has(session.parentID)) edges.push({ from: session.parentID, to: session.id, kind: "child" });
34223
+ }
34224
+ const byID = new Map(nodes.map((node) => [node.session.id, node]));
34225
+ const placed = /* @__PURE__ */ new Set();
34226
+ for (const lane of previous?.lanes || []) for (const old of lane.nodes) {
34227
+ const node = byID.get(old.session.id);
34228
+ if (node && keyFor(node.session) === lane.key) {
34229
+ node.position[1] = old.position[1];
34230
+ node.position[2] = old.position[2];
34231
+ placed.add(node.session.id);
34232
+ }
34233
+ }
34234
+ function place(node) {
34235
+ const chain = [], visited = /* @__PURE__ */ new Set();
34236
+ let current = node;
34237
+ while (current && !placed.has(current.session.id) && !visited.has(current.session.id)) {
34238
+ visited.add(current.session.id);
34239
+ const parentID = current.session.forkID || current.session.parentID;
34240
+ const candidate = parentID ? byID.get(parentID) : void 0;
34241
+ const parent2 = candidate && keyFor(candidate.session) === keyFor(current.session) ? candidate : void 0;
34242
+ chain.push({ node: current, parent: parent2 });
34243
+ current = parent2;
34244
+ }
34245
+ for (const { node: node2, parent: parent2 } of chain.reverse()) {
34246
+ const id2 = node2.session.id;
34247
+ if (parent2) {
34248
+ const direction = hash(id2 + "branch") > 0.5 ? 1 : -1;
34249
+ node2.position[1] = parent2.position[1] + direction * (9 + hash(id2) * 15);
34250
+ node2.position[2] = parent2.position[2] + (hash(id2 + "depth") - 0.5) * 18;
34251
+ }
34252
+ placed.add(id2);
34253
+ }
34254
+ }
34255
+ ordered.forEach((session) => place(byID.get(session.id)));
34256
+ nodes.forEach((node) => {
34257
+ node.startPosition = trailPosition(node, node.startPosition[0]);
34258
+ });
34259
+ return { nodes, edges, lanes, start, end, timeFrame };
34260
+ }
34101
34261
 
34102
34262
  // src/session-links.ts
34103
34263
  function visibleSessions(sessions) {
@@ -34116,6 +34276,9 @@ function visibleSessions(sessions) {
34116
34276
  forkID: session.forkID ? unique.get(session.forkID) || session.forkID : void 0
34117
34277
  }));
34118
34278
  }
34279
+ function sessionMatchesSource(session, source) {
34280
+ return !source || session.source === source || Boolean(session.source === "t3-code" && session.linkedSessionIDs?.some((id2) => id2.startsWith(`${source}:`)));
34281
+ }
34119
34282
 
34120
34283
  // server/library-query.ts
34121
34284
  var LibraryError = class extends Error {
@@ -34130,6 +34293,7 @@ var LibraryError = class extends Error {
34130
34293
  function invalid(message2) {
34131
34294
  throw new LibraryError("INVALID_ARGUMENT", message2, 2);
34132
34295
  }
34296
+ var localPath = (path) => resolve4(path === "~" ? homedir14() : path.startsWith("~/") ? resolve4(homedir14(), path.slice(2)) : path);
34133
34297
  var fingerprint2 = (value) => createHash3("sha256").update(JSON.stringify(value)).digest("hex");
34134
34298
  function pageLimit(value = 50) {
34135
34299
  if (!Number.isSafeInteger(value) || value < 1 || value > 200) invalid("Limit must be an integer from 1 to 200.");
@@ -34149,6 +34313,31 @@ function pageOffset(cursor, key) {
34149
34313
  return parsed.offset;
34150
34314
  }
34151
34315
  var nextCursor = (key, offset) => Buffer.from(JSON.stringify({ key, offset })).toString("base64url");
34316
+ function page(items, key, options = {}) {
34317
+ const limit = pageLimit(options.limit), offset = pageOffset(options.cursor, key);
34318
+ return { items: items.slice(offset, offset + limit), total: items.length, nextCursor: offset + limit < items.length ? nextCursor(key, offset + limit) : null };
34319
+ }
34320
+ var relationshipOf = (s) => s.forkID ? "fork" : s.parentID ? "child" : "root";
34321
+ function filterSessions(sessions, filters2 = {}) {
34322
+ return sessions.filter((session) => {
34323
+ if (filters2.sources?.length && !filters2.sources.some((source) => sessionMatchesSource(session, source))) return false;
34324
+ if (filters2.directory) {
34325
+ if (!session.directory || !isAbsolute6(session.directory)) return false;
34326
+ const path = relative2(filters2.directory, resolve4(session.directory));
34327
+ if (path === ".." || path.startsWith(`..${sep4}`) || isAbsolute6(path)) return false;
34328
+ }
34329
+ if (filters2.project && session.projectID !== filters2.project) return false;
34330
+ if (filters2.model && session.model !== filters2.model) return false;
34331
+ if (filters2.origin && (session.origin ?? "unknown") !== filters2.origin) return false;
34332
+ if (filters2.relationship && relationshipOf(session) !== filters2.relationship) return false;
34333
+ if (filters2.archived === "exclude" && session.archived || filters2.archived === "only" && !session.archived) return false;
34334
+ const end = sessionEnd(session);
34335
+ if (filters2.dateField === "message") return true;
34336
+ const lower = filters2.dateField === "created" ? session.created : end;
34337
+ const upper = filters2.dateField === "lastActivity" ? end : session.created;
34338
+ return !(filters2.since !== void 0 && lower < filters2.since || filters2.until !== void 0 && upper > filters2.until);
34339
+ }).sort((a, b) => sessionEnd(b) - sessionEnd(a) || a.id.localeCompare(b.id));
34340
+ }
34152
34341
 
34153
34342
  // server/commit-store.ts
34154
34343
  var COMMIT_SCHEMA = `CREATE TABLE IF NOT EXISTS session_commits (
@@ -34166,7 +34355,7 @@ function writeCommits(db2, session) {
34166
34355
  if (!supported.has(session.source || "")) return { ...base, state: "unavailable", count: null, note: "Commit history unavailable for this source." };
34167
34356
  const calls = /* @__PURE__ */ new Map();
34168
34357
  const results = /* @__PURE__ */ new Map();
34169
- const rows2 = () => db2.prepare("SELECT data FROM timeline_items WHERE session_id=? AND kind IN ('tool_call','tool_result') ORDER BY ordinal").iterate(session.id);
34358
+ const rows2 = () => iterate(db2, "SELECT data FROM timeline_items WHERE session_id=? AND kind IN ('tool_call','tool_result') ORDER BY ordinal", session.id);
34170
34359
  let tools = 0, partial = session.coverage?.history !== "complete" || Boolean(db2.prepare("SELECT partial FROM timeline_coverage WHERE session_id=?").get(session.id)?.partial);
34171
34360
  for (const row of rows2()) {
34172
34361
  const item = JSON.parse(String(row.data));
@@ -34521,7 +34710,7 @@ var SessionGraphStore = class {
34521
34710
  try {
34522
34711
  this.db.exec(EVENT_SCHEMA);
34523
34712
  for (const { id: id2 } of this.db.prepare("SELECT id FROM sessions").all()) {
34524
- writeEvents(this.db, String(id2), this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(id2));
34713
+ writeEvents(this.db, String(id2), iterate(this.db, "SELECT data FROM messages WHERE session_id=? ORDER BY ordinal", id2));
34525
34714
  }
34526
34715
  this.db.exec("PRAGMA user_version=4; COMMIT;");
34527
34716
  } catch (error) {
@@ -34550,8 +34739,8 @@ var SessionGraphStore = class {
34550
34739
  if (paths2) this.setting("sourcePaths", Object.fromEntries(Object.entries(paths2).filter(([id2]) => !retired.has(id2))));
34551
34740
  const view = this.setting("viewState");
34552
34741
  if (view && typeof view.sourceID === "string" && retired.has(view.sourceID)) this.setting("viewState", { ...view, sourceID: "" });
34553
- const remove = this.db.prepare("DELETE FROM sources WHERE id=?");
34554
- for (const id2 of retired) remove.run(id2);
34742
+ const remove2 = this.db.prepare("DELETE FROM sources WHERE id=?");
34743
+ for (const id2 of retired) remove2.run(id2);
34555
34744
  this.db.exec("PRAGMA user_version=6; COMMIT");
34556
34745
  } catch (error) {
34557
34746
  this.db.exec("ROLLBACK");
@@ -34673,7 +34862,7 @@ var SessionGraphStore = class {
34673
34862
  this.db.prepare("DELETE FROM messages WHERE session_id=?").run(s.id);
34674
34863
  const insert = this.db.prepare("INSERT INTO messages (session_id,id,ordinal,data,time,is_user) VALUES (?,?,?,?,?,?) ON CONFLICT(session_id,id) DO UPDATE SET ordinal=excluded.ordinal,data=excluded.data,time=excluded.time,is_user=excluded.is_user");
34675
34864
  messages.forEach((message2, i) => insert.run(s.id, message2.id, i, JSON.stringify(message2), message2.eventOnly ? null : messageTime(message2.time), Number(isUserMessage(message2))));
34676
- writeEvents(this.db, s.id, this.db.prepare("SELECT data FROM messages WHERE session_id=? ORDER BY ordinal").iterate(s.id));
34865
+ writeEvents(this.db, s.id, iterate(this.db, "SELECT data FROM messages WHERE session_id=? ORDER BY ordinal", s.id));
34677
34866
  const commits = writeCommits(this.db, s);
34678
34867
  if (candidate.pullRequests !== void 0) {
34679
34868
  this.db.prepare("DELETE FROM session_pull_requests WHERE session_id=?").run(s.id);
@@ -34787,9 +34976,9 @@ var SessionGraphStore = class {
34787
34976
  }
34788
34977
  }
34789
34978
  content(id2, cursor) {
34790
- const page = this.messagePage(id2, Number(cursor || 0));
34979
+ const page2 = this.messagePage(id2, Number(cursor || 0));
34791
34980
  let remaining = 64e3, truncated = false;
34792
- const fragments = page.messages.flatMap((m) => {
34981
+ const fragments = page2.messages.flatMap((m) => {
34793
34982
  truncated ||= Boolean(m.partial);
34794
34983
  return m.fragments.flatMap((f) => {
34795
34984
  const text2 = f.text.slice(0, Math.min(remaining, 8e3));
@@ -34799,7 +34988,7 @@ var SessionGraphStore = class {
34799
34988
  });
34800
34989
  });
34801
34990
  truncated ||= this.getSession(id2)?.coverage?.history !== "complete";
34802
- return { id: id2, fragments, messages: page.messages.length, nextCursor: page.next, truncated };
34991
+ return { id: id2, fragments, messages: page2.messages.length, nextCursor: page2.next, truncated };
34803
34992
  }
34804
34993
  messages(id2, options = {}) {
34805
34994
  return this.readSnapshot(id2, (session) => {
@@ -34841,10 +35030,10 @@ var SessionGraphStore = class {
34841
35030
  }
34842
35031
  detail(id2, cursor) {
34843
35032
  return this.readSnapshot(id2, (session) => {
34844
- const page = this.messagePage(id2, Number(cursor || 0), 120);
35033
+ const page2 = this.messagePage(id2, Number(cursor || 0), 120);
34845
35034
  const files = /* @__PURE__ */ new Map(), tools = /* @__PURE__ */ new Map();
34846
35035
  const locations = [];
34847
- for (const message2 of page.messages) {
35036
+ for (const message2 of page2.messages) {
34848
35037
  for (const file of message2.files) {
34849
35038
  const previous = files.get(file.path);
34850
35039
  files.set(file.path, { ...file, source: previous?.source === "snapshot" ? "snapshot" : file.source, steps: (previous?.steps || 0) + file.steps });
@@ -34866,10 +35055,10 @@ var SessionGraphStore = class {
34866
35055
  files: [...files.values()].sort((a, b) => b.steps - a.steps),
34867
35056
  tools: [...tools].map(([name, count]) => ({ name, count })),
34868
35057
  locations,
34869
- messagesScanned: page.messages.length,
34870
- snapshotSteps: page.messages.reduce((n, m) => n + (m.snapshots || 0), 0),
34871
- nextCursor: page.next,
34872
- partial: Boolean(page.next) || session.coverage?.history !== "complete",
35058
+ messagesScanned: page2.messages.length,
35059
+ snapshotSteps: page2.messages.reduce((n, m) => n + (m.snapshots || 0), 0),
35060
+ nextCursor: page2.next,
35061
+ partial: Boolean(page2.next) || session.coverage?.history !== "complete",
34873
35062
  loadedAt: Date.now(),
34874
35063
  note: session.coverage?.note || (session.coverage?.history === "pending" ? "Waiting for import." : void 0)
34875
35064
  };
@@ -34940,8 +35129,8 @@ var Importer = class {
34940
35129
  status = { running: false, discovered: 0, imported: 0, unchanged: 0, failed: 0, errors: [], warnings: [] };
34941
35130
  job;
34942
35131
  adapters;
34943
- async sources() {
34944
- return Promise.all(this.adapters.map(async (adapter) => ({ id: adapter.id, name: adapter.name, description: adapter.description, capabilities: adapter.capabilities, available: await adapter.detect().catch(() => false), selected: this.store.selected().includes(adapter.id), ...this.store.sourceInfo(adapter.id) })));
35132
+ async sources(ids) {
35133
+ return Promise.all(this.adapters.filter((adapter) => !ids || ids.includes(adapter.id)).map(async (adapter) => ({ id: adapter.id, name: adapter.name, description: adapter.description, capabilities: adapter.capabilities, available: await adapter.detect().catch(() => false), selected: this.store.selected().includes(adapter.id), ...this.store.sourceInfo(adapter.id) })));
34945
35134
  }
34946
35135
  start(ids, automatic = false) {
34947
35136
  return this.begin(ids, automatic, true);
@@ -35015,11 +35204,11 @@ var Importer = class {
35015
35204
  const cursors = /* @__PURE__ */ new Set();
35016
35205
  let cursor, partial = false, characters = 0, pages = 0, note;
35017
35206
  do {
35018
- const page = await adapter.read(candidate, cursor);
35019
- partial ||= Boolean(page.partial);
35020
- note = page.note || note;
35207
+ const page2 = await adapter.read(candidate, cursor);
35208
+ partial ||= Boolean(page2.partial);
35209
+ note = page2.note || note;
35021
35210
  let limited = false;
35022
- for (const message2 of page.messages) {
35211
+ for (const message2 of page2.messages) {
35023
35212
  if (!message2.id) continue;
35024
35213
  const previous = messages.get(message2.id);
35025
35214
  if (previous) {
@@ -35046,7 +35235,7 @@ var Importer = class {
35046
35235
  characters += message2.fragments.reduce((n, f) => n + f.text.length, 0);
35047
35236
  messages.set(message2.id, message2);
35048
35237
  }
35049
- cursor = page.cursor;
35238
+ cursor = page2.cursor;
35050
35239
  pages++;
35051
35240
  if (cursor && cursors.has(cursor)) throw new Error("Source returned a repeated history cursor.");
35052
35241
  if (cursor) cursors.add(cursor);
@@ -35088,7 +35277,7 @@ var Importer = class {
35088
35277
  import { execFile, spawn as spawn2 } from "node:child_process";
35089
35278
  import { promisify } from "node:util";
35090
35279
  import { stat as stat4 } from "node:fs/promises";
35091
- import { basename as basename12, dirname as dirname11, isAbsolute as isAbsolute7 } from "node:path";
35280
+ import { basename as basename12, dirname as dirname11, isAbsolute as isAbsolute8 } from "node:path";
35092
35281
 
35093
35282
  // src/launch-links.ts
35094
35283
  var HARNESSES = [
@@ -35123,14 +35312,14 @@ function resumeArgs(value) {
35123
35312
  // server/harnesses.ts
35124
35313
  import { access, stat as stat3 } from "node:fs/promises";
35125
35314
  import { constants as constants6 } from "node:fs";
35126
- import { homedir as homedir14 } from "node:os";
35127
- import { delimiter, isAbsolute as isAbsolute6, join as join25 } from "node:path";
35315
+ import { homedir as homedir15 } from "node:os";
35316
+ import { delimiter, isAbsolute as isAbsolute7, join as join25 } from "node:path";
35128
35317
  async function executable(name) {
35129
- const home = homedir14();
35318
+ const home = homedir15();
35130
35319
  const directories = [...(process.env.PATH || "").split(delimiter), join25(home, ".local", "bin"), join25(home, ".opencode", "bin"), join25(home, ".bun", "bin"), join25(home, "Library", "pnpm"), "/opt/homebrew/bin", "/usr/local/bin"];
35131
35320
  if (process.platform === "win32" && process.env.APPDATA) directories.push(join25(process.env.APPDATA, "npm"));
35132
35321
  if (process.platform === "win32" && process.env.SystemRoot) directories.push(join25(process.env.SystemRoot, "System32", "WindowsPowerShell", "v1.0"));
35133
- const candidates = isAbsolute6(name) ? [name] : directories.filter((dir) => isAbsolute6(dir)).flatMap((dir) => (process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""]).map((extension) => join25(dir, name + extension)));
35322
+ const candidates = isAbsolute7(name) ? [name] : directories.filter((dir) => isAbsolute7(dir)).flatMap((dir) => (process.platform === "win32" ? [".exe", ".cmd", ".bat", ""] : [""]).map((extension) => join25(dir, name + extension)));
35134
35323
  for (const path of candidates) {
35135
35324
  try {
35136
35325
  if ((await stat3(path)).isFile()) {
@@ -35146,7 +35335,7 @@ async function harnessExecutable(target) {
35146
35335
  const path = await executable(name);
35147
35336
  if (path) return path;
35148
35337
  if (target === "codex" && process.platform === "darwin") {
35149
- return await executable("/Applications/Codex.app/Contents/Resources/codex") || await executable(join25(homedir14(), "Applications/Codex.app/Contents/Resources/codex"));
35338
+ return await executable("/Applications/Codex.app/Contents/Resources/codex") || await executable(join25(homedir15(), "Applications/Codex.app/Contents/Resources/codex"));
35150
35339
  }
35151
35340
  }
35152
35341
  async function terminalExecutable() {
@@ -35271,7 +35460,7 @@ async function getLaunchConnection(session) {
35271
35460
  }
35272
35461
  async function prepareLaunch(store, session, target, directory3 = session.directory) {
35273
35462
  if (!isHarness(target)) invalid("Choose a supported destination app.");
35274
- if (typeof directory3 !== "string" || !isAbsolute7(directory3) || /[\x00-\x1f\x7f]/.test(directory3)) invalid("Choose an absolute working directory.");
35463
+ if (typeof directory3 !== "string" || !isAbsolute8(directory3) || /[\x00-\x1f\x7f]/.test(directory3)) invalid("Choose an absolute working directory.");
35275
35464
  if (!(await stat4(directory3).catch(() => void 0))?.isDirectory()) invalid("Choose an accessible working directory.");
35276
35465
  const [binary, terminal] = await Promise.all([harnessExecutable(target), terminalExecutable()]);
35277
35466
  let args;
@@ -35319,12 +35508,12 @@ async function launchTerminal(session, prepared) {
35319
35508
  const invocation2 = commandInvocation(prepared.command, terminal);
35320
35509
  try {
35321
35510
  if (process.platform === "linux") {
35322
- await new Promise((resolve5, reject) => {
35511
+ await new Promise((resolve6, reject) => {
35323
35512
  const child = spawn2(invocation2.file, invocation2.args, { detached: true, stdio: "ignore" });
35324
35513
  child.once("error", reject);
35325
35514
  child.once("spawn", () => {
35326
35515
  child.unref();
35327
- resolve5();
35516
+ resolve6();
35328
35517
  });
35329
35518
  });
35330
35519
  } else await exec(invocation2.file, invocation2.args, { timeout: 15e3, maxBuffer: 16384 });
@@ -35525,7 +35714,7 @@ var PublishingError = class extends Error {
35525
35714
  status;
35526
35715
  };
35527
35716
  var SITE = "https://sessiongraph.ai";
35528
- var hash = (value) => createHash5("sha256").update(value).digest("hex");
35717
+ var hash2 = (value) => createHash5("sha256").update(value).digest("hex");
35529
35718
  var token = () => randomBytes(32).toString("base64url");
35530
35719
  function preparePublicGraph(store, ids, inputSettings) {
35531
35720
  if (!Array.isArray(ids) || !ids.length || ids.length > PUBLIC_GRAPH_MAX_SESSIONS || ids.some((id2) => typeof id2 !== "string") || new Set(ids).size !== ids.length) throw new PublishingError("Choose a valid set of sessions.");
@@ -35622,7 +35811,7 @@ var PublishingClient = class {
35622
35811
  }
35623
35812
  login() {
35624
35813
  if (this.busy) throw new PublishingError("Wait for the current account operation to finish.", 409);
35625
- const verifier = token(), challenge = hash(verifier);
35814
+ const verifier = token(), challenge = hash2(verifier);
35626
35815
  this.pending = { verifier, expires: Date.now() + 6e5, nextPoll: 0 };
35627
35816
  return { url: `${SITE}/api/auth/github?device=${challenge}`, code: challenge.slice(0, 8).toUpperCase() };
35628
35817
  }
@@ -35690,7 +35879,7 @@ var PublishingClient = class {
35690
35879
  // server/git-checkouts.ts
35691
35880
  import { execFile as execFile2 } from "node:child_process";
35692
35881
  import { createHash as createHash6 } from "node:crypto";
35693
- import { basename as basename13, isAbsolute as isAbsolute8 } from "node:path";
35882
+ import { basename as basename13, isAbsolute as isAbsolute9 } from "node:path";
35694
35883
  import { promisify as promisify2 } from "node:util";
35695
35884
  var exec2 = promisify2(execFile2);
35696
35885
  var cache = /* @__PURE__ */ new Map();
@@ -35724,7 +35913,7 @@ function remoteIdentity(remote) {
35724
35913
  async function inspect(directory3) {
35725
35914
  try {
35726
35915
  const [worktree, common, ...extra2] = (await git(directory3, "rev-parse", "--path-format=absolute", "--show-toplevel", "--git-common-dir")).split(/\r?\n/);
35727
- if (extra2.length || !isAbsolute8(worktree) || !isAbsolute8(common)) return;
35916
+ if (extra2.length || !isAbsolute9(worktree) || !isAbsolute9(common)) return;
35728
35917
  const origin = await git(worktree, "config", "--local", "--no-includes", "--get", "remote.origin.url").catch(() => "");
35729
35918
  const remote = remoteIdentity(origin);
35730
35919
  const key = remote ? `remote:${remote.key}` : `local:${common}`;
@@ -35738,7 +35927,7 @@ async function inspect(directory3) {
35738
35927
  }
35739
35928
  }
35740
35929
  async function annotateGitCheckouts(sessions) {
35741
- const directories = [...new Set(sessions.map((session) => session.directory))].filter((path) => isAbsolute8(path) && !/^[\\/]{2}/.test(path));
35930
+ const directories = [...new Set(sessions.map((session) => session.directory))].filter((path) => isAbsolute9(path) && !/^[\\/]{2}/.test(path));
35742
35931
  const results = /* @__PURE__ */ new Map();
35743
35932
  let index = 0;
35744
35933
  await Promise.all(Array.from({ length: Math.min(8, directories.length) }, async () => {
@@ -35758,6 +35947,2295 @@ async function annotateGitCheckouts(sessions) {
35758
35947
  return sessions.map((session) => ({ ...session, checkout: results.get(session.directory) }));
35759
35948
  }
35760
35949
 
35950
+ // server/library-service.ts
35951
+ import { basename as basename14, isAbsolute as isAbsolute10 } from "node:path";
35952
+
35953
+ // node_modules/.pnpm/minisearch@7.2.0/node_modules/minisearch/dist/es/index.js
35954
+ var ENTRIES = "ENTRIES";
35955
+ var KEYS = "KEYS";
35956
+ var VALUES = "VALUES";
35957
+ var LEAF = "";
35958
+ var TreeIterator = class {
35959
+ constructor(set, type) {
35960
+ const node = set._tree;
35961
+ const keys = Array.from(node.keys());
35962
+ this.set = set;
35963
+ this._type = type;
35964
+ this._path = keys.length > 0 ? [{ node, keys }] : [];
35965
+ }
35966
+ next() {
35967
+ const value = this.dive();
35968
+ this.backtrack();
35969
+ return value;
35970
+ }
35971
+ dive() {
35972
+ if (this._path.length === 0) {
35973
+ return { done: true, value: void 0 };
35974
+ }
35975
+ const { node, keys } = last$1(this._path);
35976
+ if (last$1(keys) === LEAF) {
35977
+ return { done: false, value: this.result() };
35978
+ }
35979
+ const child = node.get(last$1(keys));
35980
+ this._path.push({ node: child, keys: Array.from(child.keys()) });
35981
+ return this.dive();
35982
+ }
35983
+ backtrack() {
35984
+ if (this._path.length === 0) {
35985
+ return;
35986
+ }
35987
+ const keys = last$1(this._path).keys;
35988
+ keys.pop();
35989
+ if (keys.length > 0) {
35990
+ return;
35991
+ }
35992
+ this._path.pop();
35993
+ this.backtrack();
35994
+ }
35995
+ key() {
35996
+ return this.set._prefix + this._path.map(({ keys }) => last$1(keys)).filter((key) => key !== LEAF).join("");
35997
+ }
35998
+ value() {
35999
+ return last$1(this._path).node.get(LEAF);
36000
+ }
36001
+ result() {
36002
+ switch (this._type) {
36003
+ case VALUES:
36004
+ return this.value();
36005
+ case KEYS:
36006
+ return this.key();
36007
+ default:
36008
+ return [this.key(), this.value()];
36009
+ }
36010
+ }
36011
+ [Symbol.iterator]() {
36012
+ return this;
36013
+ }
36014
+ };
36015
+ var last$1 = (array) => {
36016
+ return array[array.length - 1];
36017
+ };
36018
+ var fuzzySearch = (node, query, maxDistance) => {
36019
+ const results = /* @__PURE__ */ new Map();
36020
+ if (query === void 0)
36021
+ return results;
36022
+ const n = query.length + 1;
36023
+ const m = n + maxDistance;
36024
+ const matrix = new Uint8Array(m * n).fill(maxDistance + 1);
36025
+ for (let j4 = 0; j4 < n; ++j4)
36026
+ matrix[j4] = j4;
36027
+ for (let i = 1; i < m; ++i)
36028
+ matrix[i * n] = i;
36029
+ recurse(node, query, maxDistance, results, matrix, 1, n, "");
36030
+ return results;
36031
+ };
36032
+ var recurse = (node, query, maxDistance, results, matrix, m, n, prefix) => {
36033
+ const offset = m * n;
36034
+ key: for (const key of node.keys()) {
36035
+ if (key === LEAF) {
36036
+ const distance = matrix[offset - 1];
36037
+ if (distance <= maxDistance) {
36038
+ results.set(prefix, [node.get(key), distance]);
36039
+ }
36040
+ } else {
36041
+ let i = m;
36042
+ for (let pos = 0; pos < key.length; ++pos, ++i) {
36043
+ const char = key[pos];
36044
+ const thisRowOffset = n * i;
36045
+ const prevRowOffset = thisRowOffset - n;
36046
+ let minDistance = matrix[thisRowOffset];
36047
+ const jmin = Math.max(0, i - maxDistance - 1);
36048
+ const jmax = Math.min(n - 1, i + maxDistance);
36049
+ for (let j4 = jmin; j4 < jmax; ++j4) {
36050
+ const different = char !== query[j4];
36051
+ const rpl = matrix[prevRowOffset + j4] + +different;
36052
+ const del = matrix[prevRowOffset + j4 + 1] + 1;
36053
+ const ins = matrix[thisRowOffset + j4] + 1;
36054
+ const dist = matrix[thisRowOffset + j4 + 1] = Math.min(rpl, del, ins);
36055
+ if (dist < minDistance)
36056
+ minDistance = dist;
36057
+ }
36058
+ if (minDistance > maxDistance) {
36059
+ continue key;
36060
+ }
36061
+ }
36062
+ recurse(node.get(key), query, maxDistance, results, matrix, i, n, prefix + key);
36063
+ }
36064
+ }
36065
+ };
36066
+ var SearchableMap = class _SearchableMap {
36067
+ /**
36068
+ * The constructor is normally called without arguments, creating an empty
36069
+ * map. In order to create a {@link SearchableMap} from an iterable or from an
36070
+ * object, check {@link SearchableMap.from} and {@link
36071
+ * SearchableMap.fromObject}.
36072
+ *
36073
+ * The constructor arguments are for internal use, when creating derived
36074
+ * mutable views of a map at a prefix.
36075
+ */
36076
+ constructor(tree = /* @__PURE__ */ new Map(), prefix = "") {
36077
+ this._size = void 0;
36078
+ this._tree = tree;
36079
+ this._prefix = prefix;
36080
+ }
36081
+ /**
36082
+ * Creates and returns a mutable view of this {@link SearchableMap},
36083
+ * containing only entries that share the given prefix.
36084
+ *
36085
+ * ### Usage:
36086
+ *
36087
+ * ```javascript
36088
+ * let map = new SearchableMap()
36089
+ * map.set("unicorn", 1)
36090
+ * map.set("universe", 2)
36091
+ * map.set("university", 3)
36092
+ * map.set("unique", 4)
36093
+ * map.set("hello", 5)
36094
+ *
36095
+ * let uni = map.atPrefix("uni")
36096
+ * uni.get("unique") // => 4
36097
+ * uni.get("unicorn") // => 1
36098
+ * uni.get("hello") // => undefined
36099
+ *
36100
+ * let univer = map.atPrefix("univer")
36101
+ * univer.get("unique") // => undefined
36102
+ * univer.get("universe") // => 2
36103
+ * univer.get("university") // => 3
36104
+ * ```
36105
+ *
36106
+ * @param prefix The prefix
36107
+ * @return A {@link SearchableMap} representing a mutable view of the original
36108
+ * Map at the given prefix
36109
+ */
36110
+ atPrefix(prefix) {
36111
+ if (!prefix.startsWith(this._prefix)) {
36112
+ throw new Error("Mismatched prefix");
36113
+ }
36114
+ const [node, path] = trackDown(this._tree, prefix.slice(this._prefix.length));
36115
+ if (node === void 0) {
36116
+ const [parentNode, key] = last(path);
36117
+ for (const k3 of parentNode.keys()) {
36118
+ if (k3 !== LEAF && k3.startsWith(key)) {
36119
+ const node2 = /* @__PURE__ */ new Map();
36120
+ node2.set(k3.slice(key.length), parentNode.get(k3));
36121
+ return new _SearchableMap(node2, prefix);
36122
+ }
36123
+ }
36124
+ }
36125
+ return new _SearchableMap(node, prefix);
36126
+ }
36127
+ /**
36128
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/clear
36129
+ */
36130
+ clear() {
36131
+ this._size = void 0;
36132
+ this._tree.clear();
36133
+ }
36134
+ /**
36135
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/delete
36136
+ * @param key Key to delete
36137
+ */
36138
+ delete(key) {
36139
+ this._size = void 0;
36140
+ return remove(this._tree, key);
36141
+ }
36142
+ /**
36143
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/entries
36144
+ * @return An iterator iterating through `[key, value]` entries.
36145
+ */
36146
+ entries() {
36147
+ return new TreeIterator(this, ENTRIES);
36148
+ }
36149
+ /**
36150
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach
36151
+ * @param fn Iteration function
36152
+ */
36153
+ forEach(fn) {
36154
+ for (const [key, value] of this) {
36155
+ fn(key, value, this);
36156
+ }
36157
+ }
36158
+ /**
36159
+ * Returns a Map of all the entries that have a key within the given edit
36160
+ * distance from the search key. The keys of the returned Map are the matching
36161
+ * keys, while the values are two-element arrays where the first element is
36162
+ * the value associated to the key, and the second is the edit distance of the
36163
+ * key to the search key.
36164
+ *
36165
+ * ### Usage:
36166
+ *
36167
+ * ```javascript
36168
+ * let map = new SearchableMap()
36169
+ * map.set('hello', 'world')
36170
+ * map.set('hell', 'yeah')
36171
+ * map.set('ciao', 'mondo')
36172
+ *
36173
+ * // Get all entries that match the key 'hallo' with a maximum edit distance of 2
36174
+ * map.fuzzyGet('hallo', 2)
36175
+ * // => Map(2) { 'hello' => ['world', 1], 'hell' => ['yeah', 2] }
36176
+ *
36177
+ * // In the example, the "hello" key has value "world" and edit distance of 1
36178
+ * // (change "e" to "a"), the key "hell" has value "yeah" and edit distance of 2
36179
+ * // (change "e" to "a", delete "o")
36180
+ * ```
36181
+ *
36182
+ * @param key The search key
36183
+ * @param maxEditDistance The maximum edit distance (Levenshtein)
36184
+ * @return A Map of the matching keys to their value and edit distance
36185
+ */
36186
+ fuzzyGet(key, maxEditDistance) {
36187
+ return fuzzySearch(this._tree, key, maxEditDistance);
36188
+ }
36189
+ /**
36190
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get
36191
+ * @param key Key to get
36192
+ * @return Value associated to the key, or `undefined` if the key is not
36193
+ * found.
36194
+ */
36195
+ get(key) {
36196
+ const node = lookup(this._tree, key);
36197
+ return node !== void 0 ? node.get(LEAF) : void 0;
36198
+ }
36199
+ /**
36200
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/has
36201
+ * @param key Key
36202
+ * @return True if the key is in the map, false otherwise
36203
+ */
36204
+ has(key) {
36205
+ const node = lookup(this._tree, key);
36206
+ return node !== void 0 && node.has(LEAF);
36207
+ }
36208
+ /**
36209
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/keys
36210
+ * @return An `Iterable` iterating through keys
36211
+ */
36212
+ keys() {
36213
+ return new TreeIterator(this, KEYS);
36214
+ }
36215
+ /**
36216
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/set
36217
+ * @param key Key to set
36218
+ * @param value Value to associate to the key
36219
+ * @return The {@link SearchableMap} itself, to allow chaining
36220
+ */
36221
+ set(key, value) {
36222
+ if (typeof key !== "string") {
36223
+ throw new Error("key must be a string");
36224
+ }
36225
+ this._size = void 0;
36226
+ const node = createPath(this._tree, key);
36227
+ node.set(LEAF, value);
36228
+ return this;
36229
+ }
36230
+ /**
36231
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/size
36232
+ */
36233
+ get size() {
36234
+ if (this._size) {
36235
+ return this._size;
36236
+ }
36237
+ this._size = 0;
36238
+ const iter = this.entries();
36239
+ while (!iter.next().done)
36240
+ this._size += 1;
36241
+ return this._size;
36242
+ }
36243
+ /**
36244
+ * Updates the value at the given key using the provided function. The function
36245
+ * is called with the current value at the key, and its return value is used as
36246
+ * the new value to be set.
36247
+ *
36248
+ * ### Example:
36249
+ *
36250
+ * ```javascript
36251
+ * // Increment the current value by one
36252
+ * searchableMap.update('somekey', (currentValue) => currentValue == null ? 0 : currentValue + 1)
36253
+ * ```
36254
+ *
36255
+ * If the value at the given key is or will be an object, it might not require
36256
+ * re-assignment. In that case it is better to use `fetch()`, because it is
36257
+ * faster.
36258
+ *
36259
+ * @param key The key to update
36260
+ * @param fn The function used to compute the new value from the current one
36261
+ * @return The {@link SearchableMap} itself, to allow chaining
36262
+ */
36263
+ update(key, fn) {
36264
+ if (typeof key !== "string") {
36265
+ throw new Error("key must be a string");
36266
+ }
36267
+ this._size = void 0;
36268
+ const node = createPath(this._tree, key);
36269
+ node.set(LEAF, fn(node.get(LEAF)));
36270
+ return this;
36271
+ }
36272
+ /**
36273
+ * Fetches the value of the given key. If the value does not exist, calls the
36274
+ * given function to create a new value, which is inserted at the given key
36275
+ * and subsequently returned.
36276
+ *
36277
+ * ### Example:
36278
+ *
36279
+ * ```javascript
36280
+ * const map = searchableMap.fetch('somekey', () => new Map())
36281
+ * map.set('foo', 'bar')
36282
+ * ```
36283
+ *
36284
+ * @param key The key to update
36285
+ * @param initial A function that creates a new value if the key does not exist
36286
+ * @return The existing or new value at the given key
36287
+ */
36288
+ fetch(key, initial) {
36289
+ if (typeof key !== "string") {
36290
+ throw new Error("key must be a string");
36291
+ }
36292
+ this._size = void 0;
36293
+ const node = createPath(this._tree, key);
36294
+ let value = node.get(LEAF);
36295
+ if (value === void 0) {
36296
+ node.set(LEAF, value = initial());
36297
+ }
36298
+ return value;
36299
+ }
36300
+ /**
36301
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/values
36302
+ * @return An `Iterable` iterating through values.
36303
+ */
36304
+ values() {
36305
+ return new TreeIterator(this, VALUES);
36306
+ }
36307
+ /**
36308
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/@@iterator
36309
+ */
36310
+ [Symbol.iterator]() {
36311
+ return this.entries();
36312
+ }
36313
+ /**
36314
+ * Creates a {@link SearchableMap} from an `Iterable` of entries
36315
+ *
36316
+ * @param entries Entries to be inserted in the {@link SearchableMap}
36317
+ * @return A new {@link SearchableMap} with the given entries
36318
+ */
36319
+ static from(entries2) {
36320
+ const tree = new _SearchableMap();
36321
+ for (const [key, value] of entries2) {
36322
+ tree.set(key, value);
36323
+ }
36324
+ return tree;
36325
+ }
36326
+ /**
36327
+ * Creates a {@link SearchableMap} from the iterable properties of a JavaScript object
36328
+ *
36329
+ * @param object Object of entries for the {@link SearchableMap}
36330
+ * @return A new {@link SearchableMap} with the given entries
36331
+ */
36332
+ static fromObject(object5) {
36333
+ return _SearchableMap.from(Object.entries(object5));
36334
+ }
36335
+ };
36336
+ var trackDown = (tree, key, path = []) => {
36337
+ if (key.length === 0 || tree == null) {
36338
+ return [tree, path];
36339
+ }
36340
+ for (const k3 of tree.keys()) {
36341
+ if (k3 !== LEAF && key.startsWith(k3)) {
36342
+ path.push([tree, k3]);
36343
+ return trackDown(tree.get(k3), key.slice(k3.length), path);
36344
+ }
36345
+ }
36346
+ path.push([tree, key]);
36347
+ return trackDown(void 0, "", path);
36348
+ };
36349
+ var lookup = (tree, key) => {
36350
+ if (key.length === 0 || tree == null) {
36351
+ return tree;
36352
+ }
36353
+ for (const k3 of tree.keys()) {
36354
+ if (k3 !== LEAF && key.startsWith(k3)) {
36355
+ return lookup(tree.get(k3), key.slice(k3.length));
36356
+ }
36357
+ }
36358
+ };
36359
+ var createPath = (node, key) => {
36360
+ const keyLength = key.length;
36361
+ outer: for (let pos = 0; node && pos < keyLength; ) {
36362
+ for (const k3 of node.keys()) {
36363
+ if (k3 !== LEAF && key[pos] === k3[0]) {
36364
+ const len = Math.min(keyLength - pos, k3.length);
36365
+ let offset = 1;
36366
+ while (offset < len && key[pos + offset] === k3[offset])
36367
+ ++offset;
36368
+ const child2 = node.get(k3);
36369
+ if (offset === k3.length) {
36370
+ node = child2;
36371
+ } else {
36372
+ const intermediate = /* @__PURE__ */ new Map();
36373
+ intermediate.set(k3.slice(offset), child2);
36374
+ node.set(key.slice(pos, pos + offset), intermediate);
36375
+ node.delete(k3);
36376
+ node = intermediate;
36377
+ }
36378
+ pos += offset;
36379
+ continue outer;
36380
+ }
36381
+ }
36382
+ const child = /* @__PURE__ */ new Map();
36383
+ node.set(key.slice(pos), child);
36384
+ return child;
36385
+ }
36386
+ return node;
36387
+ };
36388
+ var remove = (tree, key) => {
36389
+ const [node, path] = trackDown(tree, key);
36390
+ if (node === void 0) {
36391
+ return;
36392
+ }
36393
+ node.delete(LEAF);
36394
+ if (node.size === 0) {
36395
+ cleanup(path);
36396
+ } else if (node.size === 1) {
36397
+ const [key2, value] = node.entries().next().value;
36398
+ merge(path, key2, value);
36399
+ }
36400
+ };
36401
+ var cleanup = (path) => {
36402
+ if (path.length === 0) {
36403
+ return;
36404
+ }
36405
+ const [node, key] = last(path);
36406
+ node.delete(key);
36407
+ if (node.size === 0) {
36408
+ cleanup(path.slice(0, -1));
36409
+ } else if (node.size === 1) {
36410
+ const [key2, value] = node.entries().next().value;
36411
+ if (key2 !== LEAF) {
36412
+ merge(path.slice(0, -1), key2, value);
36413
+ }
36414
+ }
36415
+ };
36416
+ var merge = (path, key, value) => {
36417
+ if (path.length === 0) {
36418
+ return;
36419
+ }
36420
+ const [node, nodeKey] = last(path);
36421
+ node.set(nodeKey + key, value);
36422
+ node.delete(nodeKey);
36423
+ };
36424
+ var last = (array) => {
36425
+ return array[array.length - 1];
36426
+ };
36427
+ var OR2 = "or";
36428
+ var AND = "and";
36429
+ var AND_NOT = "and_not";
36430
+ var MiniSearch = class _MiniSearch {
36431
+ /**
36432
+ * @param options Configuration options
36433
+ *
36434
+ * ### Examples:
36435
+ *
36436
+ * ```javascript
36437
+ * // Create a search engine that indexes the 'title' and 'text' fields of your
36438
+ * // documents:
36439
+ * const miniSearch = new MiniSearch({ fields: ['title', 'text'] })
36440
+ * ```
36441
+ *
36442
+ * ### ID Field:
36443
+ *
36444
+ * ```javascript
36445
+ * // Your documents are assumed to include a unique 'id' field, but if you want
36446
+ * // to use a different field for document identification, you can set the
36447
+ * // 'idField' option:
36448
+ * const miniSearch = new MiniSearch({ idField: 'key', fields: ['title', 'text'] })
36449
+ * ```
36450
+ *
36451
+ * ### Options and defaults:
36452
+ *
36453
+ * ```javascript
36454
+ * // The full set of options (here with their default value) is:
36455
+ * const miniSearch = new MiniSearch({
36456
+ * // idField: field that uniquely identifies a document
36457
+ * idField: 'id',
36458
+ *
36459
+ * // extractField: function used to get the value of a field in a document.
36460
+ * // By default, it assumes the document is a flat object with field names as
36461
+ * // property keys and field values as string property values, but custom logic
36462
+ * // can be implemented by setting this option to a custom extractor function.
36463
+ * extractField: (document, fieldName) => document[fieldName],
36464
+ *
36465
+ * // tokenize: function used to split fields into individual terms. By
36466
+ * // default, it is also used to tokenize search queries, unless a specific
36467
+ * // `tokenize` search option is supplied. When tokenizing an indexed field,
36468
+ * // the field name is passed as the second argument.
36469
+ * tokenize: (string, _fieldName) => string.split(SPACE_OR_PUNCTUATION),
36470
+ *
36471
+ * // processTerm: function used to process each tokenized term before
36472
+ * // indexing. It can be used for stemming and normalization. Return a falsy
36473
+ * // value in order to discard a term. By default, it is also used to process
36474
+ * // search queries, unless a specific `processTerm` option is supplied as a
36475
+ * // search option. When processing a term from a indexed field, the field
36476
+ * // name is passed as the second argument.
36477
+ * processTerm: (term, _fieldName) => term.toLowerCase(),
36478
+ *
36479
+ * // searchOptions: default search options, see the `search` method for
36480
+ * // details
36481
+ * searchOptions: undefined,
36482
+ *
36483
+ * // fields: document fields to be indexed. Mandatory, but not set by default
36484
+ * fields: undefined
36485
+ *
36486
+ * // storeFields: document fields to be stored and returned as part of the
36487
+ * // search results.
36488
+ * storeFields: []
36489
+ * })
36490
+ * ```
36491
+ */
36492
+ constructor(options) {
36493
+ if ((options === null || options === void 0 ? void 0 : options.fields) == null) {
36494
+ throw new Error('MiniSearch: option "fields" must be provided');
36495
+ }
36496
+ const autoVacuum = options.autoVacuum == null || options.autoVacuum === true ? defaultAutoVacuumOptions : options.autoVacuum;
36497
+ this._options = {
36498
+ ...defaultOptions,
36499
+ ...options,
36500
+ autoVacuum,
36501
+ searchOptions: { ...defaultSearchOptions, ...options.searchOptions || {} },
36502
+ autoSuggestOptions: { ...defaultAutoSuggestOptions, ...options.autoSuggestOptions || {} }
36503
+ };
36504
+ this._index = new SearchableMap();
36505
+ this._documentCount = 0;
36506
+ this._documentIds = /* @__PURE__ */ new Map();
36507
+ this._idToShortId = /* @__PURE__ */ new Map();
36508
+ this._fieldIds = {};
36509
+ this._fieldLength = /* @__PURE__ */ new Map();
36510
+ this._avgFieldLength = [];
36511
+ this._nextId = 0;
36512
+ this._storedFields = /* @__PURE__ */ new Map();
36513
+ this._dirtCount = 0;
36514
+ this._currentVacuum = null;
36515
+ this._enqueuedVacuum = null;
36516
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
36517
+ this.addFields(this._options.fields);
36518
+ }
36519
+ /**
36520
+ * Adds a document to the index
36521
+ *
36522
+ * @param document The document to be indexed
36523
+ */
36524
+ add(document2) {
36525
+ const { extractField, stringifyField, tokenize, processTerm, fields: fields3, idField } = this._options;
36526
+ const id2 = extractField(document2, idField);
36527
+ if (id2 == null) {
36528
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
36529
+ }
36530
+ if (this._idToShortId.has(id2)) {
36531
+ throw new Error(`MiniSearch: duplicate ID ${id2}`);
36532
+ }
36533
+ const shortDocumentId = this.addDocumentId(id2);
36534
+ this.saveStoredFields(shortDocumentId, document2);
36535
+ for (const field of fields3) {
36536
+ const fieldValue = extractField(document2, field);
36537
+ if (fieldValue == null)
36538
+ continue;
36539
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
36540
+ const fieldId = this._fieldIds[field];
36541
+ const uniqueTerms = new Set(tokens).size;
36542
+ this.addFieldLength(shortDocumentId, fieldId, this._documentCount - 1, uniqueTerms);
36543
+ for (const term of tokens) {
36544
+ const processedTerm = processTerm(term, field);
36545
+ if (Array.isArray(processedTerm)) {
36546
+ for (const t of processedTerm) {
36547
+ this.addTerm(fieldId, shortDocumentId, t);
36548
+ }
36549
+ } else if (processedTerm) {
36550
+ this.addTerm(fieldId, shortDocumentId, processedTerm);
36551
+ }
36552
+ }
36553
+ }
36554
+ }
36555
+ /**
36556
+ * Adds all the given documents to the index
36557
+ *
36558
+ * @param documents An array of documents to be indexed
36559
+ */
36560
+ addAll(documents) {
36561
+ for (const document2 of documents)
36562
+ this.add(document2);
36563
+ }
36564
+ /**
36565
+ * Adds all the given documents to the index asynchronously.
36566
+ *
36567
+ * Returns a promise that resolves (to `undefined`) when the indexing is done.
36568
+ * This method is useful when index many documents, to avoid blocking the main
36569
+ * thread. The indexing is performed asynchronously and in chunks.
36570
+ *
36571
+ * @param documents An array of documents to be indexed
36572
+ * @param options Configuration options
36573
+ * @return A promise resolving to `undefined` when the indexing is done
36574
+ */
36575
+ addAllAsync(documents, options = {}) {
36576
+ const { chunkSize = 10 } = options;
36577
+ const acc = { chunk: [], promise: Promise.resolve() };
36578
+ const { chunk, promise } = documents.reduce(({ chunk: chunk2, promise: promise2 }, document2, i) => {
36579
+ chunk2.push(document2);
36580
+ if ((i + 1) % chunkSize === 0) {
36581
+ return {
36582
+ chunk: [],
36583
+ promise: promise2.then(() => new Promise((resolve6) => setTimeout(resolve6, 0))).then(() => this.addAll(chunk2))
36584
+ };
36585
+ } else {
36586
+ return { chunk: chunk2, promise: promise2 };
36587
+ }
36588
+ }, acc);
36589
+ return promise.then(() => this.addAll(chunk));
36590
+ }
36591
+ /**
36592
+ * Removes the given document from the index.
36593
+ *
36594
+ * The document to remove must NOT have changed between indexing and removal,
36595
+ * otherwise the index will be corrupted.
36596
+ *
36597
+ * This method requires passing the full document to be removed (not just the
36598
+ * ID), and immediately removes the document from the inverted index, allowing
36599
+ * memory to be released. A convenient alternative is {@link
36600
+ * MiniSearch#discard}, which needs only the document ID, and has the same
36601
+ * visible effect, but delays cleaning up the index until the next vacuuming.
36602
+ *
36603
+ * @param document The document to be removed
36604
+ */
36605
+ remove(document2) {
36606
+ const { tokenize, processTerm, extractField, stringifyField, fields: fields3, idField } = this._options;
36607
+ const id2 = extractField(document2, idField);
36608
+ if (id2 == null) {
36609
+ throw new Error(`MiniSearch: document does not have ID field "${idField}"`);
36610
+ }
36611
+ const shortId = this._idToShortId.get(id2);
36612
+ if (shortId == null) {
36613
+ throw new Error(`MiniSearch: cannot remove document with ID ${id2}: it is not in the index`);
36614
+ }
36615
+ for (const field of fields3) {
36616
+ const fieldValue = extractField(document2, field);
36617
+ if (fieldValue == null)
36618
+ continue;
36619
+ const tokens = tokenize(stringifyField(fieldValue, field), field);
36620
+ const fieldId = this._fieldIds[field];
36621
+ const uniqueTerms = new Set(tokens).size;
36622
+ this.removeFieldLength(shortId, fieldId, this._documentCount, uniqueTerms);
36623
+ for (const term of tokens) {
36624
+ const processedTerm = processTerm(term, field);
36625
+ if (Array.isArray(processedTerm)) {
36626
+ for (const t of processedTerm) {
36627
+ this.removeTerm(fieldId, shortId, t);
36628
+ }
36629
+ } else if (processedTerm) {
36630
+ this.removeTerm(fieldId, shortId, processedTerm);
36631
+ }
36632
+ }
36633
+ }
36634
+ this._storedFields.delete(shortId);
36635
+ this._documentIds.delete(shortId);
36636
+ this._idToShortId.delete(id2);
36637
+ this._fieldLength.delete(shortId);
36638
+ this._documentCount -= 1;
36639
+ }
36640
+ /**
36641
+ * Removes all the given documents from the index. If called with no arguments,
36642
+ * it removes _all_ documents from the index.
36643
+ *
36644
+ * @param documents The documents to be removed. If this argument is omitted,
36645
+ * all documents are removed. Note that, for removing all documents, it is
36646
+ * more efficient to call this method with no arguments than to pass all
36647
+ * documents.
36648
+ */
36649
+ removeAll(documents) {
36650
+ if (documents) {
36651
+ for (const document2 of documents)
36652
+ this.remove(document2);
36653
+ } else if (arguments.length > 0) {
36654
+ throw new Error("Expected documents to be present. Omit the argument to remove all documents.");
36655
+ } else {
36656
+ this._index = new SearchableMap();
36657
+ this._documentCount = 0;
36658
+ this._documentIds = /* @__PURE__ */ new Map();
36659
+ this._idToShortId = /* @__PURE__ */ new Map();
36660
+ this._fieldLength = /* @__PURE__ */ new Map();
36661
+ this._avgFieldLength = [];
36662
+ this._storedFields = /* @__PURE__ */ new Map();
36663
+ this._nextId = 0;
36664
+ }
36665
+ }
36666
+ /**
36667
+ * Discards the document with the given ID, so it won't appear in search results
36668
+ *
36669
+ * It has the same visible effect of {@link MiniSearch.remove} (both cause the
36670
+ * document to stop appearing in searches), but a different effect on the
36671
+ * internal data structures:
36672
+ *
36673
+ * - {@link MiniSearch#remove} requires passing the full document to be
36674
+ * removed as argument, and removes it from the inverted index immediately.
36675
+ *
36676
+ * - {@link MiniSearch#discard} instead only needs the document ID, and
36677
+ * works by marking the current version of the document as discarded, so it
36678
+ * is immediately ignored by searches. This is faster and more convenient
36679
+ * than {@link MiniSearch#remove}, but the index is not immediately
36680
+ * modified. To take care of that, vacuuming is performed after a certain
36681
+ * number of documents are discarded, cleaning up the index and allowing
36682
+ * memory to be released.
36683
+ *
36684
+ * After discarding a document, it is possible to re-add a new version, and
36685
+ * only the new version will appear in searches. In other words, discarding
36686
+ * and re-adding a document works exactly like removing and re-adding it. The
36687
+ * {@link MiniSearch.replace} method can also be used to replace a document
36688
+ * with a new version.
36689
+ *
36690
+ * #### Details about vacuuming
36691
+ *
36692
+ * Repetite calls to this method would leave obsolete document references in
36693
+ * the index, invisible to searches. Two mechanisms take care of cleaning up:
36694
+ * clean up during search, and vacuuming.
36695
+ *
36696
+ * - Upon search, whenever a discarded ID is found (and ignored for the
36697
+ * results), references to the discarded document are removed from the
36698
+ * inverted index entries for the search terms. This ensures that subsequent
36699
+ * searches for the same terms do not need to skip these obsolete references
36700
+ * again.
36701
+ *
36702
+ * - In addition, vacuuming is performed automatically by default (see the
36703
+ * `autoVacuum` field in {@link Options}) after a certain number of
36704
+ * documents are discarded. Vacuuming traverses all terms in the index,
36705
+ * cleaning up all references to discarded documents. Vacuuming can also be
36706
+ * triggered manually by calling {@link MiniSearch#vacuum}.
36707
+ *
36708
+ * @param id The ID of the document to be discarded
36709
+ */
36710
+ discard(id2) {
36711
+ const shortId = this._idToShortId.get(id2);
36712
+ if (shortId == null) {
36713
+ throw new Error(`MiniSearch: cannot discard document with ID ${id2}: it is not in the index`);
36714
+ }
36715
+ this._idToShortId.delete(id2);
36716
+ this._documentIds.delete(shortId);
36717
+ this._storedFields.delete(shortId);
36718
+ (this._fieldLength.get(shortId) || []).forEach((fieldLength, fieldId) => {
36719
+ this.removeFieldLength(shortId, fieldId, this._documentCount, fieldLength);
36720
+ });
36721
+ this._fieldLength.delete(shortId);
36722
+ this._documentCount -= 1;
36723
+ this._dirtCount += 1;
36724
+ this.maybeAutoVacuum();
36725
+ }
36726
+ maybeAutoVacuum() {
36727
+ if (this._options.autoVacuum === false) {
36728
+ return;
36729
+ }
36730
+ const { minDirtFactor, minDirtCount, batchSize, batchWait } = this._options.autoVacuum;
36731
+ this.conditionalVacuum({ batchSize, batchWait }, { minDirtCount, minDirtFactor });
36732
+ }
36733
+ /**
36734
+ * Discards the documents with the given IDs, so they won't appear in search
36735
+ * results
36736
+ *
36737
+ * It is equivalent to calling {@link MiniSearch#discard} for all the given
36738
+ * IDs, but with the optimization of triggering at most one automatic
36739
+ * vacuuming at the end.
36740
+ *
36741
+ * Note: to remove all documents from the index, it is faster and more
36742
+ * convenient to call {@link MiniSearch.removeAll} with no argument, instead
36743
+ * of passing all IDs to this method.
36744
+ */
36745
+ discardAll(ids) {
36746
+ const autoVacuum = this._options.autoVacuum;
36747
+ try {
36748
+ this._options.autoVacuum = false;
36749
+ for (const id2 of ids) {
36750
+ this.discard(id2);
36751
+ }
36752
+ } finally {
36753
+ this._options.autoVacuum = autoVacuum;
36754
+ }
36755
+ this.maybeAutoVacuum();
36756
+ }
36757
+ /**
36758
+ * It replaces an existing document with the given updated version
36759
+ *
36760
+ * It works by discarding the current version and adding the updated one, so
36761
+ * it is functionally equivalent to calling {@link MiniSearch#discard}
36762
+ * followed by {@link MiniSearch#add}. The ID of the updated document should
36763
+ * be the same as the original one.
36764
+ *
36765
+ * Since it uses {@link MiniSearch#discard} internally, this method relies on
36766
+ * vacuuming to clean up obsolete document references from the index, allowing
36767
+ * memory to be released (see {@link MiniSearch#discard}).
36768
+ *
36769
+ * @param updatedDocument The updated document to replace the old version
36770
+ * with
36771
+ */
36772
+ replace(updatedDocument) {
36773
+ const { idField, extractField } = this._options;
36774
+ const id2 = extractField(updatedDocument, idField);
36775
+ this.discard(id2);
36776
+ this.add(updatedDocument);
36777
+ }
36778
+ /**
36779
+ * Triggers a manual vacuuming, cleaning up references to discarded documents
36780
+ * from the inverted index
36781
+ *
36782
+ * Vacuuming is only useful for applications that use the {@link
36783
+ * MiniSearch#discard} or {@link MiniSearch#replace} methods.
36784
+ *
36785
+ * By default, vacuuming is performed automatically when needed (controlled by
36786
+ * the `autoVacuum` field in {@link Options}), so there is usually no need to
36787
+ * call this method, unless one wants to make sure to perform vacuuming at a
36788
+ * specific moment.
36789
+ *
36790
+ * Vacuuming traverses all terms in the inverted index in batches, and cleans
36791
+ * up references to discarded documents from the posting list, allowing memory
36792
+ * to be released.
36793
+ *
36794
+ * The method takes an optional object as argument with the following keys:
36795
+ *
36796
+ * - `batchSize`: the size of each batch (1000 by default)
36797
+ *
36798
+ * - `batchWait`: the number of milliseconds to wait between batches (10 by
36799
+ * default)
36800
+ *
36801
+ * On large indexes, vacuuming could have a non-negligible cost: batching
36802
+ * avoids blocking the thread for long, diluting this cost so that it is not
36803
+ * negatively affecting the application. Nonetheless, this method should only
36804
+ * be called when necessary, and relying on automatic vacuuming is usually
36805
+ * better.
36806
+ *
36807
+ * It returns a promise that resolves (to undefined) when the clean up is
36808
+ * completed. If vacuuming is already ongoing at the time this method is
36809
+ * called, a new one is enqueued immediately after the ongoing one, and a
36810
+ * corresponding promise is returned. However, no more than one vacuuming is
36811
+ * enqueued on top of the ongoing one, even if this method is called more
36812
+ * times (enqueuing multiple ones would be useless).
36813
+ *
36814
+ * @param options Configuration options for the batch size and delay. See
36815
+ * {@link VacuumOptions}.
36816
+ */
36817
+ vacuum(options = {}) {
36818
+ return this.conditionalVacuum(options);
36819
+ }
36820
+ conditionalVacuum(options, conditions) {
36821
+ if (this._currentVacuum) {
36822
+ this._enqueuedVacuumConditions = this._enqueuedVacuumConditions && conditions;
36823
+ if (this._enqueuedVacuum != null) {
36824
+ return this._enqueuedVacuum;
36825
+ }
36826
+ this._enqueuedVacuum = this._currentVacuum.then(() => {
36827
+ const conditions2 = this._enqueuedVacuumConditions;
36828
+ this._enqueuedVacuumConditions = defaultVacuumConditions;
36829
+ return this.performVacuuming(options, conditions2);
36830
+ });
36831
+ return this._enqueuedVacuum;
36832
+ }
36833
+ if (this.vacuumConditionsMet(conditions) === false) {
36834
+ return Promise.resolve();
36835
+ }
36836
+ this._currentVacuum = this.performVacuuming(options);
36837
+ return this._currentVacuum;
36838
+ }
36839
+ async performVacuuming(options, conditions) {
36840
+ const initialDirtCount = this._dirtCount;
36841
+ if (this.vacuumConditionsMet(conditions)) {
36842
+ const batchSize = options.batchSize || defaultVacuumOptions.batchSize;
36843
+ const batchWait = options.batchWait || defaultVacuumOptions.batchWait;
36844
+ let i = 1;
36845
+ for (const [term, fieldsData] of this._index) {
36846
+ for (const [fieldId, fieldIndex] of fieldsData) {
36847
+ for (const [shortId] of fieldIndex) {
36848
+ if (this._documentIds.has(shortId)) {
36849
+ continue;
36850
+ }
36851
+ if (fieldIndex.size <= 1) {
36852
+ fieldsData.delete(fieldId);
36853
+ } else {
36854
+ fieldIndex.delete(shortId);
36855
+ }
36856
+ }
36857
+ }
36858
+ if (this._index.get(term).size === 0) {
36859
+ this._index.delete(term);
36860
+ }
36861
+ if (i % batchSize === 0) {
36862
+ await new Promise((resolve6) => setTimeout(resolve6, batchWait));
36863
+ }
36864
+ i += 1;
36865
+ }
36866
+ this._dirtCount -= initialDirtCount;
36867
+ }
36868
+ await null;
36869
+ this._currentVacuum = this._enqueuedVacuum;
36870
+ this._enqueuedVacuum = null;
36871
+ }
36872
+ vacuumConditionsMet(conditions) {
36873
+ if (conditions == null) {
36874
+ return true;
36875
+ }
36876
+ let { minDirtCount, minDirtFactor } = conditions;
36877
+ minDirtCount = minDirtCount || defaultAutoVacuumOptions.minDirtCount;
36878
+ minDirtFactor = minDirtFactor || defaultAutoVacuumOptions.minDirtFactor;
36879
+ return this.dirtCount >= minDirtCount && this.dirtFactor >= minDirtFactor;
36880
+ }
36881
+ /**
36882
+ * Is `true` if a vacuuming operation is ongoing, `false` otherwise
36883
+ */
36884
+ get isVacuuming() {
36885
+ return this._currentVacuum != null;
36886
+ }
36887
+ /**
36888
+ * The number of documents discarded since the most recent vacuuming
36889
+ */
36890
+ get dirtCount() {
36891
+ return this._dirtCount;
36892
+ }
36893
+ /**
36894
+ * A number between 0 and 1 giving an indication about the proportion of
36895
+ * documents that are discarded, and can therefore be cleaned up by vacuuming.
36896
+ * A value close to 0 means that the index is relatively clean, while a higher
36897
+ * value means that the index is relatively dirty, and vacuuming could release
36898
+ * memory.
36899
+ */
36900
+ get dirtFactor() {
36901
+ return this._dirtCount / (1 + this._documentCount + this._dirtCount);
36902
+ }
36903
+ /**
36904
+ * Returns `true` if a document with the given ID is present in the index and
36905
+ * available for search, `false` otherwise
36906
+ *
36907
+ * @param id The document ID
36908
+ */
36909
+ has(id2) {
36910
+ return this._idToShortId.has(id2);
36911
+ }
36912
+ /**
36913
+ * Returns the stored fields (as configured in the `storeFields` constructor
36914
+ * option) for the given document ID. Returns `undefined` if the document is
36915
+ * not present in the index.
36916
+ *
36917
+ * @param id The document ID
36918
+ */
36919
+ getStoredFields(id2) {
36920
+ const shortId = this._idToShortId.get(id2);
36921
+ if (shortId == null) {
36922
+ return void 0;
36923
+ }
36924
+ return this._storedFields.get(shortId);
36925
+ }
36926
+ /**
36927
+ * Search for documents matching the given search query.
36928
+ *
36929
+ * The result is a list of scored document IDs matching the query, sorted by
36930
+ * descending score, and each including data about which terms were matched and
36931
+ * in which fields.
36932
+ *
36933
+ * ### Basic usage:
36934
+ *
36935
+ * ```javascript
36936
+ * // Search for "zen art motorcycle" with default options: terms have to match
36937
+ * // exactly, and individual terms are joined with OR
36938
+ * miniSearch.search('zen art motorcycle')
36939
+ * // => [ { id: 2, score: 2.77258, match: { ... } }, { id: 4, score: 1.38629, match: { ... } } ]
36940
+ * ```
36941
+ *
36942
+ * ### Restrict search to specific fields:
36943
+ *
36944
+ * ```javascript
36945
+ * // Search only in the 'title' field
36946
+ * miniSearch.search('zen', { fields: ['title'] })
36947
+ * ```
36948
+ *
36949
+ * ### Field boosting:
36950
+ *
36951
+ * ```javascript
36952
+ * // Boost a field
36953
+ * miniSearch.search('zen', { boost: { title: 2 } })
36954
+ * ```
36955
+ *
36956
+ * ### Prefix search:
36957
+ *
36958
+ * ```javascript
36959
+ * // Search for "moto" with prefix search (it will match documents
36960
+ * // containing terms that start with "moto" or "neuro")
36961
+ * miniSearch.search('moto neuro', { prefix: true })
36962
+ * ```
36963
+ *
36964
+ * ### Fuzzy search:
36965
+ *
36966
+ * ```javascript
36967
+ * // Search for "ismael" with fuzzy search (it will match documents containing
36968
+ * // terms similar to "ismael", with a maximum edit distance of 0.2 term.length
36969
+ * // (rounded to nearest integer)
36970
+ * miniSearch.search('ismael', { fuzzy: 0.2 })
36971
+ * ```
36972
+ *
36973
+ * ### Combining strategies:
36974
+ *
36975
+ * ```javascript
36976
+ * // Mix of exact match, prefix search, and fuzzy search
36977
+ * miniSearch.search('ismael mob', {
36978
+ * prefix: true,
36979
+ * fuzzy: 0.2
36980
+ * })
36981
+ * ```
36982
+ *
36983
+ * ### Advanced prefix and fuzzy search:
36984
+ *
36985
+ * ```javascript
36986
+ * // Perform fuzzy and prefix search depending on the search term. Here
36987
+ * // performing prefix and fuzzy search only on terms longer than 3 characters
36988
+ * miniSearch.search('ismael mob', {
36989
+ * prefix: term => term.length > 3
36990
+ * fuzzy: term => term.length > 3 ? 0.2 : null
36991
+ * })
36992
+ * ```
36993
+ *
36994
+ * ### Combine with AND:
36995
+ *
36996
+ * ```javascript
36997
+ * // Combine search terms with AND (to match only documents that contain both
36998
+ * // "motorcycle" and "art")
36999
+ * miniSearch.search('motorcycle art', { combineWith: 'AND' })
37000
+ * ```
37001
+ *
37002
+ * ### Combine with AND_NOT:
37003
+ *
37004
+ * There is also an AND_NOT combinator, that finds documents that match the
37005
+ * first term, but do not match any of the other terms. This combinator is
37006
+ * rarely useful with simple queries, and is meant to be used with advanced
37007
+ * query combinations (see later for more details).
37008
+ *
37009
+ * ### Filtering results:
37010
+ *
37011
+ * ```javascript
37012
+ * // Filter only results in the 'fiction' category (assuming that 'category'
37013
+ * // is a stored field)
37014
+ * miniSearch.search('motorcycle art', {
37015
+ * filter: (result) => result.category === 'fiction'
37016
+ * })
37017
+ * ```
37018
+ *
37019
+ * ### Wildcard query
37020
+ *
37021
+ * Searching for an empty string (assuming the default tokenizer) returns no
37022
+ * results. Sometimes though, one needs to match all documents, like in a
37023
+ * "wildcard" search. This is possible by passing the special value
37024
+ * {@link MiniSearch.wildcard} as the query:
37025
+ *
37026
+ * ```javascript
37027
+ * // Return search results for all documents
37028
+ * miniSearch.search(MiniSearch.wildcard)
37029
+ * ```
37030
+ *
37031
+ * Note that search options such as `filter` and `boostDocument` are still
37032
+ * applied, influencing which results are returned, and their order:
37033
+ *
37034
+ * ```javascript
37035
+ * // Return search results for all documents in the 'fiction' category
37036
+ * miniSearch.search(MiniSearch.wildcard, {
37037
+ * filter: (result) => result.category === 'fiction'
37038
+ * })
37039
+ * ```
37040
+ *
37041
+ * ### Advanced combination of queries:
37042
+ *
37043
+ * It is possible to combine different subqueries with OR, AND, and AND_NOT,
37044
+ * and even with different search options, by passing a query expression
37045
+ * tree object as the first argument, instead of a string.
37046
+ *
37047
+ * ```javascript
37048
+ * // Search for documents that contain "zen" and ("motorcycle" or "archery")
37049
+ * miniSearch.search({
37050
+ * combineWith: 'AND',
37051
+ * queries: [
37052
+ * 'zen',
37053
+ * {
37054
+ * combineWith: 'OR',
37055
+ * queries: ['motorcycle', 'archery']
37056
+ * }
37057
+ * ]
37058
+ * })
37059
+ *
37060
+ * // Search for documents that contain ("apple" or "pear") but not "juice" and
37061
+ * // not "tree"
37062
+ * miniSearch.search({
37063
+ * combineWith: 'AND_NOT',
37064
+ * queries: [
37065
+ * {
37066
+ * combineWith: 'OR',
37067
+ * queries: ['apple', 'pear']
37068
+ * },
37069
+ * 'juice',
37070
+ * 'tree'
37071
+ * ]
37072
+ * })
37073
+ * ```
37074
+ *
37075
+ * Each node in the expression tree can be either a string, or an object that
37076
+ * supports all {@link SearchOptions} fields, plus a `queries` array field for
37077
+ * subqueries.
37078
+ *
37079
+ * Note that, while this can become complicated to do by hand for complex or
37080
+ * deeply nested queries, it provides a formalized expression tree API for
37081
+ * external libraries that implement a parser for custom query languages.
37082
+ *
37083
+ * @param query Search query
37084
+ * @param searchOptions Search options. Each option, if not given, defaults to the corresponding value of `searchOptions` given to the constructor, or to the library default.
37085
+ */
37086
+ search(query, searchOptions = {}) {
37087
+ const { searchOptions: globalSearchOptions } = this._options;
37088
+ const searchOptionsWithDefaults = { ...globalSearchOptions, ...searchOptions };
37089
+ const rawResults = this.executeQuery(query, searchOptions);
37090
+ const results = [];
37091
+ for (const [docId, { score, terms, match: match2 }] of rawResults) {
37092
+ const quality = terms.length || 1;
37093
+ const result = {
37094
+ id: this._documentIds.get(docId),
37095
+ score: score * quality,
37096
+ terms: Object.keys(match2),
37097
+ queryTerms: terms,
37098
+ match: match2
37099
+ };
37100
+ Object.assign(result, this._storedFields.get(docId));
37101
+ if (searchOptionsWithDefaults.filter == null || searchOptionsWithDefaults.filter(result)) {
37102
+ results.push(result);
37103
+ }
37104
+ }
37105
+ if (query === _MiniSearch.wildcard && searchOptionsWithDefaults.boostDocument == null) {
37106
+ return results;
37107
+ }
37108
+ results.sort(byScore);
37109
+ return results;
37110
+ }
37111
+ /**
37112
+ * Provide suggestions for the given search query
37113
+ *
37114
+ * The result is a list of suggested modified search queries, derived from the
37115
+ * given search query, each with a relevance score, sorted by descending score.
37116
+ *
37117
+ * By default, it uses the same options used for search, except that by
37118
+ * default it performs prefix search on the last term of the query, and
37119
+ * combine terms with `'AND'` (requiring all query terms to match). Custom
37120
+ * options can be passed as a second argument. Defaults can be changed upon
37121
+ * calling the {@link MiniSearch} constructor, by passing a
37122
+ * `autoSuggestOptions` option.
37123
+ *
37124
+ * ### Basic usage:
37125
+ *
37126
+ * ```javascript
37127
+ * // Get suggestions for 'neuro':
37128
+ * miniSearch.autoSuggest('neuro')
37129
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 0.46240 } ]
37130
+ * ```
37131
+ *
37132
+ * ### Multiple words:
37133
+ *
37134
+ * ```javascript
37135
+ * // Get suggestions for 'zen ar':
37136
+ * miniSearch.autoSuggest('zen ar')
37137
+ * // => [
37138
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
37139
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
37140
+ * // ]
37141
+ * ```
37142
+ *
37143
+ * ### Fuzzy suggestions:
37144
+ *
37145
+ * ```javascript
37146
+ * // Correct spelling mistakes using fuzzy search:
37147
+ * miniSearch.autoSuggest('neromancer', { fuzzy: 0.2 })
37148
+ * // => [ { suggestion: 'neuromancer', terms: [ 'neuromancer' ], score: 1.03998 } ]
37149
+ * ```
37150
+ *
37151
+ * ### Filtering:
37152
+ *
37153
+ * ```javascript
37154
+ * // Get suggestions for 'zen ar', but only within the 'fiction' category
37155
+ * // (assuming that 'category' is a stored field):
37156
+ * miniSearch.autoSuggest('zen ar', {
37157
+ * filter: (result) => result.category === 'fiction'
37158
+ * })
37159
+ * // => [
37160
+ * // { suggestion: 'zen archery art', terms: [ 'zen', 'archery', 'art' ], score: 1.73332 },
37161
+ * // { suggestion: 'zen art', terms: [ 'zen', 'art' ], score: 1.21313 }
37162
+ * // ]
37163
+ * ```
37164
+ *
37165
+ * @param queryString Query string to be expanded into suggestions
37166
+ * @param options Search options. The supported options and default values
37167
+ * are the same as for the {@link MiniSearch#search} method, except that by
37168
+ * default prefix search is performed on the last term in the query, and terms
37169
+ * are combined with `'AND'`.
37170
+ * @return A sorted array of suggestions sorted by relevance score.
37171
+ */
37172
+ autoSuggest(queryString, options = {}) {
37173
+ options = { ...this._options.autoSuggestOptions, ...options };
37174
+ const suggestions = /* @__PURE__ */ new Map();
37175
+ for (const { score, terms } of this.search(queryString, options)) {
37176
+ const phrase2 = terms.join(" ");
37177
+ const suggestion = suggestions.get(phrase2);
37178
+ if (suggestion != null) {
37179
+ suggestion.score += score;
37180
+ suggestion.count += 1;
37181
+ } else {
37182
+ suggestions.set(phrase2, { score, terms, count: 1 });
37183
+ }
37184
+ }
37185
+ const results = [];
37186
+ for (const [suggestion, { score, terms, count }] of suggestions) {
37187
+ results.push({ suggestion, terms, score: score / count });
37188
+ }
37189
+ results.sort(byScore);
37190
+ return results;
37191
+ }
37192
+ /**
37193
+ * Total number of documents available to search
37194
+ */
37195
+ get documentCount() {
37196
+ return this._documentCount;
37197
+ }
37198
+ /**
37199
+ * Number of terms in the index
37200
+ */
37201
+ get termCount() {
37202
+ return this._index.size;
37203
+ }
37204
+ /**
37205
+ * Deserializes a JSON index (serialized with `JSON.stringify(miniSearch)`)
37206
+ * and instantiates a MiniSearch instance. It should be given the same options
37207
+ * originally used when serializing the index.
37208
+ *
37209
+ * ### Usage:
37210
+ *
37211
+ * ```javascript
37212
+ * // If the index was serialized with:
37213
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
37214
+ * miniSearch.addAll(documents)
37215
+ *
37216
+ * const json = JSON.stringify(miniSearch)
37217
+ * // It can later be deserialized like this:
37218
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
37219
+ * ```
37220
+ *
37221
+ * @param json JSON-serialized index
37222
+ * @param options configuration options, same as the constructor
37223
+ * @return An instance of MiniSearch deserialized from the given JSON.
37224
+ */
37225
+ static loadJSON(json5, options) {
37226
+ if (options == null) {
37227
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
37228
+ }
37229
+ return this.loadJS(JSON.parse(json5), options);
37230
+ }
37231
+ /**
37232
+ * Async equivalent of {@link MiniSearch.loadJSON}
37233
+ *
37234
+ * This function is an alternative to {@link MiniSearch.loadJSON} that returns
37235
+ * a promise, and loads the index in batches, leaving pauses between them to avoid
37236
+ * blocking the main thread. It tends to be slower than the synchronous
37237
+ * version, but does not block the main thread, so it can be a better choice
37238
+ * when deserializing very large indexes.
37239
+ *
37240
+ * @param json JSON-serialized index
37241
+ * @param options configuration options, same as the constructor
37242
+ * @return A Promise that will resolve to an instance of MiniSearch deserialized from the given JSON.
37243
+ */
37244
+ static async loadJSONAsync(json5, options) {
37245
+ if (options == null) {
37246
+ throw new Error("MiniSearch: loadJSON should be given the same options used when serializing the index");
37247
+ }
37248
+ return this.loadJSAsync(JSON.parse(json5), options);
37249
+ }
37250
+ /**
37251
+ * Returns the default value of an option. It will throw an error if no option
37252
+ * with the given name exists.
37253
+ *
37254
+ * @param optionName Name of the option
37255
+ * @return The default value of the given option
37256
+ *
37257
+ * ### Usage:
37258
+ *
37259
+ * ```javascript
37260
+ * // Get default tokenizer
37261
+ * MiniSearch.getDefault('tokenize')
37262
+ *
37263
+ * // Get default term processor
37264
+ * MiniSearch.getDefault('processTerm')
37265
+ *
37266
+ * // Unknown options will throw an error
37267
+ * MiniSearch.getDefault('notExisting')
37268
+ * // => throws 'MiniSearch: unknown option "notExisting"'
37269
+ * ```
37270
+ */
37271
+ static getDefault(optionName) {
37272
+ if (defaultOptions.hasOwnProperty(optionName)) {
37273
+ return getOwnProperty(defaultOptions, optionName);
37274
+ } else {
37275
+ throw new Error(`MiniSearch: unknown option "${optionName}"`);
37276
+ }
37277
+ }
37278
+ /**
37279
+ * @ignore
37280
+ */
37281
+ static loadJS(js, options) {
37282
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
37283
+ const miniSearch = this.instantiateMiniSearch(js, options);
37284
+ miniSearch._documentIds = objectToNumericMap(documentIds);
37285
+ miniSearch._fieldLength = objectToNumericMap(fieldLength);
37286
+ miniSearch._storedFields = objectToNumericMap(storedFields);
37287
+ for (const [shortId, id2] of miniSearch._documentIds) {
37288
+ miniSearch._idToShortId.set(id2, shortId);
37289
+ }
37290
+ for (const [term, data] of index) {
37291
+ const dataMap = /* @__PURE__ */ new Map();
37292
+ for (const fieldId of Object.keys(data)) {
37293
+ let indexEntry = data[fieldId];
37294
+ if (serializationVersion === 1) {
37295
+ indexEntry = indexEntry.ds;
37296
+ }
37297
+ dataMap.set(parseInt(fieldId, 10), objectToNumericMap(indexEntry));
37298
+ }
37299
+ miniSearch._index.set(term, dataMap);
37300
+ }
37301
+ return miniSearch;
37302
+ }
37303
+ /**
37304
+ * @ignore
37305
+ */
37306
+ static async loadJSAsync(js, options) {
37307
+ const { index, documentIds, fieldLength, storedFields, serializationVersion } = js;
37308
+ const miniSearch = this.instantiateMiniSearch(js, options);
37309
+ miniSearch._documentIds = await objectToNumericMapAsync(documentIds);
37310
+ miniSearch._fieldLength = await objectToNumericMapAsync(fieldLength);
37311
+ miniSearch._storedFields = await objectToNumericMapAsync(storedFields);
37312
+ for (const [shortId, id2] of miniSearch._documentIds) {
37313
+ miniSearch._idToShortId.set(id2, shortId);
37314
+ }
37315
+ let count = 0;
37316
+ for (const [term, data] of index) {
37317
+ const dataMap = /* @__PURE__ */ new Map();
37318
+ for (const fieldId of Object.keys(data)) {
37319
+ let indexEntry = data[fieldId];
37320
+ if (serializationVersion === 1) {
37321
+ indexEntry = indexEntry.ds;
37322
+ }
37323
+ dataMap.set(parseInt(fieldId, 10), await objectToNumericMapAsync(indexEntry));
37324
+ }
37325
+ if (++count % 1e3 === 0)
37326
+ await wait(0);
37327
+ miniSearch._index.set(term, dataMap);
37328
+ }
37329
+ return miniSearch;
37330
+ }
37331
+ /**
37332
+ * @ignore
37333
+ */
37334
+ static instantiateMiniSearch(js, options) {
37335
+ const { documentCount, nextId, fieldIds, averageFieldLength, dirtCount, serializationVersion } = js;
37336
+ if (serializationVersion !== 1 && serializationVersion !== 2) {
37337
+ throw new Error("MiniSearch: cannot deserialize an index created with an incompatible version");
37338
+ }
37339
+ const miniSearch = new _MiniSearch(options);
37340
+ miniSearch._documentCount = documentCount;
37341
+ miniSearch._nextId = nextId;
37342
+ miniSearch._idToShortId = /* @__PURE__ */ new Map();
37343
+ miniSearch._fieldIds = fieldIds;
37344
+ miniSearch._avgFieldLength = averageFieldLength;
37345
+ miniSearch._dirtCount = dirtCount || 0;
37346
+ miniSearch._index = new SearchableMap();
37347
+ return miniSearch;
37348
+ }
37349
+ /**
37350
+ * @ignore
37351
+ */
37352
+ executeQuery(query, searchOptions = {}) {
37353
+ if (query === _MiniSearch.wildcard) {
37354
+ return this.executeWildcardQuery(searchOptions);
37355
+ }
37356
+ if (typeof query !== "string") {
37357
+ const options2 = { ...searchOptions, ...query, queries: void 0 };
37358
+ const results2 = query.queries.map((subquery) => this.executeQuery(subquery, options2));
37359
+ return this.combineResults(results2, options2.combineWith);
37360
+ }
37361
+ const { tokenize, processTerm, searchOptions: globalSearchOptions } = this._options;
37362
+ const options = { tokenize, processTerm, ...globalSearchOptions, ...searchOptions };
37363
+ const { tokenize: searchTokenize, processTerm: searchProcessTerm } = options;
37364
+ const terms = searchTokenize(query).flatMap((term) => searchProcessTerm(term)).filter((term) => !!term);
37365
+ const queries = terms.map(termToQuerySpec(options));
37366
+ const results = queries.map((query2) => this.executeQuerySpec(query2, options));
37367
+ return this.combineResults(results, options.combineWith);
37368
+ }
37369
+ /**
37370
+ * @ignore
37371
+ */
37372
+ executeQuerySpec(query, searchOptions) {
37373
+ const options = { ...this._options.searchOptions, ...searchOptions };
37374
+ const boosts = (options.fields || this._options.fields).reduce((boosts2, field) => ({ ...boosts2, [field]: getOwnProperty(options.boost, field) || 1 }), {});
37375
+ const { boostDocument, weights, maxFuzzy, bm25: bm25params } = options;
37376
+ const { fuzzy: fuzzyWeight, prefix: prefixWeight } = { ...defaultSearchOptions.weights, ...weights };
37377
+ const data = this._index.get(query.term);
37378
+ const results = this.termResults(query.term, query.term, 1, query.termBoost, data, boosts, boostDocument, bm25params);
37379
+ let prefixMatches;
37380
+ let fuzzyMatches;
37381
+ if (query.prefix) {
37382
+ prefixMatches = this._index.atPrefix(query.term);
37383
+ }
37384
+ if (query.fuzzy) {
37385
+ const fuzzy = query.fuzzy === true ? 0.2 : query.fuzzy;
37386
+ const maxDistance = fuzzy < 1 ? Math.min(maxFuzzy, Math.round(query.term.length * fuzzy)) : fuzzy;
37387
+ if (maxDistance)
37388
+ fuzzyMatches = this._index.fuzzyGet(query.term, maxDistance);
37389
+ }
37390
+ if (prefixMatches) {
37391
+ for (const [term, data2] of prefixMatches) {
37392
+ const distance = term.length - query.term.length;
37393
+ if (!distance) {
37394
+ continue;
37395
+ }
37396
+ fuzzyMatches === null || fuzzyMatches === void 0 ? void 0 : fuzzyMatches.delete(term);
37397
+ const weight = prefixWeight * term.length / (term.length + 0.3 * distance);
37398
+ this.termResults(query.term, term, weight, query.termBoost, data2, boosts, boostDocument, bm25params, results);
37399
+ }
37400
+ }
37401
+ if (fuzzyMatches) {
37402
+ for (const term of fuzzyMatches.keys()) {
37403
+ const [data2, distance] = fuzzyMatches.get(term);
37404
+ if (!distance) {
37405
+ continue;
37406
+ }
37407
+ const weight = fuzzyWeight * term.length / (term.length + distance);
37408
+ this.termResults(query.term, term, weight, query.termBoost, data2, boosts, boostDocument, bm25params, results);
37409
+ }
37410
+ }
37411
+ return results;
37412
+ }
37413
+ /**
37414
+ * @ignore
37415
+ */
37416
+ executeWildcardQuery(searchOptions) {
37417
+ const results = /* @__PURE__ */ new Map();
37418
+ const options = { ...this._options.searchOptions, ...searchOptions };
37419
+ for (const [shortId, id2] of this._documentIds) {
37420
+ const score = options.boostDocument ? options.boostDocument(id2, "", this._storedFields.get(shortId)) : 1;
37421
+ results.set(shortId, {
37422
+ score,
37423
+ terms: [],
37424
+ match: {}
37425
+ });
37426
+ }
37427
+ return results;
37428
+ }
37429
+ /**
37430
+ * @ignore
37431
+ */
37432
+ combineResults(results, combineWith = OR2) {
37433
+ if (results.length === 0) {
37434
+ return /* @__PURE__ */ new Map();
37435
+ }
37436
+ const operator = combineWith.toLowerCase();
37437
+ const combinator = combinators[operator];
37438
+ if (!combinator) {
37439
+ throw new Error(`Invalid combination operator: ${combineWith}`);
37440
+ }
37441
+ return results.reduce(combinator) || /* @__PURE__ */ new Map();
37442
+ }
37443
+ /**
37444
+ * Allows serialization of the index to JSON, to possibly store it and later
37445
+ * deserialize it with {@link MiniSearch.loadJSON}.
37446
+ *
37447
+ * Normally one does not directly call this method, but rather call the
37448
+ * standard JavaScript `JSON.stringify()` passing the {@link MiniSearch}
37449
+ * instance, and JavaScript will internally call this method. Upon
37450
+ * deserialization, one must pass to {@link MiniSearch.loadJSON} the same
37451
+ * options used to create the original instance that was serialized.
37452
+ *
37453
+ * ### Usage:
37454
+ *
37455
+ * ```javascript
37456
+ * // Serialize the index:
37457
+ * let miniSearch = new MiniSearch({ fields: ['title', 'text'] })
37458
+ * miniSearch.addAll(documents)
37459
+ * const json = JSON.stringify(miniSearch)
37460
+ *
37461
+ * // Later, to deserialize it:
37462
+ * miniSearch = MiniSearch.loadJSON(json, { fields: ['title', 'text'] })
37463
+ * ```
37464
+ *
37465
+ * @return A plain-object serializable representation of the search index.
37466
+ */
37467
+ toJSON() {
37468
+ const index = [];
37469
+ for (const [term, fieldIndex] of this._index) {
37470
+ const data = {};
37471
+ for (const [fieldId, freqs] of fieldIndex) {
37472
+ data[fieldId] = Object.fromEntries(freqs);
37473
+ }
37474
+ index.push([term, data]);
37475
+ }
37476
+ return {
37477
+ documentCount: this._documentCount,
37478
+ nextId: this._nextId,
37479
+ documentIds: Object.fromEntries(this._documentIds),
37480
+ fieldIds: this._fieldIds,
37481
+ fieldLength: Object.fromEntries(this._fieldLength),
37482
+ averageFieldLength: this._avgFieldLength,
37483
+ storedFields: Object.fromEntries(this._storedFields),
37484
+ dirtCount: this._dirtCount,
37485
+ index,
37486
+ serializationVersion: 2
37487
+ };
37488
+ }
37489
+ /**
37490
+ * @ignore
37491
+ */
37492
+ termResults(sourceTerm, derivedTerm, termWeight, termBoost, fieldTermData, fieldBoosts, boostDocumentFn, bm25params, results = /* @__PURE__ */ new Map()) {
37493
+ if (fieldTermData == null)
37494
+ return results;
37495
+ for (const field of Object.keys(fieldBoosts)) {
37496
+ const fieldBoost = fieldBoosts[field];
37497
+ const fieldId = this._fieldIds[field];
37498
+ const fieldTermFreqs = fieldTermData.get(fieldId);
37499
+ if (fieldTermFreqs == null)
37500
+ continue;
37501
+ let matchingFields = fieldTermFreqs.size;
37502
+ const avgFieldLength = this._avgFieldLength[fieldId];
37503
+ for (const docId of fieldTermFreqs.keys()) {
37504
+ if (!this._documentIds.has(docId)) {
37505
+ this.removeTerm(fieldId, docId, derivedTerm);
37506
+ matchingFields -= 1;
37507
+ continue;
37508
+ }
37509
+ const docBoost = boostDocumentFn ? boostDocumentFn(this._documentIds.get(docId), derivedTerm, this._storedFields.get(docId)) : 1;
37510
+ if (!docBoost)
37511
+ continue;
37512
+ const termFreq = fieldTermFreqs.get(docId);
37513
+ const fieldLength = this._fieldLength.get(docId)[fieldId];
37514
+ const rawScore = calcBM25Score(termFreq, matchingFields, this._documentCount, fieldLength, avgFieldLength, bm25params);
37515
+ const weightedScore = termWeight * termBoost * fieldBoost * docBoost * rawScore;
37516
+ const result = results.get(docId);
37517
+ if (result) {
37518
+ result.score += weightedScore;
37519
+ assignUniqueTerm(result.terms, sourceTerm);
37520
+ const match2 = getOwnProperty(result.match, derivedTerm);
37521
+ if (match2) {
37522
+ match2.push(field);
37523
+ } else {
37524
+ result.match[derivedTerm] = [field];
37525
+ }
37526
+ } else {
37527
+ results.set(docId, {
37528
+ score: weightedScore,
37529
+ terms: [sourceTerm],
37530
+ match: { [derivedTerm]: [field] }
37531
+ });
37532
+ }
37533
+ }
37534
+ }
37535
+ return results;
37536
+ }
37537
+ /**
37538
+ * @ignore
37539
+ */
37540
+ addTerm(fieldId, documentId, term) {
37541
+ const indexData = this._index.fetch(term, createMap);
37542
+ let fieldIndex = indexData.get(fieldId);
37543
+ if (fieldIndex == null) {
37544
+ fieldIndex = /* @__PURE__ */ new Map();
37545
+ fieldIndex.set(documentId, 1);
37546
+ indexData.set(fieldId, fieldIndex);
37547
+ } else {
37548
+ const docs = fieldIndex.get(documentId);
37549
+ fieldIndex.set(documentId, (docs || 0) + 1);
37550
+ }
37551
+ }
37552
+ /**
37553
+ * @ignore
37554
+ */
37555
+ removeTerm(fieldId, documentId, term) {
37556
+ if (!this._index.has(term)) {
37557
+ this.warnDocumentChanged(documentId, fieldId, term);
37558
+ return;
37559
+ }
37560
+ const indexData = this._index.fetch(term, createMap);
37561
+ const fieldIndex = indexData.get(fieldId);
37562
+ if (fieldIndex == null || fieldIndex.get(documentId) == null) {
37563
+ this.warnDocumentChanged(documentId, fieldId, term);
37564
+ } else if (fieldIndex.get(documentId) <= 1) {
37565
+ if (fieldIndex.size <= 1) {
37566
+ indexData.delete(fieldId);
37567
+ } else {
37568
+ fieldIndex.delete(documentId);
37569
+ }
37570
+ } else {
37571
+ fieldIndex.set(documentId, fieldIndex.get(documentId) - 1);
37572
+ }
37573
+ if (this._index.get(term).size === 0) {
37574
+ this._index.delete(term);
37575
+ }
37576
+ }
37577
+ /**
37578
+ * @ignore
37579
+ */
37580
+ warnDocumentChanged(shortDocumentId, fieldId, term) {
37581
+ for (const fieldName of Object.keys(this._fieldIds)) {
37582
+ if (this._fieldIds[fieldName] === fieldId) {
37583
+ this._options.logger("warn", `MiniSearch: document with ID ${this._documentIds.get(shortDocumentId)} has changed before removal: term "${term}" was not present in field "${fieldName}". Removing a document after it has changed can corrupt the index!`, "version_conflict");
37584
+ return;
37585
+ }
37586
+ }
37587
+ }
37588
+ /**
37589
+ * @ignore
37590
+ */
37591
+ addDocumentId(documentId) {
37592
+ const shortDocumentId = this._nextId;
37593
+ this._idToShortId.set(documentId, shortDocumentId);
37594
+ this._documentIds.set(shortDocumentId, documentId);
37595
+ this._documentCount += 1;
37596
+ this._nextId += 1;
37597
+ return shortDocumentId;
37598
+ }
37599
+ /**
37600
+ * @ignore
37601
+ */
37602
+ addFields(fields3) {
37603
+ for (let i = 0; i < fields3.length; i++) {
37604
+ this._fieldIds[fields3[i]] = i;
37605
+ }
37606
+ }
37607
+ /**
37608
+ * @ignore
37609
+ */
37610
+ addFieldLength(documentId, fieldId, count, length) {
37611
+ let fieldLengths = this._fieldLength.get(documentId);
37612
+ if (fieldLengths == null)
37613
+ this._fieldLength.set(documentId, fieldLengths = []);
37614
+ fieldLengths[fieldId] = length;
37615
+ const averageFieldLength = this._avgFieldLength[fieldId] || 0;
37616
+ const totalFieldLength = averageFieldLength * count + length;
37617
+ this._avgFieldLength[fieldId] = totalFieldLength / (count + 1);
37618
+ }
37619
+ /**
37620
+ * @ignore
37621
+ */
37622
+ removeFieldLength(documentId, fieldId, count, length) {
37623
+ if (count === 1) {
37624
+ this._avgFieldLength[fieldId] = 0;
37625
+ return;
37626
+ }
37627
+ const totalFieldLength = this._avgFieldLength[fieldId] * count - length;
37628
+ this._avgFieldLength[fieldId] = totalFieldLength / (count - 1);
37629
+ }
37630
+ /**
37631
+ * @ignore
37632
+ */
37633
+ saveStoredFields(documentId, doc) {
37634
+ const { storeFields, extractField } = this._options;
37635
+ if (storeFields == null || storeFields.length === 0) {
37636
+ return;
37637
+ }
37638
+ let documentFields = this._storedFields.get(documentId);
37639
+ if (documentFields == null)
37640
+ this._storedFields.set(documentId, documentFields = {});
37641
+ for (const fieldName of storeFields) {
37642
+ const fieldValue = extractField(doc, fieldName);
37643
+ if (fieldValue !== void 0)
37644
+ documentFields[fieldName] = fieldValue;
37645
+ }
37646
+ }
37647
+ };
37648
+ MiniSearch.wildcard = /* @__PURE__ */ Symbol("*");
37649
+ var getOwnProperty = (object5, property) => Object.prototype.hasOwnProperty.call(object5, property) ? object5[property] : void 0;
37650
+ var combinators = {
37651
+ [OR2]: (a, b) => {
37652
+ for (const docId of b.keys()) {
37653
+ const existing = a.get(docId);
37654
+ if (existing == null) {
37655
+ a.set(docId, b.get(docId));
37656
+ } else {
37657
+ const { score, terms, match: match2 } = b.get(docId);
37658
+ existing.score = existing.score + score;
37659
+ existing.match = Object.assign(existing.match, match2);
37660
+ assignUniqueTerms(existing.terms, terms);
37661
+ }
37662
+ }
37663
+ return a;
37664
+ },
37665
+ [AND]: (a, b) => {
37666
+ const combined = /* @__PURE__ */ new Map();
37667
+ for (const docId of b.keys()) {
37668
+ const existing = a.get(docId);
37669
+ if (existing == null)
37670
+ continue;
37671
+ const { score, terms, match: match2 } = b.get(docId);
37672
+ assignUniqueTerms(existing.terms, terms);
37673
+ combined.set(docId, {
37674
+ score: existing.score + score,
37675
+ terms: existing.terms,
37676
+ match: Object.assign(existing.match, match2)
37677
+ });
37678
+ }
37679
+ return combined;
37680
+ },
37681
+ [AND_NOT]: (a, b) => {
37682
+ for (const docId of b.keys())
37683
+ a.delete(docId);
37684
+ return a;
37685
+ }
37686
+ };
37687
+ var defaultBM25params = { k: 1.2, b: 0.7, d: 0.5 };
37688
+ var calcBM25Score = (termFreq, matchingCount, totalCount, fieldLength, avgFieldLength, bm25params) => {
37689
+ const { k: k3, b, d } = bm25params;
37690
+ const invDocFreq = Math.log(1 + (totalCount - matchingCount + 0.5) / (matchingCount + 0.5));
37691
+ return invDocFreq * (d + termFreq * (k3 + 1) / (termFreq + k3 * (1 - b + b * fieldLength / avgFieldLength)));
37692
+ };
37693
+ var termToQuerySpec = (options) => (term, i, terms) => {
37694
+ const fuzzy = typeof options.fuzzy === "function" ? options.fuzzy(term, i, terms) : options.fuzzy || false;
37695
+ const prefix = typeof options.prefix === "function" ? options.prefix(term, i, terms) : options.prefix === true;
37696
+ const termBoost = typeof options.boostTerm === "function" ? options.boostTerm(term, i, terms) : 1;
37697
+ return { term, fuzzy, prefix, termBoost };
37698
+ };
37699
+ var defaultOptions = {
37700
+ idField: "id",
37701
+ extractField: (document2, fieldName) => document2[fieldName],
37702
+ stringifyField: (fieldValue, fieldName) => fieldValue.toString(),
37703
+ tokenize: (text2) => text2.split(SPACE_OR_PUNCTUATION),
37704
+ processTerm: (term) => term.toLowerCase(),
37705
+ fields: void 0,
37706
+ searchOptions: void 0,
37707
+ storeFields: [],
37708
+ logger: (level, message2) => {
37709
+ if (typeof (console === null || console === void 0 ? void 0 : console[level]) === "function")
37710
+ console[level](message2);
37711
+ },
37712
+ autoVacuum: true
37713
+ };
37714
+ var defaultSearchOptions = {
37715
+ combineWith: OR2,
37716
+ prefix: false,
37717
+ fuzzy: false,
37718
+ maxFuzzy: 6,
37719
+ boost: {},
37720
+ weights: { fuzzy: 0.45, prefix: 0.375 },
37721
+ bm25: defaultBM25params
37722
+ };
37723
+ var defaultAutoSuggestOptions = {
37724
+ combineWith: AND,
37725
+ prefix: (term, i, terms) => i === terms.length - 1
37726
+ };
37727
+ var defaultVacuumOptions = { batchSize: 1e3, batchWait: 10 };
37728
+ var defaultVacuumConditions = { minDirtFactor: 0.1, minDirtCount: 20 };
37729
+ var defaultAutoVacuumOptions = { ...defaultVacuumOptions, ...defaultVacuumConditions };
37730
+ var assignUniqueTerm = (target, term) => {
37731
+ if (!target.includes(term))
37732
+ target.push(term);
37733
+ };
37734
+ var assignUniqueTerms = (target, source) => {
37735
+ for (const term of source) {
37736
+ if (!target.includes(term))
37737
+ target.push(term);
37738
+ }
37739
+ };
37740
+ var byScore = ({ score: a }, { score: b }) => b - a;
37741
+ var createMap = () => /* @__PURE__ */ new Map();
37742
+ var objectToNumericMap = (object5) => {
37743
+ const map = /* @__PURE__ */ new Map();
37744
+ for (const key of Object.keys(object5)) {
37745
+ map.set(parseInt(key, 10), object5[key]);
37746
+ }
37747
+ return map;
37748
+ };
37749
+ var objectToNumericMapAsync = async (object5) => {
37750
+ const map = /* @__PURE__ */ new Map();
37751
+ let count = 0;
37752
+ for (const key of Object.keys(object5)) {
37753
+ map.set(parseInt(key, 10), object5[key]);
37754
+ if (++count % 1e3 === 0) {
37755
+ await wait(0);
37756
+ }
37757
+ }
37758
+ return map;
37759
+ };
37760
+ var wait = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
37761
+ var SPACE_OR_PUNCTUATION = /[\n\r\p{Z}\p{P}]+/u;
37762
+
37763
+ // src/search/engine.ts
37764
+ var normalize = (text2) => text2.normalize("NFKD").replace(new RegExp("\\p{M}", "gu"), "").toLowerCase();
37765
+ var words = (text2) => normalize(text2).match(/[\p{L}\p{N}]+/gu) || [];
37766
+ var phrase = (text2) => words(text2).join(" ");
37767
+ function parseQuery(input) {
37768
+ const plan2 = { text: "", terms: [], phrases: [], filters: [] };
37769
+ const parts = [];
37770
+ for (const token3 of input.slice(0, 300).match(/(?:[^\s"]+|"[^"]*")+/g) || []) {
37771
+ const filter = /^(source|project|dir|model|is|after|before|in):(.+)$/i.exec(token3);
37772
+ if (filter) {
37773
+ const key = filter[1].toLowerCase(), value2 = normalize(filter[2].replace(/^"|"$/g, ""));
37774
+ if (key === "in") {
37775
+ const fields3 = { title: ["title"], files: ["files"], messages: ["body"], tools: ["tools"] };
37776
+ plan2.fields = fields3[value2];
37777
+ if (!plan2.fields) plan2.error = "Use in:title, in:files, in:messages, or in:tools.";
37778
+ } else if (key === "is" && !["fork", "child", "root", "archived"].includes(value2)) plan2.error = "Use is:fork, is:child, is:root, or is:archived.";
37779
+ else if (["after", "before"].includes(key) && (!/^\d{4}-\d{2}-\d{2}$/.test(value2) || !Number.isFinite(Date.parse(value2)) || new Date(value2).toISOString().slice(0, 10) !== value2)) plan2.error = "Use a valid date in YYYY-MM-DD format.";
37780
+ else plan2.filters.push([key, value2]);
37781
+ continue;
37782
+ }
37783
+ const value = token3.replace(/^"|"$/g, "");
37784
+ if (token3.startsWith('"') && token3.endsWith('"')) plan2.phrases.push(phrase(value));
37785
+ parts.push(value);
37786
+ }
37787
+ plan2.text = parts.join(" ");
37788
+ plan2.terms = words(plan2.text).slice(0, 12);
37789
+ plan2.text = plan2.terms.join(" ");
37790
+ return plan2;
37791
+ }
37792
+ function excerpt(text2, terms, length = 220) {
37793
+ const value = normalize(text2);
37794
+ const at2 = terms.reduce((best, term) => {
37795
+ const index = value.indexOf(term);
37796
+ return index < 0 ? best : Math.min(best, index);
37797
+ }, Infinity);
37798
+ const start = Number.isFinite(at2) ? Math.max(0, at2 - 55) : 0;
37799
+ return `${start ? "\u2026" : ""}${text2.slice(start, start + length).replace(/\s+/g, " ").trim()}${text2.length > start + length ? "\u2026" : ""}`;
37800
+ }
37801
+ var SessionSearchIndex = class {
37802
+ index = new MiniSearch({
37803
+ fields: ["title", "project", "directory", "model", "sessionID", "files", "body", "tools"],
37804
+ tokenize: words,
37805
+ processTerm: normalize,
37806
+ searchOptions: { combineWith: "AND", prefix: true, boost: { title: 12, files: 5, project: 3, directory: 3, model: 2, sessionID: 12, body: 1, tools: 0.6 } }
37807
+ });
37808
+ entries = /* @__PURE__ */ new Map();
37809
+ cache = /* @__PURE__ */ new Map();
37810
+ scope = /* @__PURE__ */ new Set();
37811
+ setData(sessions, projects) {
37812
+ const ids = new Set(sessions.map((s) => s.id));
37813
+ for (const [id2, entry] of this.entries) if (!ids.has(id2)) {
37814
+ this.index.remove(entry.doc);
37815
+ this.entries.delete(id2);
37816
+ }
37817
+ const names = new Map(projects.map((p) => [p.id, p.name]));
37818
+ for (const session of sessions) {
37819
+ const old = this.entries.get(session.id);
37820
+ const keep = old && contentVersion(old.session) === contentVersion(session);
37821
+ const doc = { id: session.id, title: session.title, project: names.get(session.projectID) || "", directory: session.directory, model: session.model, sessionID: session.id, body: keep ? old.doc.body : "", files: keep ? old.doc.files : "", tools: keep ? old.doc.tools : "" };
37822
+ if (keep && Object.keys(doc).every((key) => old.doc[key] === doc[key])) {
37823
+ old.session = session;
37824
+ continue;
37825
+ }
37826
+ this.entries.set(session.id, { session, doc, fragments: keep ? old.fragments : [] });
37827
+ if (old) this.index.remove(old.doc);
37828
+ this.index.add(doc);
37829
+ }
37830
+ this.cache.clear();
37831
+ }
37832
+ setScope(ids) {
37833
+ this.scope = new Set(ids);
37834
+ this.cache.clear();
37835
+ }
37836
+ content(id2) {
37837
+ return this.entries.get(id2)?.fragments.slice() || [];
37838
+ }
37839
+ addContent(id2, fragments) {
37840
+ const entry = this.entries.get(id2);
37841
+ if (!entry) return;
37842
+ entry.fragments.push(...fragments);
37843
+ const doc = { ...entry.doc };
37844
+ for (const fragment of fragments) {
37845
+ const field = fragment.kind === "File" ? "files" : fragment.kind === "Tool" ? "tools" : "body";
37846
+ doc[field] += `
37847
+ ${fragment.text}`;
37848
+ }
37849
+ this.index.remove(entry.doc);
37850
+ this.index.add(doc);
37851
+ entry.doc = doc;
37852
+ this.cache.clear();
37853
+ }
37854
+ search(input, viewOnly = false, limit = 80, offset = 0) {
37855
+ const key = `${input}\0${viewOnly}\0${limit}\0${offset}`;
37856
+ const cached2 = this.cache.get(key);
37857
+ if (cached2) return cached2;
37858
+ const plan2 = parseQuery(input);
37859
+ if (plan2.error) return { hits: [], total: 0, error: plan2.error };
37860
+ const accepts = (entry) => {
37861
+ const { session, doc } = entry;
37862
+ if (viewOnly && !this.scope.has(session.id)) return false;
37863
+ for (const [key2, value] of plan2.filters) {
37864
+ if (key2 === "source" && ![session.source || "opencode", ...(session.linkedSessionIDs || []).map((id2) => id2.split(":")[0])].some((source) => normalize(source).includes(value))) return false;
37865
+ if (key2 === "project" && !normalize(doc.project).includes(value) && !normalize(session.projectID).includes(value)) return false;
37866
+ if (key2 === "dir" && !normalize(session.directory).includes(value)) return false;
37867
+ if (key2 === "model" && !normalize(session.model).includes(value)) return false;
37868
+ if (key2 === "after" && session.created < (/* @__PURE__ */ new Date(`${value}T00:00:00`)).getTime()) return false;
37869
+ if (key2 === "before" && session.created > (/* @__PURE__ */ new Date(`${value}T23:59:59.999`)).getTime()) return false;
37870
+ if (key2 === "is") {
37871
+ if (value === "fork" && !session.forkID) return false;
37872
+ if (value === "child" && (!session.parentID || session.forkID)) return false;
37873
+ if (value === "root" && (session.parentID || session.forkID)) return false;
37874
+ if (value === "archived" && !session.archived) return false;
37875
+ }
37876
+ }
37877
+ if (plan2.phrases.length) {
37878
+ const fields3 = plan2.fields || ["title", "body", "files", "tools", "project", "directory", "model"];
37879
+ if (!plan2.phrases.every((p) => fields3.some((field) => phrase(doc[field]).includes(p)))) return false;
37880
+ }
37881
+ return true;
37882
+ };
37883
+ const matches = plan2.terms.length ? this.index.search(plan2.text, {
37884
+ fields: plan2.fields,
37885
+ fuzzy: (term) => term.length < 4 ? false : term.length > 7 ? 2 : 1,
37886
+ filter: (result2) => accepts(this.entries.get(String(result2.id)))
37887
+ }) : [...this.entries.values()].filter(accepts).map((entry) => ({ id: entry.session.id, score: 0, terms: [], match: {} }));
37888
+ const ranked = matches.map((match2) => {
37889
+ const entry = this.entries.get(String(match2.id));
37890
+ const title = phrase(entry.doc.title);
37891
+ const fields3 = new Set(Object.values(match2.match).flat());
37892
+ const tier = !plan2.text ? 0 : title.includes(plan2.text) && (!plan2.fields || plan2.fields.includes("title")) ? 5 : fields3.has("title") ? 4 : fields3.has("sessionID") ? 4 : fields3.has("files") ? 3 : fields3.has("body") ? 2 : 1;
37893
+ return { match: match2, entry, tier };
37894
+ }).sort((a, b) => b.tier - a.tier || b.match.score - a.match.score || b.entry.session.updated - a.entry.session.updated || a.entry.session.id.localeCompare(b.entry.session.id));
37895
+ const hits = ranked.slice(offset, offset + Math.min(250, Math.max(1, limit))).map(({ match: match2, entry, tier }) => {
37896
+ const terms = match2.terms.length ? match2.terms : plan2.terms;
37897
+ const candidates = entry.fragments.filter((f) => !plan2.fields || plan2.fields.includes(f.kind === "File" ? "files" : f.kind === "Tool" ? "tools" : "body"));
37898
+ let best, bestCount = 0;
37899
+ for (const fragment of candidates) {
37900
+ const text2 = normalize(fragment.text);
37901
+ const count = terms.reduce((n, term) => n + Number(text2.includes(term)), 0);
37902
+ if (count > bestCount) {
37903
+ best = fragment;
37904
+ bestCount = count;
37905
+ }
37906
+ if (count === terms.length && count > 0) break;
37907
+ }
37908
+ const fields3 = new Set(Object.values(match2.match).flat());
37909
+ const source = tier >= 4 ? fields3.has("sessionID") && !fields3.has("title") ? "Session ID" : "Title" : best ? best.kind === "File" ? "File" : best.kind === "Tool" ? "Tool" : "Message" : plan2.text ? "Metadata" : "Recent";
37910
+ return { id: entry.session.id, score: match2.score, source, excerpt: best ? excerpt(best.text, terms) : "", terms };
37911
+ });
37912
+ const result = { hits, total: ranked.length };
37913
+ if (this.cache.size >= 30) this.cache.delete(this.cache.keys().next().value);
37914
+ this.cache.set(key, result);
37915
+ return result;
37916
+ }
37917
+ };
37918
+
37919
+ // src/search/sampling.ts
37920
+ function sampleContent(page2, budget2) {
37921
+ let remaining = Math.max(0, budget2), sampled = false;
37922
+ const fragments = [];
37923
+ const ordered = [...page2.fragments].sort((a, b) => Number(b.kind === "File" || b.kind === "You") - Number(a.kind === "File" || a.kind === "You"));
37924
+ const perFragment = Math.max(160, Math.min(2e3, Math.floor(remaining / Math.max(1, ordered.length))));
37925
+ for (const fragment of ordered) {
37926
+ if (remaining <= 0) {
37927
+ sampled = true;
37928
+ break;
37929
+ }
37930
+ const text2 = fragment.text.slice(0, Math.min(remaining, perFragment));
37931
+ sampled ||= text2.length < fragment.text.length;
37932
+ fragments.push({ ...fragment, text: text2 });
37933
+ remaining -= text2.length;
37934
+ }
37935
+ return { fragments, characters: Math.max(0, budget2) - remaining, partial: page2.truncated || sampled };
37936
+ }
37937
+
37938
+ // server/library-service.ts
37939
+ var utc = (ms) => ms > 0 && ms <= 864e13 ? new Date(ms).toISOString() : null;
37940
+ var LibraryService = class {
37941
+ constructor(store, adapters2) {
37942
+ this.store = store;
37943
+ this.importer = adapters2 instanceof Importer ? adapters2 : new Importer(store, adapters2);
37944
+ }
37945
+ store;
37946
+ searchCache;
37947
+ importer;
37948
+ validateSources(ids) {
37949
+ for (const id2 of ids) if (!this.importer.adapters.some((a) => a.id === id2)) invalid(`Unknown source "${id2}". Run sessiongraph sources list.`);
37950
+ }
37951
+ snapshot(read3) {
37952
+ this.store.db.exec("BEGIN");
37953
+ try {
37954
+ const result = read3();
37955
+ this.store.db.exec("COMMIT");
37956
+ return result;
37957
+ } catch (error) {
37958
+ this.store.db.exec("ROLLBACK");
37959
+ throw error;
37960
+ }
37961
+ }
37962
+ sessions(filters2) {
37963
+ this.validateSources(filters2.sources || []);
37964
+ const library2 = this.store.library([], this.importer.status.running);
37965
+ const sessions = filters2.raw ? this.store.db.prepare("SELECT metadata FROM sessions").all().map((row) => JSON.parse(String(row.metadata))) : library2.sessions;
37966
+ let matched = filterSessions(sessions, filters2);
37967
+ if (filters2.dateField === "message") {
37968
+ const exists = this.store.db.prepare("SELECT 1 FROM messages WHERE session_id=? AND is_user IN (0,1) AND time BETWEEN ? AND ? LIMIT 1");
37969
+ matched = matched.filter((s) => exists.get(s.id, filters2.since ?? 0, filters2.until ?? Number.MAX_SAFE_INTEGER));
37970
+ }
37971
+ return { sessions: matched, projects: library2.projects };
37972
+ }
37973
+ key(kind, sessions, filters2) {
37974
+ return fingerprint2([this.store.setting("libraryID"), kind, filters2, sessions]);
37975
+ }
37976
+ async discoverSources(ids) {
37977
+ const paths2 = this.store.setting("sourcePaths") || {};
37978
+ return {
37979
+ sources: (await this.importer.sources(ids)).map((source) => ({ ...source, path: paths2[source.id] || null, pathSupported: true, pathHint: sourcePathHint(source.id) })),
37980
+ configured: this.store.setting("selected") !== void 0,
37981
+ autoImport: this.store.autoImportEnabled()
37982
+ };
37983
+ }
37984
+ /** Editing a location neither selects a source nor imports its conversations. */
37985
+ setSourcePath(id2, path) {
37986
+ this.validateSources([id2]);
37987
+ if (path !== null && (typeof path !== "string" || !path.trim() || path.includes("\0") || !isAbsolute10(path) && path !== "~" && !path.startsWith("~/"))) invalid("Enter an absolute history path, or choose Automatic.");
37988
+ return this.configure(() => {
37989
+ const paths2 = this.store.setting("sourcePaths") || {};
37990
+ if (path === null) delete paths2[id2];
37991
+ else paths2[id2] = localPath(path);
37992
+ this.store.setting("sourcePaths", paths2);
37993
+ });
37994
+ }
37995
+ configure(change) {
37996
+ if (this.importer.status.running || !this.store.acquireImport()) throw new LibraryError("IMPORT_BUSY", "Another import is running. Try again when it finishes.");
37997
+ try {
37998
+ this.store.db.exec("BEGIN IMMEDIATE");
37999
+ try {
38000
+ change();
38001
+ this.store.db.exec("COMMIT");
38002
+ } catch (error) {
38003
+ this.store.db.exec("ROLLBACK");
38004
+ throw error;
38005
+ }
38006
+ } finally {
38007
+ this.store.releaseImport();
38008
+ }
38009
+ return { selected: this.store.selected(), paths: this.store.setting("sourcePaths") || {}, autoImport: this.store.autoImportEnabled(), historyRetained: true };
38010
+ }
38011
+ async setupSources(ids, options = {}) {
38012
+ this.validateSources(ids);
38013
+ if (options.detected && ids.length) invalid("Choose source IDs or --detected, not both.");
38014
+ if (options.path !== void 0 && options.defaultPath) invalid("Choose --path or --default-path, not both.");
38015
+ if (options.path !== void 0 || options.defaultPath) {
38016
+ if (ids.length !== 1) invalid("A path override requires exactly one filesystem source.");
38017
+ if (options.path !== void 0 && (!options.path.trim() || options.path.includes("\0"))) invalid("Choose a nonempty local source directory.");
38018
+ }
38019
+ if (options.detected) ids = (await this.discoverSources()).sources.filter((s) => s.available).map((s) => s.id);
38020
+ if (!ids.length && options.autoImport === void 0) invalid("Choose source IDs or --detected. No sources were selected.");
38021
+ return this.configure(() => {
38022
+ this.store.setting("selected", [.../* @__PURE__ */ new Set([...this.store.selected(), ...ids])]);
38023
+ const paths2 = this.store.setting("sourcePaths") || {};
38024
+ if (options.path !== void 0) paths2[ids[0]] = localPath(options.path);
38025
+ if (options.defaultPath) delete paths2[ids[0]];
38026
+ this.store.setting("sourcePaths", paths2);
38027
+ if (options.autoImport !== void 0) this.store.setting("autoImport", options.autoImport);
38028
+ });
38029
+ }
38030
+ removeSources(ids, all = false) {
38031
+ this.validateSources(ids);
38032
+ if (all === !!ids.length) invalid("Choose source IDs or --all.");
38033
+ return this.configure(() => {
38034
+ const removed = all ? this.importer.adapters.map((a) => a.id) : ids;
38035
+ this.store.setting("selected", this.store.selected().filter((id2) => !removed.includes(id2)));
38036
+ const paths2 = this.store.setting("sourcePaths") || {};
38037
+ for (const id2 of removed) delete paths2[id2];
38038
+ this.store.setting("sourcePaths", paths2);
38039
+ });
38040
+ }
38041
+ async importSessions(ids) {
38042
+ const selected = this.store.selected(), sources2 = ids?.length ? ids : selected;
38043
+ this.validateSources(sources2);
38044
+ if (!sources2.length) invalid("No import sources configured. Run sessiongraph sources setup <source...> first.");
38045
+ if (sources2.some((id2) => !selected.includes(id2))) invalid("Set up each source before syncing it: sessiongraph sources setup <source...>.");
38046
+ this.importer.sync(sources2);
38047
+ await this.importer.settled();
38048
+ return { ...this.importer.status, sources: sources2, selected: this.store.selected() };
38049
+ }
38050
+ listSessions(filters2 = {}, options = {}) {
38051
+ return this.snapshot(() => {
38052
+ const { sessions } = this.sessions(filters2);
38053
+ return { ...page(sessions, this.key("sessions", sessions, filters2), options), filters: filters2, order: "latest-message-first" };
38054
+ });
38055
+ }
38056
+ listSessionSummaries(filters2, options) {
38057
+ return this.snapshot(() => {
38058
+ const { sessions, projects } = this.sessions(filters2);
38059
+ const names = new Map(projects.map((p) => [p.id, p.name]));
38060
+ const result = page(sessions, this.key("session-summaries", sessions, [filters2, projects]), options);
38061
+ return { ...result, items: result.items.map((s) => ({
38062
+ id: s.id,
38063
+ title: s.title,
38064
+ source: s.source,
38065
+ projectID: s.projectID,
38066
+ projectLabel: names.get(s.projectID) || basename14(s.directory) || "Unknown project",
38067
+ created: utc(s.created),
38068
+ lastActivity: utc(sessionEnd(s)),
38069
+ relationship: relationshipOf(s),
38070
+ origin: s.origin ?? "unknown"
38071
+ })), filters: filters2, order: "latest-message-first" };
38072
+ });
38073
+ }
38074
+ getSession(id2) {
38075
+ const session = this.store.getSession(id2);
38076
+ if (!session) throw new LibraryError("NOT_FOUND", "Session not imported. Use the full ID from sessiongraph sessions.", 1);
38077
+ return session;
38078
+ }
38079
+ getMessages(id2, options = {}) {
38080
+ this.getSession(id2);
38081
+ return this.store.messages(id2, options);
38082
+ }
38083
+ getTimeline(id2) {
38084
+ this.getSession(id2);
38085
+ return this.store.timeline(id2);
38086
+ }
38087
+ getCommits(id2, options = {}) {
38088
+ this.getSession(id2);
38089
+ return this.store.commits(id2, options);
38090
+ }
38091
+ getEvents(id2, options = {}) {
38092
+ this.getSession(id2);
38093
+ return this.store.events(id2, options);
38094
+ }
38095
+ getFileChanges(id2, cursor) {
38096
+ this.getSession(id2);
38097
+ if (cursor && (!/^\d{1,9}$/.test(cursor) || Number(cursor) > MAX_SESSION_RECORDS)) invalid("Invalid file cursor. Use nextCursor from the previous page.");
38098
+ return this.store.detail(id2, cursor);
38099
+ }
38100
+ getRelationships(id2, options = {}) {
38101
+ return this.snapshot(() => {
38102
+ const session = this.getSession(id2), sessions = this.sessions({ raw: true }).sessions;
38103
+ const relation = (target, kind, direction) => ({ id: target, kind, direction, imported: sessions.some((s) => s.id === target) });
38104
+ const items = [
38105
+ ...session.parentID && session.parentID !== session.forkID ? [relation(session.parentID, "child", "parent")] : [],
38106
+ ...session.forkID ? [relation(session.forkID, "fork", "parent")] : [],
38107
+ ...(session.linkedSessionIDs || []).map((target) => relation(target, "provider-link", "outgoing")),
38108
+ ...sessions.flatMap((s) => [
38109
+ ...s.parentID === id2 && s.forkID !== id2 ? [relation(s.id, "child", "child")] : [],
38110
+ ...s.forkID === id2 ? [relation(s.id, "fork", "child")] : [],
38111
+ ...s.linkedSessionIDs?.includes(id2) ? [relation(s.id, "provider-link", "incoming")] : []
38112
+ ])
38113
+ ];
38114
+ return { sessionID: id2, ...page(items, fingerprint2(["relationships", id2, items]), options) };
38115
+ });
38116
+ }
38117
+ searchSessions(query, filters2 = {}, options = {}) {
38118
+ if (!query.trim() || query.length > 300) invalid("Search query must contain 1\u2013300 characters.");
38119
+ const plan2 = parseQuery(query);
38120
+ if (plan2.error) invalid(plan2.error);
38121
+ return this.snapshot(() => {
38122
+ const { sessions, projects } = this.sessions(filters2);
38123
+ const generation2 = [this.store.db.prepare("PRAGMA data_version").get(), this.store.db.prepare("SELECT total_changes() AS n").get()];
38124
+ const indexKey = fingerprint2([filters2, generation2]);
38125
+ if (this.searchCache?.key !== indexKey) {
38126
+ this.searchCache = void 0;
38127
+ const index2 = new SessionSearchIndex();
38128
+ index2.setData(sessions, projects);
38129
+ let characters2 = 0, complete3 = 0;
38130
+ const quota = Math.min(SESSION_CHARACTERS, Math.floor(MAX_CHARACTERS / Math.max(1, sessions.length)));
38131
+ for (const session of sessions) {
38132
+ let cursor, used = 0, partial = session.coverage?.history !== "complete", done = false;
38133
+ for (let n = 0; n < 8 && used < quota; n++) {
38134
+ const content = this.store.content(session.id, cursor), sampled = sampleContent(content, quota - used);
38135
+ index2.addContent(session.id, sampled.fragments);
38136
+ used += sampled.characters;
38137
+ partial ||= sampled.partial;
38138
+ if (!content.nextCursor) {
38139
+ done = true;
38140
+ break;
38141
+ }
38142
+ cursor = content.nextCursor;
38143
+ }
38144
+ characters2 += used;
38145
+ if (done && !partial) complete3++;
38146
+ }
38147
+ this.searchCache = { key: indexKey, index: index2, complete: complete3, characters: characters2 };
38148
+ }
38149
+ const { index, complete, characters } = this.searchCache;
38150
+ const key = this.key("search", sessions, [query, filters2, projects]), offset = pageOffset(options.cursor, key), limit = pageLimit(options.limit);
38151
+ const result = index.search(query, false, limit, offset), byID = new Map(sessions.map((s) => [s.id, s]));
38152
+ return {
38153
+ query,
38154
+ hits: result.hits.map((hit) => ({ ...hit, session: byID.get(hit.id) })),
38155
+ total: result.total,
38156
+ nextCursor: offset + limit < result.total ? nextCursor(key, offset + limit) : null,
38157
+ coverage: { sessions: sessions.length, complete, partial: sessions.length - complete, characters, limited: complete < sessions.length },
38158
+ note: "Search samples saved content. Narrow filters for more coverage; use messages/events for details."
38159
+ };
38160
+ });
38161
+ }
38162
+ getStats(filters2 = {}, groupBy = "source", options = {}) {
38163
+ return this.snapshot(() => this.summarize(this.sessions(filters2), filters2, groupBy, options));
38164
+ }
38165
+ async getRepositoryStats(filters2, options) {
38166
+ const data = this.snapshot(() => this.sessions(filters2));
38167
+ return this.summarize({ ...data, sessions: await annotateGitCheckouts(data.sessions) }, filters2, "repository", options);
38168
+ }
38169
+ summarize(data, filters2, groupBy, options) {
38170
+ if (!["source", "model", "project", "directory", "relationship", "origin", "repository"].includes(groupBy)) invalid("Unknown stats grouping.");
38171
+ const { sessions, projects } = data, grouped2 = /* @__PURE__ */ new Map();
38172
+ const names = new Map(projects.map((p) => [p.id, p.name]));
38173
+ const usage = (values) => {
38174
+ const known = values.filter((v3) => typeof v3 === "number" && Number.isFinite(v3));
38175
+ return { knownTotal: known.length || !values.length ? known.reduce((a, b) => a + b, 0) : null, knownSessions: known.length, unknownSessions: values.length - known.length };
38176
+ };
38177
+ const summary = (values) => ({
38178
+ sessions: values.length,
38179
+ tokens: usage(values.map((s) => s.tokens)),
38180
+ cost: usage(values.map((s) => s.cost)),
38181
+ userMessages: usage(values.map((s) => s.activity?.userMessages)),
38182
+ coverage: { complete: values.filter((s) => s.coverage?.history === "complete").length, partial: values.filter((s) => s.coverage?.history === "partial").length, pending: values.filter((s) => !s.coverage || s.coverage.history === "pending").length },
38183
+ firstCreated: values.some((s) => s.created > 0) ? values.reduce((min, s) => s.created > 0 ? Math.min(min, s.created) : min, Infinity) : null,
38184
+ lastActivity: values.some((s) => sessionEnd(s) > 0) ? values.reduce((max, s) => Math.max(max, sessionEnd(s)), 0) : null
38185
+ });
38186
+ for (const s of sessions) {
38187
+ const key = (groupBy === "project" ? s.projectID : groupBy === "repository" ? s.checkout?.repository : groupBy === "relationship" ? relationshipOf(s) : s[groupBy]) || "unknown";
38188
+ if (!grouped2.has(key)) grouped2.set(key, []);
38189
+ grouped2.get(key).push(s);
38190
+ }
38191
+ const groups = [...grouped2].sort(([a], [b]) => a.localeCompare(b)).map(([key, values]) => ({
38192
+ key,
38193
+ label: groupBy === "project" ? names.get(key) || basename14(values[0].directory) || "Unknown project" : groupBy === "repository" ? values[0].checkout?.repositoryLabel || "Unverified repository" : key,
38194
+ ...groupBy === "repository" ? { worktrees: [...new Set(values.flatMap((s) => s.checkout?.worktree || []))].sort() } : {},
38195
+ ...groupBy === "relationship" ? { origins: values.reduce((counts, s) => {
38196
+ counts[s.origin ?? "unknown"]++;
38197
+ return counts;
38198
+ }, { human: 0, automated: 0, unknown: 0 }) } : {},
38199
+ ...summary(values)
38200
+ }));
38201
+ return {
38202
+ totals: summary(sessions),
38203
+ groupBy,
38204
+ groups: page(groups, this.key("stats", sessions, [filters2, groupBy, groups]), options),
38205
+ filters: filters2,
38206
+ ...filters2.origin || groupBy === "origin" || groupBy === "relationship" ? {
38207
+ interpretation: "Origin identifies launcher type, not a specific person. Report unknown origins separately. If any are unknown, the actual number personally started is undetermined; zero confirmed human launches is not a personal count of zero."
38208
+ } : {},
38209
+ note: "Totals use matched sessions\u2019 lifetime usage. Unknown usage is reported separately. userMessages also counts lifetime messages."
38210
+ };
38211
+ }
38212
+ getGraph(filters2 = {}) {
38213
+ return this.snapshot(() => {
38214
+ const { sessions, projects } = this.sessions(filters2);
38215
+ if (sessions.length > 5e3) invalid("Graph output is limited to 5,000 sessions. Narrow --source, --directory, or --since.");
38216
+ return { graph: makeGraph(sessions, projects), filters: filters2 };
38217
+ });
38218
+ }
38219
+ async diagnose() {
38220
+ const sources2 = await this.discoverSources(), checks = [];
38221
+ const integrity = this.store.db.prepare("PRAGMA quick_check").all();
38222
+ checks.push({ name: "database", ok: integrity.every((row) => row.quick_check === "ok"), message: integrity.map((row) => String(row.quick_check)).join("; ") });
38223
+ for (const source of sources2.sources.filter((s) => s.selected)) checks.push({ name: source.id, ok: source.available && !source.error, message: source.error || (source.available ? "Available" : "History unavailable. Check the source path and permissions.") });
38224
+ const lock = this.store.db.prepare("SELECT pid,heartbeat FROM import_lock WHERE id=1").get();
38225
+ return {
38226
+ ok: checks.every((c) => c.ok),
38227
+ database: this.store.path,
38228
+ node: process.versions.node,
38229
+ configured: sources2.configured,
38230
+ selected: this.store.selected(),
38231
+ autoImport: sources2.autoImport,
38232
+ importLock: lock ? { pid: Number(lock.pid), heartbeat: Number(lock.heartbeat) } : null,
38233
+ checks,
38234
+ next: !this.store.selected().length ? "Run sessiongraph sources setup <source...>, then sessiongraph sync." : checks.some((c) => c.name !== "database" && !c.ok) ? "Run sessiongraph sync to retry." : ""
38235
+ };
38236
+ }
38237
+ };
38238
+
35761
38239
  // server/middleware.ts
35762
38240
  var publishingClient;
35763
38241
  var generation = /* @__PURE__ */ Symbol("sessiongraph-backend");
@@ -35852,7 +38330,19 @@ async function sessionGraphMiddleware(req, res, next) {
35852
38330
  }
35853
38331
  return json5(200, { saved: true, autoImport: store.autoImportEnabled() });
35854
38332
  }
35855
- if (url.pathname === "/api/sessiongraph/sources" && req.method === "GET") return json5(200, { sources: await importer.sources(), onboarding: store.setting("selected") === void 0 });
38333
+ if (url.pathname === "/api/sessiongraph/sources" && req.method === "GET") {
38334
+ const result = await new LibraryService(store, importer).discoverSources();
38335
+ return json5(200, { ...result, onboarding: !result.configured });
38336
+ }
38337
+ if (url.pathname === "/api/sessiongraph/sources/path") {
38338
+ if (req.method !== "POST") return json5(405, { error: "Method not allowed." });
38339
+ const value = await body(req);
38340
+ if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.source !== "string" || value.path !== null && typeof value.path !== "string") return json5(400, { error: "Choose a source and a history path, or Automatic." });
38341
+ const service = new LibraryService(store, importer);
38342
+ service.setSourcePath(value.source, value.path);
38343
+ const result = await service.discoverSources([value.source]);
38344
+ return json5(200, { saved: true, source: result.sources[0] });
38345
+ }
35856
38346
  if (url.pathname === "/api/sessiongraph/import") {
35857
38347
  if (req.method === "GET") return json5(200, importer.status);
35858
38348
  if (req.method === "POST") {
@@ -35925,7 +38415,7 @@ var arg = (name) => {
35925
38415
  const at2 = process.argv.indexOf(name);
35926
38416
  return at2 >= 0 ? process.argv[at2 + 1] : void 0;
35927
38417
  };
35928
- var assets = resolve4(arg("--assets") || fileURLToPath5(new URL("../dist", import.meta.url)));
38418
+ var assets = resolve5(arg("--assets") || fileURLToPath5(new URL("../dist", import.meta.url)));
35929
38419
  var token2 = randomBytes2(32).toString("hex");
35930
38420
  var ipc = process.argv.includes("--desktop") ? " ipc: http://ipc.localhost" : "";
35931
38421
  var equals = (value) => /^[a-f0-9]{64}$/.test(value) && timingSafeEqual(Buffer.from(value), Buffer.from(token2));
@@ -35961,8 +38451,8 @@ var server = createServer(async (req, res) => {
35961
38451
  res.end();
35962
38452
  return;
35963
38453
  }
35964
- const path = resolve4(assets, "." + decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname));
35965
- if (!path.startsWith(assets + sep4)) {
38454
+ const path = resolve5(assets, "." + decodeURIComponent(url.pathname === "/" ? "/index.html" : url.pathname));
38455
+ if (!path.startsWith(assets + sep5)) {
35966
38456
  res.writeHead(403);
35967
38457
  res.end();
35968
38458
  return;
@@ -35970,7 +38460,7 @@ var server = createServer(async (req, res) => {
35970
38460
  const info = await stat5(path);
35971
38461
  if (!info.isFile()) throw new Error("Not found");
35972
38462
  res.setHeader("Content-Type", types[extname(path)] || "application/octet-stream");
35973
- res.setHeader("Cache-Control", path.includes(`${sep4}assets${sep4}`) ? "public, max-age=31536000, immutable" : "no-store");
38463
+ res.setHeader("Cache-Control", path.includes(`${sep5}assets${sep5}`) ? "public, max-age=31536000, immutable" : "no-store");
35974
38464
  if (req.method === "HEAD") res.end();
35975
38465
  else createReadStream(path).on("error", () => res.destroy()).pipe(res);
35976
38466
  } catch {