sessiongraph 1.0.20 → 1.0.21

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