@fffangchenghao/dsh-web-search 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Browser half of `dsh-web-search-bing`.
3
3
  *
4
4
  * Registers one Settings page into the Settings surface's `settings.section`
5
- * slot, so this plugin's 20 configuration keys can be edited in the GUI instead
5
+ * slot, so this plugin's 22 configuration keys can be edited in the GUI instead
6
6
  * of the profile's `cordis.patch.yml`. The page reads and writes the plugin's
7
7
  * Loader entry (`web-search-bing`) through the shared `configForms` service,
8
8
  * which is the same path the shipped settings pages use.
@@ -77,6 +77,17 @@
77
77
  'hint.wait': 'auto decides from the question language, all waits for everyone, fast takes the first answer',
78
78
  'field.proxy': 'Proxy (relay)',
79
79
  'hint.proxy': 'Relay address for blocked sites; empty auto-detects the system proxy',
80
+ 'field.fetchFormat': 'Fetched page style',
81
+ 'hint.fetchFormat': 'markdown keeps headings, lists, tables and links; text keeps words only',
82
+ 'field.fetchMaxLength': 'Fetched characters',
83
+ 'hint.fetchMaxLength': 'Characters returned per fetch (1000-200000); the rest is noted as truncated',
84
+ 'field.renderJs': 'JavaScript rendering',
85
+ 'hint.renderJs': 'auto renders only a page that looks like an empty script shell, always renders every page, off never does. Needs Playwright installed separately; without it the page is returned unrendered',
86
+ 'renderJs.auto': 'Auto (only shell pages)',
87
+ 'renderJs.always': 'Always render',
88
+ 'renderJs.off': 'Off',
89
+ 'field.renderTimeoutMs': 'Render wait limit (ms)',
90
+ 'hint.renderTimeoutMs': 'How long one browser render may take (1000-120000); 15000 normally, raise it for heavy pages',
80
91
  'field.limit': 'Results per search',
81
92
  'hint.limit': 'How many results come back, and how they are split across engines',
82
93
  'field.rrfConstant': 'Result blending',
@@ -100,6 +111,12 @@
100
111
  'hint.cacheTtlMs': 'How long an identical question reuses its cached answer (ms)',
101
112
  'field.cacheEntries': 'Cache size',
102
113
  'hint.cacheEntries': 'How many answers are remembered before the least recently used goes',
114
+ 'field.cachePersist': 'Save cache to disk',
115
+ 'hint.cachePersist': 'Keep recent answers across restarts; turn it off to stay memory-only',
116
+ 'cachePersist.true': 'On (save to disk)',
117
+ 'cachePersist.false': 'Off (memory only)',
118
+ 'field.cacheFile': 'Cache file',
119
+ 'hint.cacheFile': 'Empty uses ~/.dsh/cache/dsh-web-search/cache.json',
103
120
  'field.anysearchApiKey': 'AnySearch key',
104
121
  'hint.anysearchApiKey': 'Leave empty to stay anonymous at a lower rate limit; only sent to api.anysearch.com',
105
122
  'field.anysearchDomain': 'Vertical domain',
@@ -145,6 +162,17 @@
145
162
  'hint.wait': 'auto 按提问语言自动决定,all 等全部,fast 先到先用',
146
163
  'field.proxy': '代理(中转站)',
147
164
  'hint.proxy': '上网中转站地址;留空自动识别系统代理',
165
+ 'field.fetchFormat': '抓取内容的样式',
166
+ 'hint.fetchFormat': 'markdown 保留标题、列表、表格和链接;text 只留纯文字',
167
+ 'field.fetchMaxLength': '抓取字符上限',
168
+ 'hint.fetchMaxLength': '一次抓取最多返回多少字符(1000-200000);超出部分会注明已截断',
169
+ 'field.renderJs': 'JS 渲染',
170
+ 'hint.renderJs': 'auto 只在正文像空壳网页时才用浏览器渲染,always 每次抓取都渲染,off 从不渲染;需另装 Playwright,没装就跳过',
171
+ 'renderJs.auto': '自动(仅空壳页面)',
172
+ 'renderJs.always': '每次都渲染',
173
+ 'renderJs.off': '关闭',
174
+ 'field.renderTimeoutMs': '渲染等待上限(毫秒)',
175
+ 'hint.renderTimeoutMs': '一次浏览器渲染最多等多久(1000-120000);平时 15000,页面很重可调大',
148
176
  'field.limit': '返回几条',
149
177
  'hint.limit': '一次最多返回几条,也决定各引擎分到几条',
150
178
  'field.rrfConstant': '结果混合力度',
@@ -168,6 +196,12 @@
168
196
  'hint.cacheTtlMs': '同一问题复用旧结果多久(毫秒);想更快见新内容就调小',
169
197
  'field.cacheEntries': '缓存条数上限',
170
198
  'hint.cacheEntries': '最多记住多少条旧结果,满了丢最久没用的',
199
+ 'field.cachePersist': '缓存保存到磁盘',
200
+ 'hint.cachePersist': '重启后仍复用最近结果;关闭则只在内存中保存',
201
+ 'cachePersist.true': '开启(保存到磁盘)',
202
+ 'cachePersist.false': '关闭(仅内存)',
203
+ 'field.cacheFile': '缓存文件路径',
204
+ 'hint.cacheFile': '留空使用 ~/.dsh/cache/dsh-web-search/cache.json',
171
205
  'field.anysearchApiKey': 'AnySearch 通行证',
172
206
  'hint.anysearchApiKey': '没有就留空,仍可用但速率较低;只发给 api.anysearch.com',
173
207
  'field.anysearchDomain': '专业领域',
@@ -191,6 +225,10 @@
191
225
  { key: 'wait', group: 'engines', kind: 'select', options: ['auto', 'all', 'fast'] },
192
226
  { key: 'timeoutMs', group: 'engines', kind: 'number', integer: true, min: 500 },
193
227
  { key: 'proxy', group: 'engines', kind: 'text' },
228
+ { key: 'fetchFormat', group: 'engines', kind: 'select', options: ['markdown', 'text'] },
229
+ { key: 'fetchMaxLength', group: 'engines', kind: 'number', integer: true, min: 1000, max: 200000 },
230
+ { key: 'renderJs', group: 'engines', kind: 'select', options: ['auto', 'always', 'off'] },
231
+ { key: 'renderTimeoutMs', group: 'engines', kind: 'number', integer: true, min: 1000, max: 120000 },
194
232
  { key: 'anysearchApiKey', group: 'engines', kind: 'text' },
195
233
  { key: 'anysearchDomain', group: 'engines', kind: 'text' },
196
234
  { key: 'limit', group: 'ranking', kind: 'number', integer: true, min: 1, max: 20 },
@@ -202,6 +240,8 @@
202
240
  { key: 'timeRange', group: 'ranking', kind: 'select', options: ['off', 'day', 'week', 'month', 'year'] },
203
241
  { key: 'cacheTtlMs', group: 'cache', kind: 'number', integer: true, min: 0 },
204
242
  { key: 'cacheEntries', group: 'cache', kind: 'number', integer: true, min: 0 },
243
+ { key: 'cachePersist', group: 'cache', kind: 'select', options: ['true', 'false'], boolean: true },
244
+ { key: 'cacheFile', group: 'cache', kind: 'text' },
205
245
  { key: 'baseCooldownMs', group: 'cache', kind: 'number', integer: true, min: 0 },
206
246
  { key: 'maxCooldownMs', group: 'cache', kind: 'number', integer: true, min: 0 },
207
247
  { key: 'domainSources', group: 'domain', kind: 'list' },
@@ -369,8 +409,9 @@
369
409
  return { op: 'set', path: [key], value: list };
370
410
  }
371
411
  if (field.kind === 'select') {
372
- if (raw === current) return null;
373
- return raw === '' ? { op: 'unset', path: [key] } : { op: 'set', path: [key], value: raw };
412
+ var next = field.boolean === true ? raw === 'true' : raw;
413
+ if (next === current) return null;
414
+ return raw === '' ? { op: 'unset', path: [key] } : { op: 'set', path: [key], value: next };
374
415
  }
375
416
  if (field.kind === 'text') {
376
417
  var text = String(raw === undefined || raw === null ? '' : raw);
@@ -0,0 +1,96 @@
1
+ import type { Source } from './types.ts';
2
+ /** Version of the on-disk document; a different version is ignored wholesale. */
3
+ export declare const CACHE_FILE_VERSION = 1;
4
+ /** Default byte budget for the snapshot: 4 MiB. */
5
+ export declare const DEFAULT_CACHE_FILE_MAX_BYTES: number;
6
+ /** One cache entry as it travels to disk. */
7
+ export interface PersistedEntry {
8
+ /** Deterministic key produced by `cacheKey`. */
9
+ key: string;
10
+ /** Absolute expiry timestamp; expired entries are dropped on load. */
11
+ expiresAt: number;
12
+ /** The search-result summary, never a page body. */
13
+ sources: Source[];
14
+ }
15
+ /** Filesystem seam: every call may throw, and the caller contains it. */
16
+ export interface CacheFileIo {
17
+ /** Read the file as UTF-8, or return `undefined` when it is absent. */
18
+ read: (path: string) => string | undefined;
19
+ /** Write a new file (the temporary one). */
20
+ write: (path: string, data: string) => void;
21
+ /** Atomically replace the target with the temporary file. */
22
+ rename: (from: string, to: string) => void;
23
+ /** Create the containing directory, including parents. */
24
+ mkdir: (path: string) => void;
25
+ /** Best-effort removal of the temporary file. */
26
+ remove: (path: string) => void;
27
+ }
28
+ /** The real filesystem, exported so tests can override one operation. */
29
+ export declare const nodeCacheFileIo: CacheFileIo;
30
+ /** Where a snapshot is written when the config names no path. */
31
+ export declare function defaultCacheFile(): string;
32
+ /**
33
+ * Expand a configured cache path.
34
+ *
35
+ * An empty value selects {@link defaultCacheFile}; a leading `~` expands to the
36
+ * home directory so the documented default can be written verbatim in Settings.
37
+ * Relative paths are resolved against the process working directory.
38
+ *
39
+ * @param value - the `cacheFile` setting, possibly empty.
40
+ * @returns an absolute file path.
41
+ */
42
+ export declare function resolveCacheFile(value?: string): string;
43
+ /**
44
+ * Load the snapshot from disk.
45
+ *
46
+ * Every failure mode collapses to an empty list: absent file, unreadable path,
47
+ * malformed JSON, a different `version`, and individually invalid entries. An
48
+ * expired entry is dropped here rather than retained until its next read.
49
+ *
50
+ * @param file - absolute path to the snapshot.
51
+ * @param now - current time from the cache's injected clock.
52
+ * @param maxEntries - entry cap; the oldest surplus entries are discarded.
53
+ * @param io - filesystem seam, defaulting to the real one.
54
+ * @returns usable entries in stored (oldest to newest) order.
55
+ */
56
+ export declare function readCacheFile(file: string, now: number, maxEntries: number, io?: CacheFileIo): PersistedEntry[];
57
+ /** One serialised snapshot plus what survived the byte cap. */
58
+ export interface SerializedCache {
59
+ /** UTF-8 JSON document, ready for the atomic write. */
60
+ data: string;
61
+ /** Number of entries left after LRU eviction. */
62
+ entries: number;
63
+ /** Size of {@link data} in bytes. */
64
+ bytes: number;
65
+ }
66
+ /**
67
+ * Serialise entries, evicting the oldest until the document fits the budget.
68
+ *
69
+ * @param entries - entries in LRU order (oldest first).
70
+ * @param now - timestamp recorded as `savedAt`.
71
+ * @param maxBytes - byte budget; defaults to 4 MiB.
72
+ * @returns the document and how many entries it carries.
73
+ */
74
+ export declare function serializeCache(entries: readonly PersistedEntry[], now: number, maxBytes?: number): SerializedCache;
75
+ /** Write options, kept separate so the cache owns the policy, not the path. */
76
+ export interface CacheWriteOptions {
77
+ /** Byte budget; defaults to 4 MiB. */
78
+ maxBytes?: number;
79
+ /** Filesystem seam for tests. */
80
+ io?: CacheFileIo;
81
+ }
82
+ /**
83
+ * Atomically replace the snapshot.
84
+ *
85
+ * The temporary file lives beside the target so the `rename` stays on one
86
+ * filesystem. When anything fails (directory not writable, rename rejected),
87
+ * the previous document is untouched, the temporary file is removed, and the
88
+ * call returns `false` instead of throwing.
89
+ *
90
+ * @param file - absolute target path.
91
+ * @param entries - entries in LRU order (oldest first).
92
+ * @param now - timestamp recorded as `savedAt`.
93
+ * @param options - byte budget and filesystem seam.
94
+ * @returns `true` when the target now holds this snapshot.
95
+ */
96
+ export declare function writeCacheFile(file: string, entries: readonly PersistedEntry[], now: number, options?: CacheWriteOptions): boolean;
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Optional disk persistence for the search cache.
3
+ *
4
+ * The cache itself stays a tiny TTL+LRU map; this module only knows how to
5
+ * turn a snapshot of it into a file and back. Three properties matter more
6
+ * than speed here:
7
+ *
8
+ * - **Never fail the plugin.** A missing, corrupt, foreign-version or
9
+ * unreadable file is treated as an empty cache. Every filesystem call is
10
+ * contained, because a cache is an optimisation and must never be the reason
11
+ * a plugin refuses to mount.
12
+ * - **Never leave a half-written file.** The snapshot is written to a sibling
13
+ * temporary file and then `rename`d over the target, which is atomic on the
14
+ * same filesystem. A failure before the rename leaves the previous file
15
+ * intact and removes the temporary one.
16
+ * - **Never grow without bound.** The serialised snapshot is trimmed in LRU
17
+ * order (oldest first) until it fits the byte budget.
18
+ *
19
+ * Only the search-result summary (`url`, `title`, `snippet`, `publishedAt`) is
20
+ * stored. Page bodies are never touched by this cache, and any extra property a
21
+ * caller attached to a {@link Source} is dropped at the serialisation boundary.
22
+ *
23
+ * @module @fangchenghao/dsh-web-search/cache-persist
24
+ */
25
+ import { readFileSync, renameSync, mkdirSync, rmSync, writeFileSync } from 'node:fs';
26
+ import { homedir } from 'node:os';
27
+ import { dirname, join, resolve } from 'node:path';
28
+ /** Version of the on-disk document; a different version is ignored wholesale. */
29
+ export const CACHE_FILE_VERSION = 1;
30
+ /** Default byte budget for the snapshot: 4 MiB. */
31
+ export const DEFAULT_CACHE_FILE_MAX_BYTES = 4 * 1024 * 1024;
32
+ /** The real filesystem, exported so tests can override one operation. */
33
+ export const nodeCacheFileIo = {
34
+ read(path) {
35
+ try {
36
+ return readFileSync(path, 'utf8');
37
+ }
38
+ catch {
39
+ // Missing file, permission error, directory: all mean "empty cache".
40
+ return undefined;
41
+ }
42
+ },
43
+ write(path, data) {
44
+ // The file only holds public search summaries, but 0600 keeps a shared
45
+ // machine from reading another user's queries.
46
+ writeFileSync(path, data, { encoding: 'utf8', mode: 0o600 });
47
+ },
48
+ rename(from, to) {
49
+ renameSync(from, to);
50
+ },
51
+ mkdir(path) {
52
+ mkdirSync(path, { recursive: true });
53
+ },
54
+ remove(path) {
55
+ rmSync(path, { force: true });
56
+ },
57
+ };
58
+ /** Where a snapshot is written when the config names no path. */
59
+ export function defaultCacheFile() {
60
+ return join(homedir(), '.dsh', 'cache', 'dsh-web-search', 'cache.json');
61
+ }
62
+ /**
63
+ * Expand a configured cache path.
64
+ *
65
+ * An empty value selects {@link defaultCacheFile}; a leading `~` expands to the
66
+ * home directory so the documented default can be written verbatim in Settings.
67
+ * Relative paths are resolved against the process working directory.
68
+ *
69
+ * @param value - the `cacheFile` setting, possibly empty.
70
+ * @returns an absolute file path.
71
+ */
72
+ export function resolveCacheFile(value) {
73
+ const trimmed = (value ?? '').trim();
74
+ if (trimmed.length === 0)
75
+ return defaultCacheFile();
76
+ const expanded = trimmed === '~'
77
+ ? homedir()
78
+ : /^~[\\/]/u.test(trimmed)
79
+ ? join(homedir(), trimmed.slice(2))
80
+ : trimmed;
81
+ return resolve(expanded);
82
+ }
83
+ /** True for a value usable as a plain record. */
84
+ function isRecord(value) {
85
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
86
+ }
87
+ /** Read one persisted source, keeping only the four summary fields. */
88
+ function readSource(raw) {
89
+ if (!isRecord(raw))
90
+ return undefined;
91
+ const url = raw['url'];
92
+ if (typeof url !== 'string' || url.trim().length === 0)
93
+ return undefined;
94
+ const source = { url };
95
+ if (typeof raw['title'] === 'string' && raw['title'].length > 0)
96
+ source.title = raw['title'];
97
+ if (typeof raw['snippet'] === 'string' && raw['snippet'].length > 0)
98
+ source.snippet = raw['snippet'];
99
+ if (typeof raw['publishedAt'] === 'string' && raw['publishedAt'].length > 0) {
100
+ source.publishedAt = raw['publishedAt'];
101
+ }
102
+ return source;
103
+ }
104
+ /** Write one source as a summary-only record. */
105
+ function storedSource(source) {
106
+ const stored = { url: source.url };
107
+ if (source.title !== undefined && source.title.length > 0)
108
+ stored['title'] = source.title;
109
+ if (source.snippet !== undefined && source.snippet.length > 0)
110
+ stored['snippet'] = source.snippet;
111
+ if (source.publishedAt !== undefined && source.publishedAt.length > 0) {
112
+ stored['publishedAt'] = source.publishedAt;
113
+ }
114
+ return stored;
115
+ }
116
+ /** Read one persisted entry, rejecting anything malformed or already expired. */
117
+ function readEntry(raw, now) {
118
+ if (!isRecord(raw))
119
+ return undefined;
120
+ const key = raw['key'];
121
+ const expiresAt = raw['expiresAt'];
122
+ const rawSources = raw['sources'];
123
+ if (typeof key !== 'string' || key.length === 0)
124
+ return undefined;
125
+ if (typeof expiresAt !== 'number' || !Number.isFinite(expiresAt) || expiresAt <= now)
126
+ return undefined;
127
+ if (!Array.isArray(rawSources))
128
+ return undefined;
129
+ const sources = [];
130
+ for (const item of rawSources) {
131
+ const source = readSource(item);
132
+ if (source !== undefined)
133
+ sources.push(source);
134
+ }
135
+ // An entry with no usable result is not worth a slot in the file.
136
+ if (sources.length === 0)
137
+ return undefined;
138
+ return { key, expiresAt, sources };
139
+ }
140
+ /** Clamp the byte budget to a usable positive integer. */
141
+ function normaliseMaxBytes(value) {
142
+ return typeof value === 'number' && Number.isFinite(value) && value > 0
143
+ ? Math.floor(value)
144
+ : DEFAULT_CACHE_FILE_MAX_BYTES;
145
+ }
146
+ /**
147
+ * Load the snapshot from disk.
148
+ *
149
+ * Every failure mode collapses to an empty list: absent file, unreadable path,
150
+ * malformed JSON, a different `version`, and individually invalid entries. An
151
+ * expired entry is dropped here rather than retained until its next read.
152
+ *
153
+ * @param file - absolute path to the snapshot.
154
+ * @param now - current time from the cache's injected clock.
155
+ * @param maxEntries - entry cap; the oldest surplus entries are discarded.
156
+ * @param io - filesystem seam, defaulting to the real one.
157
+ * @returns usable entries in stored (oldest to newest) order.
158
+ */
159
+ export function readCacheFile(file, now, maxEntries, io) {
160
+ try {
161
+ const text = (io ?? nodeCacheFileIo).read(file);
162
+ if (text === undefined)
163
+ return [];
164
+ const parsed = JSON.parse(text);
165
+ if (!isRecord(parsed))
166
+ return [];
167
+ if (parsed['version'] !== CACHE_FILE_VERSION)
168
+ return [];
169
+ const rawEntries = parsed['entries'];
170
+ if (!Array.isArray(rawEntries))
171
+ return [];
172
+ const entries = [];
173
+ for (const raw of rawEntries) {
174
+ const entry = readEntry(raw, now);
175
+ if (entry !== undefined)
176
+ entries.push(entry);
177
+ }
178
+ const cap = Number.isFinite(maxEntries) ? Math.max(0, Math.floor(maxEntries)) : entries.length;
179
+ return entries.length > cap ? entries.slice(entries.length - cap) : entries;
180
+ }
181
+ catch {
182
+ // Corrupt JSON, a foreign document, a getter that throws: empty cache.
183
+ return [];
184
+ }
185
+ }
186
+ /**
187
+ * Serialise entries, evicting the oldest until the document fits the budget.
188
+ *
189
+ * @param entries - entries in LRU order (oldest first).
190
+ * @param now - timestamp recorded as `savedAt`.
191
+ * @param maxBytes - byte budget; defaults to 4 MiB.
192
+ * @returns the document and how many entries it carries.
193
+ */
194
+ export function serializeCache(entries, now, maxBytes) {
195
+ const budget = normaliseMaxBytes(maxBytes);
196
+ const kept = entries.map((entry) => ({
197
+ key: entry.key,
198
+ expiresAt: entry.expiresAt,
199
+ sources: entry.sources.map(storedSource),
200
+ }));
201
+ const build = () => JSON.stringify({
202
+ version: CACHE_FILE_VERSION,
203
+ savedAt: now,
204
+ entries: kept,
205
+ });
206
+ let data = build();
207
+ while (kept.length > 0 && Buffer.byteLength(data, 'utf8') > budget) {
208
+ kept.shift();
209
+ data = build();
210
+ }
211
+ return { data, entries: kept.length, bytes: Buffer.byteLength(data, 'utf8') };
212
+ }
213
+ /** Distinguishes temporary files of concurrent writers in this process. */
214
+ let tempCounter = 0;
215
+ /**
216
+ * Atomically replace the snapshot.
217
+ *
218
+ * The temporary file lives beside the target so the `rename` stays on one
219
+ * filesystem. When anything fails (directory not writable, rename rejected),
220
+ * the previous document is untouched, the temporary file is removed, and the
221
+ * call returns `false` instead of throwing.
222
+ *
223
+ * @param file - absolute target path.
224
+ * @param entries - entries in LRU order (oldest first).
225
+ * @param now - timestamp recorded as `savedAt`.
226
+ * @param options - byte budget and filesystem seam.
227
+ * @returns `true` when the target now holds this snapshot.
228
+ */
229
+ export function writeCacheFile(file, entries, now, options = {}) {
230
+ const io = options.io ?? nodeCacheFileIo;
231
+ const { data } = serializeCache(entries, now, options.maxBytes);
232
+ tempCounter += 1;
233
+ const temp = `${file}.${process.pid}.${tempCounter}.tmp`;
234
+ try {
235
+ io.mkdir(dirname(file));
236
+ io.write(temp, data);
237
+ io.rename(temp, file);
238
+ return true;
239
+ }
240
+ catch {
241
+ try {
242
+ io.remove(temp);
243
+ }
244
+ catch {
245
+ // Cleanup is best effort; the previous snapshot is still intact.
246
+ }
247
+ return false;
248
+ }
249
+ }
package/lib/cache.d.ts CHANGED
@@ -13,6 +13,23 @@
13
13
  * @module @fangchenghao/dsh-web-search/cache
14
14
  */
15
15
  import type { CacheOptions, Source, TimeRange } from './types.ts';
16
+ import type { CacheFileIo } from './cache-persist.ts';
17
+ /** Optional disk persistence, layered on top of the in-memory cache. */
18
+ export interface CachePersistOptions {
19
+ /** Custom snapshot path; empty or absent uses `~/.dsh/cache/dsh-web-search/cache.json`. */
20
+ file?: string;
21
+ /** Serialised byte budget; the oldest entries are evicted to fit. */
22
+ maxBytes?: number;
23
+ /** Minimum gap between writes in milliseconds; defaults to two seconds. */
24
+ throttleMs?: number;
25
+ /** Filesystem seam, mainly for tests. */
26
+ io?: CacheFileIo;
27
+ }
28
+ /** Constructor options: {@link CacheOptions} plus optional persistence. */
29
+ export interface SearchCacheOptions extends CacheOptions {
30
+ /** Persist the cache when present; absent keeps the cache purely in memory. */
31
+ persist?: CachePersistOptions;
32
+ }
16
33
  /** The logical inputs that decide whether two searches may share an entry. */
17
34
  export interface CacheKeyParts {
18
35
  /** Raw query text; normalised inside {@link cacheKey}. */
@@ -56,18 +73,28 @@ export declare function cacheKey(parts: CacheKeyParts): string;
56
73
  */
57
74
  export declare class SearchCache {
58
75
  /** Entry lifetime in milliseconds; `0` disables the cache completely. */
59
- private readonly ttlMs;
76
+ /** Live TTL reader: settings may change without a remount. */
77
+ private readonly ttlOf;
60
78
  /** Maximum retained entries; the oldest read is evicted first. */
61
- private readonly maxEntries;
79
+ /** Live entry-cap reader: settings may change without a remount. */
80
+ private readonly maxOf;
62
81
  /** Injected clock, so tests never wait on real time. */
63
82
  private readonly now;
64
83
  /** Insertion order doubles as LRU order: the first key is the coldest. */
65
84
  private readonly entries;
85
+ /** Snapshot destination, or `undefined` for a purely in-memory cache. */
86
+ private readonly persistTo;
87
+ /** Minimum gap between writes. */
88
+ private readonly throttleMs;
89
+ /** Whether memory changed since the last successful write. */
90
+ private dirty;
91
+ /** Pending throttled flush. */
92
+ private timer;
66
93
  /**
67
- * @param options - TTL and entry cap, both optional.
94
+ * @param options - TTL, entry cap and optional persistence.
68
95
  * @param now - clock override; defaults to `Date.now`.
69
96
  */
70
- constructor(options?: CacheOptions, now?: () => number);
97
+ constructor(options?: SearchCacheOptions, now?: () => number);
71
98
  /** Number of retained entries, including ones whose TTL already elapsed. */
72
99
  get size(): number;
73
100
  /**
@@ -87,6 +114,23 @@ export declare class SearchCache {
87
114
  * @param sources - the merged source list; copied before storage.
88
115
  */
89
116
  set(key: string, sources: Source[]): void;
117
+ /**
118
+ * Write the snapshot now, if there is anything to write.
119
+ *
120
+ * Writes are normally throttled and happen on a timer or at process exit;
121
+ * this is the deterministic seam tests use, and the call a shutdown path can
122
+ * make when it wants the newest state on disk immediately.
123
+ *
124
+ * @returns `true` when the file was replaced, `false` for "nothing to write"
125
+ * or a contained filesystem failure.
126
+ */
127
+ flush(): boolean;
128
+ /** Stop the exit hook and flush whatever is still pending. */
129
+ close(): void;
90
130
  /** Drop every entry. */
91
131
  clear(): void;
132
+ /** Mark the snapshot stale and arrange a throttled flush. */
133
+ private touch;
134
+ /** Arm the single pending timer, if persistence is enabled. */
135
+ private schedule;
92
136
  }